diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 4a293a7..4a14088 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -53,6 +53,8 @@ jobs: exit 1 fi - name: Check WebUI syntax - run: node --check webui/app.js + run: | + node --check webui/app.js + node --check webui/i18n.js - name: Check container entrypoint syntax run: sh -n docker-entrypoint.sh diff --git a/README.md b/README.md index e09316a..14d27e0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # opencode2api -[English](README.md) | [简体中文](README.zh-CN.md) +[English](README.md) | [简体中文](README.zh-CN.md) | [Tiếng Việt](README.vi.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. @@ -386,6 +386,17 @@ The server forces `stream: false`. Use `{"mode":"selected","tier":"zen","id":"KE 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. +### Interface language + +The WebUI loads its translations from `webui/i18n.js`. It ships with **简体中文** (default), **English**, and **Tiếng Việt**. The original Simplified Chinese copy lives in `index.html` and `app.js` and stays the fallback for every string without a translation, so adding a language never rewrites the original. + +- The selector sits at the right of the toolbar, and on the login card. +- The choice is stored in `localStorage` under `opencode2api.ui.lang`. +- Switching re-renders both static text (`data-i18n`, `data-i18n-attr`) and JavaScript-generated text without reloading the page. +- Dates and times follow the selected locale as well. + +To add a language, add one block to `DICTIONARY` in `webui/i18n.js`, then register its code in `SUPPORTED`, `LABELS`, and `DATE_LOCALES`. + ### 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. @@ -440,9 +451,10 @@ internal/ protocol/ Request/response conversion and SSE parsing/output telemetry/ Request tracking, metrics, logs, and recovery webui/ - embed.go Embeds the three static assets into the executable + embed.go Embeds the four static assets into the executable index.html Page structure app.js UI behavior + i18n.js Interface language and translations styles.css UI styles ``` @@ -467,9 +479,10 @@ Node.js is only needed for the WebUI JavaScript syntax check: ```bash node --check webui/app.js +node --check webui/i18n.js ``` -`.editorconfig`, `.gitattributes`, and Go formatting standardize the source. CI runs `go vet` and builds with Go 1.24 and stable Go on Linux/Windows, plus Go formatting, WebUI syntax, and entrypoint shell syntax checks. Release archives include both READMEs. +`.editorconfig`, `.gitattributes`, and Go formatting standardize the source. CI runs `go vet` and builds with Go 1.24 and stable Go on Linux/Windows, plus Go formatting, WebUI syntax, and entrypoint shell syntax checks. Release archives include all three READMEs. ## Troubleshooting diff --git a/README.vi.md b/README.vi.md new file mode 100644 index 0000000..ab623c5 --- /dev/null +++ b/README.vi.md @@ -0,0 +1,504 @@ +# opencode2api + +[English](README.md) | [简体中文](README.zh-CN.md) | [Tiếng Việt](README.vi.md) + +Một gateway viết bằng Go cho **OpenCode Zen và Zen Go**. Nó cung cấp các endpoint Chat Completions, Responses và Anthropic Messages, chuyển đổi qua lại giữa các giao thức gốc của chúng, và quản lý upstream key cùng proxy. + +File thực thi đã bao gồm WebUI. Việc chạy dịch vụ không cần Node.js runtime hay cơ sở dữ liệu. + +## Tính năng + +- Phản hồi JSON và SSE trên cả ba giao thức suy luận. +- Văn bản, hình ảnh, suy luận, function tool, tool call và tool result; nội dung tệp ở nơi giao thức đích có thể biểu diễn. +- Hai nhóm key Zen và Go riêng biệt, tier ưu tiên có thể cấu hình, retry và session affinity. +- Truy cập Zen ẩn danh tuỳ chọn bằng credential `public` của OpenCode. +- Kết nối direct, HTTP, HTTPS, SOCKS5 và SOCKS5H, bao gồm cả file proxy. +- Tự động phát hiện mô hình, metadata giao thức gốc và cache trên đĩa. +- Cổng quản trị riêng với chỉnh sửa cấu hình, Playground, chẩn đoán, thống kê token và log trực tiếp. +- Nạp lại cấu hình nóng sau khi kiểm tra, trước khi chuyển request mới sang gateway thay thế. +- Bảng hạn mức gói Go với phần trăm còn lại, thời điểm reset và danh sách mô hình khả dụng. +- Tạo, đặt tên, bật, tắt và xoá API key cục bộ, có hiệu lực tức thì. +- Nhóm mô hình `sota` / `sweet` bám dính, có thứ tự, chuyển khi lỗi, bảo vệ luồng và trạng thái được lưu. + +Giao diện quản trị hỗ trợ **简体中文** (mặc định), **English** và **Tiếng Việt**; lựa chọn được lưu trong trình duyệt và không làm thay đổi bản gốc. + +Xem [hướng dẫn bảng điều khiển quản trị (tiếng Trung)](docs/management.zh-CN.md) để biết các trang mới và tuỳ chọn cấu hình. + +## Bắt đầu nhanh + +Tải file nhị phân từ [GitHub Releases](https://github.com/jasonxu114514/opencode2api/releases), hoặc build với **Go 1.24 trở lên**: + +```bash +git clone https://github.com/jasonxu114514/opencode2api.git +cd opencode2api +cp config.example.json config.json +go build -o opencode2api ./cmd/opencode2api +``` + +Trước khi khởi động, hãy sửa `config.json`: + +1. Thay `server_keys` bằng API key cục bộ của bạn. +2. Cung cấp key Zen hoặc Go. Nếu không, đặt `anonymous: true` và để cả hai mảng key upstream rỗng. +3. Thay `webui.password`. File mẫu bật WebUI với tài khoản `admin`. + +```bash +./opencode2api -config config.json +``` + +Trên Windows, dùng `Copy-Item config.example.json config.json`, build bằng `go build -o opencode2api.exe ./cmd/opencode2api`, rồi chạy `.\opencode2api.exe -config config.json`. + +File mẫu lắng nghe `127.0.0.1:8080` cho API và `0.0.0.0:8081` cho WebUI. Mở `http://localhost:8081` ở máy cục bộ. Hãy giới hạn quyền truy cập quản trị và dùng reverse proxy HTTPS khi truy cập qua mạng. + +Tuỳ chọn dòng lệnh: + +| Tuỳ chọn | Mặc định | Mục đích | +| -------------- | -------------- | -------------------------------------------- | +| `-config` | `config.json` | Đường dẫn file cấu hình. | +| `-listen` | Không đặt | Ghi đè địa chỉ lắng nghe của API. | +| `-web-listen` | Không đặt | Ghi đè địa chỉ lắng nghe của WebUI. | + +Thư mục cấu hình phải ghi được để thực hiện việc chuyển mật khẩu, lưu cấu hình và cache mô hình. + +## Docker + +Image được phát hành là `ghcr.io/jasonxu114514/opencode2api`. + +```bash +cp config.example.json config.json +# Cấu hình key và thay mật khẩu WebUI trước khi khởi động. +docker compose up -d +docker compose logs -f +``` + +Compose chỉ import cấu hình từ máy host vào volume `opencode2api-state` **ở lần khởi động đầu tiên**. Những thay đổi sau đó nên thực hiện qua WebUI. Để import lại file cấu hình đã sửa trên host: + +```bash +docker compose cp config.json opencode2api:/var/lib/opencode2api/config.json +docker compose restart +``` + +Container chạy dịch vụ bằng user không có đặc quyền. Compose dùng hệ thống file gốc chỉ đọc, volume trạng thái ghi được và hệ thống file tạm `/tmp`. + +| Biến Compose | Mặc định | Tác dụng | +| -------------------------------- | --------- | ----------------------------------------------------------- | +| `OPENCODE2API_VERSION` | `latest` | Tag image. Ghim tag release khi cần phiên bản cố định. | +| `OPENCODE2API_PORT` | `8080` | Cổng host ánh xạ tới cổng 8080 của container. | +| `OPENCODE2API_WEBUI_PORT` | `8081` | Cổng host ánh xạ tới cổng 8081 của container. | +| `OPENCODE2API_LISTEN` | Không đặt | Ghi đè rõ ràng địa chỉ lắng nghe API trong container. | +| `OPENCODE2API_WEBUI_LISTEN` | Không đặt | Ghi đè rõ ràng địa chỉ lắng nghe WebUI trong container. | + +Hai biến cuối trở thành `LISTEN_ADDRESS` và `WEBUI_LISTEN_ADDRESS` bên trong container. Giá trị rỗng sẽ dùng file cấu hình. Khi khởi tạo cấu hình, entrypoint đổi địa chỉ API mẫu `127.0.0.1:8080` thành `0.0.0.0:8080` để các cổng đã publish truy cập được. + +Đổi cổng host không làm thay đổi cổng lắng nghe trong container. Nếu đổi cổng API bên trong, cũng phải cập nhật ánh xạ cổng và health check của image (dùng cổng 8080). + +Build image cục bộ: + +```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 +``` + +`proxyfile` dùng trong Docker cũng phải tồn tại bên trong container tại đường dẫn đã cấu hình. + +## Sử dụng API + +`server_keys` dùng để xác thực client với gateway này. Chúng tách biệt với `zen_keys` và `go_keys` và không bao giờ được dùng làm credential upstream. + +Gửi `Authorization: Bearer YOUR_LOCAL_API_KEY` hoặc `x-api-key: YOUR_LOCAL_API_KEY`. Health check không cần xác thực. + +| Phương thức | Đường dẫn | Mô tả | +| ----------- | ----------------------- | ------------------------------------------------------------- | +| GET | `/v1/models` | Các mô hình có thể định tuyến với cấu hình hiện tại. | +| POST | `/v1/chat/completions` | Chat Completions. | +| POST | `/v1/responses` | Responses. | +| POST | `/v1/messages` | Anthropic Messages. | +| POST | `/v1/systemone` | Quyết định có cấu trúc của System One. | +| GET | `/healthz` | Trạng thái sẵn sàng và tóm tắt tài nguyên. | + +Hãy tìm một mô hình khả dụng trước: + +```bash +curl http://localhost:8080/v1/models \ + -H "Authorization: Bearer YOUR_LOCAL_API_KEY" +``` + +Thay `MODEL_ID` bên dưới bằng một ID có trong phản hồi đó. + +**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"}]}' +``` + +Để dùng streaming, thêm `"stream": true` vào body và dùng `curl -N`. Phản hồi có `x-request-id` để đối chiếu. Body của request API giới hạn 32 MiB. + +**System One** + +```bash +curl http://localhost:8080/v1/systemone \ + -H "Authorization: Bearer YOUR_LOCAL_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"model":"MODEL_ID","state":"1 + 1 = 2","questions":{"arithmetic":{"type":"noul","instructions":"Is 1 + 1 equal to 2?"}}}' +``` + +System One ghép một state tự do với các câu hỏi có kiểu và trả về câu trả lời có kiểu, nên payload này không dùng chung hình dạng với cầu nối chat/responses và được chuyển tiếp nguyên văn, không bao giờ dịch. Chỉ những mô hình có giao thức gốc là System One mới được phục vụ tại đây; một payload quyết định gửi tới endpoint message (`/v1/chat/completions`, `/v1/responses`) cũng được chuyển tiếp nguyên văn thay vì chuyển đổi. Câu trả lời streaming từ upstream được chuyển tiếp nguyên trạng, không khôi phục luồng. + +### Ranh giới tương thích + +Request dùng giao thức gốc của upstream sẽ giữ nguyên các trường riêng của nhà cung cấp. Request đi qua nhiều giao thức sẽ đi qua một biểu diễn chung; không phải tuỳ chọn nào cũng có phần tương đương. Ví dụ, ràng buộc output JSON của Chat và `seed` không được chuyển tiếp sang Anthropic Messages. Nội dung hoặc loại tool không được hỗ trợ có thể bị từ chối. + +Gateway cung cấp đúng các route nêu trên. Nó không triển khai embeddings, tải tệp lên, sinh ảnh, hay truy xuất và huỷ của Responses. Nó không lưu lịch sử hội thoại; client phải tự cung cấp lịch sử hoặc dùng các tính năng được upstream thật hỗ trợ. + +## Định tuyến và mô hình + +### Phát hiện mô hình + +Gateway làm mới `/v1/models` của Zen/Go và [danh mục năng lực](https://models.opencode.ai/api.json) của OpenCode theo chu kỳ đã cấu hình. Giao thức gốc và giới hạn mô hình được theo dõi riêng cho từng tier. Tài liệu Zen/Go của OpenCode là nguồn dự phòng để xác định giao thức. + +`models.protocols` ghi đè việc phát hiện: + +```json +{ + "models": { + "refresh_seconds": 300, + "protocols": { + "custom-model": "chat" + } + } +} +``` + +Giá trị giao thức hợp lệ là `chat`, `responses` và `anthropic`. Mô hình dùng giao thức gốc không được hỗ trợ sẽ bị lọc khỏi danh sách phát hiện trừ khi được ghi đè. + +Chi phí, trạng thái ngừng cấp và giới hạn mô hình đến từ [endpoint metadata chính thức của OpenCode](https://models.opencode.ai/api.json), làm mới mỗi 24 giờ. Danh mục năng lực của OpenCode vẫn là nguồn chuẩn cho giới hạn context và token; các trường metadata `limit.context`, `limit.input` và `limit.output` điền cho các trường còn thiếu trong danh mục đó. `/v1/models` công khai các giới hạn này qua `context_window`/`context_length`, `max_input` và `max_output` cho các client phát hiện như CLIProxyAPI và Pi. Mỗi request metadata dùng timeout 30 giây trên HTTP client. Khi làm mới thất bại, dữ liệu cũ vẫn được giữ. + +Mỗi phần tử của `/v1/models` cũng mang trường `cost` (USD trên một triệu token: `input`, `output`, `cache_read`, `cache_write`, cùng `cacheRead`/`cacheWrite` của OpenClaw) khi metadata nêu giá. Mô hình có suy luận liệt kê các bậc của chúng trong `reasoning_efforts` và trong `compat.supportedReasoningEfforts` của OpenClaw: từ `minimal` đến `max`, bị chặn ở trần đã dò khi bậc của mô hình là `auto`. Bậc bị ép hoặc được dò sẽ được báo là `default_reasoning_effort`. Giá cache hiển thị sau lần làm mới metadata kế tiếp. + +### Truy cập ẩn danh và dự phòng + +Khi `anonymous: true`, chỉ cần một trong hai điều kiện sau là mô hình đủ điều kiện cho làn Zen ẩn danh: + +- ID của nó chứa `free`, không phân biệt hoa thường. +- Metadata OpenCode báo chi phí input và output bằng 0 và mô hình không bị ngừng cấp. + +Điều kiện là một quyết định định tuyến; upstream vẫn có thể từ chối hoặc giới hạn tần suất request. Request ẩn danh dùng `public` trong header xác thực của upstream. + +Trình tự định tuyến là: + +1. Với mô hình đủ điều kiện, thử lần lượt mỗi proxy ẩn danh khả dụng. +2. Thử các tier có xác thực theo thứ tự `prefer`, chỉ dùng những tier có key được cấu hình và có route cho mô hình đó. +3. Áp dụng `retry.max_attempts` riêng cho từng tier có xác thực. + +Các lần thử ẩn danh không bị `retry.max_attempts` cắt ngắn, nhưng mọi lần thử đều dùng chung timeout của request. Lỗi mạng, xác thực thất bại, giới hạn tần suất và lỗi máy chủ có thể làm luân chuyển key. Các phản hồi 4xx khác kết thúc tier hiện tại; một tier khác còn khả dụng vẫn có thể được thử. + +Request được mã hoá theo giao thức riêng của từng tier. Khi bật `performance.first_event_timeout_seconds`, một phản hồi SSE thành công sẽ được giữ lại cho tới sự kiện dữ liệu hoàn chỉnh đầu tiên. Timeout hoặc mất kết nối trước sự kiện đó sẽ dùng ngân sách retry key/proxy hiện có; comment không tính là thoát timeout. Sau khi được giải phóng xuống phía dưới, luồng không bao giờ được phát lại. Mặc định là `0` (tắt); hãy thử `15` giây cho các upstream nhận request nhưng không gửi sự kiện nào. Giới hạn này áp dụng cho sự kiện đầu tiên, không phải token văn bản đầu tiên, và không áp dụng cho System One. Bí danh luân chuyển dùng timeout riêng `rotation.first_output_seconds`. Một tham chiếu reasoning Responses bị lỗi thời đã nhận diện có thể kích hoạt một lượt sửa; chẩn đoán chọn key cụ thể không bao giờ dùng lượt phát lại đó. + +Khi chỉ cấu hình truy cập ẩn danh, `/v1/models` chỉ công khai các mô hình đủ điều kiện cho làn đó. + +Mô hình miễn phí không bao giờ cần key Zen: với `anonymous: true` chúng được phục vụ bởi làn public, và key được cấu hình chỉ là phương án dự phòng. Muốn giữ key nhưng chỉ công khai mô hình miễn phí, hãy đặt `models.free_only: true`. Khi đó mô hình trả phí biến mất khỏi `/v1/models`, request trực tiếp tới chúng bị từ chối, và bí danh luân chuyển chỉ giữ lại thành viên miễn phí; mô hình miễn phí vẫn có thể dự phòng về các key đã cấu hình. + +### Tính khả dụng của mô hình miễn phí + +Gateway dò các mô hình có ID chứa `free` (không phân biệt hoa thường), hoặc có metadata báo chi phí input/output bằng 0 mà không bị ngừng cấp, bằng một request ngắn dùng giao thức gốc của mô hình. Nó thử làn ẩn danh đang bật trước, rồi tới một Zen Key đã cấu hình. Một phản hồi hợp lệ và hoàn tất trên bất kỳ làn nào sẽ giữ mô hình ở trạng thái bật; mô hình chỉ bị tắt trong phát hiện và định tuyến khi mọi làn được thử đều báo rõ ràng rằng mô hình không tồn tại hoặc đã bị thu hồi. Lỗi xác thực, giới hạn tần suất, timeout, lỗi truyền tải, phản hồi 5xx và câu trả lời sai định dạng đều không kết luận: chúng không tạo ra lần tắt mới và sẽ được kiểm tra lại sau một giờ. Lưu lượng dò không làm thay đổi cooldown key/proxy sản xuất hay thống kê request. Nó vẫn đi tới upstream và có thể tiêu tốn hạn mức miễn phí của họ. + +Mô hình System One dùng câu hỏi `noul` gốc hỏi rằng 1 + 1 có bằng 2 không; chúng không bao giờ được gửi payload chat/tool. Việc phát hiện mô hình gồm `native_protocol` và `supported_endpoints`; bí danh luân chuyển chỉ được liệt kê khi có key Go và mô hình đủ điều kiện. Lần tắt còn sót từ bản v1.3.6 sẽ được xoá khi nạp và lên lịch kiểm tra lại ngay, vì các lần dó đó dùng session ID không hợp lệ. + +Chu kỳ là cố định: mô hình đang bật được kiểm tra mỗi **1 giờ**, mô hình đã xác nhận không khả dụng được kiểm tra mỗi **24 giờ**. Một lần kiểm tra lại không kết luận đối với mô hình đã tắt sẽ giữ nguyên lý do tắt ban đầu và hẹn thử lại sau 24 giờ. Một lần kiểm tra lại thành công sẽ tự động khôi phục mô hình. Trang **Tính khả dụng mô hình miễn phí** của WebUI có thể khôi phục ngay, và điều đó đưa mô hình về điều khiển thủ công: nó giữ nguyên bật và bị loại khỏi việc dò tự động, nên kết quả dò về sau không thể ghi đè. Dùng nút **thủ công/tự động** theo từng mô hình trên cùng trang để trở lại dò tự động; lượt của bộ lập lịch kế tiếp sẽ hẹn một lần dò. Các bản ghi để lại ở trạng thái `manually_enabled` từ phiên bản cũ sẽ được chuyển sang điều khiển thủ công khi nạp. Một lần dò đang chạy không thể huỷ việc khôi phục thủ công. Các mô hình không có làn Zen/ẩn danh dùng được, hoặc không có giao thức suy luận được hỗ trợ, sẽ bị bỏ qua. + +Điều khiển thủ công cũng tạm dừng việc dò bậc suy luận cho `reasoning.effort=auto`; các bậc đã học sẽ ngừng bị ép sau hai giờ không xác minh. Trở lại điều khiển tự động cho phép việc dò bậc suy luận tiếp tục. + +Trạng thái tồn tại qua các lần khởi động trong `config.json..availability.json`, tách theo URL upstream Zen. Bộ lập lịch nền kiểm tra mô hình đến hạn mỗi phút một lần, bỏ qua mô hình điều khiển thủ công, và dò lần lượt phần còn lại, mỗi làn timeout 60 giây. Không có kênh nào khả dụng nghĩa là không tự động tắt. + +Các endpoint quản trị (cần đăng nhập; ghi còn cần CSRF): `GET /api/models/availability`, `POST /api/models/restore` với `{"model":"MODEL_ID"}` (khôi phục và chuyển sang điều khiển thủ công), và `POST /api/models/manual` với `{"model":"MODEL_ID","manual":true|false}` để chuyển qua lại giữa điều khiển thủ công và tự động. + +### Session và proxy + +Các key ban đầu được phân bố trên nhiều proxy. Lưu lượng thật có thể kích hoạt kiểm tra proxy, gán lại key và cooldown. Proxy không khoẻ được kiểm tra lại mỗi 15 phút bằng Cloudflare trace. + +Một hash session ổn định chọn key hoặc proxy ẩn danh ưu tiên. Gửi `x-session-id` tường minh để tách các hội thoại độc lập. Gateway cũng chấp nhận `x-opencode-session`, `x-session-affinity`, `conversation-id`, `conversation_id` và `metadata.session_id`. + +Không có ID tường minh, tin nhắn người dùng đầu tiên được dùng làm seed. Vì vậy các hội thoại mở đầu bằng nội dung giống nhau có thể dùng chung affinity. Thay đổi thành phần nhóm có thể làm đổi nút được chọn. + +Cooldown tăng theo cấp số nhân tối đa tám lần `performance.failure_cooldown_seconds`, và giá trị `Retry-After` dài hơn sẽ được tôn trọng. Nếu mọi key có xác thực đều đang nghỉ, định tuyến có thể thử key mà cooldown kết thúc sớm nhất. Các nút ẩn danh còn trong cooldown sẽ bị bỏ qua. + +## Tham chiếu cấu hình + +Xem [config.example.json](config.example.json) để có một cấu hình khởi đầu đầy đủ. JSON hỗ trợ chú thích `//` và `/* ... */`; trường lạ và giá trị không hợp lệ đều bị từ chối. + +### Key, cổng lắng nghe và định tuyến + +| Trường | Mặc định / yêu cầu | +| -------------------------- | ---------------------------------------------------------------- | +| `listen` | `127.0.0.1:8080`. | +| `server_keys` | Cần ít nhất một key cục bộ. | +| `zen_keys`, `go_keys` | Cần ít nhất một key upstream trừ khi bật truy cập ẩn danh. | +| `anonymous` | `false`. | +| `prefer` | `go`; nhận `go` hoặc `zen`. | +| `upstream.zen` | `https://opencode.ai/inference/openai`. | +| `upstream.go` | `https://opencode.ai/zen/go`. | +| `proxies` | Rơi về `["direct"]` khi cả hai nguồn proxy đều rỗng. | +| `proxyfile` | Không bắt buộc; đường dẫn tương đối được phân giải cạnh file cấu hình. | +| `models.refresh_seconds` | `300`; tối thiểu 1. | +| `models.protocols` | `{}`; ghi đè giao thức gốc theo từng mô hình. | +| `models.free_only` | `false`; chỉ công khai và định tuyến mô hình miễn phí, kể cả khi có key Zen hoặc Go. | +| `reasoning.effort` | Rỗng (tắt); `minimal`, `low`, `medium`, `high`, `xhigh`, `max` hoặc `none`. | +| `reasoning.effort_by_model`| `{}`; ghi đè `reasoning.effort` theo từng mô hình. | + +### Bậc suy luận bị ép + +`reasoning.effort` đặt bậc suy luận được dùng ở upstream khi một request không tự nêu bậc của nó, và `reasoning.effort_by_model` ghi đè bậc đó cho các ID mô hình mà nó nêu. Nó áp dụng cho cả ba giao thức, theo cả hai chiều chuyển đổi, và quan trọng nhất với lưu lượng liên giao thức: `thinking.budget_tokens` của Anthropic chỉ có thể được xấp xỉ bởi bề mặt Chat và Responses, nên một bậc bị ép có thể đạt tới bậc mà ngân sách token không diễn đạt được. + +```json +{ + "reasoning": { + "effort": "high", + "effort_by_model": { "claude-opus-5": "max" } + } +} +``` + +Bậc do client nêu tường minh luôn thắng, nên thiết lập này chỉ thay thế một bậc mà không ai yêu cầu: bậc bị thiếu, hoặc bậc suy ra từ `thinking.budget_tokens`. Dùng `"none"` để loại bỏ reasoning khỏi các request không yêu cầu nó. + +Các bậc được báo trung thực theo cả hai chiều. Một `output_config.effort` tường minh sống sót qua chuyển đổi thay vì bị khối `thinking` che khuất, `budget_tokens` giữ đúng bậc của nó (`8192` là `high`, `32000` là `xhigh`, nên hai mức vẫn phân biệt được), và phía Responses mang bậc này dưới dạng `reasoning.effort` thay vì bỏ mất. + +Trung tâm cấu hình của WebUI cung cấp cùng các trường mặc định và theo mô hình. API quản trị trả chúng dưới trường `reasoning` từ `GET /api/config` và nhận đối tượng đó trong `PUT /api/config`; client bỏ qua trường sẽ giữ giá trị hiện tại, còn gửi đối tượng rỗng sẽ xoá nó. + +Các mục proxy nhận `direct`, `http://`, `https://`, `socks5://` và `socks5h://`, kể cả credential trong URL. Danh sách nội tuyến được gộp với `proxyfile` và khử trùng lặp theo thứ tự. + +Một file proxy chứa mỗi dòng một mục và hỗ trợ dòng trống cùng chú thích: + +```text +# Proxy chính +http://user:password@127.0.0.1:7890 +socks5://127.0.0.1:1080 # Proxy dự phòng +direct +``` + +Dấu bắt đầu chú thích là `#`, `;` và `//`, ở đầu dòng hoặc sau khoảng trắng. + +### Timeout và connection pool + +| Trường | Mặc định | Ý nghĩa | +| ---------------------------------------- | -------- | ----------------------------------------------------------- | +| `retry.max_attempts` | `3` | Số lần thử cho mỗi tier có xác thực, kể cả lần đầu. | +| `retry.timeout_seconds` | `300` | Timeout suy luận tổng, gồm cả thời gian đọc luồng. | +| `performance.attempt_timeout_seconds` | `0` | Giới hạn cho một lần thử; 0 dùng timeout của request. | +| `performance.connect_timeout_seconds` | `5` | Timeout thiết lập kết nối. | +| `performance.failure_cooldown_seconds` | `15` | Cooldown lỗi cơ sở. | +| `performance.max_idle_conns` | `2048` | Giới hạn kết nối rảnh cho mỗi transport proxy. | +| `performance.max_idle_conns_per_host` | `256` | Giới hạn kết nối rảnh cho mỗi host và transport. | +| `performance.max_conns_per_host` | `0` | Giới hạn kết nối cho mỗi host; 0 là không giới hạn. | +| `performance.idle_conn_timeout_seconds` | `120` | Thời gian sống của kết nối rảnh. | + +Timeout header cho mỗi lần thử bị chặn trên bởi timeout của request. Hãy đặt nó thấp hơn timeout tổng nếu muốn một upstream chậm vẫn còn thời gian chuyển sang dự phòng. Context của request đã hết hạn sẽ dừng các lần thử tiếp theo mà không phạt oan key hay proxy chưa dùng. + +### Nhật ký và quản trị + +| Trường | Mặc định / yêu cầu | +| ----------------------------- | ------------------------------------------------------- | +| `logging.level` | `info`; nhận `debug`, `info`, `warn`, `error`. | +| `logging.ring_size` | `2000`; khoảng 100–50.000. | +| `logging.dump_request_bodies` | `false`. Cần log mức `debug` để xuất body đi ra. | +| `webui.enabled` | `false` nếu bỏ qua; file mẫu đặt là `true`. | +| `webui.listen` | `0.0.0.0:8081`. | +| `webui.username` | Bắt buộc khi bật WebUI; file mẫu dùng `admin`. | +| `webui.password` | Mật khẩu khởi tạo, tối thiểu 10 ký tự. | +| `webui.password_hash` | Hash Argon2id được sinh ra; thay thế mật khẩu văn bản thuần. | +| `webui.session_ttl_minutes` | `720`; khoảng 5–10.080. | + +Khi khởi động, mật khẩu khởi tạo được băm và gỡ khỏi cấu hình. Bản sao lưu chứa bản văn bản thuần đó bị xoá. Hãy giữ file cấu hình và bản sao lưu ở chế độ riêng tư: upstream key và credential proxy vẫn là bí mật cấu hình cần thiết. + +Body dump là tuỳ chọn và giới hạn 64 KiB cho mỗi body đã chuẩn bị. Bí mật đã cấu hình bị che, nhưng nội dung hội thoại vẫn có thể nhạy cảm. + +## WebUI và chẩn đoán + +Cổng quản trị phục vụ UI và các route `/api/*`. Việc xác thực dùng một tài khoản quản trị, session phía máy chủ, cookie HttpOnly/SameSite, kiểm tra CSRF cho thao tác ghi, và giới hạn số lần đăng nhập. + +| Route quản trị | Mục đích | +| ---------------------------------------------- | --------------------------------------------------------------- | +| `POST /api/auth/login` | Đăng nhập và nhận cookie session cùng CSRF token. | +| `GET /api/auth/session`, `POST /api/auth/logout` | Kiểm tra hoặc kết thúc session. | +| `GET /api/config`, `PUT /api/config` | Đọc cấu hình đã che hoặc áp dụng thay đổi. | +| `POST /api/config/reload` | Nạp lại file từ đĩa. | +| `POST /api/config/reveal` | Hiện bí mật đã cấu hình sau khi xác minh mật khẩu. | +| `PUT /api/account` | Cập nhật thông tin đăng nhập sau khi xác minh mật khẩu; vô hiệu hoá session. | +| `GET /api/monitor` | Thống kê request, token, upstream và tài nguyên. | +| `GET /api/debug/models` | Định tuyến mô hình, vân tay key và chẩn đoán metadata. | +| `POST /api/debug/inference` | Chạy một request Playground. | +| `GET /api/logs`, `GET /api/logs/stream` | Log gần đây hoặc đăng ký SSE trực tiếp. | + +Request Playground cần session và `X-CSRF-Token`, giới hạn 12 lần mỗi phút cho mỗi IP client: + +```json +{ + "protocol": "chat", + "key": { "mode": "auto" }, + "request": { + "model": "MODEL_ID", + "messages": [{ "role": "user", "content": "Hello" }] + } +} +``` + +Máy chủ ép `stream: false`. Dùng `{"mode":"selected","tier":"zen","id":"KEY_FINGERPRINT"}` để thử một key cụ thể lấy từ `/api/debug/models`. Request chọn key tối đa chỉ thực hiện một lần thử upstream, không truy cập ẩn danh, không luân chuyển key, không dự phòng tier và không phát lại reasoning. + +**Cả chẩn đoán tự động và chọn key đều giữ nguyên cooldown key sản xuất, số lần lỗi, sức khoẻ proxy và ràng buộc của chúng.** Chúng vẫn gửi request thật tới upstream, có thể tiêu tốn hạn mức của nhà cung cấp và xuất hiện trong giám sát. + +Sau khi thực thi, endpoint quản trị trả HTTP 200 với kết quả thực tế trong `ok`, `http_status`, `request_id`, `route` và `response`. Kết quả chọn key còn có `selected_key` và `key_test`: `usable`, `rejected`, `rate_limited`, `transport_error`, `upstream_error`, `request_error` hoặc `unavailable`. Dữ liệu đầu vào quản trị không hợp lệ, lỗi xác thực, CSRF và vượt giới hạn vẫn giữ mã lỗi HTTP riêng. + +### Ngôn ngữ giao diện + +WebUI tải bản dịch từ `webui/i18n.js`. Bản dịch có sẵn gồm **简体中文** (mặc định), **English** và **Tiếng Việt**. Ngôn ngữ gốc **简体中文** nằm ngay trong `index.html` và `app.js`, và luôn được dùng làm dự phòng cho mọi chuỗi không có bản dịch — vì vậy việc thêm ngôn ngữ không làm thay đổi bản gốc. + +- Bộ chọn ngôn ngữ nằm ở góc phải thanh công cụ (và trên thẻ đăng nhập). +- Lựa chọn được lưu trong `localStorage` với khoá `opencode2api.ui.lang`. +- Đổi ngôn ngữ sẽ dịch lại cả văn bản tĩnh (`data-i18n`, `data-i18n-attr`) lẫn văn bản do JavaScript tạo ra, mà không cần tải lại trang. +- Định dạng ngày giờ cũng theo ngôn ngữ đang chọn. + +Thêm một ngôn ngữ mới chỉ cần thêm một khối vào `DICTIONARY` trong `webui/i18n.js`, rồi khai báo mã trong `SUPPORTED`, `LABELS` và `DATE_LOCALES`. + +### Lưu và nạp lại + +Máy chủ kiểm tra một cấu hình ứng viên và dựng gateway thay thế trước khi lưu và chuyển đổi. Kiểm tra hoặc lưu thất bại sẽ giữ nguyên gateway đang hoạt động. Các request đang chạy vẫn tiếp tục trên gateway gốc của chúng. + +Key, proxy, URL upstream, thiết lập retry, thiết lập mô hình, nhật ký và tuỳ chọn định tuyến có hiệu lực ngay với request mới. Thay đổi `listen`, `webui.listen` hoặc `webui.enabled` cần khởi động lại tiến trình. JSON đã lưu được chuẩn hoá; chú thích không được giữ lại. + +## Giám sát và lưu trữ + +Kết quả request mô tả lần suy luận đã hoàn tất. Một phản hồi SSE thất bại hoặc luồng bị cắt cụt vẫn được tính là lỗi kể cả khi HTTP 200 đã được gửi; kết quả của nó là `stream_error`. Việc client huỷ được ghi là `client_canceled`. WebUI hiển thị các kết quả đó bên cạnh mã trạng thái HTTP. + +Bản ghi **lần thử** upstream đo trao đổi HTTP tính tới lúc nhận được header phản hồi. Thành công và độ trễ của nó tách biệt với việc hoàn tất toàn bộ body JSON hoặc luồng. + +Thống kê token chỉ dùng usage được báo. Token input bao gồm đọc và ghi cache; token cache riêng đếm các lần đọc cache. Usage thiếu không được ước tính, và độ phủ cho biết bao nhiêu request suy luận đã định tuyến có báo usage. `usage.server_keys` tách request và token theo server key cục bộ mà caller đã xác thực (vân tay của nó, như hiển thị ở `/api/api-keys`); lưu lượng Playground được tính dưới mục `playground`. + +| Dữ liệu | Lưu trữ / thời gian giữ | +| -------------------------------------------------------- | -------------------------------------------------------------- | +| Session, số đo, tổng token, kết quả Playground gần nhất | Bộ nhớ tiến trình; bị xoá khi khởi động lại. | +| Chi tiết request và lần thử | Một giờ gần nhất, tối đa 10.000 request và 20.000 lần thử; API trả tối đa 500 mục mỗi loại. | +| Ring log trực tiếp | Bộ nhớ tiến trình; kích thước do `logging.ring_size` quy định. | +| Log có cấu trúc | JSON trên stdout; thu thập bên ngoài để lưu lâu dài. | +| Cấu hình và phiên bản trước | `config.json` và `config.json.bak`. | +| Cache danh mục mô hình | `config.json.models.catalog.json`. | +| Cache giá/ngừng cấp | `config.json.models.dev.json`. | + +Tên file cache dựa trên đường dẫn cấu hình thực tế. Các bộ đếm tuổi thọ đều tính theo tuổi thọ tiến trình hiện tại. Các instance không chia sẻ session hay trạng thái giám sát. + +### Health check + +`/healthz` không làm tăng bộ đếm giám sát cũng không phát sinh request mạng. Nó báo cáo số lượng tài nguyên mà không kèm key hay địa chỉ proxy. + +- HTTP 503: danh mục khởi tạo còn đang chờ, không có mô hình nào định tuyến được với cấu hình hiện tại, hoặc không có proxy khoẻ. +- HTTP 200: sẵn sàng, kể cả khi cache danh mục dùng được đã cũ. Trong trường hợp đó trạng thái mô hình là `stale` và trạng thái tổng thể là `degraded`. + +Ngưỡng cũ là gấp đôi `models.refresh_seconds`, tối thiểu 60 giây. Khả năng sẵn sàng là một bước kiểm tra phát hiện và tài nguyên; nó không xác minh rằng upstream key sẽ chấp nhận lần suy luận tiếp theo. + +## Phát triển + +Mã nguồn Go được tổ chức thành các package theo trách nhiệm. Lệnh điều phối dịch vụ; các package triển khai nằm dưới `internal/`. + +```text +cmd/ + opencode2api/main.go Cờ CLI, khởi động và tắt êm +internal/ + admin/ API quản trị, session đăng nhập và Playground + buildinfo/ Phiên bản dùng chung cho health và endpoint quản trị + config/ Cấu hình, lưu trữ, mật khẩu và che giấu + gateway/ Định tuyến HTTP, retry, pool, làm mới và runtime + httpx/ Phản hồi HTTP dùng chung, xử lý body và header + identity/ Request ID và session affinity + jsonutil/ Trợ giúp truy cập và giải mã JSON + models/ Danh mục mô hình, năng lực, giá và cache + protocol/ Chuyển đổi request/response và phân tích/xuất SSE + telemetry/ Theo dõi request, số đo, log và phục hồi +webui/ + embed.go Nhúng ba tài nguyên tĩnh vào file thực thi + index.html Cấu trúc trang + app.js Hành vi giao diện + i18n.js Ngôn ngữ giao diện và bảng dịch + styles.css Kiểu giao diện +``` + +Thứ tự đọc gợi ý: + +1. [Lệnh vào](cmd/opencode2api/main.go) → [quản lý runtime](internal/gateway/runtime.go) → [handler HTTP](internal/gateway/gateway.go). +2. [Lần thử upstream](internal/gateway/upstream.go) và [định tuyến mô hình](internal/models/catalog.go) giải thích một request đến nhà cung cấp bằng cách nào. +3. [Chuyển đổi request](internal/protocol/request.go), [chuyển đổi phản hồi](internal/protocol/response.go) và [vận chuyển luồng](internal/protocol/stream.go) bao phủ hành vi giao thức. +4. [Route quản trị](internal/admin/server.go) và [logic WebUI](webui/app.js) bao phủ cấu hình và chẩn đoán. + +Chạy định dạng Go, phân tích và build lệnh: + +```bash +gofmt -w cmd internal webui +go vet ./... +go build -o opencode2api ./cmd/opencode2api +``` + +Để phát triển cục bộ, khởi động dịch vụ bằng `go run ./cmd/opencode2api -config config.json`. Bản build phát hành vẫn chèn phiên bản bằng `-ldflags "-X main.version=vX.Y.Z"`. + +Node.js chỉ cần cho bước kiểm tra cú pháp JavaScript của WebUI: + +```bash +node --check webui/app.js +node --check webui/i18n.js +``` + +`.editorconfig`, `.gitattributes` và định dạng Go chuẩn hoá mã nguồn. CI chạy `go vet` và build với Go 1.24 và Go ở bản ổn định trên Linux/Windows, đồng thời kiểm tra định dạng Go, cú pháp WebUI và cú pháp shell của entrypoint. Gói phát hành gồm cả ba README. + +## Khắc phục sự cố + +| Triệu chứng | Cần kiểm tra | +| ------------------------------------------- | ----------------------------------------------------------------------------------- | +| API trả 401 | Dùng một giá trị `server_keys` cục bộ đã cấu hình. | +| Health vẫn là `starting` | Xem log làm mới danh mục và kết nối đi ra; thêm ghi đè giao thức nếu cần. | +| Không có mô hình nào được công khai | Kiểm tra tier đã cấu hình, điều kiện ẩn danh và hỗ trợ giao thức gốc. | +| Request trả 502/504 | Xem các lần thử upstream, credential, proxy và timeout tổng/theo từng lần thử. | +| HTTP 200 nhưng sinh nội dung thất bại | Xem sự kiện lỗi SSE và kết quả request, không chỉ mã trạng thái HTTP. | +| Sửa trên host không có tác dụng trong Docker | File đang hoạt động nằm trong volume trạng thái; import lại hoặc dùng WebUI. | +| Không kết nối được cổng của container | Kiểm tra địa chỉ lắng nghe, cổng đã publish và cấu hình trong volume đang dùng. | +| Số liệu giám sát mất sau khi khởi động lại | Giám sát chỉ nằm trong bộ nhớ; thu thập log stdout ra bên ngoài. | + +## Ghi nhận + +Cảm ơn cộng đồng [LINUX DO](https://linux.do) đã ủng hộ. + +### Cường độ suy luận thích ứng + +Đặt `reasoning.effort` (hoặc ghi đè theo mô hình) là `auto` để dùng cường độ cao nhất đã được bộ dò mô hình miễn phí xác minh thành công. Các bậc cụ thể sẵn có giữ nguyên ý nghĩa và cường độ do client chỉ định được ưu tiên. Không có danh sách cho phép theo tên mô hình nào được duy trì. + +Sau khi một mức nền thành công, các mô hình có suy luận được dò theo thứ tự `max`, `xhigh`, `high`, `medium`, `low`, `minimal`. Chỉ khi có tham số suy luận bị từ chối tường minh mới chuyển xuống bậc thấp hơn. Lỗi tạm thời sẽ dừng tìm kiếm và không thể bị hiểu là trần năng lực thấp hơn. Nếu mọi bậc đều bị từ chối, không có ghi đè suy luận nào được chèn vào. + +Các quan sát được lưu theo URL upstream, mô hình và giao thức gốc, hiển thị ở trang tính khả dụng, và chỉ dùng tối đa hai giờ. Lần dò đang hoạt động chỉ áp dụng cho mô hình Zen/ẩn danh miễn phí; mô hình Go/trả phí, năng lực chưa biết và bậc chưa xác minh không nhận ghi đè tự động. Đặt `auto` không mở rộng phạm vi dò và không bảo đảm upstream tuân thủ mọi trường được chấp nhận. Việc dò có thể cần vài request nhỏ cho mỗi mô hình và dùng hạn mức của upstream. + +## Giấy phép + +SPDX-License-Identifier: GPL-3.0-or-later + +Dự án này là phần mềm tự do: bạn có thể phân phối lại và sửa đổi theo Giấy phép Công cộng GNU phiên bản 3 do Free Software Foundation công bố, hoặc phiên bản 3 hoặc mới hơn (tuỳ chọn của bạn). Phần mềm được cung cấp nguyên trạng, không kèm bảo đảm. Xem [LICENSE](LICENSE) để biết đầy đủ điều khoản. \ No newline at end of file diff --git a/README.zh-CN.md b/README.zh-CN.md index 6120219..f200ba3 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,6 +1,6 @@ # opencode2api -[English](README.md) | [简体中文](README.zh-CN.md) +[English](README.md) | [简体中文](README.zh-CN.md) | [Tiếng Việt](README.vi.md) 使用 Go 编写的 **OpenCode Zen / Zen Go API 网关**。对外提供 Chat Completions、Responses 和 Anthropic Messages 接口,按上游原生协议转换请求,并统一管理上游 Key 与代理。 @@ -381,6 +381,17 @@ Playground 需要已登录的 Session 和 `X-CSRF-Token`,每个客户端 IP 执行后,管理接口返回 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 状态。 +### 界面语言 + +WebUI 从 `webui/i18n.js` 加载翻译,内置 **简体中文**(默认)、**English** 和 **Tiếng Việt**。原始简体中文文案保留在 `index.html` 和 `app.js` 中,并始终作为缺少翻译时的回退,因此新增语言不会覆盖原文。 + +- 语言选择器位于顶部工具栏右侧,登录卡片上也有一个。 +- 选择结果保存在 `localStorage`,键名为 `opencode2api.ui.lang`。 +- 切换语言会同时重绘静态文案(`data-i18n`、`data-i18n-attr`)和 JavaScript 生成的文案,无需刷新页面。 +- 日期时间格式跟随所选语言。 + +新增语言时,在 `webui/i18n.js` 的 `DICTIONARY` 中增加一个语言块,并在 `SUPPORTED`、`LABELS` 和 `DATE_LOCALES` 中登记其代码。 + ### 保存与重载 服务先验证候选配置并创建新的 Gateway,然后保存配置并切换实例。验证或保存失败时,当前 Gateway 继续处理请求;已经开始的请求继续使用原有实例。 @@ -435,9 +446,10 @@ internal/ protocol/ 请求和响应转换、SSE 解析与输出 telemetry/ 请求跟踪、指标、日志与异常恢复 webui/ - embed.go 将三个静态资源内嵌到可执行文件 + embed.go 将四个静态资源内嵌到可执行文件 index.html 页面结构 app.js 界面交互 + i18n.js 界面语言与翻译词典 styles.css 界面样式 ``` @@ -462,9 +474,10 @@ Node.js 仅用于 WebUI 的 JavaScript 语法检查: ```bash node --check webui/app.js +node --check webui/i18n.js ``` -项目通过 `.editorconfig`、`.gitattributes` 和 Go 格式化统一格式。CI 覆盖 Linux / Windows 上的 Go 1.24 与稳定版 Go 的 `go vet` 和构建,以及 Go 格式、WebUI 语法和容器入口脚本语法检查。发布压缩包包含中英文两份 README。 +项目通过 `.editorconfig`、`.gitattributes` 和 Go 格式化统一格式。CI 覆盖 Linux / Windows 上的 Go 1.24 与稳定版 Go 的 `go vet` 和构建,以及 Go 格式、WebUI 语法和容器入口脚本语法检查。发布压缩包包含中英越三份 README。 ## 常见问题 diff --git a/docs/management.zh-CN.md b/docs/management.zh-CN.md index 6852e4f..90db609 100644 --- a/docs/management.zh-CN.md +++ b/docs/management.zh-CN.md @@ -34,6 +34,7 @@ go test ./... go test -race ./... go vet ./... node --check webui/app.js +node --check webui/i18n.js go build -trimpath -o opencode2api ./cmd/opencode2api ``` @@ -81,7 +82,7 @@ Messages,以及这三种协议的流式输出。真实模型 ID 的原有调 - `POST /api/rotation/current`:`{"group":"sota","model":"glm-5.3"}`;立即 修改当前模型并解除该模型的临时暂停。 -验证:`go test -race ./...`、`go vet ./...`、`node --check webui/app.js`。 +验证:`go test -race ./...`、`go vet ./...`、`node --check webui/app.js`、`node --check webui/i18n.js`。 模拟上游测试覆盖 9 次普通错误上限、超过 3 个额度跳过、混合错误预算、 Retry-After、单个模型故障不影响 Key、三种入口协议的跨协议转换、成功保持、 别名发现与用量归属、畸形响应、输出前错误、首个输出超时、输出后故障、 diff --git a/webui/app.js b/webui/app.js index 6f4219b..79e3680 100644 --- a/webui/app.js +++ b/webui/app.js @@ -1,5 +1,9 @@ const $ = (selector) => document.querySelector(selector), $$ = (selector) => [...document.querySelectorAll(selector)]; +// Text is authored in Simplified Chinese and stays the fallback for every locale +// without a dictionary entry; window.O2I18N only replaces what it can translate. +const t = (original, key, ...args) => window.O2I18N.t(original, key, ...args); +window.O2I18N.init(); let csrf = "", config = null, monitorData = null, @@ -26,6 +30,17 @@ const pages = { "model-quotas": ["10", "模型与额度", "可用模型、共享套餐剩余额度与重置时间。"], "api-keys": ["11", "API Key 管理", "给每个调用方独立的访问密钥。"], }; +const pageMeta = (page) => [ + pages[page][0], + t(pages[page][1], `page.${page}.title`), + t(pages[page][2], `page.${page}.sub`), +]; +function renderPageHeader(page) { + const meta = pageMeta(page); + $("#page-index").textContent = t("Section {0}", "page.section", meta[0]); + $("#page-title").textContent = meta[1]; + $("#page-sub").textContent = meta[2]; +} async function api(path, options = {}) { options.headers = { ...(options.headers || {}), Accept: "application/json" }; if (options.body) options.headers["Content-Type"] = "application/json"; @@ -34,7 +49,7 @@ async function api(path, options = {}) { const response = await fetch(path, options); if (response.status === 401) { showLogin(); - throw new Error("登录已失效"); + throw new Error(t("登录已失效", "error.session")); } if (response.status === 204) return null; const data = await response.json().catch(() => ({})); @@ -108,10 +123,7 @@ function openPage(page) { 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]; + renderPageHeader(page); if (page === "access") renderAccessExamples(); if (page === "usage") renderUsage(); if (page === "model-quotas") { @@ -165,9 +177,18 @@ function fillConfig(value) { $("#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); + renderRestartNotice(value); +} +function renderRestartNotice(value) { 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.textContent = t( + `已保存但尚未生效:${value.restart_required_fields.join(", ")}。当前 API ${value.effective.listen}、WebUI ${value.effective.webui_listen}。请重启进程。`, + "config.restartNotice", + value.restart_required_fields.join(", "), + value.effective.listen, + value.effective.webui_listen, + ); notice.classList.remove("hidden"); } else notice.classList.add("hidden"); } @@ -182,7 +203,7 @@ function renderChips(name) { chip.dataset.id = item.id; text.textContent = item.display; remove.type = "button"; - remove.title = "移除"; + remove.title = t("移除", "common.remove"); remove.textContent = "×"; remove.onclick = () => chip.remove(); chip.append(text, remove); @@ -253,8 +274,12 @@ $("#config-form").addEventListener("submit", async (event) => { await loadDebugModels(); toast( result.result.restart_required - ? `已应用;${result.result.restart_fields.join(", ")} 需重启` - : "配置已保存并立即应用", + ? t( + `已应用;${result.result.restart_fields.join(", ")} 需重启`, + "toast.config.restart", + result.result.restart_fields.join(", "), + ) + : t("配置已保存并立即应用", "toast.config.saved"), ); } catch (error) { toast(error.message, true); @@ -265,13 +290,17 @@ $("#reload-config").onclick = async () => { const result = await api("/api/config/reload", { method: "POST", body: "{}" }); await loadConfig(); await loadDebugModels(); - toast(result.restart_required ? "磁盘配置已重载,监听字段需重启" : "磁盘配置已重载"); + toast( + result.restart_required + ? t("磁盘配置已重载,监听字段需重启", "toast.config.reloadedRestart") + : t("磁盘配置已重载", "toast.config.reloaded"), + ); } catch (error) { toast(error.message, true); } }; $("#reveal").onclick = async () => { - const password = prompt("请再次输入管理密码"); + const password = prompt(t("请再次输入管理密码", "config.revealPrompt")); if (password === null) return; try { const values = await api("/api/config/reveal", { @@ -299,7 +328,7 @@ $("#account-form").addEventListener("submit", async (event) => { new_password: $("#a-new").value, }), }); - toast("账号已更新,请重新登录"); + toast(t("账号已更新,请重新登录", "toast.account.updated")); setTimeout(showLogin, 800); } catch (error) { toast(error.message, true); @@ -311,7 +340,7 @@ function appendCell(row, value, className = "") { if (className) cell.className = className; row.appendChild(cell); } -function emptyRow(host, columns, message = "暂无数据") { +function emptyRow(host, columns, message = t("暂无数据", "common.empty")) { const row = document.createElement("tr"), cell = document.createElement("td"); cell.colSpan = columns; @@ -326,10 +355,14 @@ function renderResources(resources) { (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 ? "开" : "关"}`, + proxy.healthy ? t("正常", "state.healthy") : t("不可用", "state.unavailable"), + `status ${proxy.healthy ? "ok" : "bad"}`, + ); + appendCell( + row, + `Z ${proxy.zen_keys} · G ${proxy.go_keys} · A ${proxy.anonymous ? t("开", "common.on") : t("关", "common.off")}`, ); proxies.appendChild(row); }); @@ -340,7 +373,7 @@ function renderResources(resources) { const row = document.createElement("tr"); appendCell(row, "anonymous"); appendCell(row, "zen"); - appendCell(row, "已启用", "status ok"); + appendCell(row, t("已启用", "state.enabled"), "status ok"); keys.appendChild(row); } (resources.keys || []).forEach((key) => { @@ -349,7 +382,7 @@ function renderResources(resources) { appendCell(row, key.tier); appendCell( row, - key.cooldown_until ? "冷却中" : "可用", + key.cooldown_until ? t("冷却中", "state.cooling") : t("可用", "state.available"), `status ${key.cooldown_until ? "warn" : "ok"}`, ); keys.appendChild(row); @@ -360,9 +393,9 @@ function renderBreakdowns(metrics) { const host = $("#breakdowns"); host.replaceChildren(); [ - ["端点", metrics.endpoints], - ["状态码", metrics.statuses], - ["模型", metrics.models], + [t("端点", "breakdown.endpoint"), metrics.endpoints], + [t("状态码", "breakdown.status"), metrics.statuses], + [t("模型", "breakdown.model"), metrics.models], ["Tier", metrics.tiers], ].forEach(([title, data]) => { const block = document.createElement("div"), @@ -380,7 +413,7 @@ function renderBreakdowns(metrics) { appendCell(row, value); body.appendChild(row); }); - if (!body.children.length) emptyRow(body, 2, "暂无请求"); + if (!body.children.length) emptyRow(body, 2, t("暂无请求", "breakdown.empty")); table.appendChild(body); block.append(heading, table); host.appendChild(block); @@ -391,23 +424,31 @@ function renderGuide() { const resources = monitorData.resources, models = resources.models || {}, modelDescription = models.stale - ? "目录来自" + (models.cache_source || "磁盘") + "快取,等待背景刷新。" - : "上游目录已完成首次刷新且有可暴露模型。"; + ? t("目录来自{0}快取,等待背景刷新。", "guide.models.cached", models.cache_source || "磁盘") + : t("上游目录已完成首次刷新且有可暴露模型。", "guide.models.ready"); const checks = [ - ["登录管理端", "当前 Session 已通过服务端验证。", true], - ["配置本地 Key", "客户端使用 Server Key 访问 Gateway。", (config.server_keys || []).length > 0], + [t("登录管理端", "guide.step.login"), t("当前 Session 已通过服务端验证。", "guide.step.login.desc"), true], [ - "选择上游通道", - "至少有 Zen / Go Key,或启用匿名通道。", + t("配置本地 Key", "guide.step.serverkey"), + t("客户端使用 Server Key 访问 Gateway。", "guide.step.serverkey.desc"), + (config.server_keys || []).length > 0, + ], + [ + t("选择上游通道", "guide.step.upstream"), + t("至少有 Zen / Go Key,或启用匿名通道。", "guide.step.upstream.desc"), (config.zen_keys || []).length + (config.go_keys || []).length > 0 || config.anonymous, ], [ - "检查 Proxy", - "至少一个代理节点健康。", + t("检查 Proxy", "guide.step.proxy"), + t("至少一个代理节点健康。", "guide.step.proxy.desc"), (resources.proxies || []).some((proxy) => proxy.healthy), ], - ["等待模型目录", modelDescription, models.exposed > 0 && !!models.updated_at], - ["复制接入示例", "进入接入手册,替换模型与 YOUR_API_KEY。", true], + [t("等待模型目录", "guide.step.models"), modelDescription, models.exposed > 0 && !!models.updated_at], + [ + t("复制接入示例", "guide.step.access"), + t("进入接入手册,替换模型与 YOUR_API_KEY。", "guide.step.access.desc"), + true, + ], ]; const host = $("#guide-steps"); host.replaceChildren(); @@ -420,7 +461,7 @@ function renderGuide() { heading.textContent = title; copy.textContent = description; state.className = `step-state ${done ? "ok" : "warn"}`; - state.textContent = done ? "✓ 已就绪" : "○ 待处理"; + state.textContent = done ? t("✓ 已就绪", "guide.done") : t("○ 待处理", "guide.todo"); node.append(heading, copy, state); host.appendChild(node); }); @@ -458,7 +499,7 @@ function renderUsage() { appendCell(row, formatTokens(value.total_tokens)); models.appendChild(row); }); - if (!models.children.length) emptyRow(models, 4, "尚无 Token 用量"); + if (!models.children.length) emptyRow(models, 4, t("尚无 Token 用量", "usage.empty.models")); const tiers = $("#usage-tiers"), tierEntries = Object.entries(usage.tiers || {}).sort( (a, b) => (b[1].total_tokens || 0) - (a[1].total_tokens || 0), @@ -485,7 +526,7 @@ function renderUsage() { if (!tierEntries.length) { const empty = document.createElement("div"); empty.className = "empty"; - empty.textContent = "尚无 Tier 用量"; + empty.textContent = t("尚无 Tier 用量", "usage.empty.tiers"); tiers.appendChild(empty); } } @@ -511,7 +552,7 @@ function renderPlayKeys() { select.replaceChildren(); const auto = document.createElement("option"); auto.value = "auto"; - auto.textContent = "自动路由(匿名 / Tier 回退 / Key 轮询)"; + auto.textContent = t("自动路由(匿名 / Tier 回退 / Key 轮询)", "playground.key.auto"); select.appendChild(auto); const keys = debugData?.keys || {}; [ @@ -526,7 +567,11 @@ function renderPlayKeys() { const option = document.createElement("option"); option.value = `${tier}:${item.id}`; const cooling = item.cooldown_until - ? ` · 冷却至 ${new Date(item.cooldown_until).toLocaleTimeString()}` + ? t( + ` · 冷却至 ${new Date(item.cooldown_until).toLocaleTimeString()}`, + "playground.key.cooling", + new Date(item.cooldown_until).toLocaleTimeString(), + ) : ""; option.textContent = `${tier.toUpperCase()} · ${item.display} · ${item.id}${cooling}`; group.appendChild(option); @@ -561,15 +606,16 @@ async function loadDebugModels() { } function playgroundTemplate() { const protocol = $("#play-protocol").value, - model = $("#play-model").value || "YOUR_MODEL"; - if (protocol === "responses") return { model, input: "用一句话说明这个模型的能力。" }; + model = $("#play-model").value || "YOUR_MODEL", + prompt = t("用一句话说明这个模型的能力。", "playground.samplePrompt"); + if (protocol === "responses") return { model, input: prompt }; if (protocol === "anthropic") return { model, max_tokens: 512, - messages: [{ role: "user", content: "用一句话说明这个模型的能力。" }], + messages: [{ role: "user", content: prompt }], }; - return { model, messages: [{ role: "user", content: "用一句话说明这个模型的能力。" }] }; + return { model, messages: [{ role: "user", content: prompt }] }; } function resetPlayTemplate() { $("#play-request").value = JSON.stringify(playgroundTemplate(), null, 2); @@ -589,41 +635,50 @@ 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: "请求未成功", + usable: t("Key 可用", "play.key.usable"), + rejected: t("Key 被拒绝", "play.key.rejected"), + rate_limited: t("Key 已被接受但受到限流", "play.key.rateLimited"), + upstream_error: t("上游异常,无法判定 Key", "play.key.upstreamError"), + transport_error: t("网络或代理异常,无法判定 Key", "play.key.transportError"), + unavailable: t("Key 或运行时不可用", "play.key.unavailable"), + request_error: t("请求未成功", "play.key.requestError"), }[result.key_test] || result.key_test : ""; $("#play-state").textContent = result.ok - ? `请求成功 · HTTP ${result.http_status}` - : `请求失败 · HTTP ${result.http_status}`; + ? t(`请求成功 · HTTP {0}`, "play.state.ok", result.http_status) + : t(`请求失败 · HTTP {0}`, "play.state.failed", 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"}` - : "未路由"; + : t("未路由", "play.route.none"); renderFacts("#play-facts", [ - ["HTTP 状态", result.http_status, result.ok ? "ok" : "bad"], - ["耗时", `${result.duration_ms} ms`], + [t("HTTP 状态", "play.httpStatus"), result.http_status, result.ok ? "ok" : "bad"], + [t("耗时", "common.duration"), `${result.duration_ms} ms`], ["Request ID", result.request_id || "—"], - ["测试模式", selected ? `指定 ${selected.tier.toUpperCase()} Key` : "自动路由"], - ["测试 Key", selected ? `${selected.display} · ${selected.id}` : "—"], [ - "Key 判断", - keyTest || "自动路由未单独判定", + t("测试模式", "play.mode"), + selected + ? t(`指定 ${selected.tier.toUpperCase()} Key`, "play.mode.selected", selected.tier.toUpperCase()) + : t("自动路由", "play.mode.auto"), + ], + [t("测试 Key", "play.testedKey"), selected ? `${selected.display} · ${selected.id}` : "—"], + [ + t("Key 判断", "play.keyVerdict"), + keyTest || t("自动路由未单独判定", "play.keyVerdict.none"), result.key_test === "usable" ? "ok" : result.key_test ? "bad" : "", ], - ["实际路由", routeLabel], - ["原生协议", route.native_protocol || "—"], + [t("实际路由", "play.actualRoute"), routeLabel], + [t("原生协议", "play.nativeProtocol"), route.native_protocol || "—"], [ - "匿名判断", - `${eligibility.allowed ? "允许" : "拒绝"} · ${eligibility.source || "—"}`, + t("匿名判断", "play.anonymousVerdict"), + t( + `${eligibility.allowed ? "允许" : "拒绝"} · ${eligibility.source || "—"}`, + eligibility.allowed ? "play.eligibility.allowed" : "play.eligibility.denied", + eligibility.source || "—", + ), eligibility.allowed ? "ok" : "warn", ], ]); @@ -636,7 +691,7 @@ $("#play-form").addEventListener("submit", async (event) => { try { request = JSON.parse($("#play-request").value); } catch (error) { - toast(`请求 JSON 无效:${error.message}`, true); + toast(t(`请求 JSON 无效:${error.message}`, "toast.play.invalidJson", error.message), true); return; } const keyValue = $("#play-key").value, @@ -650,7 +705,9 @@ $("#play-form").addEventListener("submit", async (event) => { }; $("#play-run").disabled = true; $("#play-state").textContent = - key.mode === "selected" ? "指定 Key 测试进行中…" : "Gateway 请求进行中…"; + key.mode === "selected" + ? t("指定 Key 测试进行中…", "play.state.testingKey") + : t("Gateway 请求进行中…", "play.state.running"); try { const result = await api("/api/debug/inference", { method: "POST", @@ -659,7 +716,7 @@ $("#play-form").addEventListener("submit", async (event) => { displayPlayground(result); } catch (error) { toast(error.message, true); - $("#play-state").textContent = "诊断入口请求失败"; + $("#play-state").textContent = t("诊断入口请求失败", "play.state.failedToCall"); } finally { $("#play-run").disabled = false; } @@ -667,9 +724,9 @@ $("#play-form").addEventListener("submit", async (event) => { $("#play-copy").onclick = async () => { try { await navigator.clipboard.writeText($("#play-output").textContent); - toast("原始响应已复制"); + toast(t("原始响应已复制", "toast.play.copied")); } catch (_) { - toast("浏览器不允许剪贴板访问", true); + toast(t("浏览器不允许剪贴板访问", "common.clipboard"), true); } }; function renderDiagnostics() { @@ -677,30 +734,52 @@ function renderDiagnostics() { 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"], + [t("就绪", "diag.ready"), metadata.ready ? t("是", "common.yes") : t("否", "common.no"), metadata.ready ? "ok" : "warn"], + [t("模型数", "diag.modelCount"), formatTokens(metadata.models)], + [ + t("更新时间", "diag.updatedAt"), + metadata.updated_at + ? new Date(metadata.updated_at).toLocaleString() + : t("尚未更新", "diag.notUpdated"), + ], + [ + t("是否过期", "diag.stale"), + metadata.stale ? t("是", "common.yes") : t("否", "common.no"), + metadata.stale ? "warn" : "ok", + ], + [ + t("下次刷新", "diag.nextRefresh"), + metadata.next_refresh + ? new Date(metadata.next_refresh).toLocaleString() + : "—", + ], + [ + t("最近错误", "diag.lastError"), + metadata.last_error || t("无", "common.none"), + 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 || "—"], [ - "路由", + t("结果", "diag.result"), + last.ok ? t("成功", "diag.ok") : t("失败", "diag.failed"), + last.ok ? "ok" : "bad", + ], + ["HTTP", last.http_status], + [t("耗时", "common.duration"), `${last.duration_ms} ms`], + ["Request ID", last.request_id || "—"], + [t("模型", "common.model"), last.route?.model || "—"], + [ + t("路由", "diag.route"), last.route?.tier ? `${last.route.tier} / ${last.route.anonymous ? "anonymous" : last.route.key_id || "key"}` - : "未路由", + : t("未路由", "play.route.none"), ], ] - : [["状态", "尚无 Playground 追踪"]], + : [[t("状态", "diag.state"), t("尚无 Playground 追踪", "diag.noTrace")]], ); renderDiagnosticModels(); const requests = $("#upstream-requests"); @@ -718,8 +797,8 @@ function renderDiagnostics() { appendCell(row, request.key_id || "—"); appendCell(row, request.attempts); const terminalResults = { - stream_error: "流式响应失败", - client_canceled: "客户端已取消", + stream_error: t("流式响应失败", "diag.streamError"), + client_canceled: t("客户端已取消", "diag.clientCanceled"), }; const result = terminalResults[request.outcome] ? `HTTP ${request.status} · ${terminalResults[request.outcome]}` @@ -728,7 +807,7 @@ function renderDiagnostics() { appendCell(row, `${request.duration_ms} ms`); requests.appendChild(row); }); - if (!requests.children.length) emptyRow(requests, 9, "尚无请求路由"); + if (!requests.children.length) emptyRow(requests, 9, t("尚无请求路由", "diag.noRequests")); const attempts = $("#upstream-attempts"); attempts.replaceChildren(); (monitorData?.upstream?.recent || []) @@ -746,7 +825,7 @@ function renderDiagnostics() { appendCell(row, `${attempt.duration_ms} ms`); attempts.appendChild(row); }); - if (!attempts.children.length) emptyRow(attempts, 8, "尚无上游尝试"); + if (!attempts.children.length) emptyRow(attempts, 8, t("尚无上游尝试", "diag.noAttempts")); } function renderDiagnosticModels() { const host = $("#diagnostic-models"); @@ -763,17 +842,21 @@ function renderDiagnosticModels() { plan = [...(item.anonymous ? ["anonymous"] : []), ...(item.key_tiers || [])]; appendCell(row, item.model); appendCell(row, `${item.native_protocol} · ${item.protocol_source}`); - appendCell( +appendCell( row, item.route_error || (plan.length ? plan.join(" → ") : "—"), item.route_error ? "bad" : "", ); - appendCell(row, eligibility.allowed ? "允许" : "拒绝", eligibility.allowed ? "ok" : "warn"); + appendCell( + row, + eligibility.allowed ? t("允许", "common.allowed") : t("拒绝", "common.denied"), + 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, "没有匹配模型"); + if (!host.children.length) emptyRow(host, 6, t("没有匹配模型", "diag.noMatch")); } $("#diagnostic-model-search").addEventListener("input", renderDiagnosticModels); async function refreshMonitor() { @@ -796,7 +879,7 @@ $("#refresh-now").onclick = async () => { await Promise.all([refreshMonitor(), loadConfig(), loadDebugModels()]); if (location.hash === "#model-quotas") await loadModelQuotas(); if (location.hash === "#api-keys") await loadAPIKeys(); - toast("状态已刷新"); + toast(t("状态已刷新", "toast.refreshed")); }; function derivedAPIBase() { if (!config) return `${location.protocol}//${location.hostname}:8080`; @@ -818,13 +901,13 @@ function codeCard(label, text) { title.textContent = label; copy.type = "button"; copy.className = "copy"; - copy.textContent = "复制"; + copy.textContent = t("复制", "common.copy"); copy.onclick = async () => { try { await navigator.clipboard.writeText(text); - toast("示例已复制"); + toast(t("示例已复制", "toast.example.copied")); } catch (_) { - toast("浏览器不允许剪贴板访问", true); + toast(t("浏览器不允许剪贴板访问", "common.clipboard"), true); } }; head.append(title, copy); @@ -878,7 +961,7 @@ function connectLogs() { }); } }); - eventSource.addEventListener("gap", () => toast("较早日志已从内存清除", true)); + eventSource.addEventListener("gap", () => toast(t("较早日志已从内存清除", "logs.gap"), true)); } function renderLogs() { const level = $("#log-level").value, @@ -924,7 +1007,7 @@ function renderLogs() { if (!rows.length) { const empty = document.createElement("div"); empty.className = "empty"; - empty.textContent = "等待日志事件…"; + empty.textContent = t("等待日志事件…", "logs.waiting"); host.appendChild(empty); } host.scrollTop = host.scrollHeight; @@ -934,16 +1017,19 @@ function renderLogs() { ); $("#log-pause").onclick = () => { paused = !paused; - $("#log-pause").textContent = paused ? "继续" : "暂停"; + $("#log-pause").textContent = paused ? t("继续", "logs.resume") : t("暂停", "logs.pause"); if (!paused) renderLogs(); }; let quotaData = null, quotaTimer = null, quotaLoading = false, createdKey = "", - apiKeysLoading = false; + apiKeysLoading = false, + apiKeysData = null; const localTime = (value) => - value ? new Date(value).toLocaleString("zh-CN", { hour12: false }) : "—"; + value + ? new Date(value).toLocaleString(window.O2I18N.dateLocale(), { hour12: false }) + : "—"; function clearCreatedKey() { createdKey = ""; @@ -954,9 +1040,9 @@ function clearCreatedKey() { async function copyText(text) { try { await navigator.clipboard.writeText(text); - toast("已复制"); + toast(t("已复制", "toast.copied")); } catch { - toast("浏览器未允许复制,请手动选中复制", true); + toast(t("浏览器未允许复制,请手动选中复制", "toast.copyDenied"), true); } } @@ -964,7 +1050,7 @@ async function loadModelQuotas() { if (quotaLoading) return; quotaLoading = true; $("#quota-refresh").disabled = true; - $("#quota-refresh").textContent = "读取中…"; + $("#quota-refresh").textContent = t("读取中…", "quotas.loading"); try { const value = await api("/api/model-quotas"); if (!csrf) return; @@ -979,14 +1065,19 @@ async function loadModelQuotas() { select.appendChild(option); } if ([...select.options].some((option) => option.value === selected)) select.value = selected; - if (!select.options.length) select.appendChild(new Option("尚未配置 Go Key", "")); + if (!select.options.length) + select.appendChild(new Option(t("尚未配置 Go Key", "quotas.noKey"), "")); renderModelQuotas(); } catch (error) { - $("#quota-status").textContent = `查询失败:${error.message}。已有显示仅为上次查询结果。`; + $("#quota-status").textContent = t( + `查询失败:${error.message}。已有显示仅为上次查询结果。`, + "quotas.queryFailed", + error.message, + ); } finally { quotaLoading = false; $("#quota-refresh").disabled = false; - $("#quota-refresh").textContent = "刷新额度"; + $("#quota-refresh").textContent = t("刷新额度", "quotas.refresh"); } } @@ -997,17 +1088,23 @@ function renderModelQuotas() { const cards = $("#quota-cards"); cards.replaceChildren(); $("#quota-status").textContent = !account - ? "请先在配置中心添加 OpenCode Go Key。" + ? t("请先在配置中心添加 OpenCode Go Key。", "quotas.addKeyFirst") : account.error - ? `${account.error}${stale ? ";下方显示上次成功数据,当前额度未知。" : ";当前额度未知。"}` - : "已连接 OpenCode · 共享套餐额度。多个 Key 的额度不相加。"; + ? stale + ? t("{0};下方显示上次成功数据,当前额度未知。", "quotas.staleError", account.error) + : t("{0};当前额度未知。", "quotas.error", account.error) + : t("已连接 OpenCode · 共享套餐额度。多个 Key 的额度不相加。", "quotas.connected"); $("#quota-updated").textContent = account?.fetched_at - ? `${stale ? "上次成功查询" : "额度更新时间"}:${localTime(account.fetched_at)} · 缓存 60 秒 · 来源:OpenCode Go /v1/usage` + ? t( + `${stale ? "上次成功查询" : "额度更新时间"}:${localTime(account.fetched_at)} · 缓存 60 秒 · 来源:OpenCode Go /v1/usage`, + stale ? "quotas.lastSuccess" : "quotas.updated", + localTime(account.fetched_at), + ) : ""; const windows = [ - ["rolling", "5 小时窗口"], - ["weekly", "每周窗口"], - ["monthly", "每月窗口"], + ["rolling", t("5 小时窗口", "quotas.window.hour")], + ["weekly", t("每周窗口", "quotas.window.week")], + ["monthly", t("每月窗口", "quotas.window.month")], ]; for (const [id, label] of windows) { const item = account?.windows?.[id]; @@ -1019,15 +1116,17 @@ function renderModelQuotas() { card.className = `quota-card${item?.remaining_percent < 20 ? " quota-low" : ""}`; heading.textContent = label; value.className = "quota-value"; - value.textContent = item ? `≈ ${item.remaining_percent}%` : "未知"; + value.textContent = item ? `≈ ${item.remaining_percent}%` : t("未知", "common.unknown"); progress.max = 100; if (item) progress.value = item.remaining_percent; else progress.value = 0; - progress.setAttribute("aria-label", `${label}剩余额度`); + progress.setAttribute("aria-label", t("{0}剩余额度", "quotas.window.aria", label)); reset.className = "quota-reset"; reset.textContent = item - ? `${stale ? "历史剩余" : "剩余"} · ${item.status === "rate-limited" ? "已限额 · " : ""}重置于 ${localTime(item.resets_at)}` - : "等待上游额度数据"; + ? `${stale ? t("历史剩余", "quotas.remainingHistory") : t("剩余", "quotas.remaining")} · ${ + item.status === "rate-limited" ? t("已限额 · ", "quotas.rateLimited") : "" + }${t("重置于 {0}", "quotas.resetsAt", localTime(item.resets_at))}` + : t("等待上游额度数据", "quotas.waiting"); card.append(heading, value, progress, reset); cards.appendChild(card); } @@ -1036,7 +1135,11 @@ function renderModelQuotas() { $("#quota-model-count").textContent = `${models.length} / ${quotaData.models.length}`; const catalog = quotaData.catalog; $("#quota-catalog-status").textContent = - `${catalog?.stale ? "模型目录暂未更新,显示缓存 · " : ""}目录更新时间:${localTime(catalog?.updated_at)}`; + `${catalog?.stale ? t("模型目录暂未更新,显示缓存 · ", "quotas.catalogStale") : ""}${t( + `目录更新时间:${localTime(catalog?.updated_at)}`, + "quotas.catalogUpdated", + localTime(catalog?.updated_at), + )}`; const host = $("#quota-models"); host.replaceChildren(); for (const model of models) { @@ -1049,19 +1152,28 @@ function renderModelQuotas() { ); for (const [id] of windows) { const item = account?.windows?.[id]; - appendCell(row, item ? `≈ ${item.remaining_percent}%${stale ? "(历史)" : ""}` : "未知"); + appendCell( + row, + item ? `≈ ${item.remaining_percent}%${stale ? t("(历史)", "quotas.history") : ""}` : t("未知", "common.unknown"), + ); } const cell = document.createElement("td"), button = document.createElement("button"); button.className = "ghost"; - button.textContent = "复制名称"; + button.textContent = t("复制名称", "quotas.copyName"); button.onclick = () => copyText(model.id); cell.appendChild(button); row.appendChild(cell); host.appendChild(row); } if (!models.length) - emptyRow(host, 6, quotaData.models.length ? "没有匹配的模型" : "模型目录尚未就绪,请稍后刷新"); + emptyRow( + host, + 6, + quotaData.models.length + ? t("没有匹配的模型", "diag.noMatch") + : t("模型目录尚未就绪,请稍后刷新", "quotas.catalogPending"), + ); } $("#quota-refresh").onclick = loadModelQuotas; $("#quota-account").onchange = renderModelQuotas; @@ -1073,9 +1185,12 @@ async function loadAPIKeys() { $("#api-key-refresh").disabled = true; try { const data = await api("/api/api-keys"); - if (csrf) renderAPIKeys(data.keys); + if (csrf) { + apiKeysData = data.keys; + renderAPIKeys(data.keys); + } } catch (error) { - $("#api-key-status").textContent = `读取失败:${error.message}`; + $("#api-key-status").textContent = t(`读取失败:${error.message}`, "apikeys.loadFailed", error.message); } finally { apiKeysLoading = false; $("#api-key-refresh").disabled = false; @@ -1090,9 +1205,10 @@ async function mutateAPIKey(id, method, body, button) { ...(body ? { body: JSON.stringify(body) } : {}), }); if (!csrf) return; + apiKeysData = data.keys; renderAPIKeys(data.keys); await loadConfig(); - toast("已保存并立即生效"); + toast(t("已保存并立即生效", "toast.apikeys.saved")); } catch (error) { toast(error.message, true); } finally { @@ -1101,38 +1217,58 @@ async function mutateAPIKey(id, method, body, button) { } function renderAPIKeys(keys) { - $("#api-key-count").textContent = `${keys.length} 个`; - $("#api-key-status").textContent = `${keys.filter((key) => key.enabled).length} 个已启用`; + $("#api-key-count").textContent = t(`${keys.length} 个`, "apikeys.count", keys.length); + $("#api-key-status").textContent = t( + `${keys.filter((key) => key.enabled).length} 个已启用`, + "apikeys.enabledCount", + keys.filter((key) => key.enabled).length, + ); const host = $("#api-key-list"); host.replaceChildren(); for (const key of keys) { const row = document.createElement("tr"); appendCell(row, key.name); appendCell(row, key.display, "mono"); - appendCell(row, key.enabled ? "已启用" : "已停用", key.enabled ? "status ok" : "status warn"); + appendCell( + row, + key.enabled ? t("已启用", "state.enabled") : t("已停用", "state.disabled"), + key.enabled ? "status ok" : "status warn", + ); const usage = key.usage || {}, - summary = (value = {}) => `${formatTokens(value.requests)} 次 · ${formatTokens(value.total_tokens)} tokens`; + summary = (value = {}) => + `${formatTokens(value.requests)} ${t("次", "apikeys.times")} · ${formatTokens(value.total_tokens)} tokens`; appendCell(row, `${summary(usage.last_hour)} / ${summary(usage.lifetime)}`); - appendCell(row, key.created_at ? localTime(key.created_at) : "已有配置"); + appendCell( + row, + key.created_at ? localTime(key.created_at) : t("已有配置", "apikeys.col.legacy"), + ); const cell = document.createElement("td"), actions = document.createElement("div"); actions.className = "key-actions"; for (const [label, action] of [ [ - "重命名", + t("重命名", "apikeys.rename"), (button) => { - const name = prompt("密钥名称", key.name); + const name = prompt(t("密钥名称", "apikeys.namePrompt"), key.name); if (name !== null) mutateAPIKey(key.id, "PATCH", { name }, button); }, ], [ - key.enabled ? "停用" : "启用", + key.enabled ? t("停用", "apikeys.disable") : t("启用", "apikeys.enable"), (button) => mutateAPIKey(key.id, "PATCH", { enabled: !key.enabled }, button), ], [ - "删除", + t("删除", "apikeys.delete"), (button) => { - if (confirm(`删除“${key.name}”后,使用它的应用将无法继续访问。确定删除?`)) + if ( + confirm( + t( + `删除“${key.name}”后,使用它的应用将无法继续访问。确定删除?`, + "apikeys.confirmDelete", + key.name, + ), + ) + ) mutateAPIKey(key.id, "DELETE", null, button); }, ], @@ -1147,7 +1283,7 @@ function renderAPIKeys(keys) { row.appendChild(cell); host.appendChild(row); } - if (!keys.length) emptyRow(host, 6, "暂无 API Key"); + if (!keys.length) emptyRow(host, 6, t("暂无 API Key", "apikeys.empty")); } $("#api-key-form").onsubmit = async (event) => { event.preventDefault(); @@ -1160,6 +1296,7 @@ $("#api-key-form").onsubmit = async (event) => { }); if (!csrf) return; createdKey = data.key; + apiKeysData = data.keys; const goModels = debugData?.models?.filter((item) => item.available_go) || []; const model = goModels.find((item) => item.model === "glm-5.3-flash")?.model || @@ -1171,7 +1308,7 @@ $("#api-key-form").onsubmit = async (event) => { $("#api-key-form").reset(); renderAPIKeys(data.keys); await loadConfig(); - toast("API Key 已创建"); + toast(t("API Key 已创建", "toast.apikeys.created")); } catch (error) { toast(error.message, true); } finally { @@ -1185,16 +1322,16 @@ $("#api-key-copy-env").onclick = () => copyText($("#api-key-env").textContent); let rotationData = null, rotationDirty = false; const rotationReasons = { - success: "成功", - client_canceled: "调用方取消", - quota_or_rate_limit: "额度不足 / 限流", - transport_error: "连接错误", - first_output_timeout: "首个输出超时", - stream_error: "输出中断", - response_read_error: "读取响应失败", - response_conversion_error: "响应解析或转换失败", - request_conversion_error: "请求转换失败", - upstream_error: "上游错误", + success: t("成功", "rotation.reason.success"), + client_canceled: t("调用方取消", "rotation.reason.clientCanceled"), + quota_or_rate_limit: t("额度不足 / 限流", "rotation.reason.quota"), + transport_error: t("连接错误", "rotation.reason.transport"), + first_output_timeout: t("首个输出超时", "rotation.reason.firstOutputTimeout"), + stream_error: t("输出中断", "rotation.reason.streamError"), + response_read_error: t("读取响应失败", "rotation.reason.readError"), + response_conversion_error: t("响应解析或转换失败", "rotation.reason.conversionError"), + request_conversion_error: t("请求转换失败", "rotation.reason.requestConversion"), + upstream_error: t("上游错误", "rotation.reason.upstreamError"), }; async function loadRotation() { try { @@ -1210,7 +1347,8 @@ async function loadRotation() { function renderRotation() { const state = rotationData; $("#rotation-status").textContent = - state.persistence_error || "状态已更新 · 两组独立轮转,所有调用方共享当前位置。"; + state.persistence_error || + t("状态已更新 · 两组独立轮转,所有调用方共享当前位置。", "rotation.status"); $("#rotation-timeout").value = state.first_output_seconds; const host = $("#rotation-groups"); host.replaceChildren(); @@ -1218,9 +1356,9 @@ function renderRotation() { const section = document.createElement("div"); section.className = "section"; const title = document.createElement("h2"); - title.textContent = group.id === "sota" ? "SOTA" : "甜点"; + title.textContent = group.id === "sota" ? "SOTA" : t("甜点", "rotation.sweet"); const label = document.createElement("label"); - label.textContent = "调用别名"; + label.textContent = t("调用别名", "rotation.aliasLabel"); label.htmlFor = `rotation-alias-${group.id}`; const input = document.createElement("input"); input.id = label.htmlFor; @@ -1236,11 +1374,20 @@ function renderRotation() { field.append(label, input); const current = document.createElement("p"); current.className = "mono"; - current.textContent = `当前模型:${group.current || "等待可用模型"}`; + current.textContent = t( + `当前模型:${group.current || "等待可用模型"}`, + "rotation.current", + group.current || t("等待可用模型", "rotation.waitingModel"), + ); const table = document.createElement("table"); table.className = "table"; const header = document.createElement("tr"); - for (const text of ["顺序", "模型", "状态 / 恢复时间", "操作"]) { + for (const text of [ + t("顺序", "rotation.col.order"), + t("模型", "common.model"), + t("状态 / 恢复时间", "rotation.col.state"), + t("操作", "common.action"), + ]) { const th = document.createElement("th"); th.textContent = text; header.append(th); @@ -1259,18 +1406,18 @@ function renderRotation() { appendCell( row, !group.available[model] - ? "已下架 / 暂不可用" + ? t("已下架 / 暂不可用", "rotation.unavailable") : paused - ? `暂停至 ${localTime(until)}` + ? t(`暂停至 ${localTime(until)}`, "rotation.pausedUntil", localTime(until)) : model === group.current - ? "当前使用" - : "可用", + ? t("当前使用", "rotation.inUse") + : t("可用", "state.available"), ); const actions = document.createElement("td"); actions.className = "rotation-actions"; for (const [text, delta] of [ - ["上移", -1], - ["下移", 1], + [t("上移", "rotation.moveUp"), -1], + [t("下移", "rotation.moveDown"), 1], ]) { const button = document.createElement("button"); button.type = "button"; @@ -1292,9 +1439,9 @@ function renderRotation() { const select = document.createElement("button"); select.type = "button"; select.className = "ghost"; - select.textContent = "设为当前"; + select.textContent = t("设为当前", "rotation.setCurrent"); select.disabled = !group.available[model]; - select.setAttribute("aria-label", `使用 ${model}`); + select.setAttribute("aria-label", t(`使用 ${model}`, "rotation.useModel", model)); select.onclick = async () => { select.disabled = true; try { @@ -1313,7 +1460,7 @@ function renderRotation() { } state.persistence_error = result.persistence_error; renderRotation(); - toast("当前模型已切换"); + toast(t("当前模型已切换", "toast.rotation.switched")); } catch (error) { select.disabled = false; toast(error.message, true); @@ -1323,14 +1470,14 @@ function renderRotation() { row.append(actions); tbody.append(row); }); - if (!group.order.length) emptyRow(tbody, 4, "等待 Go 模型目录"); + if (!group.order.length) emptyRow(tbody, 4, t("等待 Go 模型目录", "rotation.waitingCatalog")); const wrap = document.createElement("div"); wrap.className = "table-wrap"; wrap.append(table); const recent = document.createElement("div"); recent.className = "rotation-switches"; const caption = document.createElement("h3"); - caption.textContent = "最近切换"; + caption.textContent = t("最近切换", "rotation.recentSwitches"); recent.append(caption); for (const item of (group.switches || []).slice(-5).reverse()) { const line = document.createElement("p"); @@ -1339,7 +1486,7 @@ function renderRotation() { } if (!group.switches?.length) { const line = document.createElement("p"); - line.textContent = "尚无切换记录"; + line.textContent = t("尚无切换记录", "rotation.noSwitches"); recent.append(line); } section.append(title, field, current, wrap, recent); @@ -1360,11 +1507,12 @@ function renderRotation() { appendCell(row, value); attempts.append(row); } - if (!state.attempts?.length) emptyRow(attempts, 6, "调用分组别名后显示最近 100 次尝试"); + if (!state.attempts?.length) + emptyRow(attempts, 6, t("调用分组别名后显示最近 100 次尝试", "rotation.attemptsEmpty")); } $("#rotation-refresh").onclick = () => { if (rotationDirty) { - toast("有未保存的修改,请先保存后刷新", true); + toast(t("有未保存的修改,请先保存后刷新", "toast.rotation.dirty"), true); return; } loadRotation(); @@ -1384,7 +1532,7 @@ $("#rotation-form").onsubmit = async (event) => { rotationData = await api("/api/rotation", { method: "PUT", body: JSON.stringify(body) }); rotationDirty = false; renderRotation(); - toast("模型轮转配置已保存并生效"); + toast(t("模型轮转配置已保存并生效", "toast.rotation.saved")); } catch (error) { toast(error.message, true); } finally { @@ -1393,78 +1541,123 @@ $("#rotation-form").onsubmit = async (event) => { }; boot(); +let availabilityData = null; + async function loadAvailability() { try { - const data = await api("/api/models/availability"); - $("#availability-error").textContent = ""; - $("#availability-models").replaceChildren(); - for (const item of data.models) { - const row = document.createElement("tr"); - const date = (value) => - value && !value.startsWith("0001-") ? new Date(value).toLocaleString() : "待探测"; - for (const value of [ - item.model, - item.disabled ? "已禁用" : "已启用", - [item.channel, item.reason].filter(Boolean).join(" / ") || "待探测", - item.manual ? "手动" : "自动", - item.auto_effort?.effort - ? `${item.auto_effort.effort}(${date(item.effort_checked_at)})` - : "未验证", - date(item.checked_at), - item.manual ? "手动控制,不自动探测" : date(item.next_check), - ]) { - const cell = document.createElement("td"); - cell.textContent = value; - row.append(cell); - } - const cell = document.createElement("td"); - const button = document.createElement("button"); - button.textContent = "恢复启用"; - button.disabled = !item.disabled; - button.onclick = async () => { - button.disabled = true; - toggle.disabled = true; - try { - await api("/api/models/restore", { - method: "POST", - body: JSON.stringify({ model: item.model }), - }); - await loadAvailability(); - await loadDebugModels(); - } catch (error) { - $("#availability-error").textContent = error.message; - button.disabled = !item.disabled; - toggle.disabled = false; - } - }; - cell.append(button); - const toggle = document.createElement("button"); - toggle.className = "ghost"; - toggle.textContent = item.manual ? "切回自动" : "切为手动"; - toggle.onclick = async () => { - button.disabled = true; - toggle.disabled = true; - try { - await api("/api/models/manual", { - method: "POST", - body: JSON.stringify({ model: item.model, manual: !item.manual }), - }); - await loadAvailability(); - await loadDebugModels(); - } catch (error) { - $("#availability-error").textContent = error.message; - button.disabled = !item.disabled; - toggle.disabled = false; - } - }; - cell.append(toggle); - row.append(cell); - $("#availability-models").append(row); - } - if (!data.models.length) - $("#availability-error").textContent = "当前模型目录中没有符合免费资格的模型。"; + availabilityData = await api("/api/models/availability"); + renderAvailability(); } catch (error) { $("#availability-error").textContent = error.message; } } + +function renderAvailability() { + const data = availabilityData; + if (!data) return; + $("#availability-error").textContent = ""; + $("#availability-models").replaceChildren(); + for (const item of data.models) { + const row = document.createElement("tr"); + const date = (value) => + value && !value.startsWith("0001-") + ? new Date(value).toLocaleString() + : t("待探测", "availability.pending"); + for (const value of [ + item.model, + item.disabled ? t("已禁用", "state.disabled") : t("已启用", "state.enabled"), + [item.channel, item.reason].filter(Boolean).join(" / ") || t("待探测", "availability.pending"), + item.manual ? t("手动", "availability.manual") : t("自动", "availability.auto"), + item.auto_effort?.effort + ? `${item.auto_effort.effort}(${date(item.effort_checked_at)})` + : t("未验证", "availability.unverified"), + date(item.checked_at), + item.manual + ? t("手动控制,不自动探测", "availability.manualControl") + : date(item.next_check), + ]) { + const cell = document.createElement("td"); + cell.textContent = value; + row.append(cell); + } + const cell = document.createElement("td"); + const button = document.createElement("button"); + button.textContent = t("恢复启用", "availability.restore"); + button.disabled = !item.disabled; + button.onclick = async () => { + button.disabled = true; + toggle.disabled = true; + try { + await api("/api/models/restore", { + method: "POST", + body: JSON.stringify({ model: item.model }), + }); + await loadAvailability(); + await loadDebugModels(); + } catch (error) { + $("#availability-error").textContent = error.message; + button.disabled = !item.disabled; + toggle.disabled = false; + } + }; + cell.append(button); + const toggle = document.createElement("button"); + toggle.className = "ghost"; + toggle.textContent = item.manual + ? t("切回自动", "availability.switchAuto") + : t("切为手动", "availability.switchManual"); + toggle.onclick = async () => { + button.disabled = true; + toggle.disabled = true; + try { + await api("/api/models/manual", { + method: "POST", + body: JSON.stringify({ model: item.model, manual: !item.manual }), + }); + await loadAvailability(); + await loadDebugModels(); + } catch (error) { + $("#availability-error").textContent = error.message; + button.disabled = !item.disabled; + toggle.disabled = false; + } + }; + cell.append(toggle); + row.append(cell); + $("#availability-models").append(row); + } + if (!data.models.length) + $("#availability-error").textContent = t( + "当前模型目录中没有符合免费资格的模型。", + "availability.noneEligible", + ); +} $("#availability-refresh").onclick = loadAvailability; + +// Re-render the text produced by JavaScript after the interface language changes. +// Static markup is already handled by O2I18N.apply() through the data-i18n hooks. +window.O2I18N.onChange(() => { + const page = location.hash.slice(1) || "overview"; + if (pages[page]) renderPageHeader(page); + $("#log-pause").textContent = paused ? t("继续", "logs.resume") : t("暂停", "logs.pause"); + if (!$("#quota-refresh").disabled) $("#quota-refresh").textContent = t("刷新额度", "quotas.refresh"); + if (monitorData) { + renderResources(monitorData.resources); + renderBreakdowns(monitorData.metrics); + } + if (config) renderRestartNotice(config); + renderGuide(); + renderUsage(); + if (lastPlayground) displayPlayground(lastPlayground); + renderDiagnostics(); + renderLogs(); + renderAccessExamples(); + renderPlayKeys(); + if (quotaData) renderModelQuotas(); + if (apiKeysData) renderAPIKeys(apiKeysData); + if (rotationData) renderRotation(); + renderAvailability(); + // Chip removal buttons carry a tooltip; keep it without rebuilding the list, + // so pending unsaved removals survive a language switch. + $$(".chips .chip button").forEach((button) => (button.title = t("移除", "common.remove"))); +}); diff --git a/webui/embed.go b/webui/embed.go index bb5c618..c85dd50 100644 --- a/webui/embed.go +++ b/webui/embed.go @@ -7,5 +7,5 @@ import ( // Assets contains the static management interface served by the admin listener. // -//go:embed index.html app.js styles.css +//go:embed index.html app.js i18n.js styles.css var Assets embed.FS diff --git a/webui/i18n.js b/webui/i18n.js new file mode 100644 index 0000000..4a42bcd --- /dev/null +++ b/webui/i18n.js @@ -0,0 +1,1221 @@ +// Interface language handling for the management console. +// +// The console ships with Simplified Chinese as its original language. That copy +// stays in index.html and app.js and is used whenever the active locale has no +// entry in DICTIONARY, so switching languages never rewrites the originals. +// +// Usage from markup: +//

…original…

+// +// Usage from app.js: +// t("配置已保存", "toast.config.saved") +// t(`${n} 个`, "apikeys.count", n) +window.O2I18N = (() => { + const STORAGE_KEY = "opencode2api.ui.lang"; + const DEFAULT_LOCALE = "zh-CN"; + const SUPPORTED = ["zh-CN", "en", "vi"]; + const LABELS = { "zh-CN": "简体中文", en: "English", vi: "Tiếng Việt" }; + const DATE_LOCALES = { "zh-CN": "zh-CN", en: "en-US", vi: "vi-VN" }; + const listeners = []; + // Snapshot of the authored copy, so switching back restores it untouched. + const originals = new WeakMap(); + + // Inline vector flags. Unicode flag emoji degrades to letters on Windows and + // emoji assets would need an extra request, so every flag is drawn in a 60x30 + // viewBox and scaled by CSS. + const FLAG_ART = { + "zh-CN": + '' + + '', + vi: + '' + + '', + en: + '' + + '' + + '' + + '' + + '', + }; + + const flagIcon = (code) => + ``; + + const DICTIONARY = { + en: { + "doc.title": "opencode2api · Operations Handbook", + "lang.label": "Language", + "lang.menu": "Choose a language", + + "login.eyebrow": "Admin operations handbook / 2026", + "login.headline": "Bring protocols, routing, and runtime state onto one desk.", + "login.intro": + "A local control plane with no external frontend. Configure, verify, connect, then keep the Gateway easy to explain.", + "login.restricted": "Restricted console", + "login.title": "Admin sign-in", + "login.username": "Username", + "login.password": "Password", + "login.submit": "Enter the Operations Handbook", + + "sidebar.kicker": "Operations console", + "sidebar.title": "Operations Handbook", + "nav.overview": "Operations desk", + "nav.guide": "First run", + "nav.access": "Integration handbook", + "nav.usage": "Token usage", + "nav.playground": "Playground", + "nav.diagnostics": "Routing diagnostics", + "nav.config": "Configuration center", + "nav.logs": "Event log", + "nav.account": "Account security", + "nav.model-quotas": "Models and quotas", + "nav.api-keys": "API Key management", + "nav.rotation": "Model rotation", + "nav.availability": "Free model availability", + + "topbar.refresh": "Refresh now", + "topbar.logout": "Sign out", + + "page.availability.title": "Free model availability", + "page.availability.sub": "Probed hourly; user-controlled models are not affected.", + "page.rotation.title": "Model rotation", + "page.rotation.sub": "Shared current model, failover on error, and attempt history.", + "page.overview.title": "Operations desk", + "page.overview.sub": "The last hour, process totals, and current resources.", + "page.guide.title": "First run", + "page.guide.sub": "Six checkpoints from configuration to your first request.", + "page.access.title": "Integration handbook", + "page.access.sub": "Chat, Responses, Anthropic, and SDK examples.", + "page.usage.title": "Token usage", + "page.usage.sub": "Coverage, per-minute trend, model ranking, and Tier distribution.", + "page.playground.title": "Playground", + "page.playground.sub": "Three input protocols sharing real Gateway routing and diagnostics.", + "page.diagnostics.title": "Routing diagnostics", + "page.diagnostics.sub": "Metadata, model eligibility, and each upstream attempt.", + "page.config.title": "Configuration center", + "page.config.sub": "Validate, then save atomically and hot-apply the fields that can change.", + "page.logs.title": "Event log", + "page.logs.sub": "Structured SSE data from the in-process ring buffer.", + "page.account.title": "Account security", + "page.account.sub": "A successful update revokes every admin session.", + "page.model-quotas.title": "Models and quotas", + "page.model-quotas.sub": "Available models, remaining shared plan quota, and reset times.", + "page.api-keys.title": "API Key management", + "page.api-keys.sub": "A separate access key for each caller.", + + "availability.title": "Probe free models", + "availability.refresh": "Refresh status", + "availability.desc": + "Probes models whose metadata name contains free or whose price is 0 and that have not been excluded. The anonymous channel is tried first, and a Zen Key only after that; a model is disabled once it is genuinely broken and retried after 24 hours. Transient errors do not add extra disabled models: an enabled model is retried after 1 hour, and a disabled one keeps its old reason and is retried after 24 hours. When a model is re-enabled or switched to manual control it stays enabled and is no longer probed automatically; when it switches back to automatic, the next scheduler tick schedules the probe. System One uses its own dedicated 1+1 decision question set. With the effort set to auto, the highest probed and verified effort is shown.", + "availability.col.model": "Model", + "availability.col.state": "State", + "availability.col.channel": "Channel / result", + "availability.col.control": "Control", + "availability.col.effort": "Verified reasoning effort", + "availability.col.checked": "Last probe", + "availability.col.next": "Next probe", + "availability.col.action": "Action", + + "overview.requests": "Requests in the last hour", + "overview.success": "Success rate", + "overview.p95": "P95 latency", + "overview.active": "Active / streaming", + "overview.hour": "Last 60 minutes", + "overview.http2xx": "HTTP 2xx–3xx", + "overview.endToEnd": "End-to-end milliseconds", + "overview.concurrent": "Concurrent requests", + "overview.proxy.title": "Proxy nodes", + "overview.proxy.caption": "These are proxy nodes; they are not described as exit IPs.", + "overview.proxy.col.node": "Node", + "overview.proxy.col.health": "Health", + "overview.proxy.col.binding": "Binding", + "overview.keys.title": "Key pool", + "overview.keys.caption": "Only the last 5 characters of a key and its cooldown state are shown.", + "overview.keys.col.tail": "Key tail", + "overview.keys.col.tier": "Tier", + "overview.keys.col.state": "State", + "overview.distribution.title": "Request distribution", + "overview.distribution.caption": + "Aggregated over the last hour by endpoint, model, Tier, and status code.", + + "guide.title": "6-step deployment check", + "guide.caption": + "State is read from the current configuration and live resources; nothing is written to browser storage.", + "guide.step.login": "Sign in to the admin console", + "guide.step.login.desc": "The current session has been verified by the server.", + "guide.step.serverkey": "Configure a Server Key", + "guide.step.serverkey.desc": "Clients use the Server Key to reach the Gateway.", + "guide.step.upstream": "Pick an upstream channel", + "guide.step.upstream.desc": "At least one Zen / Go Key, or the anonymous channel enabled.", + "guide.step.proxy": "Check the proxies", + "guide.step.proxy.desc": "At least one proxy node is still healthy.", + "guide.step.models": "Wait for the model catalog", + "guide.step.access": "Copy an integration example", + "guide.step.access.desc": "Open the Integration handbook and replace the model and YOUR_API_KEY.", + "guide.done": "✓ Ready", + "guide.todo": "○ Needs work", + + "access.base": "Base address", + "access.protocols": "Three protocols", + "access.sdk": "SDK example", + "access.notes": "Integration notes", + "access.base.title": "Base address", + "access.base.caption": "The examples never contain a real Server Key.", + "access.base.label": "Derived API Base", + "access.model.label": "Example model", + "access.protocols.title": "Three protocol endpoints", + "access.sdk.title": "Python and JavaScript", + "access.notes.title": "Notes for integration", + "access.notes.auth": "OpenAI-compatible clients use Authorization: Bearer YOUR_API_KEY.", + "access.notes.anthropic": + "Anthropic clients can use x-api-key with the /v1/messages path.", + "access.notes.stream": + "Streaming requests keep the events of the original protocol; the Gateway converts when the protocols differ.", + "access.notes.listen": + "If the listener is bound to 0.0.0.0, the examples use the current browser's hostname.", + + "usage.coverage": "Usage coverage", + "usage.coverage.note": "Requests reporting token or reasoning usage", + "usage.total": "Total tokens", + "usage.cached": "Cached tokens", + "usage.cached.note": "Cache hits reported by the upstream", + "usage.reasoning": "Reasoning tokens", + "usage.reasoning.note": "Reasoning usage reported by the upstream", + "usage.trend.title": "Per-minute token trend", + "usage.trend.caption": "Last 60 minutes; hover to see input, output, and total.", + "usage.models.title": "Model ranking", + "usage.models.caption": "Sorted by total_tokens.", + "usage.models.col.model": "Model", + "usage.models.col.input": "Input", + "usage.models.col.output": "Output", + "usage.models.col.total": "Total", + "usage.tiers.title": "Tier distribution", + "usage.tiers.caption": "Where Zen / Go tokens are going.", + + "playground.title": "Three-protocol request bench", + "playground.caption": "The server forces non-streaming and routes through the real Gateway.", + "playground.protocol": "Input protocol", + "playground.model": "Model", + "playground.key": "Upstream Key", + "playground.key.auto": "Automatic routing (anonymous / Tier fallback / Key rotation)", + "playground.key.caption": + "When a specific key is chosen, only that key is tried: no switch to another key, another Tier, or the anonymous channel, and no change to the key's cooldown state or the proxy's health.", + "playground.request": "Request JSON", + "playground.reset": "Reset sample", + "playground.run": "Send diagnostic request", + "playground.result.title": "Diagnostic result", + "playground.result.idle": "No request sent yet.", + "playground.output": "Raw protocol response", + + "diagnostics.metadata.title": "Model metadata", + "diagnostics.metadata.caption": + "Status of the OpenCode price cache from models.dev; a price of 0 or a name containing free is enough to qualify for the anonymous channel.", + "diagnostics.last.title": "Latest playground run", + "diagnostics.last.caption": + "Only the last run is retained in the current admin process.", + "diagnostics.models.title": "Model routing table", + "diagnostics.models.caption": + "Explicit protocol, anonymous eligibility source, and how cost is determined.", + "diagnostics.models.filter": "Filter models", + "diagnostics.models.col.model": "Model", + "diagnostics.models.col.protocol": "Native protocol", + "diagnostics.models.col.route": "Route", + "diagnostics.models.col.eligibility": "Anonymous eligibility", + "diagnostics.models.col.source": "Evaluation source", + "diagnostics.models.col.cost": "Input / output cost", + "diagnostics.requests.title": "Request routing", + "diagnostics.requests.caption": + "The key tail or anonymous channel actually used per request; only the 100 most recent records are shown.", + "diagnostics.attempts.title": "Upstream attempts", + "diagnostics.attempts.caption": + "Key tail, anonymous channel, and proxy node are masked; only the 100 most recent records are shown.", + "diagnostics.col.time": "Time", + "diagnostics.col.model": "Model", + "diagnostics.col.tier": "Tier", + "diagnostics.col.channel": "Channel", + "diagnostics.col.tail": "Key tail", + "diagnostics.col.attempts": "Attempts", + "diagnostics.col.state": "State", + "diagnostics.col.duration": "Duration", + "diagnostics.col.proxy": "Proxy node", + + "config.server.title": "Server and admin console", + "config.server.caption": "Listen addresses require a restart after saving.", + "config.server.prefer": "Preferred Tier for authentication keys", + "config.server.prefer.go": "Go (fall back to Zen on error)", + "config.server.prefer.zen": "Zen (fall back to Go on error)", + "config.server.session": "Session TTL (minutes)", + "config.server.enabled": "Enable WebUI (restart required after change)", + "config.secrets.title": "Secrets and anonymous channel", + "config.secrets.caption": + "Sensitive values are masked by default; a cleared value only takes effect after saving.", + "config.secrets.reveal": "Reveal after re-verification", + "config.secrets.anonymous": "Enable the Zen anonymous channel", + "config.secrets.add": "One key per line", + "config.proxy.title": "Proxy nodes", + "config.proxy.caption": "Supports direct, HTTP(S), and SOCKS URLs.", + "config.proxy.add": "Add proxies (one per line)", + "config.upstream.title": "Upstream and protocol routing", + "config.upstream.caption": + "anonymous will use every available proxy; an explicit protocol mapping wins over inferring the protocol from the model name.", + "config.upstream.freeOnly": "Only expose free models (even when Zen / Go Keys are configured)", + "config.upstream.attempts": "Max attempts per Key Tier", + "config.upstream.timeout": "Request timeout (seconds)", + "config.upstream.refresh": "Model refresh interval (seconds)", + "config.upstream.protocols": "Model protocol overrides (JSON)", + "config.reasoning.title": "Thinking effort", + "config.reasoning.caption": + "Applied only when the client does not specify an effort; per-model overrides take priority. Choosing “Off” removes reasoning for requests that do not ask for it.", + "config.reasoning.default": "Default effort", + "config.reasoning.follow": "Follow the client", + "config.reasoning.auto": "auto (probe the highest available effort)", + "config.reasoning.none": "Off", + "config.reasoning.byModel": "Per-model overrides (JSON)", + "config.reasoning.byModelNote": + "Values may be minimal, low, medium, high, xhigh, max, or none; an empty object means no overrides.", + "config.performance.title": "Performance and logging", + "config.performance.caption": "A hot reload still keeps the in-process accumulated totals.", + "config.performance.idleTimeout": "Idle timeout (seconds)", + "config.performance.connect": "Connect timeout (seconds)", + "config.performance.cooldown": "Failure cooldown (seconds)", + "config.performance.attemptTimeout": "Attempt timeout (seconds)", + "config.performance.attemptTimeoutHint": "0 = follow the request timeout", + "config.performance.firstEvent": "First SSE event timeout (seconds, 0 disables)", + "config.performance.level": "Log level", + "config.performance.ring": "Log ring size", + "config.performance.dump": + "Write outbound request dumps (masked, for tracing retries and conversions only)", + "config.reload": "Reload from disk", + "config.save": "Validate, save, and apply", + + "logs.level.all": "All levels", + "logs.component": "Module", + "logs.search": "Search events, Request ID, model", + "logs.pause": "Pause", + "logs.resume": "Resume", + "logs.gap": "Older logs were dropped from memory", + "logs.waiting": "Waiting for log events…", + + "quotas.title": "OpenCode Go plan quota", + "quotas.caption": + "Queried directly from OpenCode, cached for 60 seconds. All models share one plan window; percentages are rounded by the upstream.", + "quotas.refresh": "Refresh quota", + "quotas.loading": "Reading…", + "quotas.pending": "The quota will be read when this page opens.", + "quotas.catalog.title": "Available models", + "quotas.catalog.caption": + "Model names are used verbatim for OPENAI_MODEL. The quota column reflects the plan selected above, not a per-model quota.", + "quotas.catalog.search": "Search model names…", + "quotas.col.model": "Model name", + "quotas.col.protocol": "Upstream protocol", + "quotas.col.hour": "5-hour remaining · shared", + "quotas.col.week": "Weekly remaining · shared", + "quotas.col.month": "Monthly remaining · shared", + "quotas.col.action": "Action", + + "rotation.title": "SOTA / sweet model rotation", + "rotation.caption": + "On success the current model is kept. When the quota runs out or an error occurs it moves in order, using OpenCode Go only.", + "rotation.refresh": "Refresh status", + "rotation.usage": + "Keep your existing Base URL and API Key and set OPENAI_MODEL to the alias below. Each model is retried up to 3 times on ordinary errors, and a single request tries at most 3 models; a quota-exhausted model is skipped immediately.", + "rotation.streaming": + "Once output has started, the current answer stays on one model. A mid-stream error ends that output, and only the next request switches models. Models share the plan quota, so switching models does not guarantee escaping a quota exhaustion.", + "rotation.timeout": "Maximum wait for the first valid output (seconds)", + "rotation.save": "Save aliases and order", + "rotation.saveNote": + "Saving takes effect immediately; reordering never cuts off an answer that is already streaming. Manually selecting the current model takes effect immediately and clears that model's paused state.", + "rotation.attempts.title": "Recent attempts", + "rotation.col.time": "Time", + "rotation.col.request": "Request", + "rotation.col.alias": "Alias", + "rotation.col.model": "Actual model", + "rotation.col.attempt": "Attempt", + "rotation.col.result": "Result", + + "apikeys.create.title": "Create an API Key for a caller", + "apikeys.create.caption": + "Used to reach the B service on this machine. Each application can have its own key; creating, enabling/disabling, and deleting all take effect immediately.", + "apikeys.create.name": "Name", + "apikeys.create.namePlaceholder": "e.g. my notes helper", + "apikeys.create.value": "Custom key value (optional)", + "apikeys.create.valuePlaceholder": + "Leave blank to generate one; a custom value must be 16–256 characters", + "apikeys.create.submit": "Create API Key", + "apikeys.created.title": "Key created", + "apikeys.created.caption": + "The full key is shown only once, right after creation. Save it into the caller's environment variable immediately.", + "apikeys.created.dismiss": "Saved, close", + "apikeys.created.copy": "Copy key", + "apikeys.created.copyEnv": "Copy environment variable", + "apikeys.list.title": "Access keys", + "apikeys.list.caption": + "Manage access to the B service. OpenCode Go upstream keys stay in the Configuration center.", + "apikeys.list.refresh": "Refresh list", + "apikeys.col.name": "Name", + "apikeys.col.tail": "Key tail", + "apikeys.col.state": "State", + "apikeys.col.usage": "Usage (last hour / total)", + "apikeys.col.created": "Created at", + "apikeys.col.action": "Action", + "apikeys.col.legacy": "Already in configuration", + "apikeys.note": + "Disabling and deleting makes new requests from the matching applications return 401. At least one enabled key must remain.", + + "account.title": "Update the admin account", + "account.caption": "On success every session is revoked and you must sign in again.", + "account.user": "New username (blank to keep the current one)", + "account.current": "Current password", + "account.new": "New password (blank to keep the current one, at least 10 characters)", + "account.submit": "Update and sign in again", + + "modal.eyebrow": "Sensitive value", + "modal.title": "Sensitive configuration", + "modal.close": "Close", + + "common.copy": "Copy", + "common.clipboard": "The browser does not allow clipboard access", + "common.empty": "No data yet", + "common.remove": "Remove", + "common.duration": "Duration", + "common.model": "Model", + "common.action": "Action", + "common.yes": "Yes", + "common.no": "No", + "common.none": "None", + "common.on": "On", + "common.off": "Off", + "common.allowed": "Allowed", + "common.denied": "Denied", + "common.unknown": "Unknown", + "page.section": "Section {0}", + + "error.session": "Your session has expired", + + "state.healthy": "Healthy", + "state.unavailable": "Unavailable", + "state.enabled": "Enabled", + "state.disabled": "Disabled", + "state.cooling": "Cooling down", + "state.available": "Ready", + + "breakdown.endpoint": "Endpoint", + "breakdown.status": "Status code", + "breakdown.model": "Model", + "breakdown.empty": "No requests yet", + + "guide.models.cached": "Catalog from the {0} cache, waiting for a background refresh.", + "guide.models.ready": "The upstream catalog has passed its first refresh and has models to serve.", + + "usage.empty.models": "No token usage yet", + "usage.empty.tiers": "No per-Tier usage yet", + + "playground.key.cooling": " · cooling down until {0}", + "playground.samplePrompt": "Explain what this model can do in one sentence.", + "play.httpStatus": "HTTP", + "play.mode": "Test mode", + "play.mode.selected": "Specified {0} key", + "play.mode.auto": "Automatic routing", + "play.testedKey": "Key tested", + "play.keyVerdict": "Key verdict", + "play.keyVerdict.none": "Automatic routing has no dedicated verdict", + "play.key.usable": "Key usable", + "play.key.rejected": "Key rejected", + "play.key.rateLimited": "Key accepted but rate limited", + "play.key.upstreamError": "Upstream anomaly, no verdict on the key", + "play.key.transportError": "Network or proxy anomaly, no verdict on the key", + "play.key.unavailable": "Key or runtime unavailable", + "play.key.requestError": "Request did not succeed", + "play.actualRoute": "Actual route", + "play.nativeProtocol": "Native protocol", + "play.anonymousVerdict": "Anonymous verdict", + "play.eligibility.allowed": "Allowed · {0}", + "play.eligibility.denied": "Denied · {0}", + "play.route.none": "Not routed", + "play.state.ok": "Request succeeded · HTTP {0}", + "play.state.failed": "Request failed · HTTP {0}", + "play.state.testingKey": "Testing with the specified key…", + "play.state.running": "Sending the request through the Gateway…", + "play.state.failedToCall": "Could not reach the diagnostics endpoint", + + "diag.ready": "Ready", + "diag.modelCount": "Models", + "diag.updatedAt": "Updated at", + "diag.nextRefresh": "Next refresh", + "diag.stale": "Stale", + "diag.lastError": "Last error", + "diag.notUpdated": "Not updated", + "diag.result": "Result", + "diag.ok": "Success", + "diag.failed": "Failed", + "diag.route": "Route", + "diag.state": "State", + "diag.noTrace": "No playground trace data", + "diag.streamError": "Streaming failed", + "diag.clientCanceled": "Client canceled", + "diag.noRequests": "No requests have been routed", + "diag.noAttempts": "No upstream attempts", + "diag.noMatch": "No matching models", + + "quotas.noKey": "No Go Key configured", + "quotas.addKeyFirst": "Add an OpenCode Go Key in the Configuration center first.", + "quotas.queryFailed": "Query failed: {0}. The content shown is only the previous query result.", + "quotas.connected": "Connected to OpenCode · shared plan quota. Quotas of several keys do not add up.", + "quotas.error": "{0}; the quota is currently unknown.", + "quotas.staleError": "{0}; the most recent successful readings are shown below and the quota is currently unknown.", + "quotas.updated": "Quota updated at: {0} · 60s cache · source: OpenCode Go /v1/usage", + "quotas.lastSuccess": "Last successful query: {0} · 60s cache · source: OpenCode Go /v1/usage", + "quotas.window.hour": "5-hour window", + "quotas.window.week": "Weekly window", + "quotas.window.month": "Monthly window", + "quotas.window.aria": "Remaining quota for {0}", + "quotas.remaining": "remaining", + "quotas.remainingHistory": "remaining (history)", + "quotas.rateLimited": "cap reached · ", + "quotas.resetsAt": "resets at {0}", + "quotas.waiting": "Waiting for quota data from the upstream", + "quotas.catalogStale": "The model catalog is not up to date, showing the cache · ", + "quotas.catalogUpdated": "Catalog updated at: {0}", + "quotas.history": " (history)", + "quotas.copyName": "Copy name", + "quotas.catalogPending": "The model catalog is not ready yet; please refresh later.", + + "apikeys.loadFailed": "Read failed: {0}", + "apikeys.count": "{0} keys", + "apikeys.enabledCount": "{0} keys enabled", + "apikeys.times": "times", + "apikeys.rename": "Rename", + "apikeys.namePrompt": "Key name", + "apikeys.enable": "Enable", + "apikeys.disable": "Disable", + "apikeys.delete": "Delete", + "apikeys.confirmDelete": + "After deleting “{0}”, applications using this key will lose access. Delete it for real?", + "apikeys.empty": "No API Keys yet", + + "rotation.status": + "Status updated · the two rotation groups are independent and every caller shares the current position.", + "rotation.sweet": "sweet", + "rotation.aliasLabel": "Call alias", + "rotation.current": "Current model: {0}", + "rotation.waitingModel": "waiting for an available model", + "rotation.col.order": "Order", + "rotation.col.state": "State / resume time", + "rotation.unavailable": "Removed from the catalog / temporarily unavailable", + "rotation.pausedUntil": "Paused until {0}", + "rotation.inUse": "In use", + "rotation.moveUp": "Up", + "rotation.moveDown": "Down", + "rotation.setCurrent": "Set as current", + "rotation.useModel": "Use {0}", + "rotation.waitingCatalog": "Waiting for the Go model catalog", + "rotation.recentSwitches": "Recent switches", + "rotation.noSwitches": "No switch records yet", + "rotation.attemptsEmpty": "Call through a group alias to see the 100 most recent attempts", + "rotation.reason.success": "Succeeded", + "rotation.reason.clientCanceled": "Caller canceled", + "rotation.reason.quota": "Quota exhausted / rate limited", + "rotation.reason.transport": "Connection error", + "rotation.reason.firstOutputTimeout": "First output timeout", + "rotation.reason.streamError": "Output interrupted", + "rotation.reason.readError": "Failed to read the response", + "rotation.reason.conversionError": "Failed to parse or convert the response", + "rotation.reason.requestConversion": "Failed to convert the request", + "rotation.reason.upstreamError": "Upstream error", + + "availability.pending": "Awaiting probe", + "availability.manual": "Manual", + "availability.auto": "Automatic", + "availability.unverified": "Unverified", + "availability.manualControl": "Manual control, not probed automatically", + "availability.restore": "Re-enable", + "availability.switchAuto": "Switch back to automatic", + "availability.switchManual": "Switch to manual", + "availability.noneEligible": + "No model in the current catalog qualifies as free.", + + "config.restartNotice": + "Saved but not in effect yet: {0}. The current API is {1}, the WebUI is {2}. Please restart the process.", + "config.revealPrompt": "Re-enter the admin password", + + "toast.refreshed": "Status refreshed", + "toast.copied": "Copied", + "toast.copyDenied": "The browser denied the copy; select the text and copy it manually", + "toast.example.copied": "Example copied", + "toast.config.saved": "Configuration saved and already in effect", + "toast.config.restart": "Applied; restart required for {0}", + "toast.config.reloaded": "Configuration reloaded from disk", + "toast.config.reloadedRestart": + "Configuration reloaded from disk; listen fields require a restart", + "toast.account.updated": "Account updated, please sign in again", + "toast.play.invalidJson": "The request JSON is invalid: {0}", + "toast.play.copied": "Raw response copied", + "toast.apikeys.saved": "Saved and already in effect", + "toast.apikeys.created": "API Key created", + "toast.rotation.saved": "Model rotation configuration saved and in effect", + "toast.rotation.switched": "Current model switched", + "toast.rotation.dirty": "There are unsaved changes; save before refreshing", + }, + + vi: { + "doc.title": "opencode2api · Sổ tay vận hành", + "lang.label": "Ngôn ngữ", + "lang.menu": "Chọn ngôn ngữ", + + "login.eyebrow": "Sổ tay vận hành dành cho quản trị / 2026", + "login.headline": "Đưa giao thức, định tuyến và trạng thái vận hành lên cùng một bàn.", + "login.intro": + "Một bảng điều khiển cục bộ, không phụ thuộc frontend bên ngoài. Cấu hình, kiểm tra, kết nối, rồi để Gateway luôn dễ giải thích.", + "login.restricted": "Bảng điều khiển hạn chế", + "login.title": "Đăng nhập quản trị", + "login.username": "Tài khoản", + "login.password": "Mật khẩu", + "login.submit": "Vào Sổ tay vận hành", + + "sidebar.kicker": "Bảng điều khiển vận hành", + "sidebar.title": "Sổ tay vận hành", + "nav.overview": "Bàn vận hành", + "nav.guide": "Khởi động lần đầu", + "nav.access": "Sổ tay tích hợp", + "nav.usage": "Mức dùng token", + "nav.playground": "Playground", + "nav.diagnostics": "Chẩn đoán định tuyến", + "nav.config": "Trung tâm cấu hình", + "nav.logs": "Nhật ký sự kiện", + "nav.account": "Bảo mật tài khoản", + "nav.model-quotas": "Mô hình và hạn mức", + "nav.api-keys": "Quản lý API Key", + "nav.rotation": "Luân chuyển mô hình", + "nav.availability": "Mô hình miễn phí", + + "topbar.refresh": "Làm mới ngay", + "topbar.logout": "Đăng xuất", + + "page.availability.title": "Mô hình miễn phí", + "page.availability.sub": "Dò mỗi giờ; mô hình do người dùng điều khiển không bị ảnh hưởng.", + "page.rotation.title": "Luân chuyển mô hình", + "page.rotation.sub": "Mô hình hiện tại, chuyển đổi khi lỗi và lịch sử thử.", + "page.overview.title": "Bàn vận hành", + "page.overview.sub": "Một giờ gần nhất, số liệu tích lũy của tiến trình và tài nguyên hiện tại.", + "page.guide.title": "Khởi động lần đầu", + "page.guide.sub": "Sáu điểm kiểm tra để đi từ cấu hình đến request đầu tiên.", + "page.access.title": "Sổ tay tích hợp", + "page.access.sub": "Ví dụ Chat, Responses, Anthropic và SDK.", + "page.usage.title": "Mức dùng token", + "page.usage.sub": "Độ phủ, xu hướng mỗi phút, xếp hạng mô hình và phân bố Tier.", + "page.playground.title": "Playground", + "page.playground.sub": "Ba giao thức đầu vào dùng chung định tuyến Gateway thật và chẩn đoán.", + "page.diagnostics.title": "Chẩn đoán định tuyến", + "page.diagnostics.sub": "Metadata, điều kiện mô hình và từng lần thử upstream.", + "page.config.title": "Trung tâm cấu hình", + "page.config.sub": "Kiểm tra rồi lưu nguyên tử, áp dụng nóng các trường có thể thay đổi.", + "page.logs.title": "Nhật ký sự kiện", + "page.logs.sub": "Dữ liệu SSE có cấu trúc từ ring buffer trong bộ nhớ tiến trình.", + "page.account.title": "Bảo mật tài khoản", + "page.account.sub": "Cập nhật xong sẽ thu hồi toàn bộ session quản trị.", + "page.model-quotas.title": "Mô hình và hạn mức", + "page.model-quotas.sub": "Mô hình khả dụng, hạn mức gói dùng chung và thời điểm reset.", + "page.api-keys.title": "Quản lý API Key", + "page.api-keys.sub": "Khóa truy cập riêng cho từng bên gọi.", + + "availability.title": "Dò mô hình miễn phí", + "availability.refresh": "Làm mới trạng thái", + "availability.desc": + "Kiểm tra các mô hình có tên chứa free hoặc giá bằng 0 trong metadata và chưa bị loại bỏ. Ưu tiên kênh ẩn danh, sau đó mới thử Zen Key; chỉ vô hiệu hóa khi mô hình hẳn đã hỏng và thử lại sau 24 giờ. Lỗi tạm thời không tạo thêm mô hình bị vô hiệu hóa: mô hình đang bật thử lại sau 1 giờ, mô hình đã tắt giữ nguyên lý do cũ và thử lại sau 24 giờ. Khi khôi phục bật hoặc chuyển sang điều khiển thủ công, mô hình giữ nguyên bật và không còn được dò tự động; khi chuyển lại tự động, lượt định tuyến kế tiếp sẽ sắp xếp lần dò. System One dùng bộ câu hỏi quyết định riêng 1+1. Khi đặt cường độ auto, hiển thị bậc cao nhất đã được dò xác minh.", + "availability.col.model": "Mô hình", + "availability.col.state": "Trạng thái", + "availability.col.channel": "Kênh / Kết quả", + "availability.col.control": "Điều khiển", + "availability.col.effort": "Bậc suy luận đã xác minh", + "availability.col.checked": "Lần dò gần nhất", + "availability.col.next": "Lần dò kế tiếp", + "availability.col.action": "Thao tác", + + "overview.requests": "Yêu cầu 1 giờ qua", + "overview.success": "Tỷ lệ thành công", + "overview.p95": "Độ trễ P95", + "overview.active": "Đang chạy / luồng", + "overview.hour": "60 phút gần nhất", + "overview.http2xx": "HTTP 2xx–3xx", + "overview.endToEnd": "Mili giây đầu–cuối", + "overview.concurrent": "Số request đồng thời", + "overview.proxy.title": "Nút Proxy", + "overview.proxy.caption": "Ở đây hiển thị các nút proxy, không mô tả chúng là IP đầu ra.", + "overview.proxy.col.node": "Nút", + "overview.proxy.col.health": "Sức khoẻ", + "overview.proxy.col.binding": "Ràng buộc", + "overview.keys.title": "Nhóm Key", + "overview.keys.caption": "Chỉ hiển thị 5 ký tự cuối của Key và trạng thái cooldown.", + "overview.keys.col.tail": "Đuôi Key", + "overview.keys.col.tier": "Tier", + "overview.keys.col.state": "Trạng thái", + "overview.distribution.title": "Phân bố yêu cầu", + "overview.distribution.caption": + "Tổng hợp 1 giờ gần nhất theo endpoint, mô hình, Tier và mã trạng thái.", + + "guide.title": "Kiểm tra 6 bước để triển khai", + "guide.caption": + "Trạng thái lấy từ cấu hình hiện tại và tài nguyên thời gian thực, không ghi vào bộ nhớ trình duyệt.", + "guide.step.login": "Đăng nhập bảng quản trị", + "guide.step.login.desc": "Session hiện tại đã được máy chủ xác minh.", + "guide.step.serverkey": "Cấu hình Key cục bộ", + "guide.step.serverkey.desc": "Client dùng Server Key để truy cập Gateway.", + "guide.step.upstream": "Chọn kênh upstream", + "guide.step.upstream.desc": "Có ít nhất một Zen / Go Key, hoặc đã bật kênh ẩn danh.", + "guide.step.proxy": "Kiểm tra Proxy", + "guide.step.proxy.desc": "Có ít nhất một nút proxy còn khỏe.", + "guide.step.models": "Chờ danh mục mô hình", + "guide.step.access": "Sao chép ví dụ tích hợp", + "guide.step.access.desc": "Vào Sổ tay tích hợp, thay mô hình và YOUR_API_KEY.", + "guide.done": "✓ Đã sẵn sàng", + "guide.todo": "○ Cần xử lý", + + "access.base": "Địa chỉ cơ sở", + "access.protocols": "Ba giao thức", + "access.sdk": "Ví dụ SDK", + "access.notes": "Lưu ý tích hợp", + "access.base.title": "Địa chỉ cơ sở", + "access.base.caption": "Ví dụ không ghi Server Key thật.", + "access.base.label": "API Base được suy ra", + "access.model.label": "Mô hình ví dụ", + "access.protocols.title": "Các cổng vào theo ba giao thức", + "access.sdk.title": "Python và JavaScript", + "access.notes.title": "Lưu ý khi tích hợp", + "access.notes.auth": "Client tương thích OpenAI dùng Authorization: Bearer YOUR_API_KEY.", + "access.notes.anthropic": + "Client Anthropic có thể dùng x-api-key, với đường dẫn /v1/messages.", + "access.notes.stream": + "Request streaming giữ nguyên sự kiện của giao thức gốc; khi khác giao thức, Gateway sẽ chuyển đổi.", + "access.notes.listen": + "Nếu cấu hình lắng nghe ở 0.0.0.0, ví dụ sẽ dùng tên máy chủ của trình duyệt hiện tại.", + + "usage.coverage": "Độ phủ sử dụng", + "usage.coverage.note": "Yêu cầu có token trả về / suy luận", + "usage.total": "Tổng token", + "usage.cached": "Token đã cache", + "usage.cached.note": "Cache hit do upstream báo", + "usage.reasoning": "Token suy luận", + "usage.reasoning.note": "Mức dùng suy luận do upstream báo", + "usage.trend.title": "Xu hướng token mỗi phút", + "usage.trend.caption": "60 phút gần nhất; di chuột để xem input, output và tổng.", + "usage.models.title": "Xếp hạng mô hình", + "usage.models.caption": "Sắp xếp theo total_tokens.", + "usage.models.col.model": "Mô hình", + "usage.models.col.input": "Input", + "usage.models.col.output": "Output", + "usage.models.col.total": "Tổng", + "usage.tiers.title": "Phân bố Tier", + "usage.tiers.caption": "Token của Zen / Go đi về đâu.", + + "playground.title": "Bàn gửi request ba giao thức", + "playground.caption": "Máy chủ ép buộc không streaming và định tuyến qua Gateway thật.", + "playground.protocol": "Giao thức đầu vào", + "playground.model": "Mô hình", + "playground.key": "Key upstream", + "playground.key.auto": "Định tuyến tự động (ẩn danh / dự phòng Tier / luân phiên Key)", + "playground.key.caption": + "Khi chọn một Key cụ thể, chỉ Key đó được thử: không chuyển sang Key khác, Tier khác hay kênh ẩn danh, và không làm thay đổi trạng thái cooldown của Key hay sức khoẻ của proxy.", + "playground.request": "JSON của request", + "playground.reset": "Đặt lại mẫu", + "playground.run": "Gửi request chẩn đoán", + "playground.result.title": "Kết quả chẩn đoán", + "playground.result.idle": "Chưa gửi request nào.", + "playground.output": "Phản hồi giao thức gốc", + + "diagnostics.metadata.title": "Metadata mô hình", + "diagnostics.metadata.caption": + "Trạng thái cache giá OpenCode từ models.dev; giá bằng 0 hoặc tên chứa free là đủ điều kiện vào kênh ẩn danh.", + "diagnostics.last.title": "Playground gần nhất", + "diagnostics.last.caption": + "Chỉ giữ lần theo dõi cuối cùng trong tiến trình quản trị hiện tại.", + "diagnostics.models.title": "Bảng định tuyến mô hình", + "diagnostics.models.caption": + "Giao thức tường minh, nguồn điều kiện ẩn danh và cách xác định chi phí.", + "diagnostics.models.filter": "Lọc mô hình", + "diagnostics.models.col.model": "Mô hình", + "diagnostics.models.col.protocol": "Giao thức gốc", + "diagnostics.models.col.route": "Định tuyến", + "diagnostics.models.col.eligibility": "Điều kiện ẩn danh", + "diagnostics.models.col.source": "Nguồn đánh giá", + "diagnostics.models.col.cost": "Chi phí input / output", + "diagnostics.requests.title": "Định tuyến request", + "diagnostics.requests.caption": + "Đuôi Key hoặc anonymous thực sự được dùng cho từng request; hiển thị tối đa 100 bản ghi gần nhất.", + "diagnostics.attempts.title": "Lần thử upstream", + "diagnostics.attempts.caption": + "Đuôi Key, kênh ẩn danh và nút proxy đã che; hiển thị tối đa 100 bản ghi gần nhất.", + "diagnostics.col.time": "Thời gian", + "diagnostics.col.model": "Mô hình", + "diagnostics.col.tier": "Tier", + "diagnostics.col.channel": "Kênh", + "diagnostics.col.tail": "Đuôi Key", + "diagnostics.col.attempts": "Lần thử", + "diagnostics.col.state": "Trạng thái", + "diagnostics.col.duration": "Thời gian", + "diagnostics.col.proxy": "Nút proxy", + + "config.server.title": "Máy chủ và bảng quản trị", + "config.server.caption": "Địa chỉ lắng nghe cần khởi động lại sau khi lưu.", + "config.server.prefer": "Tier ưu tiên cho Key xác thực", + "config.server.prefer.go": "Go (lỗi thì dự phòng Zen)", + "config.server.prefer.zen": "Zen (lỗi thì dự phòng Go)", + "config.server.session": "Session TTL (phút)", + "config.server.enabled": "Bật WebUI (cần khởi động lại khi thay đổi)", + "config.secrets.title": "Khóa và kênh ẩn danh", + "config.secrets.caption": + "Giá trị nhạy cảm mặc định chỉ hiện dạng che; chỉ lưu sau khi gỡ bỏ mới có hiệu lực.", + "config.secrets.reveal": "Xem sau khi xác minh lại", + "config.secrets.anonymous": "Bật kênh ẩn danh Zen", + "config.secrets.add": "Mỗi dòng thêm một key", + "config.proxy.title": "Nút Proxy", + "config.proxy.caption": "Hỗ trợ direct, HTTP(S) và URL SOCKS.", + "config.proxy.add": "Thêm Proxy (mỗi dòng một cái)", + "config.upstream.title": "Upstream và định tuyến giao thức", + "config.upstream.caption": + "anonymous sẽ dùng hết các Proxy khả dụng; ánh xạ protocol tường minh được ưu tiên hơn việc suy luận từ tên mô hình.", + "config.upstream.freeOnly": "Chỉ công khai mô hình miễn phí (kể cả khi đã cấu hình Zen / Go Key)", + "config.upstream.attempts": "Số lần thử tối đa cho mỗi Key Tier", + "config.upstream.timeout": "Timeout của request (giây)", + "config.upstream.refresh": "Làm mới mô hình (giây)", + "config.upstream.protocols": "Ghi đè giao thức mô hình (JSON)", + "config.reasoning.title": "Cường độ Thinking", + "config.reasoning.caption": + "Chỉ áp dụng khi client không chỉ định rõ; có thể ghi đè theo từng mô hình. Chọn “Tắt” sẽ bỏ reasoning cho các request không yêu cầu rõ.", + "config.reasoning.default": "Cường độ mặc định", + "config.reasoning.follow": "Theo client", + "config.reasoning.auto": "auto (dò mức cao nhất khả dụng)", + "config.reasoning.none": "Tắt", + "config.reasoning.byModel": "Ghi đè theo mô hình (JSON)", + "config.reasoning.byModelNote": + "Giá trị có thể là minimal, low, medium, high, xhigh, max hoặc none; đối tượng rỗng nghĩa là không ghi đè.", + "config.performance.title": "Hiệu năng và nhật ký", + "config.performance.caption": "Nạp lại nóng vẫn giữ số liệu tích lũy trong bộ nhớ tiến trình.", + "config.performance.idleTimeout": "Idle Timeout (giây)", + "config.performance.connect": "Connect Timeout (giây)", + "config.performance.cooldown": "Failure Cooldown (giây)", + "config.performance.attemptTimeout": "Attempt Timeout (giây)", + "config.performance.attemptTimeoutHint": "0 = theo timeout của request", + "config.performance.firstEvent": + "Timeout sự kiện SSE đầu tiên (giây, 0 để tắt)", + "config.performance.level": "Mức log", + "config.performance.ring": "Kích thước ring log", + "config.performance.dump": + "Ghi dump request đi ra (đã che, chỉ dùng để truy vết retry và chuyển đổi)", + "config.reload": "Nạp lại từ đĩa", + "config.save": "Kiểm tra, lưu và áp dụng", + + "logs.level.all": "Tất cả mức", + "logs.component": "Module", + "logs.search": "Tìm sự kiện, Request ID, mô hình", + "logs.pause": "Tạm dừng", + "logs.resume": "Tiếp tục", + "logs.gap": "Log cũ hơn đã bị xóa khỏi bộ nhớ", + "logs.waiting": "Đang chờ sự kiện log…", + + "quotas.title": "Hạn mức gói OpenCode Go", + "quotas.caption": + "Truy vấn trực tiếp từ OpenCode, cache 60 giây. Mọi mô hình dùng chung một cửa sổ gói, phần trăm do upstream làm tròn.", + "quotas.refresh": "Làm mới hạn mức", + "quotas.loading": "Đang đọc…", + "quotas.pending": "Sẽ đọc hạn mức khi mở trang.", + "quotas.catalog.title": "Mô hình khả dụng", + "quotas.catalog.caption": + "Tên mô hình dùng thẳng cho OPENAI_MODEL. Cột hạn mức ứng với gói đã chọn ở trên, không phải mỗi mô hình có hạn mức riêng.", + "quotas.catalog.search": "Tìm tên mô hình…", + "quotas.col.model": "Tên mô hình", + "quotas.col.protocol": "Giao thức upstream", + "quotas.col.hour": "Còn lại 5 giờ · dùng chung", + "quotas.col.week": "Còn lại tuần · dùng chung", + "quotas.col.month": "Còn lại tháng · dùng chung", + "quotas.col.action": "Thao tác", + + "rotation.title": "Luân chuyển mô hình SOTA / sweet", + "rotation.caption": + "Thành công thì giữ nguyên mô hình hiện tại. Khi hết hạn mức hoặc gặp lỗi sẽ chuyển theo thứ tự, chỉ dùng OpenCode Go.", + "rotation.refresh": "Làm mới trạng thái", + "rotation.usage": + "Giữ nguyên Base URL và API Key hiện có, đặt OPENAI_MODEL là bí danh bên dưới. Mỗi mô hình lỗi thường được thử tối đa 3 lần, mỗi request tối đa thử 3 mô hình; hết hạn mức thì bỏ qua ngay.", + "rotation.streaming": + "Sau khi bắt đầu có output, câu trả lời hiện tại giữ nguyên một mô hình. Lỗi giữa chừng sẽ kết thúc output đó, chỉ request sau mới đổi mô hình. Các mô hình dùng chung hạn mức gói, chuyển mô hình không bảo đảm thoát khỏi tình trạng hết hạn mức.", + "rotation.timeout": "Giới hạn chờ output hợp lệ đầu tiên (giây)", + "rotation.save": "Lưu bí danh và thứ tự", + "rotation.saveNote": + "Lưu là có hiệu lực ngay; đổi thứ tự không cắt ngang câu trả lời đang xuất. Chọn thủ công mô hình hiện tại sẽ có hiệu lực ngay và gỡ trạng thái tạm dừng của mô hình đó.", + "rotation.attempts.title": "Các lần thử gần nhất", + "rotation.col.time": "Thời gian", + "rotation.col.request": "Request", + "rotation.col.alias": "Bí danh", + "rotation.col.model": "Mô hình thực", + "rotation.col.attempt": "Lần thử", + "rotation.col.result": "Kết quả", + + "apikeys.create.title": "Tạo API Key cho bên gọi", + "apikeys.create.caption": + "Dùng để truy cập dịch vụ B trên máy này. Mỗi ứng dụng có thể dùng một khóa riêng; tạo, bật/tắt và xoá đều có hiệu lực ngay.", + "apikeys.create.name": "Tên", + "apikeys.create.namePlaceholder": "Ví dụ: trợ lý ghi chú của tôi", + "apikeys.create.value": "Key tuỳ chọn (không bắt buộc)", + "apikeys.create.valuePlaceholder": + "Để trống để tự sinh; tuỳ chọn cần 16–256 ký tự", + "apikeys.create.submit": "Tạo API Key", + "apikeys.created.title": "Đã tạo khóa", + "apikeys.created.caption": + "Khóa đầy đủ chỉ hiển thị sau khi tạo, hãy lưu ngay vào biến môi trường của bên gọi.", + "apikeys.created.dismiss": "Đã lưu, đóng", + "apikeys.created.copy": "Sao chép Key", + "apikeys.created.copyEnv": "Sao chép biến môi trường", + "apikeys.list.title": "Khóa truy cập", + "apikeys.list.caption": + "Quản lý quyền truy cập vào dịch vụ B. Khóa upstream của OpenCode Go vẫn nằm ở Trung tâm cấu hình.", + "apikeys.list.refresh": "Làm mới danh sách", + "apikeys.col.name": "Tên", + "apikeys.col.tail": "Đuôi khóa", + "apikeys.col.state": "Trạng thái", + "apikeys.col.usage": "Mức dùng (1 giờ gần nhất / tích lũy)", + "apikeys.col.created": "Thời điểm tạo", + "apikeys.col.action": "Thao tác", + "apikeys.col.legacy": "Đã có trong cấu hình", + "apikeys.note": + "Tắt và xoá sẽ khiến các request mới của ứng dụng tương ứng trả về 401. Phải giữ lại ít nhất một Key đang bật.", + + "account.title": "Cập nhật tài khoản quản trị", + "account.caption": "Thành công sẽ thu hồi toàn bộ Session và yêu cầu đăng nhập lại.", + "account.user": "Tài khoản mới (để trống để giữ nguyên)", + "account.current": "Mật khẩu hiện tại", + "account.new": "Mật khẩu mới (để trống để giữ nguyên, tối thiểu 10 ký tự)", + "account.submit": "Cập nhật và đăng nhập lại", + + "modal.eyebrow": "Giá trị nhạy cảm", + "modal.title": "Cấu hình nhạy cảm", + "modal.close": "Đóng", + + "common.copy": "Sao chép", + "common.clipboard": "Trình duyệt không cho phép truy cập clipboard", + "common.empty": "Chưa có dữ liệu", + "common.remove": "Gỡ bỏ", + "common.duration": "Thời gian", + "common.model": "Mô hình", + "common.action": "Thao tác", + "common.yes": "Có", + "common.no": "Không", + "common.none": "Không có", + "common.on": "Bật", + "common.off": "Tắt", + "common.allowed": "Cho phép", + "common.denied": "Từ chối", + "common.unknown": "Không rõ", + "page.section": "Mục {0}", + + "error.session": "Phiên đăng nhập đã hết hạn", + + "state.healthy": "Khỏe", + "state.unavailable": "Không dùng được", + "state.enabled": "Đang bật", + "state.disabled": "Đang tắt", + "state.cooling": "Đang nghỉ (cooldown)", + "state.available": "Sẵn sàng", + + "breakdown.endpoint": "Endpoint", + "breakdown.status": "Mã trạng thái", + "breakdown.model": "Mô hình", + "breakdown.empty": "Chưa có request", + + "guide.models.cached": "Danh mục lấy từ cache {0}, đang chờ nền làm mới.", + "guide.models.ready": "Danh mục upstream đã qua lần làm mới đầu tiên và có mô hình để phục vụ.", + + "usage.empty.models": "Chưa có mức dùng token", + "usage.empty.tiers": "Chưa có mức dùng theo Tier", + + "playground.key.cooling": " · nghỉ đến {0}", + "playground.samplePrompt": "Giải thích năng lực của mô hình này trong một câu.", + "play.httpStatus": "HTTP", + "play.mode": "Chế độ thử", + "play.mode.selected": "Chỉ định Key {0}", + "play.mode.auto": "Định tuyến tự động", + "play.testedKey": "Key được thử", + "play.keyVerdict": "Kết luận về Key", + "play.keyVerdict.none": "Định tuyến tự động không có kết luận riêng", + "play.key.usable": "Key dùng được", + "play.key.rejected": "Key bị từ chối", + "play.key.rateLimited": "Key được chấp nhận nhưng bị giới hạn tần suất", + "play.key.upstreamError": "Upstream bất thường, không kết luận được về Key", + "play.key.transportError": "Mạng hoặc proxy bất thường, không kết luận được về Key", + "play.key.unavailable": "Key hoặc môi trường chạy không dùng được", + "play.key.requestError": "Request không thành công", + "play.actualRoute": "Định tuyến thực tế", + "play.nativeProtocol": "Giao thức gốc", + "play.anonymousVerdict": "Kết luận ẩn danh", + "play.eligibility.allowed": "Cho phép · {0}", + "play.eligibility.denied": "Từ chối · {0}", + "play.route.none": "Chưa định tuyến", + "play.state.ok": "Request thành công · HTTP {0}", + "play.state.failed": "Request thất bại · HTTP {0}", + "play.state.testingKey": "Đang thử với Key được chỉ định…", + "play.state.running": "Đang gửi request qua Gateway…", + "play.state.failedToCall": "Không gọi được cổng chẩn đoán", + + "diag.ready": "Sẵn sàng", + "diag.modelCount": "Số mô hình", + "diag.updatedAt": "Thời điểm cập nhật", + "diag.nextRefresh": "Lần làm mới kế tiếp", + "diag.stale": "Đã cũ", + "diag.lastError": "Lỗi gần nhất", + "diag.notUpdated": "Chưa cập nhật", + "diag.result": "Kết quả", + "diag.ok": "Thành công", + "diag.failed": "Thất bại", + "diag.route": "Định tuyến", + "diag.state": "Trạng thái", + "diag.noTrace": "Chưa có dữ liệu theo dõi Playground", + "diag.streamError": "Streaming thất bại", + "diag.clientCanceled": "Client đã huỷ", + "diag.noRequests": "Chưa có request nào được định tuyến", + "diag.noAttempts": "Chưa có lần thử upstream", + "diag.noMatch": "Không có mô hình phù hợp", + + "quotas.noKey": "Chưa cấu hình Go Key", + "quotas.addKeyFirst": "Hãy thêm OpenCode Go Key trong Trung tâm cấu hình trước.", + "quotas.queryFailed": "Truy vấn thất bại: {0}. Nội dung đang hiển thị chỉ là kết quả truy vấn trước.", + "quotas.connected": "Đã kết nối OpenCode · hạn mức gói dùng chung. Hạn mức của nhiều Key không cộng dồn.", + "quotas.error": "{0}; hiện không rõ hạn mức.", + "quotas.staleError": "{0}; bên dưới hiển thị dữ liệu thành công gần nhất, hiện không rõ hạn mức.", + "quotas.updated": "Thời điểm cập nhật hạn mức: {0} · cache 60 giây · nguồn: OpenCode Go /v1/usage", + "quotas.lastSuccess": "Truy vấn thành công gần nhất: {0} · cache 60 giây · nguồn: OpenCode Go /v1/usage", + "quotas.window.hour": "Cửa sổ 5 giờ", + "quotas.window.week": "Cửa sổ theo tuần", + "quotas.window.month": "Cửa sổ theo tháng", + "quotas.window.aria": "Hạn mức còn lại của {0}", + "quotas.remaining": "Còn lại", + "quotas.remainingHistory": "Còn lại (lịch sử)", + "quotas.rateLimited": "đã chạm trần · ", + "quotas.resetsAt": "reset lúc {0}", + "quotas.waiting": "Đang chờ dữ liệu hạn mức từ upstream", + "quotas.catalogStale": "Danh mục mô hình chưa cập nhật, đang hiện cache · ", + "quotas.catalogUpdated": "Danh mục cập nhật lúc: {0}", + "quotas.history": "(lịch sử)", + "quotas.copyName": "Sao chép tên", + "quotas.catalogPending": "Danh mục mô hình chưa sẵn sàng, vui lòng làm mới sau", + + "apikeys.loadFailed": "Đọc thất bại: {0}", + "apikeys.count": "{0} khóa", + "apikeys.enabledCount": "{0} khóa đang bật", + "apikeys.times": "lần", + "apikeys.rename": "Đổi tên", + "apikeys.namePrompt": "Tên khóa", + "apikeys.enable": "Bật", + "apikeys.disable": "Tắt", + "apikeys.delete": "Xoá", + "apikeys.confirmDelete": + "Sau khi xoá “{0}”, các ứng dụng đang dùng khóa này sẽ không truy cập được. Xoá thật chứ?", + "apikeys.empty": "Chưa có API Key", + + "rotation.status": + "Đã cập nhật trạng thái · hai nhóm luân chuyển độc lập, mọi bên gọi dùng chung vị trí hiện tại.", + "rotation.sweet": "sweet", + "rotation.aliasLabel": "Bí danh gọi", + "rotation.current": "Mô hình hiện tại: {0}", + "rotation.waitingModel": "đang chờ mô hình khả dụng", + "rotation.col.order": "Thứ tự", + "rotation.col.state": "Trạng thái / thời điểm hồi phục", + "rotation.unavailable": "Đã gỡ khỏi danh mục / tạm không dùng được", + "rotation.pausedUntil": "Tạm dừng đến {0}", + "rotation.inUse": "Đang dùng", + "rotation.moveUp": "Lên", + "rotation.moveDown": "Xuống", + "rotation.setCurrent": "Đặt làm hiện tại", + "rotation.useModel": "Dùng {0}", + "rotation.waitingCatalog": "Đang chờ danh mục mô hình Go", + "rotation.recentSwitches": "Chuyển đổi gần đây", + "rotation.noSwitches": "Chưa có bản ghi chuyển đổi", + "rotation.attemptsEmpty": "Gọi bằng bí danh nhóm để xem 100 lần thử gần nhất", + "rotation.reason.success": "Thành công", + "rotation.reason.clientCanceled": "Bên gọi huỷ", + "rotation.reason.quota": "Hết hạn mức / bị giới hạn tần suất", + "rotation.reason.transport": "Lỗi kết nối", + "rotation.reason.firstOutputTimeout": "Timeout output đầu tiên", + "rotation.reason.streamError": "Output bị gián đoạn", + "rotation.reason.readError": "Đọc phản hồi thất bại", + "rotation.reason.conversionError": "Phân tích hoặc chuyển đổi phản hồi thất bại", + "rotation.reason.requestConversion": "Chuyển đổi request thất bại", + "rotation.reason.upstreamError": "Lỗi upstream", + + "availability.pending": "Chờ dò", + "availability.manual": "Thủ công", + "availability.auto": "Tự động", + "availability.unverified": "Chưa xác minh", + "availability.manualControl": "Điều khiển thủ công, không dò tự động", + "availability.restore": "Khôi phục bật", + "availability.switchAuto": "Chuyển lại tự động", + "availability.switchManual": "Chuyển sang thủ công", + "availability.noneEligible": + "Danh mục mô hình hiện tại không có mô hình nào đủ điều kiện miễn phí.", + + "config.restartNotice": + "Đã lưu nhưng chưa có hiệu lực: {0}. API hiện tại {1}, WebUI {2}. Vui lòng khởi động lại tiến trình.", + "config.revealPrompt": "Nhập lại mật khẩu quản trị", + + "toast.refreshed": "Đã làm mới trạng thái", + "toast.copied": "Đã sao chép", + "toast.copyDenied": "Trình duyệt không cho phép sao chép, hãy chọn và sao chép thủ công", + "toast.example.copied": "Đã sao chép ví dụ", + "toast.config.saved": "Cấu hình đã lưu và có hiệu lực ngay", + "toast.config.restart": "Đã áp dụng; cần khởi động lại cho {0}", + "toast.config.reloaded": "Đã nạp lại cấu hình từ đĩa", + "toast.config.reloadedRestart": + "Đã nạp lại cấu hình từ đĩa, các trường lắng nghe cần khởi động lại", + "toast.account.updated": "Đã cập nhật tài khoản, vui lòng đăng nhập lại", + "toast.play.invalidJson": "JSON của request không hợp lệ: {0}", + "toast.play.copied": "Đã sao chép phản hồi gốc", + "toast.apikeys.saved": "Đã lưu và có hiệu lực ngay", + "toast.apikeys.created": "Đã tạo API Key", + "toast.rotation.saved": "Đã lưu cấu hình luân chuyển mô hình và có hiệu lực", + "toast.rotation.switched": "Đã chuyển mô hình hiện tại", + "toast.rotation.dirty": "Có thay đổi chưa lưu, hãy lưu trước khi làm mới", + }, + }; + + let locale = DEFAULT_LOCALE; + + const fill = (text, args) => + args.reduce((value, item, index) => value.replaceAll(`{${index}}`, String(item)), text); + + const lookup = (key) => { + for (const code of [locale, DEFAULT_LOCALE]) { + const value = DICTIONARY[code]?.[key]; + if (value !== undefined) return value; + } + return undefined; + }; + + const interpolate = (value, args) => + args.length ? fill(value, args) : value; + + const t = (original, key, ...args) => { + const value = lookup(key); + return interpolate(value === undefined ? original : value, args); + }; + + const apply = (root = document) => { + const dictionary = DICTIONARY[locale] || {}; + root.querySelectorAll("[data-i18n]").forEach((node) => { + if (!originals.has(node)) originals.set(node, node.innerHTML); + const value = dictionary[node.dataset.i18n]; + node.innerHTML = value === undefined ? originals.get(node) : value; + }); + root.querySelectorAll("[data-i18n-attr]").forEach((node) => { + const targets = node.dataset.i18nAttr.split(",").map((pair) => pair.trim().split(":")); + if (!originals.has(node)) + originals.set( + node, + targets.map(([attribute]) => node.getAttribute(attribute) || ""), + ); + const snapshot = originals.get(node); + targets.forEach(([attribute, key], index) => { + const value = dictionary[key]; + node.setAttribute(attribute, value === undefined ? snapshot[index] : value); + }); + }); + }; + + const closeMenus = (except) => + document.querySelectorAll("[data-lang]").forEach((host) => { + if (host === except) return; + const menu = host.querySelector("[data-lang-menu]"); + if (menu) menu.hidden = true; + const button = host.querySelector("[data-lang-toggle]"); + if (button) button.setAttribute("aria-expanded", "false"); + }); + + const syncControls = () => { + document.querySelectorAll("[data-lang]").forEach((host) => { + const button = host.querySelector("[data-lang-toggle]"); + const menu = host.querySelector("[data-lang-menu]"); + if (button) { + const label = `${t("语言", "lang.label")}: ${LABELS[locale]}`; + button.innerHTML = flagIcon(locale); + button.title = label; + button.setAttribute("aria-label", label); + } + if (menu) { + menu.replaceChildren( + ...SUPPORTED.map((code) => { + const option = document.createElement("button"); + option.type = "button"; + option.className = "lang-option"; + option.dataset.locale = code; + option.setAttribute("aria-current", String(code === locale)); + option.append(...[flagIcon(code), document.createTextNode(LABELS[code])]); + option.onclick = () => { + menu.hidden = true; + button?.setAttribute("aria-expanded", "false"); + setLocale(code); + }; + return option; + }), + ); + } + }); + }; + + const notify = () => listeners.forEach((listener) => listener(locale)); + + const setLocale = (code, persist = true) => { + const next = SUPPORTED.includes(code) ? code : DEFAULT_LOCALE; + const changed = next !== locale; + if (changed) { + locale = next; + if (persist) { + try { + localStorage.setItem(STORAGE_KEY, locale); + } catch (_) {} + } + document.documentElement.lang = locale; + apply(); + } + syncControls(); + if (changed) notify(); + }; + + const stored = () => { + try { + return localStorage.getItem(STORAGE_KEY) || ""; + } catch { + return ""; + } + }; + + const init = () => { + document.documentElement.lang = locale; + document.querySelectorAll("[data-lang]").forEach((host) => { + const button = host.querySelector("[data-lang-toggle]"); + const menu = host.querySelector("[data-lang-menu]"); + if (!button || !menu) return; + button.onclick = (event) => { + event.stopPropagation(); + const open = menu.hidden; + closeMenus(host); + menu.hidden = !open; + button.setAttribute("aria-expanded", String(open)); + }; + }); + document.addEventListener("click", () => closeMenus(null)); + document.addEventListener("keydown", (event) => { + if (event.key === "Escape") closeMenus(null); + }); + if (SUPPORTED.includes(stored())) setLocale(stored(), false); + else apply(); + syncControls(); + }; + + return { + locales: SUPPORTED, + locale: () => locale, + localeLabel: (code) => LABELS[code] || code, + dateLocale: () => DATE_LOCALES[locale] || locale, + t, + apply, + setLocale, + onChange: (listener) => listeners.push(listener), + init, + }; +})(); \ No newline at end of file diff --git a/webui/index.html b/webui/index.html index 10299c1..59c0ab7 100644 --- a/webui/index.html +++ b/webui/index.html @@ -3,7 +3,7 @@ - opencode2api · Field Manual + opencode2api · Field Manual @@ -11,26 +11,47 @@ @@ -38,36 +59,50 @@