Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ test/

*.rotation.json
.rotation-*.tmp
*.freequota.json
.freequota-*.tmp

# Local credentials, deployment backups, and verification artifacts
.local/
Expand Down
4 changes: 4 additions & 0 deletions README.it.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,10 @@ La disponibilità viene appresa dal traffico reale per impostazione predefinita.

`warp.pool_size` è il massimo di uscite adattato alla concorrenza, da 1 a 32, predefinito 2. `warp.stack` ammette `ipv6` (predefinito), `ipv4` o `dual`. Cambiare uscita non garantisce nuova quota upstream. `warp.source_ipv6` è facoltativo, richiede stack IPv6 e prefisso `/64` o più corto; su Windows gli indirizzi sorgente scelti devono essere già assegnati a un'interfaccia. Il gateway non configura la rete del computer.

### Stima dell'uso dei modelli gratuiti

Il gateway conta le richieste ai modelli gratuiti dei client accettate per uscita — ogni proxy configurato, `direct` e ogni blocco di uscita WARP — per il giorno UTC corrente. Solo le risposte 2xx alle richieste dei client contano come utilizzo; le probe di disponibilità sono escluse. Un `FreeUsageLimitError` registra il limite minimo di quell'uscita solo quando il suo `Retry-After` punta alla mezzanotte UTC successiva e l'uscita ha già servito una richiesta nello stesso giorno; rifiuti di forma, throttling brevi e rifiuti su un'uscita nuova non insegnano nulla. Il limite minimo resta su quell'uscita attraverso la mezzanotte; `free_quota.assumed_daily_limit` è il valore usato per un'uscita che non ha ancora insegnato il proprio (`0` lascia sconosciuto). I conteggi locali si azzerano a mezzanotte UTC; l'azzeramento upstream non è verificato. Lo stato vive accanto alla configurazione in `config.json.freequota.json`; un file mancante o corrotto azzera solo la stima. `GET /api/free-quotas` restituisce la stima; la WebUI la mostra nella pagina Modelli e quote.

## Gestione e OAuth

La WebUI comprende panoramica, diagnostica/Playground/log, accesso client, chiavi API, modelli/quota, rotazione, configurazione e account. Supporta cinese semplificato, inglese, vietnamita e italiano; lingua e tema sono conservati nel browser. La [guida di gestione](docs/management.it.md) contiene i dettagli degli endpoint.
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,10 @@ Availability is learned from real traffic by default. Synthetic checks run only

`warp.pool_size` is a concurrency-driven exit ceiling from 1 to 32, default 2. `warp.stack` accepts `ipv6` (default), `ipv4`, or `dual`. Replacing an exit does not guarantee a fresh upstream allowance. `warp.source_ipv6` is optional, requires the IPv6 stack and a prefix of `/64` or shorter, and on Windows the selected source addresses must already be assigned to an interface. It does not configure host networking.

### Free-model usage estimate

The gateway counts accepted free-model client requests per egress — each configured proxy, `direct`, and each WARP exit block — for the current UTC day. Only 2xx responses to client requests count as usage; availability probes are excluded. A `FreeUsageLimitError` records that egress's allowance floor only when its `Retry-After` points at the next UTC midnight and the egress already served a request that day; shape refusals, short throttles and refusals on a fresh exit teach nothing. The floor stays with that egress across midnight; `free_quota.assumed_daily_limit` is the prior for an egress that has not taught its own (`0` leaves it unknown). Local counters reset at UTC midnight; the upstream reset time is not verified. State lives beside the configuration in `config.json.freequota.json`; a missing or corrupt file only resets the estimate. `GET /api/free-quotas` serves it, and the WebUI shows it under Model & quotas.

## Management and OAuth

The WebUI has overview, diagnostics/Playground/logs, client access, API keys, models/quota, rotation, configuration, and account pages. It supports Simplified Chinese, English, Vietnamese, and Italian; language/theme choices are stored in the browser. See the [management guide](docs/management.md) for endpoint details.
Expand Down
4 changes: 4 additions & 0 deletions README.vi.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,10 @@ Mặc định học khả dụng từ lưu lượng thật. Yêu cầu thử t

`warp.pool_size` là trần số lối ra điều chỉnh theo đồng thời, từ 1 đến 32, mặc định 2. `warp.stack` nhận `ipv6` (mặc định), `ipv4`, `dual`. Thay lối ra không bảo đảm có hạn mức mới. `warp.source_ipv6` là tùy chọn, cần stack IPv6 và prefix `/64` hoặc ngắn hơn; trên Windows, địa chỉ nguồn được chọn phải được gán sẵn cho giao diện. Gateway không cấu hình mạng của máy.

### Ước lượng mức dùng model miễn phí

Gateway đếm request model miễn phí từ client được chấp nhận theo từng exit — mỗi proxy đã cấu hình, `direct`, và từng dải địa chỉ exit WARP — trong ngày UTC hiện tại. Chỉ phản hồi 2xx cho request của client mới tính là đã dùng; probe khả dụng không được tính. `FreeUsageLimitError` chỉ ghi nhận mức sàn hạn mức của exit đó khi `Retry-After` trỏ tới nửa đêm UTC kế tiếp và exit đã phục vụ ít nhất một request trong ngày; lỗi hình dạng request, throttle ngắn và từ chối trên exit mới không dạy được gì. Mức sàn chỉ thuộc exit đó và giữ qua nửa đêm; `free_quota.assumed_daily_limit` là prior cho exit chưa tự chứng minh (`0` = chưa biết). Bộ đếm cục bộ đặt lại lúc nửa đêm UTC; thời điểm đặt lại của upstream chưa được xác minh. Trạng thái nằm cạnh cấu hình trong `config.json.freequota.json`; file thiếu hoặc hỏng chỉ đặt lại ước lượng. `GET /api/free-quotas` trả về ước lượng, WebUI hiển thị ở trang Model & quotas.

## Quản trị và OAuth

WebUI có tổng quan, chẩn đoán/Playground/log, hướng dẫn client, key API, mô hình/hạn mức, luân chuyển, cấu hình và tài khoản. Hỗ trợ tiếng Trung giản thể, Anh, Việt và Ý; lựa chọn ngôn ngữ/giao diện lưu trong trình duyệt. Chi tiết endpoint có trong [hướng dẫn quản trị](docs/management.vi.md).
Expand Down
4 changes: 4 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,10 @@ OAuth 另有规则:请求选择 OAuth 路由后,只使用该 Tier 已确认

`warp.pool_size` 是随并发调整的出口上限,范围 1–32,默认 2。`warp.stack` 为 `ipv6`(默认)、`ipv4` 或 `dual`。替换出口不保证获得新的上游额度。可选 `warp.source_ipv6` 要求 IPv6 堆栈及 `/64` 或更短前缀;Windows 下实际选择的源地址必须已分配到网卡,程序不会配置主机网络。

### 免费模型用量估算

网关按出口统计当天(UTC)客户端已接受的免费模型请求——每个已配置代理、`direct`,以及每个 WARP 出口地址段。只有客户端请求的 2xx 响应计为用量;可用性探测不计入。`FreeUsageLimitError` 只有在该出口当天已经成功应答过请求、且 `Retry-After` 指向下一个 UTC 零点时才记录该出口的额度下限,因此请求形状拒绝、短暂限流和新出口上的拒绝都不会产生学习。学到的下限只属于该出口并跨日保留;`free_quota.assumed_daily_limit` 是尚未学到下限的出口使用的先验值(`0` 表示未知)。本地计数在 UTC 零点重置,上游重置时间未经验证。状态保存在配置文件旁的 `config.json.freequota.json`;文件缺失或损坏只会重置估算。`GET /api/free-quotas` 返回该估算,WebUI 在「模型与额度」页展示。

## 管理与 OAuth

WebUI 包含概览、诊断/Playground/日志、接入、API Key、模型与额度、轮转、配置、账号页面,提供简中、英语、越南语及意大利语。语言与主题选择保存在浏览器。完整操作与端点见[管理指南](docs/management.zh-CN.md)。
Expand Down
3 changes: 3 additions & 0 deletions config.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
"free_only": false,
"active_probes": false
},
"free_quota": {
"assumed_daily_limit": 200
},
"performance": {
"max_idle_conns": 2048,
"max_idle_conns_per_host": 256,
Expand Down
11 changes: 11 additions & 0 deletions docs/management.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,17 @@ Key、代理、上游、超时、模型、偏好、reasoning 和日志设置热
| `logging.dump_request_bodies` | `false`;还需 debug 才输出,每个准备好的请求体最多 64 KiB。 |
| `models.active_probes` | `false`;真实流量提供默认可用性观察。 |

### 免费模型用量估算

「免费模型」标签页还显示当天(UTC)按出口统计的免费模型请求,数据来自 `GET /api/free-quotas`。

- 只统计客户端请求中上游返回 2xx 的响应;重试按每次真实请求分别计数,可用性探测不计入。
- 出口为代理 URL、`direct` 或 WARP 出口网段。
- 额度是估计值:只有当某个出口当天已经产生用量,并且收到的 `FreeUsageLimitError` 带有指向下一个 UTC 零点的 `Retry-After` 时,才把当时的用量记为该出口的下限。请求形状拒绝和短暂节流不会改变估计;学到的下限只属于该出口,跨 UTC 日保留。
- `free_quota.assumed_daily_limit`(默认 200,`0` 表示未知)用于尚未学到下限的出口。该字段只能在 `config.json` 中修改,管理页面保存其他配置时会保留它。
- 本地计数在 UTC 零点重置;上游是否同时重置未经验证。已用尽的出口不会在零点立即重新列出,而是在新一天的首个 2xx 请求后重新出现,且只反映本网关的观测。
- 状态保存在配置文件旁的 `config.json.freequota.json`;文件缺失或损坏只会清空估计。

## Go OAuth 与 Zen PAYG OAuth

「模型与额度」有两个独立面板。Go 使用订阅路由;Zen 使用 Console 工作区按量计费(PAYG),**推理会消耗该工作区 credits**。Go 登录不代表获得 Zen 权限或余额,不会自动连接 PAYG。
Expand Down
15 changes: 15 additions & 0 deletions internal/admin/free_quotas.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package admin

import (
"net/http"

"opencode2api/internal/httpx"
)

// handleFreeQuotas returns the current UTC day's free-model usage per egress.
// The upstream exposes no remaining-quota endpoint, so every number is a local
// estimate learned from traffic this gateway already sent.
func (a *Server) handleFreeQuotas(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, http.StatusOK, a.manager.FreeQuotas())
}
3 changes: 2 additions & 1 deletion internal/admin/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ func (a *Server) Handler() http.Handler {
mux.Handle("POST /api/zen/auth/poll", a.authenticate(a.csrf(http.HandlerFunc(a.handleZenOAuthPoll))))
mux.Handle("DELETE /api/zen/auth", a.authenticate(a.csrf(http.HandlerFunc(a.handleZenOAuthCancel))))
mux.Handle("DELETE /api/zen/connection", a.authenticate(a.csrf(http.HandlerFunc(a.handleZenOAuthDisconnect))))
mux.Handle("GET /api/free-quotas", a.authenticate(http.HandlerFunc(a.handleFreeQuotas)))
mux.Handle("GET /api/api-keys", a.authenticate(http.HandlerFunc(a.handleListAPIKeys)))
mux.Handle("POST /api/api-keys", a.authenticate(a.csrf(http.HandlerFunc(a.handleCreateAPIKey))))
mux.Handle("PATCH /api/api-keys/{id}", a.authenticate(a.csrf(http.HandlerFunc(a.handleUpdateAPIKey))))
Expand Down Expand Up @@ -277,7 +278,7 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) {
ZenOAuth: current.ZenOAuth,
Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Warp: update.Warp, Proxies: proxies, ProxyFile: update.ProxyFile,
ProxyBindings: proxyBindings,
Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer,
Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, FreeQuota: current.FreeQuota, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer,
Reasoning: reasoning,
WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes},
}
Expand Down
23 changes: 23 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ type Config struct {
Upstream UpstreamConfig `json:"upstream"`
Retry RetryConfig `json:"retry"`
Models ModelsConfig `json:"models"`
FreeQuota FreeQuotaConfig `json:"free_quota"`
Performance PerformanceConfig `json:"performance"`
Logging LoggingConfig `json:"logging"`
WebUI WebUIConfig `json:"webui"`
Expand Down Expand Up @@ -216,6 +217,25 @@ type AnonymousBackoffConfig struct {
MaxHours int `json:"max_hours,omitempty"`
}

// DefaultAssumedFreeQuotaLimit is the per-egress free-model allowance the
// console shows until an egress teaches its own.
const DefaultAssumedFreeQuotaLimit = 200

// FreeQuotaConfig tunes the passive free-model usage estimate. An absent
// AssumedDailyLimit uses DefaultAssumedFreeQuotaLimit; zero shows unknown.
type FreeQuotaConfig struct {
AssumedDailyLimit *int `json:"assumed_daily_limit,omitempty"`
}

// AssumedLimit returns the configured starting allowance, or the default when
// the pointer is nil.
func (f FreeQuotaConfig) AssumedLimit() int {
if f.AssumedDailyLimit == nil {
return DefaultAssumedFreeQuotaLimit
}
return *f.AssumedDailyLimit
}

// Normalize fills the defaults and rejects nonsensical windows.
func (b *AnonymousBackoffConfig) Normalize() error {
if b == nil {
Expand Down Expand Up @@ -462,6 +482,9 @@ func Normalize(path string, cfg Config) (Config, error) {
if cfg.Models.RefreshSeconds < 1 {
return Config{}, errors.New("models.refresh_seconds must be at least 1")
}
if limit := cfg.FreeQuota.AssumedDailyLimit; limit != nil && (*limit < 0 || *limit > 1000000) {
return Config{}, errors.New("free_quota.assumed_daily_limit must be between 0 and 1000000")
}
if cfg.Performance.MaxIdleConns < 1 || cfg.Performance.MaxIdleConnsPerHost < 1 || cfg.Performance.MaxConnsPerHost < 0 || cfg.Performance.IdleConnTimeoutSeconds < 1 || cfg.Performance.ConnectTimeoutSeconds < 1 || cfg.Performance.FailureCooldownSeconds < 1 {
return Config{}, errors.New("performance values must be positive (max_conns_per_host may be zero for unlimited)")
}
Expand Down
Loading
Loading