diff --git a/README.it.md b/README.it.md index 38b97d9..20ca576 100644 --- a/README.it.md +++ b/README.it.md @@ -2,26 +2,9 @@ [English](README.md) | [简体中文](README.zh-CN.md) | [Tiếng Việt](README.vi.md) | [Italiano](README.it.md) -Gateway scritto in Go per **OpenCode Zen e Zen Go**. Espone gli endpoint Chat Completions, Responses e Anthropic Messages, traduce tra i rispettivi protocolli nativi e gestisce le chiavi upstream e i proxy. +Gateway Go per OpenCode Zen e Zen Go. I client usano OpenAI Chat Completions, OpenAI Responses o Anthropic Messages; il gateway sceglie un upstream disponibile e converte richieste e risposte quando il protocollo nativo è diverso. Le decisioni System One hanno un endpoint di inoltro dedicato. -L'eseguibile include la WebUI: per eseguire il servizio non servono Node.js né un database. - -## Funzionalità - -- Risposte JSON e SSE per tutti e tre i protocolli di inferenza. -- Testo, immagini, ragionamento, function tool, tool call e tool result; contenuti di file quando il protocollo di destinazione li supporta. -- Pool separati di chiavi Zen e Go, preferenza del tier configurabile, retry e affinità di sessione. -- Accesso anonimo opzionale a Zen con la credenziale `public` di OpenCode. -- Uscita Cloudflare WARP in userspace per il traffico dei modelli gratuiti, senza TUN né root. -- Connessioni dirette e tramite HTTP, HTTPS, SOCKS5 e SOCKS5H, anche da un file proxy. -- Rilevamento dinamico dei modelli, metadati del protocollo nativo e cache su disco. -- Porta di gestione separata con modifica della configurazione, Playground, diagnostica, statistiche dei token e log in tempo reale. -- Ricaricamento a caldo della configurazione, con convalida prima di passare le nuove richieste a un gateway sostitutivo. -- Dashboard delle quote dell'abbonamento Go con percentuali residue, orari di reset e modelli disponibili. -- Creazione, denominazione, abilitazione, disabilitazione ed eliminazione immediata di API key locali. -- Gruppi di modelli `sota` / `sweet` con affinità, ordinamento, failover, protezione dello streaming e stato persistente. - -Consulta la [guida della console di gestione (in cinese)](docs/management.zh-CN.md) per informazioni sulle nuove pagine e sulla configurazione. +La WebUI di gestione è inclusa nell'eseguibile: per eseguirlo non servono Node.js né un database. Rilevamento dei modelli, inferenza, OAuth e WARP opzionale richiedono comunque l'accesso ai rispettivi servizi upstream. ## Sponsor @@ -53,7 +36,7 @@ go build -o opencode2api ./cmd/opencode2api Prima di avviare il servizio, modifica `config.json`: 1. Sostituisci `server_keys` con una tua API key locale. -2. Prima dell'avvio, inserisci una Zen API Key (consigliata) in `zen_keys` oppure una chiave Go in `go_keys`. L'esempio disabilita l'accesso anonimo (`anonymous: false`) e lascia vuoti entrambi gli array; anche una connessione Go in abbonamento già salvata soddisfa il requisito. Il canale anonimo potrebbe essere fortemente bloccato a monte: preferisci una Zen API Key. +2. Prima dell'avvio, inserisci una Zen API Key (consigliata) in `zen_keys` oppure una chiave Go in `go_keys`. L'esempio disabilita l'accesso anonimo (`anonymous: false`) e lascia vuoti entrambi gli array; anche una connessione Go OAuth (`go_oauth`) o Zen OAuth (`zen_oauth`) già salvata soddisfa il requisito. Non è supportato avviare senza credenziali soltanto per effettuare il primo login OAuth nella WebUI. Il canale anonimo potrebbe essere fortemente bloccato a monte: preferisci una Zen API Key. 3. Sostituisci `webui.password`. La configurazione di esempio abilita la WebUI con l'utente `admin`. ```bash @@ -74,493 +57,268 @@ Opzioni da riga di comando: La directory di configurazione deve essere scrivibile per migrare la password, salvare la configurazione e memorizzare le cache dei modelli. -## Docker +## Docker e Compose -L'immagine pubblicata è `ghcr.io/jasonxu114514/opencode2api`. +L'immagine pubblicata è `ghcr.io/jasonxu114514/opencode2api`. Prepara `config.json` prima dell'avvio. Per raggiungere le porte pubblicate, mantieni i listener interni API/WebUI su `0.0.0.0:8080` e `0.0.0.0:8081`; limita l'accesso tramite il binding delle porte host e HTTPS dove necessario. ```bash -cp config.example.json config.json -# Configura le chiavi e sostituisci la password WebUI prima dell'avvio. docker compose up -d docker compose logs -f ``` -Compose importa la configurazione dell'host nel volume `opencode2api-state` **solo al primo avvio**. Le modifiche successive vanno effettuate tramite la WebUI. Per importare di nuovo una configurazione modificata sull'host: +Compose importa la configurazione host in `opencode2api-state` **solo al primo avvio**. Successivamente il file attivo è nel volume: modificalo dalla WebUI. Per importare di nuovo un file host modificato: ```bash docker compose cp config.json opencode2api:/var/lib/opencode2api/config.json docker compose restart ``` -Il container esegue il servizio con un utente non privilegiato. Compose usa un filesystem root in sola lettura, un volume di stato scrivibile e un filesystem temporaneo `/tmp`. +Prima della sostituzione salva configurazione e stato attivi. L'entrypoint esegue il servizio senza privilegi e cambia l'esatto listener API dell'esempio `127.0.0.1:8080` in `0.0.0.0:8080` soltanto durante l'inizializzazione. Compose usa filesystem radice in sola lettura, volume di stato scrivibile e tmpfs `/tmp`. Le porte pubblicate si legano per default a tutte le interfacce host; per uso locale modifica `ports` in `127.0.0.1:8080:8080` e `127.0.0.1:8081:8081`. -WARP richiede solo UDP in uscita (endpoint Cloudflare, porta `2408`), quindi la configurazione dell'immagine senza privilegi e senza `NET_ADMIN` funziona così com'è; non serve passare a host networking né aggiungere `--cap-add`. Se la rete del container blocca UDP, l'abilitazione di WARP fallisce all'avvio. +| Variabile Compose | Predefinito | Effetto | +| --- | --- | --- | +| `OPENCODE2API_VERSION` | `latest` | Tag immagine; fissa un tag di rilascio per una versione precisa. | +| `OPENCODE2API_PORT` | `8080` | Porta API pubblicata sull'host. | +| `OPENCODE2API_WEBUI_PORT` | `8081` | Porta di gestione pubblicata sull'host. | +| `OPENCODE2API_LISTEN` | Non impostata | Override esplicito del listener API interno. | +| `OPENCODE2API_WEBUI_LISTEN` | Non impostata | Override esplicito del listener di gestione interno. | -| Variabile Compose | Predefinito | Effetto | -| --------------------------- | ----------- | ---------------------------------------------------------- | -| `OPENCODE2API_VERSION` | `latest` | Tag dell'immagine; fissa un tag di release per una versione precisa. | -| `OPENCODE2API_PORT` | `8080` | Porta host mappata alla porta 8080 del container. | -| `OPENCODE2API_WEBUI_PORT` | `8081` | Porta host mappata alla porta 8081 del container. | -| `OPENCODE2API_LISTEN` | Non impostata | Sostituisce esplicitamente l'ascolto API nel container. | -| `OPENCODE2API_WEBUI_LISTEN` | Non impostata | Sostituisce esplicitamente l'ascolto WebUI nel container. | +Le ultime due diventano `LISTEN_ADDRESS` e `WEBUI_LISTEN_ADDRESS` nel container; se vuote, vale il file attivo. Cambiare porte host non modifica i listener interni. Se cambia la porta API interna, aggiorna mapping e health check dell'immagine, che usa 8080. Un `proxyfile` deve essere montato nel percorso configurato del container. -Le ultime due variabili diventano `LISTEN_ADDRESS` e `WEBUI_LISTEN_ADDRESS` nel container. I valori vuoti usano quelli del file di configurazione. Durante l'inizializzazione, l'entrypoint cambia l'indirizzo API di esempio `127.0.0.1:8080` in `0.0.0.0:8080`, così le porte pubblicate possono raggiungerlo. - -Cambiare le porte host non cambia gli indirizzi di ascolto nel container. Se cambi la porta API interna, aggiorna anche la mappatura delle porte e l'health check dell'immagine, che usa la porta 8080. - -Per creare un'immagine locale: +Per un'immagine locale: ```bash docker build -t opencode2api:local . docker volume create opencode2api-state docker run -d --name opencode2api \ - -p 8080:8080 -p 8081:8081 \ + -p 127.0.0.1:8080:8080 -p 127.0.0.1:8081:8081 \ -e CONFIG_SEED_PATH=/run/config/opencode2api.json \ - -v "$(pwd)/config.json:/run/config/opencode2api.json:ro" \ + -v "$PWD/config.json:/run/config/opencode2api.json:ro" \ -v opencode2api-state:/var/lib/opencode2api \ opencode2api:local ``` -Anche il file `proxyfile` usato in Docker deve essere presente nel container al percorso configurato. +WARP richiede UDP in uscita verso Cloudflare sulla porta `2408`, senza rete host o capacità di rete aggiuntive. Se la rete blocca questo traffico, WARP non può inizializzarsi. ## Uso dell'API -`server_keys` autentica i client presso questo gateway. È separato da `zen_keys` e `go_keys` e non viene mai usato come credenziale upstream. +Queste sono le rotte di compatibilità esistenti. Per un client compatibile OpenAI usa `http://127.0.0.1:8080/v1` come URL di base; la gestione usa un listener separato. -Invia `Authorization: Bearer YOUR_LOCAL_API_KEY` oppure `x-api-key: YOUR_LOCAL_API_KEY`. Gli health check non richiedono autenticazione. +| Metodo | Percorso | Comportamento | +| --- | --- | --- | +| `GET` | `/v1/models` | Modelli instradabili con la configurazione attuale e alias di rotazione disponibili. | +| `POST` | `/v1/chat/completions` | Chat Completions, JSON o SSE. | +| `POST` | `/v1/responses` | Responses, JSON o SSE. | +| `POST` | `/v1/messages` | Anthropic Messages, JSON o SSE. | +| `POST` | `/v1/systemone` | Decisioni System One native, senza traduzione. | +| `GET` | `/healthz` | Stato di disponibilità e risorse, senza autenticazione. | -| Metodo | Percorso | Descrizione | -| ------ | ---------------------- | ---------------------------------------------------------- | -| GET | `/v1/models` | Modelli instradabili con la configurazione corrente. | -| POST | `/v1/chat/completions` | Chat Completions. | -| POST | `/v1/responses` | Responses. | -| POST | `/v1/messages` | Anthropic Messages. | -| POST | `/v1/systemone` | Decisioni strutturate System One. | -| GET | `/healthz` | Stato di disponibilità e riepilogo delle risorse. | +Tutte le rotte `/v1/*` richiedono una chiave abilitata di `server_keys` in `Authorization: Bearer ...` o `x-api-key`. Il corpo ha un limite di 32 MiB. Le risposte di inferenza includono `x-request-id` per trovare i log correlati. -Prima individua un modello disponibile: +Consulta prima gli ID dei modelli effettivamente disponibili: ```bash -curl http://localhost:8080/v1/models \ - -H "Authorization: Bearer YOUR_LOCAL_API_KEY" +curl http://127.0.0.1:8080/v1/models \ + -H 'Authorization: Bearer YOUR_LOCAL_API_KEY' + +curl http://127.0.0.1:8080/v1/chat/completions \ + -H 'Authorization: Bearer YOUR_LOCAL_API_KEY' \ + -H 'Content-Type: application/json' \ + -d '{"model":"MODEL_ID","messages":[{"role":"user","content":"Ciao"}]}' ``` -Sostituisci `MODEL_ID` negli esempi seguenti con un ID restituito dalla richiesta. +Per Responses e Anthropic Messages invia, rispettivamente, questi corpi JSON standard al relativo endpoint: -**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"}]}' +```json +{"model":"MODEL_ID","input":"Ciao"} ``` -**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"}' +```json +{"model":"MODEL_ID","max_tokens":512,"messages":[{"role":"user","content":"Ciao"}]} ``` -**Anthropic Messages** +I client Anthropic possono inviare anche `anthropic-version: 2023-06-01`. Per SSE aggiungi `"stream": true` e usa `curl -N` o un client che consumi gli eventi mentre arrivano. Uno stream può fallire dopo HTTP 200: controlla gli eventi di errore e l'esito finale. -```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"}]}' +System One richiede un modello con `native_protocol: "systemone"` e un corpo decisionale, per esempio: + +```json +{"model":"SYSTEM_ONE_MODEL_ID","state":"1 + 1 = 2","questions":{"arithmetic":{"type":"noul","instructions":"Is 1 + 1 equal to 2?"}}} ``` -Per lo streaming, aggiungi `"stream": true` al body e usa `curl -N`. Le risposte includono `x-request-id` per la correlazione. I body delle richieste API sono limitati a 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 associa uno stato libero a domande tipizzate e restituisce risposte tipizzate. Il payload non condivide la struttura del bridge Chat/Responses: viene inoltrato senza modifiche e non viene mai tradotto. Questo endpoint serve solo modelli con protocollo nativo System One; anche un payload decisionale inviato a un endpoint messaggi (`/v1/chat/completions`, `/v1/responses`) viene inoltrato senza conversione. Le risposte streaming upstream vengono inoltrate così come sono, senza recupero dopo un'interruzione. +Il corpo e la risposta sono inoltrati senza conversione. Gli endpoint dei messaggi riconoscono questa struttura per i modelli System One, ma non convertono messaggi di chat ordinari in decisioni. Uno stream System One viene inoltrato senza recupero tramite reset. ### Limiti di compatibilità -Le richieste che usano il protocollo nativo dell'upstream conservano i campi specifici del provider. Quelle che passano da un protocollo all'altro usano una rappresentazione comune e non tutte le opzioni hanno un equivalente. Per esempio, i vincoli JSON di Chat e `seed` non vengono inoltrati ad Anthropic Messages. Contenuti o tipi di tool non supportati possono essere rifiutati. +I tre protocolli dei messaggi supportano testo, contenuti immagine/file rappresentabili, ragionamento, funzioni, chiamate e risultati degli strumenti, e streaming. Le richieste native mantengono i campi del provider che il gateway non modifica deliberatamente. La conversione trasferisce solo i campi con una rappresentazione supportata: ad esempio `seed` e i vincoli JSON di Chat non diventano opzioni Anthropic. Contenuti o strumenti non supportati possono causare un errore di validazione. -Il gateway espone i percorsi elencati sopra. Non implementa embeddings, caricamento di file, generazione di immagini, né recupero o annullamento di Responses. Non memorizza la cronologia delle conversazioni: i client devono inviarla o usare le funzionalità supportate dall'upstream effettivo. +Nella conversione della cronologia Responses, ragionamento, testo e chiamate a funzioni dell'assistente vengono raggruppati in turni. Messaggi utente e risultati degli strumenti separano i turni; risultati mancanti o non corrispondenti restano errori nella conversione verso Chat Completions. -## Instradamento e modelli +Non sono implementati embeddings, caricamento di file, generazione di immagini, recupero o annullamento Responses. Il gateway non conserva la cronologia delle conversazioni per i client. Inviala nelle richieste; le funzionalità con stato dell'upstream non costituiscono una memoria locale del gateway. -### Rilevamento dei modelli +## Configurazione e instradamento -Il gateway aggiorna `/v1/models` di Zen/Go e il [catalogo delle capacità](https://models.opencode.ai/api.json) di OpenCode all'intervallo configurato. Protocolli nativi e limiti dei modelli sono tracciati separatamente per ogni tier. La documentazione Zen/Go di OpenCode è una fonte di ripiego per il rilevamento del protocollo. +Parti da [config.example.json](config.example.json). Il file ammette commenti `//` e `/* ... */`; i corpi delle API richiedono JSON standard. Campi sconosciuti, valori non validi, campi duplicati al livello principale e conflitti tra vecchi e nuovi nomi OAuth vengono rifiutati. Il salvataggio normalizza il file ed elimina i commenti. -`models.protocols` permette di sovrascrivere il rilevamento: +| Impostazione | Predefinito / significato | +| --- | --- | +| `server_keys` | Deve restare almeno una chiave locale abilitata. | +| `zen_keys`, `go_keys` | Pool upstream separati, vuoti nell'esempio. | +| `prefer` | `go`; accetta anche `zen` e sceglie il tier autenticato disponibile preferito. | +| `anonymous` | `false`; abilita la credenziale upstream `public` per modelli gratuiti idonei. | +| `upstream.zen` | `https://opencode.ai/zen` per chiavi Zen manuali. | +| `upstream.go` | `https://opencode.ai/zen/go` per chiavi Go manuali e relativo consumo. | +| `upstream.anonymous` | `https://opencode.ai/inference` per richieste anonime. | +| `models.refresh_seconds` | `300`; intervallo di rilevamento. | +| `models.protocols` | Override per modello: `chat`, `responses`, `anthropic`, `systemone`. | +| `models.free_only` | `false`; limita elenco e instradamento ai modelli gratuiti. | +| `models.active_probes` | `false`; test sintetici di inferenza gratuiti facoltativi. | +| `reasoning.effort` | Non impostato nei valori interni; l'esempio usa `high`. | +| `reasoning.effort_by_model` | Override del ragionamento per modello. | + +### Modelli e scelta dell'upstream + +Il rilevamento combina gli elenchi upstream con capacità e prezzi OpenCode da `https://models.opencode.ai/api.json`. I protocolli nativi sono distinti per tier. `/v1/models` espone i limiti noti di contesto/token, prezzi, `native_protocol`, `supported_endpoints` e metadati del ragionamento. Prezzi e deprecazioni vengono aggiornati ogni 24 ore; gli errori conservano i dati precedenti. I prezzi non sono un saldo né una stima della fattura. + +Con chiavi manuali, i modelli gratuiti idonei possono usare prima la corsia anonima, se abilitata esplicitamente, poi i tier con chiave nell'ordine `prefer`. Con accesso anonimo disabilitato usano le chiavi configurate. Sono gratuiti gli ID che contengono `free` senza distinzione di maiuscole, oppure i modelli non deprecati con costo di input/output zero nei metadati; l'idoneità non garantisce l'accettazione upstream. I modelli a pagamento richiedono una rotta autenticata appropriata. `models.free_only` filtra anche i gruppi di rotazione. + +OAuth ha regole separate: una richiesta che seleziona un tier OAuth usa soltanto le sue rotte confermate, senza ripiego su anonimo, chiavi manuali o altri tier dopo un errore. Go OAuth non attiva PAYG quando falliscono autorizzazione, quota o richieste con 429. Se entrambi i tier servono un modello, scegliere esplicitamente `prefer: "zen"` consente l'uso della connessione Zen PAYG. + +### Timeout, proxy e affinità + +| Impostazione | Predefinito | Significato | +| --- | --- | --- | +| `retry.max_attempts` | `3` | Budget dei cicli con chiavi; anonimo e rotazione hanno regole proprie. | +| `retry.timeout_seconds` | `300` | Budget totale dell'inferenza, incluso il consumo dello stream. | +| `performance.attempt_timeout_seconds` | `0` | Limite facoltativo più breve per tentativo; zero mantiene il timeout totale. | +| `performance.first_event_timeout_seconds` | `0` | Attesa facoltativa del primo evento; zero la disabilita. | +| `performance.connect_timeout_seconds` | `5` | Timeout di connessione. | +| `performance.failure_cooldown_seconds` | `15` | Pausa di base dopo un errore. | +| `performance.max_anonymous_exits` | `8` effettivo | Uscite statiche distinte per richiesta anonima; zero usa il limite interno. | +| `performance.free_tier_block_seconds` | `900` effettivo | Pausa di un'uscita bloccata dal tier gratuito; zero usa il valore interno. | +| `performance.max_idle_conns` | `2048` | Connessioni inattive per transport. | +| `performance.max_idle_conns_per_host` | `256` | Connessioni inattive per host/transport. | +| `performance.max_conns_per_host` | `0` | Limite connessioni; zero significa illimitato. | +| `performance.idle_conn_timeout_seconds` | `120` | Durata delle connessioni inattive. | + +`proxies` accetta `direct`, HTTP, HTTPS, SOCKS5 e SOCKS5H. `proxyfile` aggiunge un proxy per riga non vuota, con percorso relativo alla configurazione; i duplicati sono eliminati e un elenco risolto vuoto equivale ad accesso diretto. I commenti iniziano con `#`, `;` o `//` a inizio riga o dopo spazi. Le credenziali nei relativi URL sono segrete. + +Per un endpoint già ruotato dal provider usa `pool+https://proxy.example:8443` o `https://proxy.example:8443#pool`. Ogni tentativo apre una connessione nuova senza riuso keep-alive/HTTP/2, cooldown o esclusione sanitaria dei nodi statici. La rotazione deve essere fornita dal provider. I proxy statici mantengono riuso, stato di salute e associazione alle chiavi. `proxy_bindings` può associare l'impronta di una chiave a un proxy configurato. + +Un `x-session-id` esplicito determina l'affinità di conversazione. Sono riconosciuti anche gli header OpenCode e i campi di conversazione supportati; in loro assenza il seme deriva dal contenuto iniziale system/user. Gli ID generati sono isolati per chiave locale e durata del processo. Gli ID ufficiali OpenCode validi sono conservati. Usa ID distinti per conversazioni indipendenti e chiavi separate per isolare gli utenti: inizi identici con la stessa chiave possono condividere affinità. + +L'oggetto facoltativo `models.anonymous_backoff` sospende la corsia anonima dopo errori ripetuti: soglia predefinita `6`, durata base `1` ora, massimo `24` ore. Ometterlo disabilita questa protezione a livello di corsia. + +### Adattamento dei modelli gratuiti e ragionamento + +La compatibilità gratuita può inserire prompt e strumenti ufficiali OpenCode, rinominare gli strumenti sul collegamento upstream e ripristinarne i nomi nelle risposte. Riguarda anche modelli gratuiti serviti con chiave. Il gateway inoltra le chiamate, senza eseguire strumenti sul computer. System One è escluso dall'adattamento di messaggi e strumenti. + +Il prompt inserito include directory, workspace, piattaforma, modello e data UTC. Normalmente descrive il computer del gateway. Per i client remoti configura il testo in `upstream.prompt_environment`: ```json -{ - "models": { - "refresh_seconds": 300, - "protocols": { - "custom-model": "chat" - } - } -} +{"working_directory":"C:\\work\\project","workspace_root":"C:\\work\\project","platform":"windows","is_git_repo":true} ``` -I valori di protocollo consentiti sono `chat`, `responses` e `anthropic`. I modelli con protocolli nativi non supportati vengono esclusi dal rilevamento, a meno che non siano sovrascritti. +Inserisci l'oggetto nel campo indicato della configurazione. I percorsi sono testo e non vengono aperti. `windows` diventa `win32`; sono ammessi anche `linux` e `darwin`. Un prompt ufficiale già fornito dal client non viene sostituito. Questi valori avanzati non hanno campi dedicati nella UI: modifica e ricarica il file. Gli override arbitrari non sono stati verificati con la validazione reale dell'upstream. -Costi, stato di deprecazione e limiti dei modelli provengono dall'[endpoint ufficiale dei metadati OpenCode](https://models.opencode.ai/api.json), aggiornato ogni 24 ore. Il catalogo delle capacità di OpenCode resta la fonte autorevole per i limiti di contesto e token; i metadati `limit.context`, `limit.input` e `limit.output` completano i campi mancanti. `/v1/models` espone questi limiti come `context_window`/`context_length`, `max_input` e `max_output` per client di rilevamento quali CLIProxyAPI e Pi. Ogni client HTTP attende al massimo 30 secondi per una richiesta di metadati. Gli aggiornamenti non riusciti conservano i dati esistenti. +Il ragionamento accetta `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, `none`, `auto` o un valore vuoto. Il livello esplicito del client ha precedenza. `none` rimuove le impostazioni. `auto` usa un limite recentemente verificato soltanto per modelli gratuiti Zen/anonimi e non estende la portata dei test. La scoperta richiede test attivi, può consumare quota con più richieste e scade dopo due ore. Nessun livello viene dedotto per Go, modelli a pagamento o capacità non verificate. -Quando i metadati indicano un prezzo, ogni elemento di `/v1/models` include anche `cost` (USD per milione di token: `input`, `output`, `cache_read`, `cache_write`, oltre a `cacheRead`/`cacheWrite` di OpenClaw). I modelli con ragionamento elencano i livelli in `reasoning_efforts` e in `compat.supportedReasoningEfforts` di OpenClaw: da `minimal` a `max`, limitati al livello massimo verificato quando il livello del modello è `auto`. Un livello forzato o verificato è esposto come `default_reasoning_effort`. I prezzi della cache compaiono dopo il successivo aggiornamento dei metadati. +La disponibilità viene appresa dal traffico reale per impostazione predefinita. I test sintetici richiedono `models.active_probes: true`; il comando di gestione li pianifica senza aggirare l'opzione. Solo prove esplicite di modello ritirato/inesistente possono disabilitarlo. Rate limit, errori di autenticazione, errori generici e timeout non dimostrano un ritiro. Il ripristino manuale mantiene il modello abilitato e lo esclude dai test fino al ritorno al controllo automatico. -### Accesso anonimo e fallback +### WARP -Con `anonymous: true`, un modello può usare il canale Zen anonimo se soddisfa una delle seguenti condizioni: +`warp.enabled` è `false`. Se abilitato, il traffico gratuito anonimo/Zen manuale e i relativi elenchi/test passano per il tunnel Cloudflare WARP del processo. Go, modelli a pagamento e OAuth mantengono i proxy configurati. Serve UDP in uscita verso Cloudflare sulla porta `2408`; non occorrono dispositivi TUN o modifiche alle tabelle di routing. Un errore di inizializzazione rifiuta l'avvio o la configurazione candidata. -- Il suo ID contiene `free`, senza distinzione tra maiuscole e minuscole. -- I metadati OpenCode indicano un costo input e output pari a zero e il modello non è deprecato. +`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. -L'idoneità determina l'instradamento; l'upstream può comunque rifiutare o limitare la richiesta. Le richieste anonime usano `public` nell'header di autenticazione upstream. +## Gestione e OAuth -L'ordine di instradamento è: +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. -1. Per un modello idoneo, prova una volta ciascun proxy anonimo disponibile. -2. Prova i tier autenticati nell'ordine `prefer`, usando solo i tier con una chiave configurata e una route per quel modello. -3. Applica `retry.max_attempts` separatamente a ogni tier autenticato. +La gestione usa cookie di sessione amministratore, token CSRF per le scritture e limiti al login. Modificare le credenziali amministrative invalida le sessioni. Le chiavi API locali non concedono accesso amministrativo. `GET /api/config` maschera i segreti; la visualizzazione con verifica della password può mostrare chiavi manuali/proxy, ma mai token OAuth. -I tentativi anonimi non sono limitati da `retry.max_attempts`, ma condividono il timeout della richiesta. Errori di rete, autenticazione, limiti di frequenza ed errori del server possono causare la rotazione delle chiavi. Gli altri errori 4xx terminano il tier corrente; è comunque possibile provare un altro tier disponibile. +Da **Modelli e quota** avvia un login Device OAuth. Apri personalmente l'URL ufficiale mostrato, inserisci `user_code`, autorizza la richiesta iniziata da te e seleziona organizzazione/workspace se richiesto. Il backend gestisce polling e rinnovo. Non si incollano token, importano file di credenziali locali o inviano URL di callback. -Le richieste vengono codificate con il protocollo specifico di ogni tier. Se è attivo `performance.first_event_timeout_seconds`, una risposta SSE riuscita viene trattenuta fino al primo evento dati completo. Un timeout o una disconnessione prima dell'evento usa il budget di retry esistente per chiavi e proxy; i commenti non soddisfano il timeout. Dopo l'invio al client, lo stream non viene mai riprodotto. Il valore predefinito è `0` (disattivato); prova `15` secondi per upstream che accettano richieste ma non inviano eventi. Questo limite riguarda il primo evento, non il primo token di testo, e non si applica a System One. Gli alias di rotazione usano il timeout separato `rotation.first_output_seconds`. Un riferimento di ragionamento Responses obsoleto riconosciuto può attivare un singolo tentativo di correzione; la diagnostica con chiave selezionata non usa mai tale ripetizione. +| Connessione | Ambito e limiti | +| --- | --- | +| Go OAuth | Solo rotte ufficiali dell'abbonamento Go; quota sconosciuta. | +| Zen OAuth | Console PAYG che consuma credits del workspace; conferma esplicita prima dell'avvio, saldo sconosciuto. | -Quando è configurato solo l'accesso anonimo, `/v1/models` espone esclusivamente i modelli idonei per quel canale. +Login in attesa, credenziali, rinnovi e disconnessioni Go e Zen sono separati. Nascondere o lasciare la pagina interrompe il polling; tornando si può riprendere un login non scaduto. Il logout annulla i login in attesa della sessione senza rimuovere le connessioni completate. Annullare un login non disconnette l'account già salvato. -I modelli gratuiti non richiedono una chiave Zen: con `anonymous: true` usano il canale pubblico e un'eventuale chiave configurata serve solo come fallback. Per conservare le chiavi ma esporre solo modelli gratuiti, imposta `models.free_only: true`. I modelli a pagamento scompaiono da `/v1/models`, le richieste dirette vengono rifiutate e gli alias di rotazione mantengono solo i membri gratuiti; questi ultimi possono comunque usare le chiavi configurate come fallback. +Le connessioni `go_oauth` e `zen_oauth` nella configurazione contengono credenziali di accesso e rinnovo: proteggi file e backup. Le chiavi manuali sono conservate ma non sono alternative mentre esiste l'OAuth corrispondente, anche se richiede un nuovo login. Disconnettere rimuove soltanto la connessione locale, ripristina le rotte manuali dopo il rilevamento e non revoca la sessione ufficiale. Conserva un'altra credenziale prima di rimuovere l'ultima con accesso anonimo disabilitato. -### Uscita WARP per i modelli gratuiti +Sono accettate solo rotte della configurazione remota ufficiale autenticata che superano i controlli URL/SDK del relativo piano. Non si ricavano URL PAYG da Go né si importano header remoti arbitrari. I normali salvataggi conservano le credenziali OAuth gestite dal backend. I vecchi campi `go_subscription`/`zen_subscription` migrano al caricamento; combinare nome vecchio e nuovo per uno stesso piano causa un errore. -`warp.enabled` sposta ogni richiesta di un modello gratuito sul canale gratuito — canale anonimo, fallback dei modelli gratuiti tramite chiave Zen, probe di disponibilità e aggiornamento anonimo del catalogo — su un tunnel Cloudflare WARP in userspace. Queste richieste non usano alcun proxy, quindi l'upstream vede l'indirizzo di uscita WARP invece del nodo configurato. Le chiavi del piano Go e i modelli a pagamento mantengono i loro proxy. +L'implementazione segue le versioni sorgente upstream elencate nella guida. È una descrizione del codice, non una verifica di autorizzazione o inferenza reale per ogni account: permessi e formati delle rotte possono cambiare. -Il tunnel vive nel processo del gateway: registra un dispositivo WARP, parla WireGuard su UDP con Cloudflare e termina in uno stack di rete in userspace. Non richiede dispositivi TUN, root, `NET_ADMIN` né modifiche alla tabella di routing, ma l'host o il container deve poter inviare UDP verso l'endpoint di Cloudflare (porta `2408`). Registrazione e probe del trace `warp=on` avvengono all'avvio; se WARP non riesce a inizializzarsi, l'avvio fallisce invece di ripiegare silenziosamente sui proxy. Anche l'abilitazione dalla WebUI è fail-closed: un valore errato restituisce un errore e il runtime precedente continua a servire. +### Chiavi locali, quota e rotazione -`warp.pool_size` (1–32, predefinito `2`) è un **limite massimo**, non un numero fisso. La prima uscita viene registrata in modo sincrono e determina la readiness; poi il pool registra in background metà del massimo (almeno una), così un picco trova uscite già calde senza attendere. Il ring attivo segue la concorrenza: un'uscita per ogni richiesta in corso più una di riserva, mai oltre il massimo; le uscite in eccesso rimaste inattive per 60 secondi vengono ritirate. La prima risposta 429 o 403 ritira subito l'uscita e una uscita pre-registrata ne prende il posto; una richiesta per modelli gratuiti continua a cambiare uscita e restituisce l'ultimo 429 al client solo dopo aver esaurito `retry.max_attempts`, mentre l'uscita ritirata viene registrata di nuovo subito in background. Le registrazioni restano serializzate; il 429/Retry-After di Cloudflare detta il ritmo al posto di un intervallo fisso. Se il colo assegna meno blocchi di uscita distinti del preload, il pool arretra invece di registrare all'infinito; le probe automatiche dei modelli gratuiti saltano un pool senza uscita di riserva e fermano il ciclo dopo che una probe ha ritirato un'uscita. `warp.stack` seleziona `ipv6` (predefinito), `ipv4` o `dual`. +La pagina delle chiavi crea, rinomina, abilita, disabilita ed elimina le chiavi locali. Quelle generate contengono 192 bit casuali. Le chiavi personalizzate ammettono 16–256 lettere, cifre, `.`, `_`, `-`; i nomi 1–80 caratteri, fino a 200 chiavi e almeno una abilitata. Le modifiche valgono subito per nuove richieste. Non ci sono permessi per modello, limiti di spesa o scadenze per chiave. -La quota gratuita dell'upstream è legata al **blocco di uscita**, quindi la rotazione serve solo se la nuova uscita proviene da un blocco diverso: un'uscita IPv6 è identificata e raffreddata per 30 minuti dal suo `/64`, una IPv4 dal suo `/32`. L'uscita IPv4 di Cloudflare WARP è di solito un unico indirizzo NAT condiviso, spesso già esaurito da altri utenti; lo stack IPv6 ricava l'uscita dall'indirizzo sorgente WireGuard esterno. Imposta `warp.source_ipv6` su un prefisso IPv6 instradato verso l'host (di solito un `/64`, lo stack predefinito è già `ipv6`) perché ogni uscita associ il proprio indirizzo sorgente da quel prefisso. Su Linux l'indirizzo viene associato con `IPV6_FREEBIND` (impostato dal gateway) oppure deve essere già assegnato a un'interfaccia. La famiglia degli endpoint non viene verificata in anticipo: l'handshake prova prima gli endpoint IPv6 e ripiega su quelli IPv4 quando nessuno risponde (in quel caso l'uscita è l'indirizzo condiviso). Lasciando vuoto il campo si usa l'indirizzo sorgente predefinito dell'host. Su reti con il pool di uscite WARP già saturo anche una nuova uscita può rispondere 429: il gateway continua a ruotare e restituisce un 429 solo esaurito il budget di tentativi. `/healthz` restituisce un blocco `warp` e risponde 503 quando WARP è attivo ma nessuna uscita è operativa; `no_healthy_proxies` blocca la readiness solo con WARP disattivato o quando servono proxy per le chiavi Go. Le richieste diagnostiche acquisiscono un'uscita ma non la ruotano né la penalizzano. Disattivando WARP, i canali gratuiti tornano a usare i proxy. +La quota delle chiavi Go manuali deriva da `/v1/usage` dell'upstream Go configurato: finestre condivise mobili, settimanali e mensili, non saldi per modello. Più chiavi possono condividere la stessa quota, quindi non sommare le percentuali. Cache: 60 secondi sui successi, 15 sugli errori; i dati precedenti sono segnalati come obsoleti. Quota/credits OAuth restano sconosciuti e non vengono dedotti da chiavi manuali o richieste riuscite. -### System prompt ufficiale +Gli alias `sota` e `sweet` usano modelli Go sui tre endpoint dei messaggi, anche in streaming. Ogni gruppo ha un modello corrente condiviso dal servizio: rimane dopo un successo e avanza dopo un errore. SOTA contiene `deepseek-v4.1-flash`, `glm-5.3`, `grok-4.6`, `kimi-k3`, `qwen3.8-max`; Sweet raccoglie gli altri modelli Go idonei. La disponibilità effettiva dipende dal rilevamento. Modifica alias, ordine e timeout del primo output in `/#rotation`. -Ogni richiesta di un modello gratuito già normalizzata porta il system prompt della CLI OpenCode — istruzioni di base, blocco `` ed elenco delle skill integrate — perché il canale gratuito verifica che il traffico abbia forma di agent. Il canale v1 `/zen` usa i nomi degli strumenti 1.x; `/inference` e `/zen/go` usano quelli 2.x. Il blocco ambiente indica il modello richiesto, la directory di lavoro del gateway, la piattaforma e la data UTC. +Il budget ordinario è di tre modelli, fino a tre tentativi ciascuno. Quota/rate limit passano direttamente al successivo; la rotazione non crea quota condivisa aggiuntiva. Dopo l'inizio effettivo dello stream, un errore termina la risposta e fa avanzare il gruppo per la richiesta seguente. `model` conserva l'alias, `X-Resolved-Model` indica il modello reale. Lo stato è salvato accanto alla configurazione. -L'iniezione dipende dal protocollo: i messaggi system e developer di Chat vengono fusi in un unico messaggio `system` iniziale; Anthropic riceve un valore `system` (stringa, oppure un blocco di testo iniziale quando il chiamante invia blocchi); Responses riceve `instructions`. Se il contenuto system contiene già il marcatore `You are opencode, an interactive CLI tool`, la richiesta passa invariata, quindi un client che invia già il prompt ufficiale non ne riceve una seconda copia. I modelli gratuiti serviti da una chiave Zen o Go ricevono la stessa normalizzazione, ma escono comunque dal proxy di quel tier. +## Esercizio e sicurezza -### Normalizzazione degli strumenti +Il salvataggio convalida e costruisce un nuovo runtime prima di applicarlo. Errori di validazione o persistenza mantengono quello attivo. Chiavi, proxy, rotte, modelli e log si applicano alle nuove richieste; listener e abilitazione WebUI richiedono riavvio. Dopo modifiche al file usa la ricarica nella UI o `POST /api/config/reload`: non esiste un monitor automatico del file. -Su ogni richiesta di un modello gratuito già normalizzata il gateway rinomina ogni strumento nominato del client in un nome opaco fatto di un prefisso di namespace più i primi 12 caratteri esadecimali dello SHA-256 del nome dello strumento — i caratteri fuori da `A-Za-z0-9_-` diventano `_`, i nomi sono limitati a 64 byte e le collisioni ricevono il suffisso `_2`, `_3`, … — e aggiunge l'intero set ufficiale del canale: le definizioni 1.x (`bash`, `edit`, `glob`, `grep`, `read`, `skill`, `task`, `todowrite`, `webfetch`, `websearch`, `write`) su `/zen` e il set di 13 strumenti 2.x su `/inference` e `/zen/go`. Le richieste senza `tools`, con un array vuoto o con il vecchio array `functions` ricevono lo stesso set; `tool_choice`, il vecchio `function_call` e la cronologia delle tool call vengono riscritti di conseguenza. Gli strumenti integrati di Responses e quelli server di Anthropic restano invariati. +| Dati | Memorizzazione | +| --- | --- | +| Configurazione e versione precedente | `config.json`, `config.json.bak`. | +| Cache modelli e metadati | `config.json.models.catalog.json`, `config.json.models.dev.json`. | +| Disponibilità e rotazione | `config.json..availability.json`, `config.json.rotation.json`. | +| Sessioni, uso, richieste/tentativi recenti, log circolari, ultimo Playground | Memoria; azzerati al riavvio del processo. | +| Log strutturati | JSON su stdout; occorre un raccoglitore per conservarli. | -Le risposte vengono riportate ai nomi dichiarati dal client, sia in streaming sia non, incluso un nome Chat suddiviso su più chunk. Se l'upstream chiama uno strumento ufficiale che il client non ha dichiarato, il nome passa invariato: il gateway non riproduce né nasconde le chiamate ufficiali. +I nomi derivano dal percorso di configurazione effettivo. Il monitoraggio sopravvive alla ricarica ma non è condiviso fra processi. I token sono quelli dichiarati dall'upstream; i dati mancanti non vengono stimati. Completamento delle richieste e tentativi fino agli header sono misure diverse. Playground ha un conteggio separato. Nell'ultima ora sono conservate al massimo 10.000 richieste/20.000 tentativi e l'API ne restituisce fino a 500 per tipo. -### Disponibilità dei modelli gratuiti +`GET /healthz` non chiama l'upstream e non richiede chiavi. Rilevamento in attesa/vuoto, WARP indisponibile o assenza di proxy sani necessari producono 503. Un catalogo obsoleto ma utilizzabile può restituire 200 e `status: "degraded"`; la soglia è due volte l'intervallo di aggiornamento, almeno 60 secondi. La disponibilità non certifica chiavi, quota o inferenza. La risposta pubblica include conteggi/stato, senza segreti o indirizzi proxy. -Il gateway verifica con una breve richiesta e il protocollo nativo i modelli il cui ID contiene `free` (senza distinzione tra maiuscole e minuscole) oppure i cui metadati indicano un costo input/output pari a zero e che non sono deprecati. Prova prima il canale anonimo abilitato, poi una chiave Zen configurata. Con `warp.enabled`, ogni canale di probe esce tramite WARP invece che da un proxy; se non è possibile acquisire un'uscita il risultato è `warp_unavailable` e resta inconcludente. Una risposta valida e completa su uno dei canali mantiene il modello abilitato. Il modello viene disabilitato nel rilevamento e nell'instradamento solo quando tutti i canali provati indicano esplicitamente che non esiste o è stato ritirato. Errori di autenticazione, limiti di frequenza, timeout, errori di trasporto, risposte 5xx e risposte malformate non sono conclusivi: non disabilitano nuovi modelli e vengono verificati di nuovo dopo un'ora. I controlli non alterano cooldown, stato dei proxy o statistiche delle richieste di produzione, ma raggiungono comunque l'upstream e possono consumare la quota gratuita. +Per uso locale limita API e gestione a loopback. Per accesso in rete usa HTTPS e limita l'ingresso amministrativo. Un reverse proxy fidato deve impostare correttamente `X-Forwarded-Proto`; i limiti usano il peer diretto, quindi i client dietro un proxy li condividono. L'eseguibile serve HTTP. -I modelli System One usano una domanda nativa `noul` che chiede se 1 + 1 è uguale a 2; non ricevono mai payload chat/tool. Il rilevamento dei modelli include `native_protocol` e `supported_endpoints`; gli alias di rotazione sono elencati solo quando esistono chiavi Go e modelli idonei. Le disabilitazioni legacy della versione v1.3.6 vengono cancellate al caricamento e verificate subito, perché quei controlli usavano ID sessione non validi. +Configurazione e backup contengono chiavi upstream, password proxy e token OAuth; l'hash della password non li cifra. Limita i permessi dei file, con ACL su Windows, ed escludi i file di runtime dalla condivisione del codice. `logging.dump_request_bodies` è disabilitato e richiede livello debug; i corpi possono rivelare conversazioni anche dopo riduzione e mascheramento. Playground e test attivi consumano potenzialmente quota o credits reali. -Gli intervalli sono fissi: i modelli abilitati vengono verificati ogni **1 ora**, quelli confermati non disponibili ogni **24 ore**. Una verifica inconclusiva di un modello disabilitato conserva il motivo originale e pianifica un nuovo tentativo dopo 24 ore. Una verifica riuscita riabilita il modello automaticamente. La pagina WebUI **Disponibilità modelli gratuiti** può ripristinarlo subito, mettendolo sotto controllo manuale: resta abilitato e viene escluso dai controlli automatici, così i risultati successivi non possono sovrascrivere la scelta. Usa l'interruttore per modello **manuale/automatico** nella stessa pagina per riprendere i controlli automatici; il tick successivo dello scheduler pianifica una verifica. I record `manually_enabled` delle versioni precedenti migrano al controllo manuale al caricamento. Un controllo già in corso non può annullare un ripristino manuale. I modelli senza un canale Zen/anonimo utilizzabile o senza un protocollo di inferenza supportato vengono ignorati. +## Sviluppo locale e verifiche -Il controllo manuale sospende anche il rilevamento dei livelli per `reasoning.effort=auto`; i livelli appresi smettono di essere forzati dopo due ore senza verifica. Tornando al controllo automatico, il rilevamento può riprendere. +`cmd/opencode2api` avvia il servizio. In `internal`, `admin` gestisce l'amministrazione, `gateway` rotte/runtime, `protocol` conversione JSON/SSE, `models` rilevamento, `oauth` autorizzazione ufficiale, `config` validazione/persistenza, `telemetry` metriche/log. Le risorse statiche sono in `webui`; non occorre installare pacchetti frontend. -Lo stato persiste tra i riavvii in `config.json..availability.json`, separato per URL upstream Zen. Lo scheduler in background verifica ogni minuto i modelli in scadenza, ignora quelli sotto controllo manuale e controlla gli altri in sequenza, con un timeout di 60 secondi per canale. Se non sono disponibili canali, non avviene alcuna disabilitazione automatica. - -Endpoint di amministrazione (richiede l'accesso; le scritture richiedono anche CSRF): `GET /api/models/availability`, `POST /api/models/restore` con `{"model":"MODEL_ID"}` (ripristina e attiva il controllo manuale) e `POST /api/models/manual` con `{"model":"MODEL_ID","manual":true|false}` per passare dal controllo manuale a quello automatico e viceversa. - -### Sessioni e proxy - -Inizialmente le chiavi vengono distribuite tra i proxy. Il traffico reale può avviare controlli dei proxy, riassegnazioni delle chiavi e cooldown. I proxy non integri vengono ricontrollati ogni 15 minuti tramite Cloudflare Trace. - -Un hash di sessione stabile seleziona la chiave o il proxy anonimo preferito. Invia un `x-session-id` esplicito per separare conversazioni indipendenti. Il gateway accetta anche `x-opencode-session`, `x-session-affinity`, `conversation-id`, `conversation_id` e `metadata.session_id`. - -Senza un ID esplicito, il primo messaggio dell'utente viene usato come seme. Conversazioni che iniziano con lo stesso contenuto possono quindi condividere l'affinità. Modificare i membri del pool può cambiare il nodo selezionato. - -I cooldown aumentano esponenzialmente fino a otto volte `performance.failure_cooldown_seconds`; viene rispettato anche un valore `Retry-After` più lungo. Se tutte le chiavi autenticate sono in cooldown, l'instradamento può provare quella il cui cooldown termina prima. I nodi anonimi ancora in cooldown vengono ignorati. - -## Riferimento della configurazione - -Consulta [config.example.json](config.example.json) per una configurazione iniziale completa. Il JSON supporta i commenti `//` e `/* ... */`; i campi sconosciuti e i valori non validi vengono rifiutati. - -### Chiavi, indirizzi di ascolto e instradamento - -| Campo | Predefinito / requisito | -| --------------------------- | ----------------------------------------------------------------------------- | -| `listen` | `127.0.0.1:8080`. | -| `server_keys` | È richiesta almeno una chiave locale. | -| `zen_keys`, `go_keys` | È richiesta una chiave upstream, salvo accesso anonimo abilitato. | -| `anonymous` | `false`. | -| `warp.enabled` | `false`; il traffico dei canali gratuiti esce via Cloudflare WARP, senza proxy. | -| `warp.pool_size` | `2`; limite massimo di uscite WARP (metà pre-registrata in background; il ring attivo segue la concorrenza), 1–32. | -| `warp.stack` | `ipv6`; `ipv6`, `ipv4` o `dual`. | -| `warp.source_ipv6` | vuoto; prefisso IPv6 (`/64`) da cui ogni uscita associa la sorgente esterna; richiede `stack = "ipv6"`. | -| `prefer` | `go`; accetta `go` o `zen`. | -| `upstream.zen` | `https://opencode.ai/inference/openai`. | -| `upstream.go` | `https://opencode.ai/zen/go`. | -| `proxies` | Fallback a `["direct"]` se entrambe le fonti proxy sono vuote. | -| `proxyfile` | Opzionale; i percorsi relativi sono risolti accanto al file di configurazione. | -| `models.refresh_seconds` | `300`; minimo 1. | -| `models.protocols` | `{}`; override del protocollo nativo per modello. | -| `models.free_only` | `false`; mostra e instrada solo modelli gratuiti, anche con chiavi Zen o Go. | -| `reasoning.effort` | Vuoto (disattivato); `minimal`, `low`, `medium`, `high`, `xhigh`, `max` o `none`. | -| `reasoning.effort_by_model` | `{}`; override di `reasoning.effort` per modello. | - -### Livello di ragionamento forzato - -`reasoning.effort` imposta il livello usato dall'upstream quando la richiesta non ne specifica uno; `reasoning.effort_by_model` lo sovrascrive per gli ID indicati. Si applica a tutti e tre i protocolli e in entrambe le direzioni di conversione. È particolarmente utile per il traffico tra protocolli: `thinking.budget_tokens` di Anthropic può essere approssimato solo dalle interfacce Chat e Responses, quindi un livello forzato può raggiungere un livello che il solo budget non esprime. - -```json -{ - "reasoning": { - "effort": "high", - "effort_by_model": { "claude-opus-5": "max" } - } -} -``` - -Le disattivazioni esplicite del client restano attive durante la conversione tra protocolli: `thinking.type="disabled"` nativo di Anthropic e l'effort `"none"` di Chat/Responses non possono essere riattivati da un valore predefinito configurato. - -I livelli vengono riportati fedelmente in entrambe le direzioni. Un `output_config.effort` esplicito sopravvive alla conversione e non viene sovrascritto da un blocco `thinking`; `budget_tokens` conserva il proprio livello (`8192` corrisponde a `high`, `32000` a `xhigh`), e la destinazione Responses trasporta il livello in `reasoning.effort`. - -Il Centro configurazione WebUI espone gli stessi campi predefiniti e per modello. L'API di gestione li restituisce in `reasoning` da `GET /api/config` e accetta l'oggetto con `PUT /api/config`; se il client omette il campo, il valore esistente resta invariato, mentre un oggetto vuoto lo cancella. - -Le voci proxy accettano `direct`, `http://`, `https://`, `socks5://` e `socks5h://`, incluse credenziali nell'URL. L'elenco inline viene unito a `proxyfile` e deduplicato mantenendo l'ordine. - -Un file proxy contiene una voce per riga e supporta righe vuote e commenti: - -```text -# Proxy principale -http://user:password@127.0.0.1:7890 -socks5://127.0.0.1:1080 # Proxy di riserva -direct -``` - -I marcatori di commento sono `#`, `;` e `//` all'inizio della riga o dopo uno spazio. - -#### Pool di proxy rotanti - -Aggiungi il suffisso `#pool` (o il prefisso `pool+`) a una voce per indicare un pool di proxy rotante come [Resin](https://github.com/Resinat/Resin), in cui ogni nuova connessione TCP esce da un IP diverso: - -```text -http://127.0.0.1:7890#pool -socks5://127.0.0.1:1080#pool -pool+http://127.0.0.1:7891 -``` - -Una voce pool viene gestita diversamente da un proxy statico: - -| Comportamento | Proxy statico | Voce `#pool` | -| ------------------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------------- | -| Riutilizzo connessioni | Keep-alive e multiplexing HTTP/2 (impostazioni `performance.*`) | Nuovo tunnel TCP + CONNECT per richiesta (`DisableKeepAlives`, senza HTTP/2) | -| Cooldown dopo un errore | Backoff esponenziale 15–120 s, esteso da `Retry-After` | Nessuno: la richiesta successiva usa un nuovo IP di uscita | -| Esclusione per stato | Segnalato come non integro, chiavi riassegnate, verifica ogni 15 min | Mai escluso; il controllo di integrità viene saltato | -| Retry del canale anonimo | Al massimo un tentativo per proxy configurato | Fino a `retry.max_attempts`, ruotando la voce del pool | - -Usalo quando l'endpoint dietro l'URL esegue già la rotazione e i singoli IP di uscita sono soggetti a limiti o instabilità. Il gateway tratterà ogni tentativo come un endpoint nuovo invece di fissare la conversazione a un solo IP. Basta una voce `#pool`: non serve elencare decine di indirizzi. Le voci statiche mantengono il comportamento del pool di connessioni descritto sotto. - -### Timeout e pool di connessioni - -| Campo | Predefinito | Descrizione | -| ------------------------------------------ | ----------- | ---------------------------------------------------------- | -| `retry.max_attempts` | `3` | Tentativi per tier autenticato, incluso il primo. | -| `retry.timeout_seconds` | `300` | Timeout totale di inferenza, compreso lo stream. | -| `performance.attempt_timeout_seconds` | `0` | Limite per tentativo; 0 usa il timeout della richiesta. | -| `performance.connect_timeout_seconds` | `5` | Timeout per stabilire la connessione. | -| `performance.failure_cooldown_seconds` | `15` | Cooldown di errore di base. | -| `performance.max_idle_conns` | `2048` | Limite connessioni inattive per trasporto proxy. | -| `performance.max_idle_conns_per_host` | `256` | Limite connessioni inattive per host e trasporto. | -| `performance.max_conns_per_host` | `0` | Limite connessioni per host; 0 significa illimitato. | -| `performance.idle_conn_timeout_seconds` | `120` | Durata delle connessioni inattive. | - -Il timeout degli header per tentativo è limitato dal timeout della richiesta. Impostalo sotto il timeout totale se vuoi lasciare tempo per il fallback in caso di upstream lento. La scadenza del contesto della richiesta interrompe i tentativi successivi senza penalizzare chiavi o proxy non usati. - -### Log e gestione - -| Campo | Predefinito / requisito | -| ----------------------------- | -------------------------------------------------------- | -| `logging.level` | `info`; accetta `debug`, `info`, `warn`, `error`. | -| `logging.ring_size` | `2000`; intervallo 100–50.000. | -| `logging.dump_request_bodies` | `false`; richiede il livello `debug` per emettere i body in uscita. | -| `webui.enabled` | `false` se omesso; la configurazione di esempio usa `true`. | -| `webui.listen` | `0.0.0.0:8081`. | -| `webui.username` | Obbligatorio con WebUI attiva; l'esempio usa `admin`. | -| `webui.password` | Password iniziale, almeno 10 caratteri. | -| `webui.password_hash` | Hash Argon2id generato, sostituisce la password in chiaro. | -| `webui.session_ttl_minutes` | `720`; intervallo 5–10.080. | - -All'avvio, la password iniziale viene sottoposta a hash e rimossa dalla configurazione. Il backup che contiene la password in chiaro viene eliminato. Proteggi i file di configurazione e i backup: le chiavi upstream e le credenziali proxy restano segreti necessari. - -I dump dei body sono opzionali e limitati a 64 KiB per body preparato. I segreti configurati vengono oscurati, ma il contenuto delle conversazioni può essere sensibile. - -## WebUI e diagnostica - -Il listener di gestione serve la UI e le route `/api/*`. L'autenticazione usa un account amministratore, sessioni lato server, cookie HttpOnly/SameSite, controlli CSRF per le scritture e limitazione dei tentativi di accesso. - -| Route di gestione | Scopo | -| -------------------------------------------------- | ---------------------------------------------------------------------- | -| `POST /api/auth/login` | Accesso e ottenimento del cookie di sessione e del token CSRF. | -| `GET /api/auth/session`, `POST /api/auth/logout` | Verifica o chiusura della sessione. | -| `GET /api/config`, `PUT /api/config` | Lettura della configurazione mascherata o applicazione delle modifiche. | -| `POST /api/config/reload` | Ricaricamento del file dal disco. | -| `POST /api/config/reveal` | Visualizzazione dei segreti configurati dopo verifica della password. | -| `PUT /api/account` | Aggiornamento delle credenziali dopo la verifica; invalida le sessioni. | -| `GET /api/monitor` | Statistiche su richieste, token, upstream e risorse. | -| `GET /api/debug/models` | Route dei modelli, impronte delle chiavi e diagnostica dei metadati. | -| `POST /api/debug/inference` | Esecuzione di una richiesta Playground. | -| `GET /api/logs`, `GET /api/logs/stream` | Log recenti o iscrizione SSE in tempo reale. | - -Le richieste Playground richiedono una sessione e `X-CSRF-Token`; il limite è 12 al minuto per IP client: - -```json -{ - "protocol": "chat", - "key": { "mode": "auto" }, - "request": { - "model": "MODEL_ID", - "messages": [{ "role": "user", "content": "Hello" }] - } -} -``` - -Il server forza `stream: false`. Usa `{"mode":"selected","tier":"zen","id":"KEY_FINGERPRINT"}` per provare una chiave specifica di `/api/debug/models`. Una richiesta con chiave selezionata esegue al massimo un tentativo upstream, senza accesso anonimo, rotazione delle chiavi, fallback di tier o ripetizione del ragionamento. - -**Le diagnostiche automatiche e quelle con chiave selezionata preservano cooldown, conteggi di errore, stato dei proxy e associazioni delle chiavi di produzione.** Inviano comunque richieste reali all'upstream, possono consumare la quota del provider e compaiono nel monitoraggio. - -Al termine, l'endpoint di gestione restituisce HTTP 200 e il risultato effettivo nei campi `ok`, `http_status`, `request_id`, `route` e `response`. I risultati con chiave selezionata includono anche `selected_key` e `key_test`: `usable`, `rejected`, `rate_limited`, `transport_error`, `upstream_error`, `request_error` o `unavailable`. Input di gestione non validi, errori di autenticazione o CSRF e richieste limitate mantengono i rispettivi codici HTTP di errore. - -### Lingua dell'interfaccia - -La WebUI carica le traduzioni da `webui/js/i18n.js`. Include **简体中文** (predefinito), **English**, **Tiếng Việt** e **Italiano**. I testi originali in cinese semplificato restano in `index.html` e `webui/js/` e vengono usati come fallback per ogni stringa non tradotta; aggiungere una lingua non modifica quindi il testo originale. - -- Il selettore si trova nella barra superiore e nella scheda di accesso. -- La scelta è salvata in `localStorage` con la chiave `opencode2api.ui.lang`. -- Il cambio lingua aggiorna i testi statici (`data-i18n`, `data-i18n-attr`) e quelli generati da JavaScript senza ricaricare la pagina. -- Date e orari seguono la lingua selezionata. - -Per aggiungere una lingua, inserisci un blocco in `DICTIONARY` in `webui/js/i18n.js`, registra il codice in `SUPPORTED`, `LABELS`, `FLAGS` e `DATE_LOCALES` e aggiungilo alla catena di rilevamento `browserLocale`. - -### Salvataggio e ricaricamento - -Il server convalida una configurazione candidata e prepara un gateway sostitutivo prima di salvare e attivare le modifiche. Se la convalida o il salvataggio falliscono, il gateway attivo resta invariato. Le richieste già in corso continuano sul gateway originale. - -Chiavi, proxy, URL upstream, retry, impostazioni dei modelli, log e preferenze di instradamento si applicano subito alle nuove richieste. Le modifiche a `listen`, `webui.listen` o `webui.enabled` richiedono il riavvio del processo. Il JSON salvato è normalizzato e non conserva i commenti. - -## Monitoraggio e persistenza - -L'esito di una richiesta descrive l'inferenza completata. Una risposta SSE non riuscita o uno stream troncato viene conteggiato come errore anche se HTTP 200 è già stato inviato; l'esito è `stream_error`. L'annullamento da parte del client viene registrato come `client_canceled`. La WebUI mostra questi esiti insieme al codice di stato HTTP. - -I record dei **tentativi** upstream misurano lo scambio HTTP fino alla ricezione degli header della risposta. Esito e latenza sono separati dal completamento dell'intero body JSON o dello stream. - -Le statistiche dei token usano solo i valori riportati. I token input includono letture e scritture della cache; i token cache separati contano le letture. I valori mancanti non vengono stimati; la copertura indica quante richieste di inferenza instradate riportano l'utilizzo. `usage.server_keys` suddivide richieste e token in base alla chiave server locale usata per l'autenticazione (la relativa impronta è mostrata in `/api/api-keys`); il traffico Playground è conteggiato sotto `playground`. - -| Dati | Memorizzazione / conservazione | -| -------------------------------------------------------- | ------------------------------------------------------------------------------------ | -| Sessioni, metriche, totali token, ultimo risultato Playground | Memoria del processo; cancellati al riavvio. | -| Dettagli di richieste e tentativi | Ultima ora, massimo 10.000 richieste e 20.000 tentativi; API fino a 500 per tipo. | -| Buffer circolare dei log | Memoria del processo; dimensione impostata da `logging.ring_size`. | -| Log strutturati | JSON su stdout; raccoglili esternamente per conservarli. | -| Configurazione e versione precedente | `config.json` e `config.json.bak`. | -| Cache del catalogo modelli | `config.json.models.catalog.json`. | -| Cache prezzi/deprecazioni | `config.json.models.dev.json`. | - -I nomi dei file di cache dipendono dal percorso effettivo della configurazione. I contatori di durata si riferiscono al processo corrente. Le istanze non condividono sessioni o stato di monitoraggio. - -### Health check - -`/healthz` non incrementa i contatori di monitoraggio né avvia richieste di rete. Riporta il numero di risorse senza esporre chiavi o indirizzi proxy. - -- HTTP 503: catalogo iniziale ancora in attesa, nessun modello instradabile con la configurazione attuale oppure nessun proxy integro. -- HTTP 200: servizio pronto, anche se una cache del catalogo utilizzabile è obsoleta. In questo caso lo stato del modello è `stale` e lo stato complessivo è `degraded`. - -La soglia di obsolescenza è il doppio di `models.refresh_seconds`, con un minimo di 60 secondi. Il controllo verifica rilevamento e risorse; non verifica se una chiave upstream accetterà la prossima inferenza. - -## Sviluppo - -Il codice Go è organizzato in package per responsabilità. Il comando collega i componenti del servizio; i package di implementazione si trovano sotto `internal/`. - -```text -cmd/ - opencode2api/main.go Flag CLI, avvio e arresto graduale -internal/ - admin/ API di gestione, sessioni di accesso e Playground - buildinfo/ Versione condivisa da health check e API di gestione - config/ Configurazione, persistenza, password e oscuramento - gateway/ Instradamento HTTP, retry, pool, aggiornamenti e runtime - httpx/ Risposte HTTP condivise, gestione dei body e header - identity/ ID richiesta e affinità di sessione - jsonutil/ Accesso e decodifica JSON - models/ Catalogo modelli, capacità, prezzi e cache - protocol/ Conversione richieste/risposte e parsing/emissione SSE - telemetry/ Tracciamento richieste, metriche, log e recupero -webui/ - embed.go Incorpora le risorse statiche nell'eseguibile - index.html Struttura delle pagine - css/ Token di design, stili base, componenti e layout - js/ Moduli ES: shell, i18n, helper condivisi e un modulo per pagina -``` - -Ordine di lettura consigliato: - -1. [Punto di ingresso](cmd/opencode2api/main.go) → [gestione runtime](internal/gateway/runtime.go) → [handler HTTP](internal/gateway/gateway.go). -2. [Tentativi upstream](internal/gateway/upstream.go) e [instradamento modelli](internal/models/catalog.go) spiegano come una richiesta raggiunge il provider. -3. [Conversione richieste](internal/protocol/request.go), [conversione risposte](internal/protocol/response.go) e [trasporto streaming](internal/protocol/stream.go) descrivono il comportamento dei protocolli. -4. [Route di gestione](internal/admin/server.go) e [logica WebUI](webui/js/main.js) trattano configurazione e diagnostica. - -Esegui formattazione, analisi e build Go: +In un normale ambiente di sviluppo usa questi comandi nativi. Per cache nel progetto, imposta `GOCACHE` e `GOMODCACHE` su directory persistenti locali: ```bash -gofmt -w cmd internal webui go vet ./... -go build -o opencode2api ./cmd/opencode2api +go build -trimpath -o opencode2api ./cmd/opencode2api ``` -Per lo sviluppo locale, avvia il servizio con `go run ./cmd/opencode2api -config config.json`. Le build di release iniettano la versione con `-ldflags "-X main.version=vX.Y.Z"`. - -Node.js serve solo per controllare la sintassi JavaScript della WebUI: +Node.js serve soltanto per il controllo facoltativo della sintassi JavaScript, senza installazione di pacchetti. In Bash, oppure Git Bash su Windows: ```bash -for f in webui/js/*.js webui/js/pages/*.js; do node --input-type=module --check < "$f"; done +for file in webui/js/*.js webui/js/pages/*.js; do + node --input-type=module --check < "$file" || exit 1 +done ``` -`.editorconfig`, `.gitattributes` e la formattazione Go standardizzano il codice. La CI esegue `go vet` e build con Go 1.24 e la versione stabile su Linux/Windows, oltre ai controlli di formattazione Go, sintassi WebUI e sintassi shell dell'entrypoint. Gli archivi di release includono tutti e quattro i README. +Esegui i controlli in Bash; su Windows puoi usare Git Bash. Per le verifiche prima della distribuzione consulta [Verifica e manutenzione](docs/management.it.md#verifica-e-manutenzione). La versione di rilascio si inietta con `-ldflags "-X main.version=vX.Y.Z"`. -## Risoluzione dei problemi +| Sintomo | Cosa controllare | +| --- | --- | +| API 401 | Chiave locale, abilitazione e header del client. | +| Avvio senza credenziali | Configurare chiavi/OAuth salvato o abilitare consapevolmente l'anonimo. | +| Nessun modello / health 503 | Catalogo, protocolli supportati, credenziali configurate e risorse. | +| Errori OAuth | Stato sicuro dell'account e necessità di nuovo login; nessun ripiego automatico PAYG. | +| HTTP 200 ma generazione fallita | Eventi SSE, esito e log `x-request-id`. | +| Modifiche senza effetto | Salvare/ricaricare il file attivo; riavviare per i listener. | +| Modifiche host senza effetto in Compose | Il file attivo è nel volume di stato; importarlo di nuovo o usare la WebUI. | +| Uso azzerato al riavvio | I contatori sono in memoria; conservare i log separatamente. | -| Sintomo | Verifica | -| ---------------------------------------- | ---------------------------------------------------------------------------------------- | -| L'API restituisce 401 | Usa un valore `server_keys` locale configurato. | -| Health resta `starting` | Controlla i log di aggiornamento del catalogo e la connettività in uscita; aggiungi override di protocollo se necessario. | -| Non vengono esposti modelli | Verifica i tier configurati, l'idoneità anonima e il supporto del protocollo nativo. | -| Le richieste restituiscono 502/504 | Controlla tentativi upstream, credenziali, proxy e timeout totali/per tentativo. | -| HTTP 200 ma generazione non riuscita | Controlla l'evento di errore SSE e l'esito della richiesta, non solo lo stato HTTP. | -| Le modifiche host non hanno effetto in Docker | Il file attivo è nel volume di stato; importalo di nuovo o usa la WebUI. | -| Le porte del container non sono raggiungibili | Controlla indirizzi di ascolto, porte pubblicate e configurazione del volume attivo. | -| Il monitoraggio scompare dopo il riavvio | È conservato solo in memoria; raccogli esternamente i log stdout. | +Prima dell'aggiornamento salva in modo sicuro eseguibile, configurazione e stato. Arresta il processo per sostituire il programma; per tornare indietro ripristina versioni compatibili di tutti e tre. ## Ringraziamenti Grazie alla community [LINUX DO](https://linux.do) per il supporto. -### Livello di ragionamento adattivo - -Imposta `reasoning.effort` (o un override per modello) su `auto` per usare il livello più alto verificato con successo dal controllo dei modelli gratuiti. I livelli concreti mantengono il proprio significato e il livello specificato dal client ha la precedenza. Non viene mantenuta una lista di modelli consentiti. - -Dopo il successo di un livello di base, i modelli con capacità di ragionamento vengono verificati nell'ordine `max`, `xhigh`, `high`, `medium`, `low`, `minimal`. Si passa a un livello inferiore solo se un parametro di ragionamento viene rifiutato esplicitamente. Gli errori transitori interrompono la ricerca e non vengono interpretati come un limite di capacità inferiore. Se tutti i livelli vengono rifiutati, non viene applicato alcun override di ragionamento. - -Le osservazioni sono persistite per URL upstream, modello e protocollo nativo, mostrate nella pagina di disponibilità e usate per non più di due ore. I controlli attivi coprono solo modelli Zen/anonimi gratuiti; modelli Go/a pagamento, capacità sconosciute e livelli non verificati non ricevono override automatici. Impostare `auto` non amplia l'ambito dei controlli e non garantisce che gli upstream applichino ogni campo accettato. Il controllo può richiedere diverse piccole richieste per modello e consumare la quota upstream. - ## Licenza -SPDX-License-Identifier: GPL-3.0-or-later - -Questo progetto è software libero: puoi ridistribuirlo e modificarlo secondo la GNU General Public License pubblicata dalla Free Software Foundation, versione 3 o, a tua scelta, una versione successiva. Il software è fornito senza garanzie. Consulta [LICENSE](LICENSE) per i termini completi. +SPDX-License-Identifier: GPL-3.0-or-later. Termini completi in [LICENSE](LICENSE). Il software è fornito senza garanzia. diff --git a/README.md b/README.md index 2c35f27..aa74c49 100644 --- a/README.md +++ b/README.md @@ -2,26 +2,9 @@ [English](README.md) | [简体中文](README.zh-CN.md) | [Tiếng Việt](README.vi.md) | [Italiano](README.it.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. +A Go gateway for OpenCode Zen and Zen Go. Clients use OpenAI Chat Completions, OpenAI Responses, or Anthropic Messages; the gateway selects an available upstream and converts the request and response when the native protocol differs. System One decisions have a separate pass-through endpoint. -The executable includes the WebUI. Running the service requires no Node.js runtime or database. - -## Capabilities - -- JSON and SSE responses across all three inference protocols. -- Text, images, reasoning, function tools, tool calls, and tool results; file content where the target protocol can represent it. -- Separate Zen and Go key pools, configurable tier preference, retries, and session affinity. -- Opt-in anonymous Zen access with the OpenCode `public` credential; disabled by default because upstream blocking can make it unavailable. -- Optional userspace Cloudflare WARP egress for free-model traffic, without TUN or root. -- Direct, HTTP, HTTPS, SOCKS5, and SOCKS5H connections, including a proxy file. -- Dynamic model discovery, native protocol metadata, and disk caches. -- A separate management port with configuration editing, a Playground, diagnostics, token statistics, and live logs. -- Configuration hot reload with validation before switching new requests to a replacement gateway. -- Go subscription quota dashboard with remaining percentages, reset times, and available models. -- Local API key creation, naming, enabling, disabling, and deletion with immediate updates. -- Sticky `sota` / `sweet` model groups with ordering, failure fallback, streaming protection, and persisted state. - -See the [management console guide (Chinese)](docs/management.zh-CN.md) for the new pages and configuration. +The executable embeds the management WebUI. Running it requires neither Node.js nor a database. Model discovery, inference, OAuth, and optional WARP still require access to their upstream services. ## Sponsors @@ -53,7 +36,7 @@ go build -o opencode2api ./cmd/opencode2api Before starting, edit `config.json`: 1. Replace `server_keys` with your own local API key. -2. Supply a Zen API Key in `zen_keys` (recommended), or a Go key in `go_keys`. The example leaves both arrays empty and disables anonymous access, so configure an upstream credential before starting. An existing Go subscription connection also satisfies this requirement. +2. Supply a Zen API Key in `zen_keys` (recommended), or a Go key in `go_keys`. The example leaves both arrays empty and disables anonymous access, so configure an upstream credential before starting. An already saved Go OAuth (`go_oauth`) or Zen OAuth (`zen_oauth`) connection also satisfies this requirement; starting from empty credentials solely to open the OAuth WebUI is not supported. 3. Replace `webui.password`. The example enables the WebUI with username `admin`. **Anonymous traffic may be heavily blocked upstream. Prefer a Zen API Key.** Anonymous access is off by default in the configuration and WebUI; existing configurations that explicitly set `anonymous: true` keep that choice. Enable it deliberately only if you accept that free requests may still fail. @@ -76,583 +59,268 @@ Command-line options: The configuration directory must be writable for password migration, configuration saves, and model caches. -## Docker +## Docker and Compose -The published image is `ghcr.io/jasonxu114514/opencode2api`. +The published image is `ghcr.io/jasonxu114514/opencode2api`. Prepare `config.json` as above before starting. For published container ports, keep the internal API/WebUI listeners on `0.0.0.0:8080` and `0.0.0.0:8081`; restrict access using host-side port bindings and HTTPS where needed. ```bash -cp config.example.json config.json -# Configure keys and replace the WebUI password before starting. docker compose up -d docker compose logs -f ``` -Compose imports the host configuration into the `opencode2api-state` volume **only on first startup**. Subsequent changes should be made through the WebUI. To import an edited host configuration again: +Compose seeds `opencode2api-state` from the host configuration **only on first startup**. Later, the active configuration lives in that volume; use the WebUI for changes. To import an edited host file again: ```bash docker compose cp config.json opencode2api:/var/lib/opencode2api/config.json docker compose restart ``` -The container runs the service as an unprivileged user. Compose uses a read-only root filesystem, a writable state volume, and a temporary `/tmp` filesystem. +Back up the active configuration and state before replacing them. The entrypoint runs the service as an unprivileged user and changes the exact example API listener `127.0.0.1:8080` to `0.0.0.0:8080` only while seeding. Compose uses a read-only root filesystem, a writable state volume, and a `/tmp` tmpfs. Default published ports bind on all host interfaces; edit `ports` to use `127.0.0.1:8080:8080` and `127.0.0.1:8081:8081` for local access only. -WARP needs only outbound UDP (Cloudflare endpoint port `2408`), so the image's non-root, no-`NET_ADMIN` setup still works; do not switch to host networking or add `--cap-add` for it. If the container network blocks UDP, enabling WARP fails at startup. +| Compose variable | Default | Effect | +| --- | --- | --- | +| `OPENCODE2API_VERSION` | `latest` | Image tag; pin a release tag for a fixed version. | +| `OPENCODE2API_PORT` | `8080` | Published host API port. | +| `OPENCODE2API_WEBUI_PORT` | `8081` | Published host management port. | +| `OPENCODE2API_LISTEN` | Unset | Explicit container API listener override. | +| `OPENCODE2API_WEBUI_LISTEN` | Unset | Explicit container management listener override. | -| Compose variable | Default | Effect | -| --------------------------- | -------- | ------------------------------------------------- | -| `OPENCODE2API_VERSION` | `latest` | Image tag. Pin a release tag for a fixed version. | -| `OPENCODE2API_PORT` | `8080` | Host port mapped to container port 8080. | -| `OPENCODE2API_WEBUI_PORT` | `8081` | Host port mapped to container port 8081. | -| `OPENCODE2API_LISTEN` | Unset | Explicit container API listen override. | -| `OPENCODE2API_WEBUI_LISTEN` | Unset | Explicit container WebUI listen override. | +The last two become `LISTEN_ADDRESS` and `WEBUI_LISTEN_ADDRESS` in the container. Empty values defer to the active config. Changing host ports does not change internal listeners. If the internal API port changes, update both the port mapping and image health check, which uses 8080. A `proxyfile` must be mounted at its configured container path. -The last two variables become `LISTEN_ADDRESS` and `WEBUI_LISTEN_ADDRESS` inside the container. Empty values defer to the configuration file. While initializing a configuration, the entrypoint changes the example API address `127.0.0.1:8080` to `0.0.0.0:8080` so published ports can reach it. - -Changing host ports does not change container listeners. If you change the internal API port, also update the port mapping and the image health check, which uses port 8080. - -For a local image: +Build and run a local image if needed: ```bash docker build -t opencode2api:local . docker volume create opencode2api-state docker run -d --name opencode2api \ - -p 8080:8080 -p 8081:8081 \ + -p 127.0.0.1:8080:8080 -p 127.0.0.1:8081:8081 \ -e CONFIG_SEED_PATH=/run/config/opencode2api.json \ - -v "$(pwd)/config.json:/run/config/opencode2api.json:ro" \ + -v "$PWD/config.json:/run/config/opencode2api.json:ro" \ -v opencode2api-state:/var/lib/opencode2api \ opencode2api:local ``` -A `proxyfile` used in Docker must also be available inside the container at the configured path. +WARP needs outbound UDP to Cloudflare port `2408`; the image does not need host networking or additional network capabilities. A network that blocks this traffic prevents WARP initialization. -## API usage +## Call the API -`server_keys` authenticate clients to this gateway. They are separate from `zen_keys` and `go_keys` and are never used as upstream credentials. +The following are the existing compatibility routes. Set an OpenAI-compatible client's base URL to `http://127.0.0.1:8080/v1`; management uses its separate listener. -Send `Authorization: Bearer YOUR_LOCAL_API_KEY` or `x-api-key: YOUR_LOCAL_API_KEY`. Health checks require no authentication. +| Method | Path | Behavior | +| --- | --- | --- | +| `GET` | `/v1/models` | Models routable with the current configuration, including eligible rotation aliases. | +| `POST` | `/v1/chat/completions` | Chat Completions, JSON or SSE. | +| `POST` | `/v1/responses` | Responses, JSON or SSE. | +| `POST` | `/v1/messages` | Anthropic Messages, JSON or SSE. | +| `POST` | `/v1/systemone` | Native System One decisions, without protocol translation. | +| `GET` | `/healthz` | Unauthenticated readiness and resource summary. | -| Method | Path | Description | -| ------ | ---------------------- | --------------------------------------------------------- | -| GET | `/v1/models` | Models that can be routed with the current configuration. | -| POST | `/v1/chat/completions` | Chat Completions. | -| POST | `/v1/responses` | Responses. | -| POST | `/v1/messages` | Anthropic Messages. | -| POST | `/v1/systemone` | System One structured decisions. | -| GET | `/healthz` | Readiness and resource summary. | +All `/v1/*` routes require an enabled `server_keys` value in `Authorization: Bearer ...` or `x-api-key`. Requests are limited to 32 MiB. Inference responses carry `x-request-id` for log correlation. -Discover an available model first: +Discover the actual model IDs before making a request: ```bash -curl http://localhost:8080/v1/models \ - -H "Authorization: Bearer YOUR_LOCAL_API_KEY" -``` +curl http://127.0.0.1:8080/v1/models \ + -H 'Authorization: Bearer YOUR_LOCAL_API_KEY' -Replace `MODEL_ID` below with an ID from that response. - -**Chat Completions** - -```bash -curl http://localhost:8080/v1/chat/completions \ - -H "Authorization: Bearer YOUR_LOCAL_API_KEY" \ - -H "Content-Type: application/json" \ +curl http://127.0.0.1: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** +Use these standard JSON bodies with the corresponding endpoint: + +```json +{"model":"MODEL_ID","input":"Hello"} +``` + +```json +{"model":"MODEL_ID","max_tokens":512,"messages":[{"role":"user","content":"Hello"}]} +``` + +The first body is for Responses, the second for Anthropic Messages. Anthropic clients may also send `anthropic-version: 2023-06-01`. For SSE, add `"stream": true` and use `curl -N` or another client that consumes events as they arrive. A stream can fail after HTTP 200; inspect its error events and final outcome. + +System One requires a model whose `native_protocol` is `systemone`, with a decision body such as: + +```json +{"model":"SYSTEM_ONE_MODEL_ID","state":"1 + 1 = 2","questions":{"arithmetic":{"type":"noul","instructions":"Is 1 + 1 equal to 2?"}}} +``` + +It forwards the decision body and answer without conversion. The message endpoints also recognize this decision shape for a System One model; ordinary chat messages cannot be converted into decisions. An upstream System One stream is relayed without stream-reset recovery. + +### Compatibility limits + +The three message protocols support text, representable image/file content, reasoning, function definitions, tool calls, tool results, and streaming. Native requests preserve provider-specific fields where the gateway does not deliberately shape them. Cross-protocol conversion only carries fields with a supported equivalent; for example, Chat `seed` and JSON output constraints are not translated into Anthropic options. Unsupported content or tools can produce a validation error. + +Responses assistant reasoning, text, and function-call items are grouped into assistant turns when converted. User messages and tool results separate turns; incomplete or unmatched tool results remain errors when converting to Chat Completions. + +The gateway does not implement embeddings, file uploads, image generation, or Responses retrieval/cancellation. It does not store conversation history for clients. Supply the history in requests; upstream stateful features are not a promise of local session storage. + +## Configuration and routing + +[config.example.json](config.example.json) is the configuration reference to start from. File input permits `//` and `/* ... */` comments; API request bodies require standard JSON. Unknown fields, invalid values, repeated top-level fields, and conflicting old/new OAuth fields are rejected. Saving normalizes the configuration and removes comments. + +| Setting | Default / meaning | +| --- | --- | +| `server_keys` | At least one enabled local key is required. | +| `zen_keys`, `go_keys` | Independent upstream key pools; empty in the example. | +| `prefer` | `go`; selects the preferred available authenticated tier, or `zen`. | +| `anonymous` | `false`; enables the upstream `public` credential for eligible free models. | +| `upstream.zen` | `https://opencode.ai/zen` for manual Zen keys. | +| `upstream.go` | `https://opencode.ai/zen/go` for manual Go keys and their usage endpoint. | +| `upstream.anonymous` | `https://opencode.ai/inference` for anonymous traffic. | +| `models.refresh_seconds` | `300`; model discovery interval. | +| `models.protocols` | Per-model native-protocol overrides: `chat`, `responses`, `anthropic`, or `systemone`. | +| `models.free_only` | `false`; filters both model discovery and routing to free models. | +| `models.active_probes` | `false`; optional synthetic free-model inference probes. | +| `reasoning.effort` | Unset in built-in defaults; the example sets `high`. | +| `reasoning.effort_by_model` | Per-model override of the default effort. | + +### Models and upstream selection + +Discovery combines upstream model lists with the OpenCode capability and price catalog at `https://models.opencode.ai/api.json`. It tracks native protocols per tier and exposes available context/token limits, prices, `native_protocol`, `supported_endpoints`, and reasoning metadata through `/v1/models`. Price/deprecation metadata refreshes every 24 hours; failed refreshes retain existing data. Prices are metadata, not a billing estimate or account balance. + +With manual keys, eligible free models can first use the anonymous lane when explicitly enabled, then the available keyed tiers in `prefer` order. Without anonymous access they use configured keys. Free eligibility comes from a case-insensitive `free` in the model ID or non-deprecated metadata with zero input and output cost; eligibility does not guarantee acceptance upstream. Paid models require an appropriate authenticated route. `models.free_only` also filters members of rotation groups. + +OAuth routes follow separate rules: the selected OAuth tier owns the request, uses only its confirmed routes, and does not fall back to anonymous traffic, manual keys, or another tier after failure. Selecting Go OAuth never triggers a PAYG request on authorization failure, quota exhaustion, or 429. When both tiers serve a model, explicitly choosing `prefer: "zen"` permits the connected Zen PAYG route. + +### Timeouts, proxies, and affinity + +| Setting | Default | Meaning | +| --- | --- | --- | +| `retry.max_attempts` | `3` | Retry budget for keyed loops; anonymous and rotation paths have their own selection rules. | +| `retry.timeout_seconds` | `300` | Whole inference budget, including stream consumption. | +| `performance.attempt_timeout_seconds` | `0` | Optional shorter attempt bound; zero leaves the request timeout. | +| `performance.first_event_timeout_seconds` | `0` | Optional first-event wait; zero disables it. | +| `performance.connect_timeout_seconds` | `5` | Connection establishment timeout. | +| `performance.failure_cooldown_seconds` | `15` | Base cooldown after failures. | +| `performance.max_anonymous_exits` | `8` effective | Maximum distinct static anonymous exits; zero selects this built-in limit. | +| `performance.free_tier_block_seconds` | `900` effective | Free-tier exit block cooldown; zero selects the built-in value. | +| `performance.max_idle_conns` | `2048` | Idle connections per transport. | +| `performance.max_idle_conns_per_host` | `256` | Idle connections per host/transport. | +| `performance.max_conns_per_host` | `0` | Connection cap; zero means unlimited. | +| `performance.idle_conn_timeout_seconds` | `120` | Idle connection lifetime. | + +`proxies` accepts `direct`, HTTP, HTTPS, SOCKS5, and SOCKS5H URLs. `proxyfile` adds one proxy per nonempty line, relative to the configuration directory; entries are deduplicated and an empty resolved list means direct access. Line comments start with `#`, `;`, or `//` at the beginning or after whitespace. Credentials embedded in proxy URLs are secrets. + +Mark a provider-managed rotating endpoint with `pool+https://proxy.example:8443` or `https://proxy.example:8443#pool`. Each attempt then opens a fresh connection without keep-alive/HTTP/2 reuse; these entries do not use static-node cooldown or health eviction. The provider must actually rotate its exits. Static proxies retain connection reuse, health tracking, and key bindings. `proxy_bindings` can pin a key fingerprint to a configured proxy. + +An explicit `x-session-id` provides conversation affinity. OpenCode session headers and supported conversation fields also work; otherwise the initial system/user content supplies a seed. Generated identities are scoped to the local API key and process lifetime. Valid official OpenCode session IDs are preserved. Separate independent conversations with explicit IDs and use separate keys where user isolation is required; identical starts under one key can share affinity. + +An optional `models.anonymous_backoff` object pauses the anonymous lane after repeated failures. Its defaults are threshold `6`, base `1` hour, maximum `24` hours. Omitting the object disables this lane-level breaker. + +### Free-model request shaping and reasoning + +Free-model compatibility can inject the official OpenCode system prompt and tool definitions, rename client tools on the wire, and restore their names in responses. This also affects free models served by keys. The gateway relays tool calls; it does not execute tools on the host. System One is excluded from message/tool shaping. + +The injected prompt includes a working directory, workspace, platform, model, and UTC date. By default these describe the gateway host. Set `upstream.prompt_environment` to supply compatibility text for remote clients: + +```json +{"working_directory":"C:\\work\\project","workspace_root":"C:\\work\\project","platform":"windows","is_git_repo":true} +``` + +Merge that object into `upstream.prompt_environment`. Paths are text, not accessed by this setting. `windows` normalizes to `win32`; `linux` and `darwin` are also accepted. A client-supplied official prompt is not replaced. There are no dedicated UI fields for these advanced values; edit the file and reload it. Arbitrary environment overrides have not been verified against upstream validation. + +Reasoning accepts `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, `none`, `auto`, or an empty value. Explicit client effort takes precedence. `none` removes reasoning settings. `auto` uses a recently validated effort ceiling only for eligible free Zen/anonymous models; it does not expand probe scope. Automatic discovery needs active probes, may make several billable/quota-consuming requests, and expires after two hours. Go/paid models and unverified levels get no inferred override. + +Availability is learned from real traffic by default. Synthetic checks run only with `models.active_probes: true`; the management probe action schedules checks but does not override this switch. Explicit model-retired/not-found evidence can disable a model. Rate limits, authentication failures, generic errors, and timeouts do not prove retirement. Manual restore keeps a model enabled and excludes it from automatic probing until automatic control is restored. + +### WARP + +`warp.enabled` defaults to `false`. When enabled, free anonymous/manual-Zen traffic and their discovery/probe paths use an in-process Cloudflare WARP tunnel. Go traffic, paid traffic, and OAuth routes retain their configured proxy routing. WARP needs outbound UDP to Cloudflare port `2408`; no TUN device or routing-table change is required. Initialization failure rejects startup or the candidate configuration. + +`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. + +## 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. + +Management authentication uses an administrator session cookie, CSRF tokens for writes, and login throttling. Changing the administrator credentials invalidates sessions. Local API keys do not grant management access. `GET /api/config` masks secrets; password-confirmed reveal can expose manual keys/proxy values, but never OAuth tokens. + +Use **Models & Quota** to start a Device OAuth login. Open the displayed official verification URL yourself, enter `user_code`, authorize the request you initiated, and select an organization/workspace if asked. The backend polls and refreshes credentials; there is no token-paste, local credential-file import, or callback-URL workflow. + +| Connection | Scope and constraints | +| --- | --- | +| Go OAuth | Official Go subscription routes only; allowance is shown as unknown. | +| Zen OAuth | Console PAYG using workspace credits; explicit acknowledgement is required before starting. Credit balance is shown as unknown. | + +Go and Zen pending logins, saved credentials, refresh state, and disconnect actions are separate. Hiding/leaving the page stops automatic polling; returning can resume an unexpired login. Logout cancels that session's pending logins and preserves completed connections. Canceling a pending login does not disconnect an existing account. + +Saved connections are `go_oauth` and `zen_oauth` in the configuration and contain access/refresh credentials. Protect the configuration and its backups. Manual keys remain saved but are not fallback routes while the corresponding OAuth connection exists, including when it needs a new login. Disconnect removes only the local connection, restores manual routing after discovery, and does not revoke the official session. Keep another credential before disconnecting the last usable connection with anonymous access disabled. + +Only routes from authenticated official remote configuration that pass plan-specific URL and SDK validation are accepted. The gateway does not derive PAYG URLs from Go routes or import arbitrary remote headers. Ordinary config saves preserve backend-managed OAuth credentials. Legacy `go_subscription`/`zen_subscription` fields migrate on load; combining old and new fields for one plan is rejected. + +OAuth integration follows the upstream source snapshots listed in the management guide. This documents implementation behavior, not successful live authorization or inference against every account; upstream permissions and route formats can change. + +### Local keys, quota, and rotation + +The API-key page creates, names, enables, disables, and deletes local keys. Generated keys contain 192 random bits. Custom keys accept 16–256 characters from letters, digits, `.`, `_`, and `-`; names accept 1–80 characters, with at most 200 keys. At least one must remain enabled. New requests observe changes immediately. There are no per-key model permissions, spending limits, or expiry settings. + +Manual Go-key quota comes from the configured Go upstream's `/v1/usage`: shared rolling/weekly/monthly percentage windows, not per-model balances. Keys can share the same allowance, so their percentages are not added. Successes cache for 60 seconds, failures for 15; old data is marked stale. OAuth quota/credits are unknown and are never inferred from manual keys or successful requests. + +Rotation aliases `sota` and `sweet` use Go models and work with the three message endpoints, including streaming. Each group has a service-wide current model that stays after success and advances on failure. SOTA contains `deepseek-v4.1-flash`, `glm-5.3`, `grok-4.6`, `kimi-k3`, and `qwen3.8-max`; Sweet collects other eligible Go models. Availability follows actual discovery, not the fixed names. Aliases/order and the first-output timeout are editable in `/#rotation`. + +The ordinary-error budget is three models with up to three attempts each. Quota/rate-limit failures skip directly to the next model; rotating cannot create extra shared quota. Once stream output is committed, an error ends that answer and advances the group for the next request. Responses keep the requested alias in `model`; `X-Resolved-Model` identifies the actual model. State persists beside the configuration. + +## Operations and security + +Configuration saves validate and construct a replacement runtime before applying it. Failed validation or persistence keeps the active runtime. Keys, proxies, routing, model settings, and logging apply to new requests; listeners and WebUI enablement require restart. File edits require `POST /api/config/reload` or the UI reload action; there is no automatic file watcher. + +| Data | Storage | +| --- | --- | +| Configuration and previous version | `config.json`, `config.json.bak`. | +| Model and metadata caches | `config.json.models.catalog.json`, `config.json.models.dev.json`. | +| Availability and rotation | `config.json..availability.json`, `config.json.rotation.json`. | +| Sessions, usage, recent requests/attempts, log ring, last Playground result | Memory; reset on process restart. | +| Structured logs | JSON on stdout; retention requires an external collector. | + +Names use the actual configuration path. Monitoring survives hot reloads but is not shared across processes. Token counts use upstream-reported usage; missing usage is not estimated. Request completion and upstream header-attempt metrics measure different things. Playground has a separate usage bucket. The recent-hour buffers retain at most 10,000 requests/20,000 attempts and return at most 500 of each. + +`GET /healthz` makes no upstream request and requires no key. Pending/empty discovery, unavailable WARP, or missing required healthy proxies return 503. A usable stale catalog can return 200 with `status: "degraded"`; stale means older than twice the refresh interval, at least 60 seconds. Readiness is not proof of a valid key, remaining allowance, or successful inference. The public response contains counts/status, not secret values or proxy addresses. + +Keep API and management listeners on loopback for local use. For network access, use HTTPS and restrict access to management. A trusted reverse proxy must set `X-Forwarded-Proto` consistently; rate limiting uses the direct peer, so clients behind one proxy share its limits. The executable itself serves HTTP. + +Configuration files and backups hold upstream keys, proxy passwords, and OAuth tokens; password hashing does not encrypt them. Restrict filesystem permissions (Windows ACLs when applicable) and exclude runtime files from source sharing. `logging.dump_request_bodies` is off by default and requires debug logging; even redacted, capped body dumps can reveal conversation content. Playground and availability probes send real upstream requests and can consume quota or credits. + +## Local development and verification + +`cmd/opencode2api` starts the service. `internal/admin` owns management, `gateway` owns routing/runtime, `protocol` handles JSON/SSE conversion, `models` owns discovery, `oauth` owns official authorization, `config` owns validation/persistence, and `telemetry` owns metrics/logging. Static assets live in `webui`; no frontend package installation is required. + +The native Go commands for a normal development environment are: ```bash -curl http://localhost:8080/v1/responses \ - -H "Authorization: Bearer YOUR_LOCAL_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{"model":"MODEL_ID","input":"Hello"}' -``` - -**Anthropic Messages** - -```bash -curl http://localhost:8080/v1/messages \ - -H "x-api-key: YOUR_LOCAL_API_KEY" \ - -H "anthropic-version: 2023-06-01" \ - -H "Content-Type: application/json" \ - -d '{"model":"MODEL_ID","max_tokens":512,"messages":[{"role":"user","content":"Hello"}]}' -``` - -For streaming, add `"stream": true` to the body and use `curl -N`. Responses include an `x-request-id` for correlation. API request bodies are limited to 32 MiB. - -**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 pairs a free-form state with typed questions and returns typed answers, so the payload shares no shape with the chat/responses bridge and is relayed verbatim, never translated. Only models whose native protocol is System One are served here; a decision payload submitted on a message endpoint (`/v1/chat/completions`, `/v1/responses`) is likewise relayed verbatim instead of converted. Streaming upstream replies are relayed as-is without reset recovery. - -### Compatibility boundaries - -Requests using the upstream's native protocol retain provider-specific fields. Requests crossing protocols pass through a common representation; not every option has an equivalent. For example, Chat JSON output constraints and `seed` are not forwarded to Anthropic Messages. Unsupported content or tool types may be rejected. - -When converting Responses history, adjacent assistant reasoning, text, and function-call items form one assistant turn, including text interleaved between function calls. Tool results and user messages separate turns; missing or unmatched tool results remain validation errors when converting to Chat Completions. - -The gateway exposes the routes listed above. It does not implement embeddings, file uploads, image generation, or Responses retrieval and cancellation. It does not store conversation history; clients must supply the history or use features supported by the actual upstream. - -## Routing and models - -### Model discovery - -The gateway refreshes Zen/Go `/v1/models` and OpenCode's [capability catalog](https://models.opencode.ai/api.json) on the configured interval. Native protocols and model limits are tracked separately for each tier. OpenCode's Zen/Go documentation is a fallback for protocol discovery. - -`models.protocols` overrides discovery: - -```json -{ - "models": { - "refresh_seconds": 300, - "protocols": { - "custom-model": "chat" - } - } -} -``` - -Allowed protocol values are `chat`, `responses`, and `anthropic`. Models using unsupported native protocols are filtered from discovery unless overridden. - -Cost, deprecation, and model limits come from the official [OpenCode metadata endpoint](https://models.opencode.ai/api.json), refreshed every 24 hours. OpenCode's capability catalog remains authoritative for context and token limits; metadata `limit.context`, `limit.input`, and `limit.output` fill fields missing from that catalog. These limits are exposed by `/v1/models` as `context_window`/`context_length`, `max_input`, and `max_output` for discovery clients such as CLIProxyAPI and Pi. Metadata requests use a 30-second timeout per HTTP client. Refresh failures retain existing data. - -Each `/v1/models` entry also carries `cost` (USD per million tokens: `input`, `output`, `cache_read`, `cache_write`, plus OpenClaw's `cacheRead`/`cacheWrite`) when the metadata states a price. Reasoning models list their levels in `reasoning_efforts` and in OpenClaw's `compat.supportedReasoningEfforts`: `minimal` through `max`, capped at the probed ceiling when the model's effort is `auto`. A forced or probed level is reported as `default_reasoning_effort`. Cache prices appear after the next metadata refresh. - -### Anonymous access and fallback - -**Anonymous traffic may be heavily blocked upstream. Prefer a Zen API Key.** The built-in default and example configuration set `anonymous: false`; the WebUI does not opt you in automatically or change an existing explicit `true` value. - -With `anonymous: true`, either condition makes a model eligible for the anonymous Zen lane: - -- Its ID contains `free`, case-insensitively. -- OpenCode metadata reports zero input and output cost and the model is not deprecated. - -Eligibility is a routing decision; the upstream can still reject or rate-limit the request. Anonymous requests use `public` in the upstream authentication header. - -The routing sequence is: - -1. For an eligible model, try up to `performance.max_anonymous_exits` available anonymous proxies once each. Every proxy uses the v2 `/inference` lane; the v1 `/zen` fallback is retired for free models and its call site is commented out. -2. Try authenticated tiers in `prefer` order, using only tiers with a configured key and a route for that model. -3. Apply `retry.max_attempts` separately to each authenticated tier. - -Anonymous attempts are not cut short by `retry.max_attempts`, but all attempts share the request timeout. Network errors, authentication failures, rate limits, and server errors can rotate exits. A request-level `400`/`413`/`422` (for example `context_length_exceeded`) ends the request immediately: another exit or tier cannot change the request. An IP-level abuse `403` blocks only that exit; if every exit is blocked, the gateway stops walking them, and an authenticated Go key can still serve the request. - -If a retry fails before producing an HTTP response, the gateway retains the latest upstream HTTP error instead of replacing it with a transport error. Its status and `Retry-After` are preserved, and up to 64 KiB of its body is retained for the existing error-message conversion. The previous response connection or WARP lease is released before another attempt. A later HTTP response replaces the earlier one, and a client cancellation still takes precedence. This does not change session IDs, retry budgets, or upstream quotas. - -When the free tier is blocked for the whole deployment (an IP-level `403` abuse response), retrying only extends the penalty, so an optional lane-level circuit breaker can stop the probing. With `models.anonymous_backoff` configured, `threshold` consecutive failed anonymous attempts or an all-exits IP block pause the whole anonymous lane for `base_hours`, doubling on every further trip up to `max_hours`. A single non-abuse `403` or `429` does not open the breaker; it counts toward the threshold. While paused, requests skip the lane entirely: no proxy is drawn, no upstream request is made, and routing goes straight to the authenticated tiers. Catalog refreshes and availability probes honour the pause as well. When the window expires one request wins the half-open probe; success closes the breaker and restores the free lane, failure opens the next, longer window. The block is absent, and so the breaker stays off, by default. - -Requests are encoded for each tier's own protocol. With `performance.first_event_timeout_seconds` enabled, a successful SSE response is held until the first complete data event. A timeout or disconnect before that event uses the existing key/proxy retry budget; comments do not satisfy the timeout. Once released downstream, the stream is never replayed. The default is `0` (disabled); try `15` seconds for upstreams that accept requests but send no events. This bounds the first event, not the first text token, and does not apply to System One. Rotation aliases use their separate `rotation.first_output_seconds` timeout. A recognized stale Responses reasoning reference can trigger one repair pass; selected-key diagnostics never use that replay. - -Known OpenCode title requests are identified before prompt and message shaping, so those mutations cannot accidentally add agent tools to a title request or classify an ordinary agent request as a title request. The existing title-pattern and history restrictions still apply; this is not a general fix for every `FreeUsageLimitError`. - -When only anonymous access is configured, `/v1/models` exposes only models eligible for that lane. - -An eligible free model can be attempted without a Zen key only when anonymous access is explicitly enabled; eligibility does not guarantee upstream access. To keep authenticated keys but expose free models only, set `models.free_only: true`. Paid models then disappear from `/v1/models`, direct requests for them are rejected, and rotation aliases keep only free members; free models use the configured keys when anonymous access is off, or may fall back to them when it is on. - -### WARP egress for free models - -`warp.enabled` moves every free-model request on a free lane — the anonymous lane, the free-model fallback through a Zen key, free-model availability probes, and the anonymous catalog refresh — onto a userspace Cloudflare WARP tunnel. Those requests use no proxy, so the free tier sees the WARP exit address instead of a configured node. Go-plan keys and paid models keep their proxy bindings. - -The tunnel lives inside the gateway process: it registers a WARP device, speaks WireGuard over UDP to Cloudflare, and terminates in a userspace network stack. It needs no TUN device, root, `NET_ADMIN`, or routing-table change, but the host or container must be able to send UDP to Cloudflare's endpoint (port `2408`). Registration and the `warp=on` trace probe run at startup; if WARP cannot initialize, startup fails instead of silently falling back to proxies. Enabling it through the WebUI is also fail-closed: a bad value returns an error and the previous runtime keeps serving. - -`warp.pool_size` (1–32, default `2`) is an upper bound, not a fixed count. The first exit registers synchronously and gates readiness; the pool then registers half of the ceiling (at least one) in the background, so a burst finds warm exits instead of waiting for registrations. The active ring follows concurrency: one exit per in-flight lease plus a spare, never more than the maximum. Surplus exits that stay idle for 60 seconds are retired, so a quiet period scales back down. An exit answered with 429 or 403 is retired immediately and a pre-registered exit takes its place — a free-model request keeps switching to another exit and only returns the last 429 to the client once `retry.max_attempts` is spent — and the retired exit is re-registered in the background right away. Registrations are serialized; Cloudflare's 429/Retry-After answer sets the pacing instead of a fixed delay. If the colo hands out fewer distinct egress blocks than the preload, the pool backs off instead of registering forever, and automatic free-model probes skip a pool without a spare exit and stop the sweep after one probe retires an exit. `warp.stack` selects `ipv6` (default), `ipv4`, or `dual`. - -The upstream free quota is scoped to the egress block, so rotation only helps when a replacement leaves from a different one: an IPv6 exit is keyed and cooled by its `/64` for 30 minutes, an IPv4 exit by its `/32`. Cloudflare's WARP IPv4 egress is usually one shared NAT address, which other users routinely exhaust; the IPv6 stack gets an egress derived from the outer WireGuard source. Set `warp.source_ipv6` to an IPv6 prefix routed to the host (usually a `/64`), with the default `ipv6` stack to make every exit bind its own source address from that prefix. The prefix needs `IPV6_FREEBIND` on Linux (the gateway sets it) or addresses already assigned to an interface. Endpoint family is not probed in advance: the handshake tries IPv6 endpoints first and falls back to IPv4 ones when none answer (the exit then egresses from the shared address). Leave `source_ipv6` empty to keep the host's default source address. On networks whose WARP egress pool is saturated every fresh exit can still answer 429; the gateway then churns exits without ever surfacing a 429 before the attempt budget is spent. `/healthz` reports a `warp` block and answers 503 while WARP is enabled but no exit is active; `no_healthy_proxies` only blocks readiness when WARP is off or Go keys need proxies. Diagnostics acquire an exit but never rotate or penalize it. Turning WARP off restores proxy routing for the free lanes. - -### Official system prompt - -Every shaped free-model request carries the OpenCode CLI's own system prompt — its base instructions, the `` block, and the built-in skill listing — because the free tier validates agent-shaped traffic. The v1 `/zen` lane uses the 1.x tool names; `/inference` and `/zen/go` use the 2.x names. The environment block names the requested model, the gateway's working directory, the platform, and a UTC date. - -For remote clients, optionally set `upstream.prompt_environment` to replace the injected environment values without removing fields, changing their order, or modifying the official base prompt: - -```json -{ - "upstream": { - "prompt_environment": { - "working_directory": "/workspace", - "workspace_root": "/workspace", - "platform": "linux", - "is_git_repo": true - } - } -} -``` - -This is a configuration fragment to merge into the existing `upstream` object, not a complete configuration. An absent or empty object preserves the previous host-based behavior. A nonempty `working_directory` also supplies the workspace root unless `workspace_root` is set separately; omitted values otherwise keep their existing defaults, including `is_git_repo: true`. Supported platforms are `linux`, `darwin`, and `win32` (`windows` is normalized to `win32`). An explicit platform also selects the corresponding shell-tool description; the gateway does not execute or translate client commands. Paths are used as text, not resolved or accessed, and control characters, line separators, and angle brackets are rejected. These are operator-supplied compatibility values, not automatically detected client facts: use separate gateway configurations when clients require different environments. The requested model and UTC date remain unchanged. Arbitrary overrides, including the macOS description, have not been verified against upstream validation. - -Injection is protocol-aware: Chat system and developer messages are folded into one leading `system` message, Anthropic receives a `system` value (a string, or a leading text block when the caller sent blocks), and Responses receives `instructions`. A body whose system content already contains the marker `You are opencode, an interactive CLI tool` is passed through, so a client that sends the official prompt never gets a second copy. Free models served by a Zen or Go key receive the same shaping even though they still leave through that tier's proxy. - -The override applies only to the gateway-injected block; a client's existing official prompt is left untouched. It is shared by anonymous, keyed, WARP, and probe shaping, and is preserved when saving other settings through the WebUI. Edit the JSON configuration and reload it to change these advanced values; no dedicated WebUI fields are provided. - -### Tool shaping - -On every shaped free-model request the gateway replaces each named client tool with an opaque wire name — a namespace prefix plus the first 12 hex characters of the client name's SHA-256 (collisions get a `_2`, `_3`, … suffix) — and appends the complete official tool set for the lane: the 1.x definitions (`bash`, `edit`, `glob`, `grep`, `read`, `skill`, `task`, `todowrite`, `webfetch`, `websearch`, `write`) on `/zen`, and the 13-tool 2.x set on `/inference` and `/zen/go`. The prefix must stay a plain namespace a tool name could carry: the free tier refuses a prefix it has learned to recognise, so it must not become a gateway marker. The digest is not cosmetic: the free tier refuses a shaped body that still carries another client's vocabulary — a Claude Code request that declares both `ReportFindings` and `ScheduleWakeup` is answered with `FreeUsageLimitError`, and removing either name lifts the refusal — so no client tool name reaches the wire. Requests without a `tools` array, with an empty one, or with a legacy `functions` array get the same official set; `tool_choice`, legacy `function_call`, and the tool-call history are rewritten to match. Responses built-in tools and Anthropic server tools are left untouched. - -Responses are restored to client-declared names in streaming and non-streaming replies, including Chat tool names split across chunks. An official name is mapped when the client declared an equivalent tool; otherwise it remains unchanged in the response. In request history, unknown tool calls and official calls without a declared equivalent are removed with their paired results, and a named `tool_choice` targeting one of those dropped calls is removed too. - -Legacy `functions` definitions pass through the same single renaming step as modern tools, keeping definitions, named choices, history references, and response restoration consistent. - -### Free model availability - -The gateway probes models whose IDs contain `free` (case-insensitive), or whose metadata reports zero input/output cost without deprecation, with a short request using its native protocol. It tries the enabled anonymous lane first and then one configured Zen Key. With `warp.enabled`, every probe lane leaves through WARP instead of a proxy; when no exit can be acquired the probe reports `warp_unavailable` and stays inconclusive. A valid completed response on either lane keeps the model enabled; the model is disabled in discovery and routing only when every attempted lane explicitly reports that the model does not exist or has been retired. Authentication errors, rate limits, timeouts, transport errors, 5xx responses, and malformed replies are inconclusive: they do not create a new disable, and are checked again in one hour. Probe traffic does not alter production key/proxy cooldowns or request statistics. It still reaches the upstream and may consume its free allowance. - -System One models use a native `noul` question asking whether 1 + 1 equals 2; they are never sent chat/tool payloads. Model discovery includes `native_protocol` and `supported_endpoints`; rotation aliases are listed only when Go keys and eligible models exist. Legacy v1.3.6 disables are cleared on load and scheduled for immediate recheck because those probes used invalid session IDs. - -The intervals are fixed: enabled models are checked every **1 hour**, models confirmed unavailable every **24 hours**. An inconclusive due recheck of a disabled model preserves its original disable reason and schedules another retry in 24 hours. A successful recheck restores the model automatically. The WebUI **Free model availability** page can restore it immediately, which puts the model under manual control: it stays enabled and is excluded from automatic probing, so later probe results cannot overwrite it. Use the per-model **manual/automatic toggle** on the same page to return it to automatic probing; the next scheduler pass then schedules a probe. Records left as `manually_enabled` by older versions migrate to manual control on load. An in-flight probe cannot undo a manual restore. Models without a usable Zen/anonymous lane, or without a supported inference protocol, are skipped. - -Manual control also pauses effort discovery for `reasoning.effort=auto`; learned levels stop being forced after two hours without verification. Returning to automatic control allows effort discovery to resume. - -State survives restarts in `config.json..availability.json`, separated by the Zen upstream URL. The background scheduler checks for due models once per minute, skips manually controlled models, and probes the rest sequentially, with a 60-second timeout per lane. No channels available means no automatic disable. - -Administration endpoints (login required; writes also require CSRF): `GET /api/models/availability`, `POST /api/models/probe` (marks every automatic free model due and starts a probe sweep right away, so the WebUI's refresh status button re-probes instead of only reloading the cached view), `POST /api/models/restore` with `{"model":"MODEL_ID"}` (restores and takes manual control), and `POST /api/models/manual` with `{"model":"MODEL_ID","manual":true|false}` to switch between manual and automatic control. - -### Sessions and proxies - -Keys are initially spread across proxies. Real traffic can trigger proxy checks, key rebinding, and cooldowns. Unhealthy proxies are rechecked every 15 minutes against Cloudflare trace. - -A stable session hash selects the preferred key or anonymous proxy. Send an explicit `x-session-id` to separate independent conversations. The gateway also accepts the `x-opencode-session`, `x-session-affinity`, `session_id`, `conversation-id`, and `conversation_id` headers, the `conversation_id` and `metadata.session_id` body fields, and the session ID inside Claude Code's `metadata.user_id`. - -Sessions and projects the gateway derives itself are scoped to the caller's server key, so different keys never share an upstream session, preferred key, or anonymous proxy. Official OpenCode sessions (`ses_…`) sent by the client are kept as-is. Derived session ids are salted per process, so restarting the gateway re-mints them instead of resuming the upstream session of the previous run. Without an explicit ID, the system prompt and the first user message are used as a seed. Conversations under the same key that begin with the same system prompt and content can therefore still share affinity; give users who must stay isolated their own server keys. Changing pool membership can change the selected node. - -Cooldowns grow exponentially up to eight times `performance.failure_cooldown_seconds`, and a longer `Retry-After` is honored. A configured `models.anonymous_backoff` breaker is a separate lane-level guard: it pauses the whole anonymous lane for hours, while these cooldowns stay per exit and short. If every authenticated key is cooling down, routing may try the key whose cooldown ends first. Anonymous nodes still in cooldown are skipped. - -## Configuration reference - -See [config.example.json](config.example.json) for a starting configuration; add an upstream credential before starting. The configuration-file loader supports `//` and `/* ... */` comments, which are not part of standard JSON; management API bodies must be standard JSON. Unknown fields, including `_comment`, and invalid values are rejected. - -### Keys, listeners, and routing - -| Field | Default / requirement | -| --------------------------- | --------------------------------------------------------------------------- | -| `listen` | `127.0.0.1:8080`. | -| `server_keys` | At least one local key is required. | -| `zen_keys`, `go_keys` | At least one upstream key or saved `go_subscription` connection is required unless anonymous access is explicitly enabled. | -| `anonymous` | `false`; opt-in only. Upstream blocking may make this lane unavailable; prefer a Zen API Key. | -| `warp.enabled` | `false`; free-lane traffic leaves through Cloudflare WARP and no proxy. | -| `warp.pool_size` | `2`; upper bound on WARP exits (half pre-registered in the background; the active ring follows concurrency), 1–32. | -| `warp.stack` | `ipv6`; `ipv6`, `ipv4`, or `dual`. | -| `warp.source_ipv6` | empty; IPv6 prefix (`/64`) each exit binds its outer source from; requires `stack = "ipv6"`. | -| `prefer` | `go`; accepts `go` or `zen`. | -| `upstream.zen` | `https://opencode.ai/zen`. | -| `upstream.go` | `https://opencode.ai/zen/go`. | -| `upstream.anonymous` | `https://opencode.ai/inference`; the only anonymous lane (the retired `/zen` fallback is commented out in `anonymousUpstreams`). | -| `proxies` | Falls back to `["direct"]` when both proxy sources are empty. | -| `proxyfile` | Optional; relative paths resolve beside the configuration file. | -| `models.refresh_seconds` | `300`; minimum 1. | -| `models.protocols` | `{}`; per-model native protocol overrides. | -| `models.free_only` | `false`; expose and route only free models, even with Zen or Go keys. | -| `models.active_probes` | `false`; when disabled, model availability is tracked passively from live requests without sending synthetic inference probes. Set to `true` to opt in to background inference probes. | -| `models.anonymous_backoff` | Absent (off); `{threshold, base_hours, max_hours}`, defaulting to `6`, `1`, `24`. | -| `reasoning.effort` | Empty (off); `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, or `none`. | -| `reasoning.effort_by_model` | `{}`; per-model overrides of `reasoning.effort`. | - -### Forced thinking level - -`reasoning.effort` sets the thinking level used upstream when a request does not -state one of its own, and `reasoning.effort_by_model` overrides it for the model -IDs it names. It applies to all three protocols, in either direction of -conversion, and matters most for cross-protocol traffic: an Anthropic -`thinking.budget_tokens` can only be approximated by the Chat and Responses -surfaces, so a forced level reaches a rung that the budget alone cannot express. - -```json -{ - "reasoning": { - "effort": "high", - "effort_by_model": { "claude-opus-5": "max" } - } -} -``` - -Explicit client disables remain disabled across protocol conversion: Anthropic -`thinking.type="disabled"` and Chat/Responses effort `"none"` cannot be re-enabled -by a configured default. - -Levels are reported faithfully in both directions. An explicit -`output_config.effort` survives conversion instead of being shadowed by a -`thinking` block, `budget_tokens` keeps its rung (`8192` is `high`, `32000` is -`xhigh`, so the two stay distinguishable), and the Responses target carries the -level as `reasoning.effort` rather than dropping it. - -The WebUI Configuration Center exposes the same default and per-model fields. -The management API returns them as `reasoning` from `GET /api/config` and accepts -the object in `PUT /api/config`; clients that omit the field keep the existing -value, while sending an empty object clears it. - -Proxy entries accept `direct`, `http://`, `https://`, `socks5://`, and `socks5h://`, including URL credentials. The inline list is merged with `proxyfile` and deduplicated in order. - -A proxy file contains one entry per line and supports blank lines and comments: - -```text -# Primary proxy -http://user:password@127.0.0.1:7890 -socks5://127.0.0.1:1080 # Backup proxy -direct -``` - -Comment markers are `#`, `;`, and `//` at the start of a line or after whitespace. - -#### Rotating proxy pools - -Suffix an entry with `#pool` (or prefix it with `pool+`) to declare that the endpoint is a rotating proxy pool such as [Resin](https://github.com/Resinat/Resin), where every new TCP connection exits from a different IP: - -```text -http://127.0.0.1:7890#pool -socks5://127.0.0.1:1080#pool -pool+http://127.0.0.1:7891 -``` - -A pool entry is handled differently from a static proxy: - -| Behavior | Static proxy | `#pool` entry | -| ------------------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| Connection reuse | Keep-alive plus HTTP/2 multiplexing (`performance.*` pool settings) | A fresh TCP + CONNECT tunnel per request (`DisableKeepAlives`, no HTTP/2) | -| Failure cooldown | 15s–120s exponential backoff, inflated by `Retry-After` | None: the next request simply draws a new exit IP | -| Health eviction | Marked unhealthy, keys rebound, rechecked every 15 minutes | Never evicted; the health check is skipped entirely | -| Anonymous lane retries | One visit per exit, up to `performance.max_anonymous_exits` exits | Up to `retry.max_attempts`, cycling the pool entry | - -Use it when the endpoint behind the URL already performs the rotation and the pool's own exit IPs are individually rate-limited or flaky; the gateway then treats each attempt as a fresh endpoint instead of pinning the conversation to one exit. A single `#pool` entry is enough — you no longer need to list dozens of exits. Static entries keep the pooling behavior described below. - -### Timeouts and connection pools - -| Field | Default | Meaning | -| --------------------------------------- | ------- | ------------------------------------------------------ | -| `retry.max_attempts` | `3` | Attempts per authenticated tier, including the first. | -| `retry.timeout_seconds` | `300` | Total inference timeout, including stream consumption. | -| `performance.attempt_timeout_seconds` | `0` | Whole-attempt bound; 0 uses the request timeout. | -| `performance.max_anonymous_exits` | `8` | Distinct static proxy exits per anonymous request. | -| `performance.free_tier_block_seconds` | `900` | Cool-down for an exit the free tier flagged. | -| `performance.connect_timeout_seconds` | `5` | Connection establishment timeout. | -| `performance.failure_cooldown_seconds` | `15` | Base failure cooldown. | -| `performance.max_idle_conns` | `2048` | Idle connection limit per proxy transport. | -| `performance.max_idle_conns_per_host` | `256` | Idle connection limit per host and transport. | -| `performance.max_conns_per_host` | `0` | Connection limit per host; 0 is unlimited. | -| `performance.idle_conn_timeout_seconds` | `120` | Idle connection lifetime. | - -The per-attempt header timeout is capped by the request timeout. Set it below the total timeout if a slow upstream should leave time for fallback. Expired request contexts stop further attempts without penalizing unused keys or proxies. - -### Logging and management - -| Field | Default / requirement | -| ----------------------------- | ------------------------------------------------------------- | -| `logging.level` | `info`; accepts `debug`, `info`, `warn`, `error`. | -| `logging.ring_size` | `2000`; range 100–50,000. | -| `logging.dump_request_bodies` | `false`. Requires `debug` logging to emit outbound bodies. | -| `webui.enabled` | `false` when omitted; the example sets it to `true`. | -| `webui.listen` | `0.0.0.0:8081`. | -| `webui.username` | Required when the WebUI is enabled; the example uses `admin`. | -| `webui.password` | Bootstrap password with a minimum length of 10. | -| `webui.password_hash` | Generated Argon2id hash; replaces the plaintext password. | -| `webui.session_ttl_minutes` | `720`; range 5–10,080. | - -On startup, a bootstrap password is hashed and removed from the configuration. The backup containing that bootstrap plaintext is deleted. Keep configuration files and backups private: upstream keys and proxy credentials remain necessary configuration secrets. - -Body dumps are opt-in and capped at 64 KiB per prepared body. Configured secrets are redacted, but conversation content may still be sensitive. - -## WebUI and diagnostics - -The management listener serves the UI and `/api/*` routes. Authentication uses one administrator account, server-side sessions, HttpOnly/SameSite cookies, CSRF checks for writes, and login throttling. - -| Management route | Purpose | -| ------------------------------------------------ | --------------------------------------------------------------------- | -| `POST /api/auth/login` | Log in and obtain a session cookie and CSRF token. | -| `GET /api/auth/session`, `POST /api/auth/logout` | Inspect or end the session. | -| `GET /api/config`, `PUT /api/config` | Read masked configuration or apply changes. | -| `POST /api/config/reload` | Reload the file from disk. | -| `POST /api/config/reveal` | Reveal configured secrets after password verification. | -| `PUT /api/account` | Update credentials after password verification; invalidates sessions. | -| `GET /api/monitor` | Request, token, upstream, and resource statistics. | -| `GET /api/debug/models` | Model routes, key fingerprints, and metadata diagnostics. | -| `POST /api/debug/inference` | Run a Playground request. | -| `POST /api/proxies/check` | Check one saved or draft proxy's connectivity to the configured Zen upstream. | -| `GET /api/logs`, `GET /api/logs/stream` | Recent logs or a live SSE subscription. | - -Playground requests require a session and `X-CSRF-Token` and are limited to 12 per minute per client IP: - -```json -{ - "protocol": "chat", - "key": { "mode": "auto" }, - "request": { - "model": "MODEL_ID", - "messages": [{ "role": "user", "content": "Hello" }] - } -} -``` - -The server forces `stream: false`. Use `{"mode":"selected","tier":"zen","id":"KEY_FINGERPRINT"}` to test a specific key from `/api/debug/models`. A selected request makes at most one upstream attempt, without anonymous access, key rotation, tier fallback, or reasoning replay. - -**Both automatic and selected diagnostics preserve production key cooldowns, failure counts, proxy health, and bindings.** They still make real upstream requests, can consume provider quota, and appear in monitoring. - -After execution, the management endpoint returns HTTP 200 with the actual result in `ok`, `http_status`, `request_id`, `route`, and `response`. Selected-key results also include `selected_key` and `key_test`: `usable`, `rejected`, `rate_limited`, `transport_error`, `upstream_error`, `request_error`, or `unavailable`. Invalid management input, authentication, CSRF, and throttling retain their own HTTP error statuses. - -### Bulk proxy management - -The WebUI can import multiple inline proxies, check selected entries, and stage selected entries for removal. Checks call `POST /api/proxies/check` once per proxy, with a login session, `X-CSRF-Token`, and exactly one of these standard JSON bodies: - -```json -{"id":"SAVED_PROXY_ID"} -``` - -```json -{"value":"https://proxy.example:8443"} -``` - -Use the masked entry ID from `GET /api/config` for an existing proxy, or `value` for an unsaved draft. Results return HTTP 200 with `ok`, `state`, and `reason`; `latency_ms` and upstream `status` may also be present. Invalid management requests, authentication, CSRF, and concurrency limits use their own HTTP error statuses. Each check has a 20-second timeout. The WebUI runs at most four checks concurrently; the server accepts at most eight and rejects excess checks without queuing. - -**This checks only proxy-to-Zen connectivity, not inference, key validity, or quota.** It sends an unauthenticated `GET` to the configured `upstream.zen` URL plus `/v1/models` through an isolated Bun client using only the selected proxy. No Zen/Go key, anonymous `public` credential, or OAuth token is sent, no inference is performed, redirects are not followed, and WARP is not used. It works with `anonymous: false` without enabling anonymous access. - -| `state` | Meaning / cleanup guidance | -| ------- | -------------------------- | -| `available` | The upstream responded with HTTP 200–399 or 401. A 401 means the endpoint was reached but requires authentication (`authentication_required`), not that a key was validated. | -| `unavailable` | A confirmed proxy-side connection refusal or DNS failure (`proxy_unreachable`), or proxy CONNECT HTTP 407 (`proxy_authentication_required`); eligible for unavailable-only selection for this check, not proof of permanent failure. | -| `limited` | The upstream returned 429; this is not evidence that the proxy is broken. | -| `rejected` | The upstream responded with 403 or another error status, excluding 401 and 429 (`upstream_responded`), or the proxy rejected the tunnel (`proxy_tunnel_rejected`); this is not evidence that the proxy is broken. An origin HTTP 407 is not classified as proxy authentication failure. | -| `inconclusive` | A timeout, other transport failure, or unavailable check prerequisite; do not treat this as a confirmed broken proxy. | - -Checks do not change production proxy health, key cooldowns, or bindings. A result describes this connection attempt, not permanent proxy health; upstream rejection, rate limiting, and timeouts must not be selected for cleanup as confirmed proxy failures. - -Removal is staged in the WebUI and takes effect only after saving the full configuration through `PUT /api/config`; checking does not delete anything. Proxies supplied by `proxyfile` are managed in that source file, not in the inline-proxy table. - -### Go subscription sign-in - -In **Models & Quota** (`/#model-quotas`), select **Sign in to Go in your browser**, open the displayed official OpenCode Device OAuth link, and enter the displayed `user_code`. Authorize the request you initiated; the WebUI schedules backend polling to complete sign-in. No token pasting, local credential-file import, or callback URL submission is required. If the account has multiple organizations, select the organization with the Go subscription in the WebUI. - -- The backend refreshes access credentials when needed and persists the connection in the local configuration (`go_subscription`). This includes access and refresh secrets: protect the configuration and its backups. These credentials are not sent to the WebUI. -- **Disconnect** removes the gateway's saved connection, not the official OpenCode session. Manually configured `go_keys` are retained but are not fallback routes while OAuth is connected; disconnecting restores their existing routing. If sign-in becomes invalid, reconnect rather than relying on those keys as a fallback. -- OAuth uses only confirmed official Go subscription routes, never a pay-as-you-go route as fallback. OAuth quota is currently shown as **unknown**; the gateway does not infer remaining allowance from models or request results. The existing usage endpoint remains available for manually configured Go keys. - -The implementation follows the upstream source snapshots [v2 `4617210822bdbb31e5749751afbfb4584ccedac8`](https://github.com/anomalyco/opencode/tree/4617210822bdbb31e5749751afbfb4584ccedac8) and [dev `7745079647b65036fe142e09ccd8623b25be1878`](https://github.com/anomalyco/opencode/tree/7745079647b65036fe142e09ccd8623b25be1878). Source compatibility and local checks are not a claim of live subscription validation; upstream authorization and routing can change. See the [management guide](docs/management.zh-CN.md) for lifecycle and management endpoints. - -### Interface language - -The WebUI loads its translations from `webui/js/i18n.js`. It ships with **简体中文** (default), **English**, **Tiếng Việt**, and **Italiano**. The original Simplified Chinese copy lives in `index.html` and `webui/js/` and stays the fallback for every string without a translation, so adding a language never rewrites the original. - -- The selector sits in the topbar, 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/js/i18n.js`, then register its code in `SUPPORTED`, `LABELS`, `FLAGS`, and `DATE_LOCALES`, and add it to the `browserLocale` detection chain. - -### Saving and reloading - -The server validates a candidate configuration and builds its replacement gateway before saving and switching. Failed validation or persistence leaves the active gateway in place. Requests already running continue on their original gateway. - -Keys, proxies, upstream URLs, retry settings, model settings, logging, and routing preferences apply to new requests immediately. Changes to `listen`, `webui.listen`, or `webui.enabled` require a process restart. Saved JSON is normalized; comments are not retained. - -## Monitoring and persistence - -Request outcomes describe the completed inference. A failed SSE response or truncated stream counts as an error even when HTTP 200 was already sent; its outcome is `stream_error`. Client cancellations are recorded as `client_canceled`. The WebUI displays those outcomes alongside the HTTP status. - -Upstream **attempt** records measure the HTTP exchange through receipt of response headers. Their success and latency are separate from completion of the full JSON body or stream. - -Token statistics use reported usage only. Input tokens include cache reads and writes; cached tokens separately count cache reads. Missing usage is not estimated, and coverage shows how many routed inference requests reported usage. `usage.server_keys` splits requests and tokens by the local server key the caller authenticated with (its fingerprint, as shown in `/api/api-keys`); Playground traffic is counted under `playground`. - -| Data | Storage / retention | -| --------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -| Sessions, metrics, token totals, latest Playground result | Process memory; cleared on restart. | -| Request and attempt details | Recent hour, capped at 10,000 requests and 20,000 attempts; API returns at most 500 of each. | -| Live log ring | Process memory; size set by `logging.ring_size`. | -| Structured logs | JSON on stdout; collect externally for durable history. | -| Configuration and previous version | `config.json` and `config.json.bak`. | -| Model directory cache | `config.json.models.catalog.json`. | -| Price/deprecation cache | `config.json.models.dev.json`. | - -Cache filenames are based on the actual configuration path. Lifetime counters mean the current process lifetime. Instances do not share sessions or monitoring state. - -### Health checks - -`/healthz` does not increment monitoring counters or trigger network requests. It reports resource counts without keys or proxy addresses. - -- HTTP 503: initial catalog pending, no models routable with the current configuration, or no healthy proxies. -- HTTP 200: ready, including when a usable catalog cache is stale. In that case the model status is `stale` and overall status is `degraded`. - -The staleness threshold is twice `models.refresh_seconds`, with a minimum of 60 seconds. Readiness is a discovery and resource check; it does not verify that an upstream key will accept the next inference. - -## Development - -Go source is organized into packages by responsibility. The command wires the service together; implementation packages live under `internal/`. - -```text -cmd/ - opencode2api/main.go CLI flags, startup, and graceful shutdown -internal/ - admin/ Management API, login sessions, and Playground - buildinfo/ Version shared by health and management endpoints - config/ Configuration, persistence, passwords, and redaction - gateway/ HTTP routing, retries, pools, refresh, and runtime - httpx/ Shared HTTP responses, body handling, and headers - identity/ Request IDs and session affinity - jsonutil/ JSON access and decoding helpers - models/ Model catalog, capabilities, pricing, and caches - protocol/ Request/response conversion and SSE parsing/output - telemetry/ Request tracking, metrics, logs, and recovery -webui/ - embed.go Embeds the static assets into the executable - index.html Page structure - css/ Design tokens, base styles, components and page layouts - js/ ES modules: shell, i18n, shared helpers and one module per page -``` - -Suggested reading order: - -1. [Command entry](cmd/opencode2api/main.go) → [runtime management](internal/gateway/runtime.go) → [HTTP handlers](internal/gateway/gateway.go). -2. [Upstream attempts](internal/gateway/upstream.go) and [model routing](internal/models/catalog.go) explain how a request reaches a provider. -3. [Request conversion](internal/protocol/request.go), [response conversion](internal/protocol/response.go), and [stream transport](internal/protocol/stream.go) cover protocol behavior. -4. [Management routes](internal/admin/server.go) and [WebUI logic](webui/js/main.js) cover configuration and diagnostics. - -Run Go formatting, analysis, and the command build: - -```bash -gofmt -w cmd internal webui go vet ./... -go build -o opencode2api ./cmd/opencode2api +go build -trimpath -o opencode2api ./cmd/opencode2api ``` -For local development, start the service with `go run ./cmd/opencode2api -config config.json`. Release builds still inject the version with `-ldflags "-X main.version=vX.Y.Z"`. - -Node.js is only needed for the WebUI JavaScript syntax check: +For workspace-local caches, set `GOCACHE` and `GOMODCACHE` to persistent project directories before invoking Go. Node.js is optional for checking JavaScript syntax, without installing packages: ```bash -for f in webui/js/*.js webui/js/pages/*.js; do node --input-type=module --check < "$f"; done +for file in webui/js/*.js webui/js/pages/*.js; do + node --input-type=module --check < "$file" || exit 1 +done ``` -`.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 four READMEs. +Run these commands in Bash (Git Bash on Windows). See [verification and maintenance](docs/management.md#verification-and-maintenance) for deployment checks. A release version can be injected with `-ldflags "-X main.version=vX.Y.Z"`. -## Troubleshooting +| Symptom | What to inspect | +| --- | --- | +| API 401 | The local key, its enabled state, and the client header. | +| Startup rejects credentials | Configure an upstream key/saved OAuth connection, or deliberately enable anonymous access. | +| No models / health 503 | Discovery status, supported native protocols, configured credentials, and resource availability. | +| OAuth requests fail | Safe connection state and whether reauthorization is required; no automatic PAYG fallback occurs. | +| HTTP 200 but generation fails | SSE error events, request outcome, and `x-request-id` logs. | +| Changes do not apply | Save/reload the active config; restart for listener changes. | +| Host config edits do not affect Compose | The active config is in the state volume; import the file again or use the WebUI. | +| Usage disappears after restart | Counters are in memory; retain structured logs separately. | -| Symptom | Check | -| ------------------------------------ | ----------------------------------------------------------------------------------------- | -| API returns 401 | Use a configured local `server_keys` value. | -| Health remains `starting` | Inspect catalog refresh logs and outbound connectivity; add protocol overrides if needed. | -| No models are exposed | Check configured tiers, anonymous eligibility, and native protocol support. | -| Requests return 502/504 | Inspect upstream attempts, credentials, proxies, and total/per-attempt timeouts. | -| HTTP 200 but generation failed | Inspect the SSE error event and request outcome, not only HTTP status. | -| Host edits have no effect in Docker | The active file is in the state volume; import it again or use the WebUI. | -| Container ports are unreachable | Check listener addresses, published ports, and the active volume configuration. | -| Monitoring disappeared after restart | Monitoring is stored only in memory; collect stdout logs externally. | +Before upgrading, back up the executable, configuration, and state securely. Stop the process before replacing the executable; rollback should restore a matching program/config/state set. ## Acknowledgements Thanks to the [LINUX DO](https://linux.do) community for its support. -### Adaptive reasoning effort - -Set `reasoning.effort` (or a per-model override) to `auto` to use the highest effort successfully validated by the free-model probe. Existing concrete levels retain their meaning and client-specified effort takes precedence. No model-name allowlist is maintained. - -After a baseline succeeds, reasoning-capable models are probed in `max`, `xhigh`, `high`, `medium`, `low`, `minimal` order. Only an explicit reasoning-parameter rejection advances to a lower level. Transient failures stop the search and cannot be interpreted as a lower capability ceiling. If every level is rejected, no reasoning override is injected. - -Observations are persisted by upstream URL, model and native protocol, displayed in the availability page, and used for at most two hours. Active probes cover only free Zen/anonymous models; Go/paid models, unknown capabilities and unverified levels receive no automatic override. Setting `auto` does not expand the probe scope or guarantee that upstreams enforce every accepted field. Probing may require several small requests per model and uses upstream allowance. - ## License -SPDX-License-Identifier: GPL-3.0-or-later - -This project is free software: you may redistribute and modify it under the GNU General Public License as published by the Free Software Foundation, either version 3 or (at your option) any later version. It is distributed without any warranty. See [LICENSE](LICENSE) for the full terms. - +SPDX-License-Identifier: GPL-3.0-or-later. See [LICENSE](LICENSE). The software is provided without warranty. diff --git a/README.vi.md b/README.vi.md index d361b0a..8e5ebc2 100644 --- a/README.vi.md +++ b/README.vi.md @@ -2,28 +2,9 @@ [English](README.md) | [简体中文](README.zh-CN.md) | [Tiếng Việt](README.vi.md) | [Italiano](README.it.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. +Gateway viết bằng Go cho OpenCode Zen và Zen Go. Client dùng OpenAI Chat Completions, OpenAI Responses hoặc Anthropic Messages; gateway chọn upstream khả dụng và chuyển đổi yêu cầu, phản hồi khi giao thức gốc khác nhau. Quyết định System One dùng endpoint chuyển tiếp riêng. -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. -- Đầu ra Cloudflare WARP chạy trong tiến trình cho lưu lượng mô hình miễn phí, không cần TUN hay root. -- 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**, **Tiếng Việt** và **Italiano**; 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. +WebUI quản trị được nhúng trong tệp thực thi, không cần Node.js hay cơ sở dữ liệu khi chạy. Khám phá mô hình, suy luận, OAuth và WARP tùy chọn vẫn cần kết nối đến dịch vụ upstream tương ứng. ## Nhà tài trợ @@ -55,7 +36,7 @@ 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. Điền Zen API Key (khuyến nghị) vào `zen_keys` hoặc Go key vào `go_keys` trước khi khởi động. Cấu hình mẫu tắt truy cập ẩn danh (`anonymous: false`) và để trống cả hai mảng key; một kết nối thuê bao Go đã lưu cũng đáp ứng yêu cầu này. Làn ẩn danh có thể bị chặn mạnh ở thượng nguồn, nên ưu tiên Zen API Key. +2. Điền Zen API Key (khuyến nghị) vào `zen_keys` hoặc Go key vào `go_keys` trước khi khởi động. Cấu hình mẫu tắt truy cập ẩn danh (`anonymous: false`) và để trống cả hai mảng key; kết nối Go OAuth (`go_oauth`) hoặc Zen OAuth (`zen_oauth`) đã lưu cũng đáp ứng yêu cầu này. Không hỗ trợ khởi động khi chưa có thông tin xác thực chỉ để đăng nhập OAuth lần đầu trong WebUI. Làn ẩn danh có thể bị chặn mạnh ở thượng nguồn, nên ưu tiên Zen API Key. 3. Thay `webui.password`. File mẫu bật WebUI với tài khoản `admin`. ```bash @@ -76,501 +57,268 @@ Tuỳ chọn dòng lệnh: 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 +## Docker và Compose -Image được phát hành là `ghcr.io/jasonxu114514/opencode2api`. +Image phát hành là `ghcr.io/jasonxu114514/opencode2api`. Chuẩn bị `config.json` trước khi chạy. Để dùng cổng xuất bản, listener API/WebUI bên trong phải là `0.0.0.0:8080`, `0.0.0.0:8081`; giới hạn truy cập bằng địa chỉ bind phía host và HTTPS khi cần. ```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: +Compose nạp cấu hình host vào volume `opencode2api-state` **chỉ ở lần khởi động đầu**. Sau đó cấu hình hoạt động nằm trong volume; nên sửa qua WebUI. Để nhập lại tệp host đã sửa: ```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`. +Sao lưu cấu hình/trạng thái đang dùng trước khi thay. Entrypoint chạy dịch vụ bằng người dùng không đặc quyền và chỉ đổi đúng giá trị API mẫu `127.0.0.1:8080` thành `0.0.0.0:8080` lúc tạo cấu hình ban đầu. Compose có filesystem gốc chỉ đọc, volume trạng thái ghi được và tmpfs `/tmp`. Cổng mặc định bind mọi giao diện host; chỉ dùng cục bộ thì đổi `ports` thành `127.0.0.1:8080:8080`, `127.0.0.1:8081:8081`. -WARP chỉ cần UDP ra ngoài (endpoint Cloudflare, cổng `2408`), nên thiết lập user thường, không `NET_ADMIN` của image vẫn dùng được; không cần chuyển sang host networking hay thêm `--cap-add`. Nếu mạng container chặn UDP, việc bật WARP sẽ thất bại lúc khởi động. +| Biến Compose | Mặc định | Tác dụng | +| --- | --- | --- | +| `OPENCODE2API_VERSION` | `latest` | Tag image; ghim tag phát hành để cố định phiên bản. | +| `OPENCODE2API_PORT` | `8080` | Cổng API phía host. | +| `OPENCODE2API_WEBUI_PORT` | `8081` | Cổng quản trị phía host. | +| `OPENCODE2API_LISTEN` | Chưa đặt | Ghi đè listener API trong container. | +| `OPENCODE2API_WEBUI_LISTEN` | Chưa đặt | Ghi đè listener quản trị trong container. | -| 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 thành `LISTEN_ADDRESS`, `WEBUI_LISTEN_ADDRESS` trong container; rỗng thì theo cấu hình hoạt động. Đổi cổng host không đổi listener bên trong. Nếu đổi cổng API bên trong, cập nhật mapping và health check image vốn dùng 8080. `proxyfile` phải được mount tại đường dẫn container đã cấu hình. -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ộ: +Để dùng image tự biên dịch: ```bash docker build -t opencode2api:local . docker volume create opencode2api-state docker run -d --name opencode2api \ - -p 8080:8080 -p 8081:8081 \ + -p 127.0.0.1:8080:8080 -p 127.0.0.1:8081:8081 \ -e CONFIG_SEED_PATH=/run/config/opencode2api.json \ - -v "$(pwd)/config.json:/run/config/opencode2api.json:ro" \ + -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. +WARP cần UDP ra Cloudflare cổng `2408`, không cần host networking hay quyền mạng bổ sung. Nếu mạng chặn lưu lượng này, WARP không thể khởi tạo. -## Sử dụng API +## Gọi 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. +Đây là các tuyến tương thích hiện có. Với client tương thích OpenAI, đặt URL gốc là `http://127.0.0.1:8080/v1`; quản trị dùng listener riêng. -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 | Hành vi | +| --- | --- | --- | +| `GET` | `/v1/models` | Mô hình có thể định tuyến với cấu hình hiện tại và bí danh luân chuyển đủ điều kiện. | +| `POST` | `/v1/chat/completions` | Chat Completions, JSON hoặc SSE. | +| `POST` | `/v1/responses` | Responses, JSON hoặc SSE. | +| `POST` | `/v1/messages` | Anthropic Messages, JSON hoặc SSE. | +| `POST` | `/v1/systemone` | Quyết định System One gốc, không chuyển đổi. | +| `GET` | `/healthz` | Mức sẵn sàng và tóm tắt tài nguyên, 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. | +Mọi tuyến `/v1/*` yêu cầu giá trị `server_keys` đang bật qua `Authorization: Bearer ...` hoặc `x-api-key`. Giới hạn nội dung yêu cầu là 32 MiB. Phản hồi suy luận có `x-request-id` để đối chiếu log. -Hãy tìm một mô hình khả dụng trước: +Lấy ID mô hình thực tế trước khi gửi yêu cầu: ```bash -curl http://localhost:8080/v1/models \ - -H "Authorization: Bearer YOUR_LOCAL_API_KEY" +curl http://127.0.0.1:8080/v1/models \ + -H 'Authorization: Bearer YOUR_LOCAL_API_KEY' + +curl http://127.0.0.1:8080/v1/chat/completions \ + -H 'Authorization: Bearer YOUR_LOCAL_API_KEY' \ + -H 'Content-Type: application/json' \ + -d '{"model":"MODEL_ID","messages":[{"role":"user","content":"Xin chào"}]}' ``` -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. - -Để kiểm tra các mô hình và lưu ID của những mô hình gọi thành công vào `working-models.txt`, chạy `bash scripts/check-models.sh`. Script dùng `config.json` để lấy `server_keys` và sẽ hỏi xác nhận trước khi gửi request; thêm `--yes` để bỏ qua xác nhận. - -### 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: +Với Responses và Anthropic Messages, lần lượt gửi nội dung JSON chuẩn sau đến endpoint tương ứng: ```json -{ - "models": { - "refresh_seconds": 300, - "protocols": { - "custom-model": "chat" - } - } -} +{"model":"MODEL_ID","input":"Xin chào"} ``` -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ử tối đa `performance.max_anonymous_exits` proxy ẩn danh khả dụng, mỗi proxy một lần; mỗi proxy thử làn v2 `/inference` trước, rồi làn v1 `/zen`. -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 exit. Request-level `400`/`413`/`422` (ví dụ `context_length_exceeded`) kết thúc request ngay: đổi exit hay tier không thể thay đổi bản thân request. Abuse `403` ở mức IP chỉ loại bỏ exit hiện tại; khi mọi exit đều bị chặn, gateway ngừng quét và key Go đã cấu hình vẫn có thể phục vụ. - -Khi bật `models.anonymous_backoff`, `threshold` lần lỗi ẩn danh liên tiếp hoặc việc mọi exit bị chặn IP sẽ tạm dừng toàn bộ làn ẩn danh trong `base_hours`, tăng gấp đôi sau mỗi lần kích hoạt cho tới `max_hours`. Một `403` không phải lạm dụng hoặc `429` đơn lẻ không mở cầu dao mà chỉ tính vào ngưỡng. Trong thời gian tạm dừng, không rút proxy và không gửi request thượng nguồn (kể cả làm mới catalog và probe), định tuyến chuyển thẳng sang tier có xác thực. Khi hết cửa sổ, chỉ một request thắng probe bán mở: thành công sẽ đóng cầu dao và khôi phục làn ẩn danh, thất bại sẽ mở cửa sổ dài hơn tiếp theo. Bỏ khối cấu hình này thì cầu dao tắt. - -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. - -### Đầu ra WARP cho mô hình miễn phí - -`warp.enabled` đưa mọi request mô hình miễn phí trên làn miễn phí — làn ẩn danh, dự phòng mô hình miễn phí qua Zen Key, dò tính khả dụng mô hình miễn phí, và làm mới danh mục mô hình ẩn danh — sang đường hầm Cloudflare WARP chạy trong tiến trình. Các request này không dùng proxy nào, nên upstream thấy địa chỉ đầu ra WARP thay vì nút đã cấu hình. Key gói Go và mô hình trả phí vẫn giữ proxy. - -Đường hầm chạy bên trong tiến trình gateway: đăng ký thiết bị WARP, nói WireGuard qua UDP với Cloudflare và kết thúc trong một ngăn xếp mạng userspace. Nó không cần thiết bị TUN, root, `NET_ADMIN` hay thay đổi bảng định tuyến, nhưng máy chủ hoặc container phải gửi được UDP tới endpoint của Cloudflare (cổng `2408`). Đăng ký và probe trace `warp=on` chạy lúc khởi động; nếu WARP không khởi tạo được, quá trình khởi động thất bại thay vì âm thầm quay về proxy. Bật qua WebUI cũng đóng khi lỗi: giá trị sai trả về lỗi và runtime cũ tiếp tục phục vụ. - -`warp.pool_size` (1–32, mặc định `2`) là **giới hạn trên**, không phải số cố định. Đầu ra đầu tiên được đăng ký đồng bộ và quyết định trạng thái sẵn sàng; sau đó pool đăng ký nền một nửa giới hạn (ít nhất một) để lưu lượng đột biến có sẵn đầu ra đã ấm. Vòng đầu ra hoạt động thay đổi theo mức đồng thời: một đầu ra cho mỗi request đang chạy cộng một đầu ra dự phòng, không vượt quá giới hạn; các đầu ra thừa rảnh rỗi 60 giây sẽ bị thu hồi. Đầu ra nhận 429 hoặc 403 lần đầu sẽ bị loại ngay và một đầu ra đã đăng ký trước thay vào; request model miễn phí tiếp tục đổi đầu ra và chỉ trả 429 cuối cùng cho client sau khi dùng hết `retry.max_attempts`, còn đầu ra bị loại được đăng ký lại ngay ở nền. Việc đăng ký vẫn tuần tự; phản hồi 429/Retry-After của Cloudflare quyết định nhịp thay cho khoảng nghỉ cố định. Nếu colo cấp ít khối đầu ra khác nhau hơn mức preload, pool sẽ lùi lại thay vì đăng ký vô hạn; kiểm tra tự động model miễn phí bỏ qua pool không có đầu ra dự phòng và dừng lượt sau khi một lần kiểm tra loại bỏ một đầu ra. `warp.stack` chọn `ipv6` (mặc định), `ipv4` hoặc `dual`. - -Hạn mức miễn phí của upstream tính theo **dải đầu ra**, nên luân chuyển chỉ có tác dụng khi đầu ra thay thế đến từ dải khác: đầu ra IPv6 được nhận diện và làm nguội theo `/64` trong 30 phút, đầu ra IPv4 theo `/32`. Đầu ra IPv4 của Cloudflare WARP thường là một địa chỉ NAT dùng chung và đã bị người dùng khác dùng hết; ngăn xếp IPv6 lấy đầu ra từ địa chỉ nguồn WireGuard bên ngoài. Đặt `warp.source_ipv6` thành tiền tố IPv6 được định tuyến tới máy chủ (thường là `/64`, stack mặc định đã là `ipv6`) để mỗi đầu ra tự bind một địa chỉ nguồn trong tiền tố đó. Trên Linux địa chỉ này được bind qua `IPV6_FREEBIND` (gateway tự đặt), hoặc phải được gán sẵn cho giao diện. Không dò trước họ địa chỉ: handshake thử các endpoint IPv6 trước và tự quay về endpoint IPv4 khi tất cả đều lỗi (khi đó đầu ra là địa chỉ dùng chung). Để trống thì dùng địa chỉ nguồn mặc định của máy chủ. Trên mạng có pool đầu ra WARP đã cạn, đầu ra mới cũng có thể trả 429: gateway vẫn tiếp tục luân chuyển và chỉ trả 429 khi hết ngân sách thử. `/healthz` trả về khối `warp` và 503 khi WARP bật nhưng không có đầu ra nào hoạt động; `no_healthy_proxies` chỉ chặn readiness khi WARP tắt hoặc có key Go cần proxy. Request chẩn đoán có lấy đầu ra nhưng không bao giờ luân chuyển hay phạt nó. Tắt WARP sẽ khôi phục định tuyến qua proxy cho các làn miễn phí. - -### System prompt chính thức - -Mỗi request mô hình miễn phí đã được định hình đều mang system prompt của chính OpenCode CLI — hướng dẫn gốc, khối `` và danh sách skill tích hợp — vì làn miễn phí kiểm tra request có dạng agent. Làn v1 `/zen` dùng tên công cụ 1.x; `/inference` và `/zen/go` dùng tên 2.x. Khối môi trường nêu mô hình được yêu cầu, thư mục làm việc của gateway, nền tảng và ngày theo UTC. - -Việc chèn phụ thuộc giao thức: các message system và developer của Chat được gộp thành một message `system` duy nhất ở đầu; Anthropic nhận giá trị `system` (chuỗi, hoặc một text block ở đầu khi bên gọi gửi danh sách block); Responses nhận `instructions`. Nếu nội dung system đã chứa dấu hiệu `You are opencode, an interactive CLI tool`, request được giữ nguyên, nên client đã gửi prompt chính thức sẽ không bị chèn lần hai. Mô hình miễn phí phục vụ qua Zen hoặc Go Key cũng được định hình như vậy nhưng vẫn ra ngoài qua proxy của tier đó. - -### Định hình công cụ - -Trên mỗi request mô hình miễn phí đã được định hình, gateway đổi tên từng công cụ có tên của client thành một tên không lộ nội dung: tiền tố namespace cộng 12 ký tự hex đầu của mã SHA-256 tính trên tên công cụ — ký tự ngoài `A-Za-z0-9_-` thành `_`, tên tối đa 64 byte, trùng tên thì thêm hậu tố `_2`, `_3`, … — rồi thêm toàn bộ bộ công cụ chính thức của làn: định nghĩa 1.x (`bash`, `edit`, `glob`, `grep`, `read`, `skill`, `task`, `todowrite`, `webfetch`, `websearch`, `write`) trên `/zen`, và bộ 13 công cụ 2.x trên `/inference` và `/zen/go`. Request không có `tools`, có mảng rỗng, hoặc dùng mảng `functions` kiểu cũ cũng nhận bộ chính thức; `tool_choice`, `function_call` kiểu cũ và lịch sử tool call được viết lại tương ứng. Công cụ tích hợp của Responses và công cụ máy chủ của Anthropic được giữ nguyên. - -Phản hồi được khôi phục về tên client đã khai báo, cho cả luồng và không luồng, kể cả tên công cụ Chat bị chia qua nhiều chunk. Nếu upstream gọi một công cụ chính thức mà client chưa khai báo, tên đó được truyền nguyên: gateway không phát lại hay che các lời gọi công cụ chính thức. - -### 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. Khi bật `warp.enabled`, mọi làn dò đi qua WARP thay vì proxy; nếu không lấy được đầu ra, kết quả là `warp_unavailable` và được coi là không kết luận. 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 các header `x-opencode-session`, `x-session-affinity`, `session_id`, `conversation-id`, `conversation_id`, các trường body `conversation_id`, `metadata.session_id`, và session ID nằm trong `metadata.user_id` của Claude Code. - -Session và project do gateway tự tạo được tách theo server key của bên gọi, nên các key khác nhau không bao giờ dùng chung session upstream, key ưu tiên hay proxy ẩn danh. Session OpenCode chính thức (`ses_…`) do client gửi được giữ nguyên. Không có ID tường minh, system prompt cùng 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 trong cùng một key có system prompt và nội dung mở đầu giống nhau vẫn có thể dùng chung affinity; hãy cấp server key riêng cho những người dùng cần tách biệt. 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`. | -| `warp.enabled` | `false`; lưu lượng làn miễn phí đi qua Cloudflare WARP, không dùng proxy. | -| `warp.pool_size` | `2`; giới hạn trên số đầu ra WARP (một nửa đăng ký trước ở nền; vòng hoạt động theo mức đồng thời), 1–32. | -| `warp.stack` | `ipv6`; `ipv6`, `ipv4` hoặc `dual`. | -| `warp.source_ipv6` | rỗng; tiền tố IPv6 (`/64`) mỗi đầu ra bind nguồn bên ngoài; cần `stack = "ipv6"`. | -| `prefer` | `go`; nhận `go` hoặc `zen`. | -| `upstream.zen` | `https://opencode.ai/zen`. | -| `upstream.go` | `https://opencode.ai/zen/go`. | -| `upstream.anonymous` | `https://opencode.ai/inference`; kênh ẩn danh thử trước, dự phòng về `/zen`. | -| `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. | -| `models.anonymous_backoff` | Tắt khi vắng mặt; `{threshold, base_hours, max_hours}`, mặc định 6, 1, 24. | -| `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" } - } -} +{"model":"MODEL_ID","max_tokens":512,"messages":[{"role":"user","content":"Xin chào"}]} ``` -Việc tắt reasoning do client chỉ định luôn được ưu tiên. `thinking.type="disabled"` nguyên bản của Anthropic và effort `"none"` của Chat/Responses vẫn được giữ ở trạng thái tắt sau khi chuyển đổi giao thức, không thể bị bật lại bởi giá trị mặc định đã cấu hình. +Client Anthropic cũng có thể gửi `anthropic-version: 2023-06-01`. Để dùng SSE, thêm `"stream": true`, dùng `curl -N` hoặc client đọc sự kiện ngay khi nhận. Stream có thể lỗi sau HTTP 200; cần xem sự kiện lỗi và kết quả cuối. -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. - -#### Proxy pool luân chuyển - -Thêm hậu tố `#pool` (hoặc tiền tố `pool+`) vào một mục để khai báo rằng endpoint đó là proxy pool luân chuyển như [Resin](https://github.com/Resinat/Resin), nơi mỗi kết nối TCP mới đi ra từ một IP khác: - -```text -http://127.0.0.1:7890#pool -socks5://127.0.0.1:1080#pool -pool+http://127.0.0.1:7891 -``` - -Mục `#pool` được xử lý khác hoàn toàn so với proxy tĩnh: - -| Hành vi | Proxy tĩnh | Mục `#pool` | -| --------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------ | -| Tái sử dụng kết nối | Keep-alive và ghép kênh HTTP/2 (tham số `performance.*`) | Một tunnel TCP + CONNECT mới cho mỗi request (`DisableKeepAlives`, không HTTP/2) | -| Cooldown khi lỗi | 15s–120s lùi theo cấp số nhân, cộng thêm `Retry-After` | Không: request kế tiếp lấy luôn exit IP mới | -| Loại bỏ theo sức khoẻ | Đánh dấu không khoẻ, chuyển key, kiểm tra lại mỗi 15 phút | Không bao giờ bị loại bỏ; bỏ qua hoàn toàn health check | -| Số lần thử kênh ẩn danh | Một lần ghé mỗi exit, tối đa `performance.max_anonymous_exits` exit | Tối đa `retry.max_attempts` lần, quay vòng mục pool | - -Dùng khi bản thân endpoint sau URL đã tự luân chuyển, còn từng exit IP trong pool bị giới hạn riêng hoặc chập chờn: gateway sẽ coi mỗi lần thử là một endpoint mới thay vì ghim cả phiên vào một exit. Chỉ cần một mục `#pool` là đủ, không cần liệt kê hàng chục exit. Các mục tĩnh vẫn giữ hành vi pooling mô tả bên dưới. - -### 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.max_anonymous_exits` | `8` | Số exit proxy tĩnh tối đa cho mỗi request ẩn danh. | -| `performance.free_tier_block_seconds` | `900` | Thời gian cooldown cho exit bị tầng miễn phí đánh dấu. | -| `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: +System One cần mô hình có `native_protocol: "systemone"` và nội dung quyết định như: ```json -{ - "protocol": "chat", - "key": { "mode": "auto" }, - "request": { - "model": "MODEL_ID", - "messages": [{ "role": "user", "content": "Hello" }] - } -} +{"model":"SYSTEM_ONE_MODEL_ID","state":"1 + 1 = 2","questions":{"arithmetic":{"type":"noul","instructions":"Is 1 + 1 equal to 2?"}}} ``` -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. +Nội dung và câu trả lời được chuyển tiếp nguyên dạng. Endpoint tin nhắn cũng nhận cấu trúc quyết định này cho mô hình System One, nhưng không chuyển tin nhắn chat thông thường thành quyết định. Stream System One từ upstream được chuyển tiếp, không có cơ chế khôi phục bằng reset stream. -**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. +### Giới hạn tương thích -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. +Ba giao thức tin nhắn hỗ trợ văn bản, ảnh/tệp biểu diễn được ở giao thức đích, suy luận, hàm, lời gọi/kết quả công cụ và streaming. Yêu cầu dùng giao thức gốc giữ các trường riêng của nhà cung cấp nếu gateway không chủ động chỉnh dạng. Chuyển đổi chỉ giữ những trường có biểu diễn tương ứng; ví dụ `seed` và ràng buộc JSON của Chat không được đổi thành tùy chọn Anthropic. Nội dung hoặc công cụ không hỗ trợ có thể bị từ chối. -### Ngôn ngữ giao diện +Khi đổi lịch sử Responses, suy luận, văn bản và lời gọi hàm của assistant được nhóm thành lượt. Tin nhắn user và kết quả công cụ ngăn cách lượt; kết quả thiếu hoặc không khớp vẫn là lỗi khi đổi sang Chat Completions. -WebUI tải bản dịch từ `webui/js/i18n.js`. Bản dịch có sẵn gồm **简体中文** (mặc định), **English**, **Tiếng Việt** và **Italiano**. Ngôn ngữ gốc **简体中文** nằm ngay trong `index.html` và `webui/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. +Gateway không triển khai embeddings, tải tệp lên, sinh ảnh, truy xuất/hủy Responses. Nó không lưu lịch sử hội thoại cho client. Hãy gửi lịch sử trong yêu cầu; tính năng có trạng thái của upstream không có nghĩa gateway lưu phiên cục bộ. -- 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. +## Cấu hình và định tuyến -Thêm một ngôn ngữ mới chỉ cần thêm một khối vào `DICTIONARY` trong `webui/js/i18n.js`, rồi khai báo mã trong `SUPPORTED`, `LABELS`, `FLAGS` và `DATE_LOCALES`, và thêm vào chuỗi phát hiện `browserLocale`. +Bắt đầu từ [config.example.json](config.example.json). Tệp cho phép chú thích `//` và `/* ... */`; nội dung API phải là JSON chuẩn. Trường không biết, giá trị sai, trường cấp cao nhất lặp lại và xung đột tên OAuth cũ/mới đều bị từ chối. Khi lưu, cấu hình được chuẩn hóa và bỏ chú thích. -### Lưu và nạp lại +| Thiết lập | Mặc định / ý nghĩa | +| --- | --- | +| `server_keys` | Phải giữ ít nhất một key cục bộ đang bật. | +| `zen_keys`, `go_keys` | Hai pool key upstream độc lập; cấu hình mẫu để trống. | +| `prefer` | `go`; cũng nhận `zen`, chọn tier xác thực ưu tiên trong các tier khả dụng. | +| `anonymous` | `false`; bật thông tin xác thực upstream `public` cho mô hình miễn phí đủ điều kiện. | +| `upstream.zen` | `https://opencode.ai/zen` cho key Zen thủ công. | +| `upstream.go` | `https://opencode.ai/zen/go` cho key Go thủ công và endpoint hạn mức. | +| `upstream.anonymous` | `https://opencode.ai/inference` cho lưu lượng ẩn danh. | +| `models.refresh_seconds` | `300`; chu kỳ khám phá mô hình. | +| `models.protocols` | Ghi đè theo mô hình: `chat`, `responses`, `anthropic`, `systemone`. | +| `models.free_only` | `false`; chỉ liệt kê và định tuyến mô hình miễn phí. | +| `models.active_probes` | `false`; yêu cầu suy luận thử cho mô hình miễn phí, tùy chọn. | +| `reasoning.effort` | Chưa đặt trong mặc định nội bộ; mẫu dùng `high`. | +| `reasoning.effort_by_model` | Ghi đè mức suy luận theo mô hình. | -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. +### Mô hình và chọn upstream -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. +Khám phá kết hợp danh sách upstream với khả năng và giá OpenCode tại `https://models.opencode.ai/api.json`. Giao thức gốc được lưu riêng theo tier. `/v1/models` cung cấp giới hạn ngữ cảnh/token đã biết, giá, `native_protocol`, `supported_endpoints` và thông tin suy luận. Giá và trạng thái ngừng hỗ trợ cập nhật mỗi 24 giờ; lỗi cập nhật giữ dữ liệu trước đó. Giá không phải số dư hay dự toán hóa đơn. -## Giám sát và lưu trữ +Với key thủ công, mô hình miễn phí đủ điều kiện có thể thử kênh ẩn danh trước nếu chủ động bật, sau đó các tier có key theo `prefer`. Khi tắt ẩn danh, dùng key đã cấu hình. Điều kiện miễn phí là ID chứa `free` không phân biệt hoa thường, hoặc metadata chưa ngừng hỗ trợ có giá input/output bằng không; điều này không bảo đảm upstream chấp nhận. Mô hình trả phí cần tuyến xác thực phù hợp. `models.free_only` cũng lọc thành viên nhóm luân chuyển. -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. +OAuth có quy tắc riêng: yêu cầu đã chọn tier OAuth chỉ dùng tuyến được xác nhận của tier đó, không chuyển sang ẩn danh, key thủ công hay tier khác sau lỗi. Go OAuth không kích hoạt PAYG khi lỗi xác thực, hết hạn mức hoặc 429. Nếu cả hai tier có mô hình, chủ động chọn `prefer: "zen"` cho phép dùng kết nối Zen PAYG. -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. +### Timeout, proxy và gắn kết phiên -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`. +| Thiết lập | Mặc định | Ý nghĩa | +| --- | --- | --- | +| `retry.max_attempts` | `3` | Ngân sách vòng thử với key; ẩn danh và luân chuyển có quy tắc riêng. | +| `retry.timeout_seconds` | `300` | Ngân sách toàn yêu cầu, kể cả đọc stream. | +| `performance.attempt_timeout_seconds` | `0` | Giới hạn ngắn hơn cho từng lần thử; zero giữ timeout toàn yêu cầu. | +| `performance.first_event_timeout_seconds` | `0` | Thời gian đợi sự kiện đầu, tùy chọn; zero tắt. | +| `performance.connect_timeout_seconds` | `5` | Timeout thiết lập kết nối. | +| `performance.failure_cooldown_seconds` | `15` | Thời gian nghỉ cơ sở sau lỗi. | +| `performance.max_anonymous_exits` | Hiệu lực `8` | Số lối ra tĩnh riêng biệt cho một yêu cầu ẩn danh; zero dùng giới hạn nội bộ. | +| `performance.free_tier_block_seconds` | Hiệu lực `900` | Thời gian nghỉ khi upstream chặn lối ra miễn phí; zero dùng giá trị nội bộ. | +| `performance.max_idle_conns` | `2048` | Kết nối nhàn rỗi cho mỗi transport. | +| `performance.max_idle_conns_per_host` | `256` | Kết nối nhàn rỗi theo host/transport. | +| `performance.max_conns_per_host` | `0` | Giới hạn kết nối; zero là không giới hạn. | +| `performance.idle_conn_timeout_seconds` | `120` | Tuổi thọ kết nối nhàn rỗi. | -| 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`. | +`proxies` nhận `direct`, HTTP, HTTPS, SOCKS5 và SOCKS5H. `proxyfile` thêm một proxy trên mỗi dòng không trống, đường dẫn tương đối với thư mục cấu hình; loại trùng và dùng trực tiếp nếu danh sách cuối trống. Chú thích bắt đầu bằng `#`, `;`, `//` ở đầu dòng hoặc sau khoảng trắng. Tài khoản/mật khẩu trong URL proxy là bí mật. -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. +Với endpoint do nhà cung cấp tự xoay lối ra, dùng `pool+https://proxy.example:8443` hoặc `https://proxy.example:8443#pool`. Mỗi lần thử mở kết nối mới, không tái sử dụng keep-alive/HTTP/2, không áp dụng thời gian nghỉ hay loại theo sức khỏe như nút tĩnh. Nhà cung cấp phải thực hiện việc xoay. Proxy tĩnh giữ tái sử dụng kết nối, theo dõi sức khỏe và gắn key. `proxy_bindings` gắn dấu vân tay key với proxy đã cấu hình. -### Health check +Gửi `x-session-id` để tách hội thoại rõ ràng. Header phiên OpenCode và các trường hội thoại được hỗ trợ cũng có hiệu lực; nếu thiếu, nội dung system/user ban đầu làm hạt giống. ID tự tạo được giới hạn theo key cục bộ và vòng đời tiến trình. ID chính thức OpenCode hợp lệ được giữ nguyên. Dùng ID riêng cho hội thoại độc lập và key riêng để cách ly người dùng: các hội thoại cùng key có mở đầu giống nhau có thể chia sẻ gắn kết. -`/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. +Đối tượng tùy chọn `models.anonymous_backoff` tạm dừng cả kênh ẩn danh sau nhiều lỗi: ngưỡng mặc định `6`, thời gian cơ sở `1` giờ, tối đa `24` giờ. Không đặt đối tượng này sẽ tắt bộ ngắt cấp kênh. -- 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`. +### Chỉnh dạng yêu cầu miễn phí và suy luận -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. +Tương thích mô hình miễn phí có thể chèn prompt/công cụ chính thức OpenCode, đổi tên công cụ trên đường truyền và khôi phục tên trong phản hồi. Mô hình miễn phí dùng key cũng chịu xử lý này. Gateway chỉ chuyển tiếp lời gọi, không chạy công cụ trên máy. System One không đi qua chỉnh dạng tin nhắn/công cụ. -## Phát triển +Prompt chèn thêm có thư mục, workspace, nền tảng, mô hình và ngày UTC; mặc định mô tả máy gateway. Có thể đặt văn bản tương thích cho client từ xa trong `upstream.prompt_environment`: -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 các tài nguyên tĩnh vào file thực thi - index.html Cấu trúc trang - css/ Design token, kiểu cơ sở, thành phần và bố cục trang - js/ Module ES: vỏ giao diện, i18n, trợ giúp dùng chung và mỗi trang một module +```json +{"working_directory":"C:\\work\\project","workspace_root":"C:\\work\\project","platform":"windows","is_git_repo":true} ``` -Thứ tự đọc gợi ý: +Ghép đối tượng vào trường trên. Đường dẫn chỉ là văn bản, không được truy cập do thiết lập này. `windows` thành `win32`; cũng chấp nhận `linux`, `darwin`. Prompt chính thức client đã gửi không bị thay. UI chưa có trường riêng cho giá trị nâng cao này; sửa và nạp lại tệp. Giá trị ghi đè tùy ý chưa được xác minh với kiểm tra thực tế của upstream. -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/js/main.js) bao phủ cấu hình và chẩn đoán. +Mức suy luận nhận `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, `none`, `auto` hoặc rỗng. Mức client chỉ định rõ có ưu tiên. `none` bỏ thiết lập suy luận. `auto` dùng mức trần mới được xác minh cho mô hình miễn phí Zen/ẩn danh, không mở rộng phạm vi thử. Khám phá tự động cần bật thử chủ động, có thể dùng nhiều yêu cầu tiêu hao hạn mức và hết hiệu lực sau hai giờ. Không suy đoán mức cho Go, mô hình trả phí hay khả năng chưa xác minh. -Chạy định dạng Go, phân tích và build lệnh: +Mặc định học khả dụng từ lưu lượng thật. Yêu cầu thử tổng hợp chỉ chạy khi `models.active_probes: true`; lệnh thử trong quản trị chỉ lên lịch, không bỏ qua công tắc. Chỉ bằng chứng rõ ràng mô hình không tồn tại/đã nghỉ mới có thể tắt mô hình. Giới hạn tốc độ, lỗi xác thực, lỗi chung và timeout không chứng minh việc ngừng cung cấp. Khôi phục thủ công giữ mô hình bật và loại khỏi thử tự động cho đến khi chuyển lại điều khiển tự động. + +### WARP + +`warp.enabled` mặc định `false`. Khi bật, lưu lượng miễn phí ẩn danh/Zen thủ công cùng đường khám phá/thử dùng tunnel Cloudflare WARP trong tiến trình. Go, mô hình trả phí và OAuth vẫn dùng proxy đã cấu hình. Cần UDP đi ra đến Cloudflare cổng `2408`; không cần TUN hay đổi bảng định tuyến. Lỗi khởi tạo khiến việc khởi động hoặc cấu hình mới bị từ chối. + +`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. + +## 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). + +Quản trị dùng cookie phiên, token CSRF cho thao tác ghi và giới hạn đăng nhập. Đổi thông tin quản trị làm phiên mất hiệu lực. Key API cục bộ không cấp quyền quản trị. `GET /api/config` che bí mật; xác minh mật khẩu lại có thể hiện key thủ công/proxy nhưng không bao giờ trả token OAuth. + +Từ **Mô hình và hạn mức**, bắt đầu Device OAuth. Tự mở URL xác minh chính thức, nhập `user_code`, chấp thuận yêu cầu do mình khởi tạo và chọn tổ chức/workspace nếu được hỏi. Backend xử lý thăm dò và làm mới; không dùng dán token, nhập tệp xác thực cục bộ hay gửi URL callback. + +| Kết nối | Phạm vi và giới hạn | +| --- | --- | +| Go OAuth | Chỉ tuyến gói Go chính thức; hạn mức hiển thị chưa biết. | +| Zen OAuth | Console PAYG tiêu hao credits workspace; phải xác nhận rõ trước khi bắt đầu, số dư chưa biết. | + +Go và Zen tách riêng phiên đăng nhập chờ, thông tin xác thực, làm mới và ngắt kết nối. Ẩn/rời trang dừng thăm dò; quay lại có thể tiếp tục đăng nhập chưa hết hạn. Đăng xuất quản trị hủy đăng nhập chờ của phiên nhưng giữ kết nối hoàn tất. Hủy đăng nhập chờ không ngắt tài khoản đã lưu. + +`go_oauth` và `zen_oauth` trong cấu hình chứa thông tin truy cập/làm mới: phải bảo vệ cấu hình và bản sao lưu. Key thủ công còn được giữ nhưng không làm dự phòng khi OAuth tương ứng tồn tại, kể cả khi cần đăng nhập lại. Ngắt chỉ xóa kết nối cục bộ, phục hồi tuyến thủ công sau khám phá, không thu hồi phiên chính thức. Giữ thông tin xác thực khác trước khi ngắt kết nối cuối với ẩn danh đang tắt. + +Chỉ nhận tuyến từ cấu hình từ xa chính thức đã xác thực, vượt kiểm tra URL/SDK theo từng gói. Không suy ra URL PAYG từ Go hay nhập header từ xa tùy ý. Lưu cấu hình thông thường giữ thông tin OAuth do backend quản lý. Trường cũ `go_subscription`/`zen_subscription` được chuyển khi nạp; kết hợp tên cũ/mới cho cùng gói sẽ bị từ chối. + +Triển khai dựa trên ảnh chụp mã nguồn upstream liệt kê trong hướng dẫn. Đây là mô tả mã, không phải xác minh đăng nhập/suy luận thật cho mọi tài khoản; quyền và định dạng tuyến có thể đổi. + +### Key cục bộ, hạn mức và luân chuyển + +Trang key hỗ trợ tạo, đặt tên, bật, tắt, xóa. Key sinh tự động có 192 bit ngẫu nhiên. Key tự đặt dài 16–256 ký tự chữ, số, `.`, `_`, `-`; tên dài 1–80 ký tự, tối đa 200 key, ít nhất một key bật. Thay đổi áp dụng ngay cho yêu cầu mới. Chưa có quyền mô hình, trần chi tiêu hay ngày hết hạn riêng theo key. + +Hạn mức key Go thủ công lấy từ `/v1/usage` trên upstream Go đã cấu hình: phần trăm cửa sổ dùng chung theo chu kỳ trượt/tuần/tháng, không phải số dư từng mô hình. Nhiều key có thể dùng chung gói, không cộng phần trăm. Thành công cache 60 giây, lỗi 15 giây; dữ liệu trước đó được đánh dấu cũ. Hạn mức/credits OAuth chưa biết và không suy từ key thủ công hay yêu cầu thành công. + +Bí danh `sota`, `sweet` dùng mô hình Go tại ba endpoint tin nhắn, kể cả streaming. Mỗi nhóm có mô hình hiện tại dùng chung toàn dịch vụ: giữ sau thành công, tiến khi lỗi. SOTA gồm `deepseek-v4.1-flash`, `glm-5.3`, `grok-4.6`, `kimi-k3`, `qwen3.8-max`; Sweet thu thập các mô hình Go phù hợp còn lại. Khả dụng thực tế theo kết quả khám phá. Sửa bí danh, thứ tự, timeout đầu ra đầu tiên tại `/#rotation`. + +Ngân sách lỗi thường là ba mô hình, tối đa ba lần mỗi mô hình. Hết hạn mức/giới hạn tốc độ bỏ qua ngay; luân chuyển không tạo thêm hạn mức dùng chung. Khi nội dung stream đã gửi, lỗi kết thúc câu trả lời và tiến nhóm cho yêu cầu tiếp theo. `model` giữ bí danh, `X-Resolved-Model` chỉ mô hình thật. Trạng thái lưu cạnh cấu hình. + +## Vận hành và bảo mật + +Lưu cấu hình kiểm tra và tạo runtime thay thế trước khi áp dụng. Lỗi kiểm tra/lưu giữ runtime hiện tại. Key, proxy, tuyến, mô hình và log áp dụng cho yêu cầu mới; listener và bật/tắt WebUI cần khởi động lại. Sau khi sửa tệp, nạp lại qua UI hoặc `POST /api/config/reload`; không tự theo dõi tệp. + +| Dữ liệu | Nơi lưu | +| --- | --- | +| Cấu hình và phiên bản trước | `config.json`, `config.json.bak`. | +| Cache mô hình/metadata | `config.json.models.catalog.json`, `config.json.models.dev.json`. | +| Khả dụng và luân chuyển | `config.json..availability.json`, `config.json.rotation.json`. | +| Phiên, sử dụng, yêu cầu/lần thử gần đây, log vòng, Playground gần nhất | Bộ nhớ; xóa khi tiến trình khởi động lại. | +| Log cấu trúc | JSON trên stdout; cần bộ thu để lưu lâu dài. | + +Tên tệp theo đường dẫn cấu hình thực tế. Theo dõi giữ qua nạp nóng nhưng không chia sẻ giữa tiến trình. Token chỉ lấy số upstream báo, không ước tính phần thiếu. Kết quả toàn yêu cầu và lần thử đến khi nhận header là hai thước đo khác nhau. Playground có nhóm sử dụng riêng. Một giờ gần nhất giữ tối đa 10.000 yêu cầu/20.000 lần thử, API trả tối đa 500 mỗi loại. + +`GET /healthz` không gọi upstream, không cần key. Khám phá chưa xong/trống, WARP không dùng được hoặc thiếu proxy khỏe bắt buộc trả 503. Danh mục cũ nhưng dùng được có thể trả 200 với `status: "degraded"`; ngưỡng cũ là hai lần chu kỳ, ít nhất 60 giây. Sẵn sàng không chứng minh key hợp lệ, đủ hạn mức hay suy luận thành công. Phản hồi công khai chỉ có số lượng/trạng thái, không có bí mật hay địa chỉ proxy. + +Dùng loopback cho API và quản trị cục bộ. Khi truy cập qua mạng, dùng HTTPS và giới hạn lối vào quản trị. Reverse proxy tin cậy phải đặt `X-Forwarded-Proto` đúng; giới hạn dùng địa chỉ peer trực tiếp, nên client cùng proxy chia sẻ giới hạn. Tệp thực thi phục vụ HTTP. + +Cấu hình/bản sao lưu chứa key upstream, mật khẩu proxy, token OAuth; hash mật khẩu không mã hóa chúng. Hạn chế quyền tệp, dùng ACL trên Windows, và loại tệp runtime khi chia sẻ mã. `logging.dump_request_bodies` mặc định tắt và cần mức debug; nội dung đã cắt/che vẫn có thể lộ hội thoại. Playground và thử chủ động có thể tiêu hao hạn mức hoặc credits thật. + +## Phát triển và xác minh cục bộ + +`cmd/opencode2api` khởi động dịch vụ. Trong `internal`, `admin` quản trị, `gateway` định tuyến/runtime, `protocol` chuyển JSON/SSE, `models` khám phá, `oauth` xác thực chính thức, `config` kiểm tra/lưu, `telemetry` số liệu/log. Tài nguyên tĩnh ở `webui`, không cần cài gói frontend. + +Trong môi trường phát triển thông thường, dùng các lệnh Go sau. Muốn giữ cache trong dự án, đặt `GOCACHE`, `GOMODCACHE` vào thư mục cục bộ bền vững: ```bash -gofmt -w cmd internal webui go vet ./... -go build -o opencode2api ./cmd/opencode2api +go build -trimpath -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: +Node.js chỉ cần cho kiểm tra cú pháp JavaScript tùy chọn, không cài gói. Chạy Bash, hoặc Git Bash trên Windows: ```bash -for f in webui/js/*.js webui/js/pages/*.js; do node --input-type=module --check < "$f"; done +for file in webui/js/*.js webui/js/pages/*.js; do + node --input-type=module --check < "$file" || exit 1 +done ``` -`.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ả bốn README. +Chạy các lệnh bằng Bash; trên Windows có thể dùng Git Bash. Xem các bước kiểm tra trước khi triển khai trong [hướng dẫn quản trị](docs/management.vi.md#kiểm-tra-và-bảo-trì). Có thể chèn phiên bản phát hành bằng `-ldflags "-X main.version=vX.Y.Z"`. -## Khắc phục sự cố +| Hiện tượng | Nội dung cần xem | +| --- | --- | +| API 401 | Key cục bộ, trạng thái bật và header client. | +| Không khởi động do thiếu xác thực | Cấu hình key/OAuth đã lưu hoặc chủ động bật ẩn danh. | +| Không có mô hình / health 503 | Danh mục, giao thức hỗ trợ, xác thực cấu hình và tài nguyên. | +| OAuth lỗi | Trạng thái tài khoản an toàn và yêu cầu đăng nhập lại; không tự chuyển PAYG. | +| HTTP 200 nhưng sinh thất bại | Sự kiện SSE, kết quả yêu cầu và log `x-request-id`. | +| Thay đổi không có hiệu lực | Lưu/nạp tệp đang dùng; khởi động lại khi đổi listener. | +| Sửa tệp host không đổi Compose | Cấu hình hoạt động ở volume trạng thái; nhập lại hoặc dùng WebUI. | +| Sử dụng mất sau khởi động lại | Bộ đếm ở bộ nhớ; lưu log riêng. | -| 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. | +Trước nâng cấp, sao lưu an toàn chương trình, cấu hình và trạng thái. Dừng tiến trình trước khi thay tệp thực thi; quay lui cần khôi phục bộ phiên bản tương thích của cả ba. ## 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. +SPDX-License-Identifier: GPL-3.0-or-later. Xem đầy đủ tại [LICENSE](LICENSE). Phần mềm không kèm bảo hành. diff --git a/README.zh-CN.md b/README.zh-CN.md index 35d7c47..42180c8 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -2,26 +2,9 @@ [English](README.md) | [简体中文](README.zh-CN.md) | [Tiếng Việt](README.vi.md) | [Italiano](README.it.md) -使用 Go 编写的 **OpenCode Zen / Zen Go API 网关**。对外提供 Chat Completions、Responses 和 Anthropic Messages 接口,按上游原生协议转换请求,并统一管理上游 Key 与代理。 +使用 Go 编写的 OpenCode Zen / Zen Go 网关。客户端调用 OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages,网关选择可用上游,并在原生协议不同时转换请求和响应。System One 决策使用独立透传接口。 -WebUI 内嵌在可执行文件中,运行服务无需 Node.js 或数据库。 - -## 功能 - -- 三种推理协议之间的普通 JSON 响应与 SSE 流式转换。 -- 文本、图片、reasoning、函数工具、工具调用和工具结果;目标协议允许时支持文件内容转换。 -- 独立的 Zen / Go Key 池,可配置优先级、重试和会话亲和性。 -- 使用 OpenCode `public` 凭证的可选 Zen 匿名通道,默认关闭,上游封堵可能使其不可用。 -- 可选的用户态 Cloudflare WARP 出口,免费模型流量无需 TUN 或 root 权限。 -- 直连、HTTP、HTTPS、SOCKS5、SOCKS5H 连接,以及代理文件。 -- 动态模型发现、原生协议与能力信息、磁盘缓存。 -- 独立管理端口,支持配置编辑、Playground、路由诊断、Token 统计和实时日志。 -- 配置热重载:先验证新配置,再切换新请求使用的 Gateway。 -- Go 共享套餐额度看板,显示剩余百分比、重置时间和可用模型。 -- API Key 生成、自定义、命名、启停和删除,变更立即生效。 -- `sota` / `sweet` 分组别名,支持模型排序、故障切换、流式输出保护和状态恢复。 - -新增页面及调用示例见[管理控制台说明](docs/management.zh-CN.md)。 +管理 WebUI 内嵌于可执行文件,运行时无需 Node.js 或数据库。模型发现、推理、OAuth 和可选 WARP 仍需访问相应上游服务。 ## 赞助商 @@ -53,7 +36,7 @@ go build -o opencode2api ./cmd/opencode2api 启动前编辑 `config.json`: 1. 将 `server_keys` 替换为自己的本地 API Key。 -2. 在 `zen_keys` 填入 Zen API Key(推荐),或在 `go_keys` 填入 Go Key。示例关闭匿名通道,且两个上游 Key 数组为空,必须先配置上游凭证才能启动;已有的 Go 订阅连接也满足此要求。 +2. 在 `zen_keys` 填入 Zen API Key(推荐),或在 `go_keys` 填入 Go Key。示例关闭匿名通道,且两个上游 Key 数组为空,必须先配置上游凭证才能启动;已保存的 Go OAuth(`go_oauth`)或 Zen OAuth(`zen_oauth`)连接也满足此要求。不支持在凭证全空时先启动服务、再进入 WebUI 完成首次 OAuth 登录。 3. 替换 `webui.password`。示例配置启用了 WebUI,用户名为 `admin`。 **匿名通道可能已被上游重点封堵,优先使用 Zen API Key。** 配置与 WebUI 默认关闭匿名访问;已有配置中明确设置的 `anonymous: true` 不会被自动改为关闭。只有接受免费请求仍可能失败时,才主动开启。 @@ -76,558 +59,268 @@ Windows 下使用 `Copy-Item config.example.json config.json` 复制配置,执 配置所在目录需要可写,以便迁移密码、保存配置和写入模型缓存。 -## Docker 部署 +## Docker 与 Compose -已发布镜像:`ghcr.io/jasonxu114514/opencode2api`。 +已发布镜像为 `ghcr.io/jasonxu114514/opencode2api`。先按前文准备 `config.json`。需要通过发布端口访问时,容器内部 API/WebUI 应监听 `0.0.0.0:8080`、`0.0.0.0:8081`;访问范围由宿主机端口绑定及必要的 HTTPS 入口限制。 ```bash -cp config.example.json config.json -# 启动前填写 Key,并替换 WebUI 密码。 docker compose up -d docker compose logs -f ``` -Compose **仅在首次启动时**将宿主机配置导入 `opencode2api-state` 命名卷。后续建议通过 WebUI 修改配置。需要重新导入宿主机文件时: +Compose **仅在首次启动**从宿主配置初始化 `opencode2api-state` 卷。此后实际配置位于卷中,建议通过 WebUI 修改。需重新导入宿主文件时: ```bash docker compose cp config.json opencode2api:/var/lib/opencode2api/config.json docker compose restart ``` -容器内的服务进程使用普通用户运行。Compose 启用只读根文件系统,并提供可写状态卷和临时 `/tmp` 文件系统。 +覆盖前先备份实际配置与状态。入口脚本以普通用户运行服务,仅在初始化时把示例 API 的准确值 `127.0.0.1:8080` 改为 `0.0.0.0:8080`。Compose 使用只读根文件系统、可写状态卷与 `/tmp` tmpfs。发布端口默认绑定宿主全部接口;仅本机访问时,将 `ports` 改为 `127.0.0.1:8080:8080`、`127.0.0.1:8081:8081`。 -WARP 只需要出站 UDP(Cloudflare 端点端口 `2408`),因此镜像的普通用户、无 `NET_ADMIN` 配置无需改动;不要为此改用 host 网络或添加 `--cap-add`。如果容器网络禁止 UDP,启用 WARP 会在启动时失败。 +| Compose 变量 | 默认值 | 作用 | +| --- | --- | --- | +| `OPENCODE2API_VERSION` | `latest` | 镜像标签;固定版本时指定发行标签。 | +| `OPENCODE2API_PORT` | `8080` | 宿主 API 端口。 | +| `OPENCODE2API_WEBUI_PORT` | `8081` | 宿主管理端口。 | +| `OPENCODE2API_LISTEN` | 未设置 | 显式覆盖容器 API 监听。 | +| `OPENCODE2API_WEBUI_LISTEN` | 未设置 | 显式覆盖容器管理监听。 | -| Compose 环境变量 | 默认值 | 作用 | -| --------------------------- | -------- | ------------------------------------ | -| `OPENCODE2API_VERSION` | `latest` | 镜像标签;可指定发行标签来固定版本。 | -| `OPENCODE2API_PORT` | `8080` | 映射到容器 8080 的宿主机端口。 | -| `OPENCODE2API_WEBUI_PORT` | `8081` | 映射到容器 8081 的宿主机端口。 | -| `OPENCODE2API_LISTEN` | 未设置 | 显式覆盖容器内 API 监听地址。 | -| `OPENCODE2API_WEBUI_LISTEN` | 未设置 | 显式覆盖容器内 WebUI 监听地址。 | +后两项在容器内为 `LISTEN_ADDRESS`、`WEBUI_LISTEN_ADDRESS`,为空时沿用实际配置。更改宿主端口不更改内部监听;更改内部 API 端口还须修改映射及默认检查 8080 的镜像健康检查。`proxyfile` 必须挂载到配置的容器内路径。 -后两项在容器内对应 `LISTEN_ADDRESS` 与 `WEBUI_LISTEN_ADDRESS`。值为空时使用配置文件中的地址。首次初始化配置时,入口脚本会将示例 API 地址 `127.0.0.1:8080` 改为 `0.0.0.0:8080`,使其能够通过发布端口访问。 - -修改宿主机端口不会改变容器内监听地址。如果修改容器内 API 端口,还需要同步调整端口映射和镜像健康检查;默认健康检查使用 8080 端口。 - -构建并运行本地镜像: +需要本地镜像时: ```bash docker build -t opencode2api:local . docker volume create opencode2api-state docker run -d --name opencode2api \ - -p 8080:8080 -p 8081:8081 \ + -p 127.0.0.1:8080:8080 -p 127.0.0.1:8081:8081 \ -e CONFIG_SEED_PATH=/run/config/opencode2api.json \ - -v "$(pwd)/config.json:/run/config/opencode2api.json:ro" \ + -v "$PWD/config.json:/run/config/opencode2api.json:ro" \ -v opencode2api-state:/var/lib/opencode2api \ opencode2api:local ``` -在 Docker 中使用 `proxyfile` 时,代理文件也需要挂载到容器内配置指定的位置。 +WARP 需要向 Cloudflare `2408` 端口发送 UDP,不需要 host 网络或额外网络能力;网络阻断该流量时无法初始化 WARP。 -## API 调用 +## 调用 API -`server_keys` 用于客户端调用本地网关,与 `zen_keys`、`go_keys` 相互独立,不会作为上游认证凭证发送。 +以下是现有兼容接口。OpenAI 兼容客户端的 Base URL 可填 `http://127.0.0.1:8080/v1`;管理接口位于另一监听端口。 -请求可以使用 `Authorization: Bearer YOUR_LOCAL_API_KEY` 或 `x-api-key: YOUR_LOCAL_API_KEY`。健康检查无需认证。 +| 方法 | 路径 | 行为 | +| --- | --- | --- | +| `GET` | `/v1/models` | 当前配置可路由的模型,以及符合条件的轮转别名。 | +| `POST` | `/v1/chat/completions` | Chat Completions,支持 JSON 和 SSE。 | +| `POST` | `/v1/responses` | Responses,支持 JSON 和 SSE。 | +| `POST` | `/v1/messages` | Anthropic Messages,支持 JSON 和 SSE。 | +| `POST` | `/v1/systemone` | 原生 System One 决策透传,不转换协议。 | +| `GET` | `/healthz` | 无需认证的就绪检查与资源摘要。 | -| 方法 | 路径 | 用途 | -| ---- | ---------------------- | -------------------------- | -| GET | `/v1/models` | 当前配置下可以路由的模型。 | -| POST | `/v1/chat/completions` | Chat Completions。 | -| POST | `/v1/responses` | Responses。 | -| POST | `/v1/messages` | Anthropic Messages。 | -| POST | `/v1/systemone` | System One 结构化决策。 | -| GET | `/healthz` | 就绪状态与资源汇总。 | +全部 `/v1/*` 接口要求通过 `Authorization: Bearer ...` 或 `x-api-key` 提交已启用的 `server_keys` 值。请求体上限为 32 MiB。推理响应的 `x-request-id` 可用于关联日志。 -先获取可用模型: +先查询实际可用的模型 ID: ```bash -curl http://localhost:8080/v1/models \ - -H "Authorization: Bearer YOUR_LOCAL_API_KEY" +curl http://127.0.0.1:8080/v1/models \ + -H 'Authorization: Bearer YOUR_LOCAL_API_KEY' + +curl http://127.0.0.1:8080/v1/chat/completions \ + -H 'Authorization: Bearer YOUR_LOCAL_API_KEY' \ + -H 'Content-Type: application/json' \ + -d '{"model":"MODEL_ID","messages":[{"role":"user","content":"你好"}]}' ``` -将以下示例中的 `MODEL_ID` 替换为模型列表返回的 ID。 - -**Chat Completions** - -```bash -curl http://localhost:8080/v1/chat/completions \ - -H "Authorization: Bearer YOUR_LOCAL_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{"model":"MODEL_ID","messages":[{"role":"user","content":"Hello"}]}' -``` - -**Responses** - -```bash -curl http://localhost:8080/v1/responses \ - -H "Authorization: Bearer YOUR_LOCAL_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{"model":"MODEL_ID","input":"Hello"}' -``` - -**Anthropic Messages** - -```bash -curl http://localhost:8080/v1/messages \ - -H "x-api-key: YOUR_LOCAL_API_KEY" \ - -H "anthropic-version: 2023-06-01" \ - -H "Content-Type: application/json" \ - -d '{"model":"MODEL_ID","max_tokens":512,"messages":[{"role":"user","content":"Hello"}]}' -``` - -需要流式响应时,在请求体中加入 `"stream": true`,并使用 `curl -N`。响应通过 `x-request-id` 提供请求关联标识。API 请求体上限为 32 MiB。 - -**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 将自由文本状态与类型化问题配对,并返回类型化答案,因此其负载与 chat/responses 桥接结构完全不同,只做原样转发,不做任何转换。只有原生协议为 System One 的模型才能在本接口提供服务;在消息接口(`/v1/chat/completions`、`/v1/responses`)上提交的决策负载同样原样转发,而不经过转换。上游的流式回复按原样透传,不做中断恢复。 - -### 协议兼容边界 - -客户端协议与上游原生协议相同时,会保留供应商特有字段。跨协议请求经过统一中间结构转换,部分参数没有等价表达。例如,Chat 的 JSON 输出约束与 `seed` 不会被转发到 Anthropic Messages。不支持的内容块或工具类型可能被拒绝。 - -转换 Responses 历史时,相邻的 assistant reasoning、文本和函数调用项目会组成同一轮 assistant 消息,包括函数调用之间穿插文本的情况。工具结果和 user 消息会分隔轮次;转换为 Chat Completions 时,缺失或不匹配的工具结果仍会被拒绝。 - -网关仅实现上表中的接口,不提供 embeddings、文件上传、图像生成、Responses 查询或取消接口。网关不保存会话历史;客户端需要提交历史,或使用实际上游支持的相关能力。 - -## 路由与模型 - -### 模型发现 - -服务按配置周期刷新 Zen / Go 的 `/v1/models` 和 OpenCode [能力目录](https://models.opencode.ai/api.json),分别记录两个 Tier 的原生协议与模型限制。OpenCode 的 Zen / Go 文档作为协议发现的回退来源。 - -可通过 `models.protocols` 覆盖自动发现结果: +Responses 与 Anthropic Messages 分别使用以下标准 JSON 请求体,发送到对应接口: ```json -{ - "models": { - "refresh_seconds": 300, - "protocols": { - "custom-model": "chat" - } - } -} +{"model":"MODEL_ID","input":"你好"} ``` -协议值仅允许 `chat`、`responses`、`anthropic`。使用不支持的原生协议的模型会从模型列表中隐藏,除非配置了覆盖值。 - -成本、弃用信息及模型限制来自官方 [OpenCode 元数据地址](https://models.opencode.ai/api.json),每 24 小时刷新一次。能力目录中的限制优先;元数据中的 `limit.context`、`limit.input` 和 `limit.output` 仅补充缺失字段,通过 `/v1/models` 的 `context_window` / `context_length`、`max_input`、`max_output` 暴露。每个 HTTP 客户端的拉取超时为 30 秒,刷新失败时保留已有数据。升级后继续兼容原有 `.models.dev.json` 缓存文件名,无需删除缓存。 - -元数据给出价格时,`/v1/models` 的每个条目还会带上 `cost`(每百万 token 的美元价格:`input`、`output`、`cache_read`、`cache_write`,以及 OpenClaw 使用的 `cacheRead` / `cacheWrite`)。推理模型会在 `reasoning_efforts` 和 OpenClaw 读取的 `compat.supportedReasoningEfforts` 中列出可用档位:`minimal` 到 `max`;思考强度为 `auto` 时截止到探测得到的上限。强制或探测得到的档位通过 `default_reasoning_effort` 给出。缓存价格字段会在下一次元数据刷新后出现。 - -### 匿名通道与回退 - -**匿名通道可能已被上游重点封堵,优先使用 Zen API Key。** 内置默认值与示例均为 `anonymous: false`,WebUI 不自动启用匿名通道,也不修改已有配置中明确设置的 `true`。 - -启用 `anonymous: true` 后,满足以下任一条件的模型可以进入 Zen 匿名通道: - -- 模型 ID 包含 `free`,不区分大小写。 -- OpenCode 元数据中的输入、输出成本均为零,且模型未弃用。 - -这只是网关的路由判断,上游仍可能拒绝或限制请求。匿名请求在上游认证头中使用 `public` 凭证。 - -路由顺序: - -1. 符合条件的模型最多尝试 `performance.max_anonymous_exits` 个可用匿名代理,每个代理一次;仅使用 v2 `/inference`,免费模型的 v1 `/zen` 回退已停用。 -2. 按 `prefer` 顺序尝试认证通道,仅包含已配置 Key 且可以提供该模型的 Tier。 -3. 每个认证 Tier 分别使用 `retry.max_attempts` 预算。 - -匿名阶段不受 `retry.max_attempts` 截断,但所有阶段共享请求总超时。网络错误、认证失败、限流和服务端错误可以触发出口轮换。请求级 `400`/`413`/`422`(例如 `context_length_exceeded`)会立即结束请求:换出口或换 Tier 都无法改变请求本身。IP 级 abuse `403` 只淘汰当前出口;所有出口都被封时停止扫描,已配置的 Go Key 仍可继续服务。 - -如果后续重试在收到 HTTP 响应前发生传输错误,网关会保留最近一次上游 HTTP 错误,而不是用传输错误覆盖它。状态码和 `Retry-After` 保持不变,响应体最多在内存中保留 64 KiB,沿用现有错误消息转换。重试前会释放原响应连接或 WARP 出口;后续真实 HTTP 响应会取代旧响应,客户端取消仍优先处理。此行为不更换会话标识、不增加重试预算,也不改变上游额度。 - -配置 `models.anonymous_backoff` 后,连续 `threshold` 次匿名失败或所有出口都被 IP 封禁会暂停整条匿名通道 `base_hours`,之后每次再触发翻倍,直到 `max_hours`。单个非滥用 `403` 或 `429` 不会立即熔断,只计入连续失败。暂停期间不取代理、不发任何上游请求(包括模型目录刷新和可用性探测),路由直接落到认证通道。窗口到期后只允许一个请求做半开探测:成功关闭熔断并恢复匿名通道,失败则开启下一个更长的窗口。省略该配置块时熔断关闭。 - -每个 Tier 使用自己的原生协议编码请求。启用 `performance.first_event_timeout_seconds` 后,会先等待完整的 SSE data 事件再向客户端交付响应;注释心跳不算首事件。首事件前超时或断开会沿用现有 Key / 代理重试预算,交付后不再重放。默认 `0` 关闭,可对接受请求后无事件的上游尝试设置为 `15` 秒。它限制首事件而非首个文本 token,不适用于 System One;轮转别名使用独立的 `rotation.first_output_seconds`。识别到过期的 Responses reasoning 引用时,可执行一次修复重试;指定 Key 的诊断不会执行该重试。 - -已知 OpenCode 标题请求在提示词和消息整形前判定,避免整形改变消息数量后,误加 agent 工具或把普通 agent 请求误判为标题请求。既有标题特征和历史限制保持不变;这并不代表所有 `FreeUsageLimitError` 都已解决。 - -只有匿名通道可用时,`/v1/models` 仅展示符合匿名条件的模型。 - -只有明确启用匿名通道后,符合条件的免费模型才可尝试不使用 Zen Key,但这不保证上游允许访问。如果想保留认证 Key 但只暴露免费模型,设置 `models.free_only: true`:付费模型不再出现在 `/v1/models`,直接请求会被拒绝,轮转别名只保留免费成员;匿名关闭时免费模型使用已配置的 Key,开启时也可回退到这些 Key。 - -### 免费模型 WARP 出口 - -启用 `warp.enabled` 后,免费通道上的所有免费模型请求——匿名通道、通过 Zen Key 的免费模型回退、免费模型可用性探测,以及匿名模型目录刷新——都改走用户态 Cloudflare WARP 隧道,不再使用任何代理,因此上游看到的是 WARP 出口地址,而不是配置的节点。Go 套餐 Key 与付费模型仍使用原有代理绑定。 - -隧道运行在网关进程内:注册 WARP 设备,通过 UDP 与 Cloudflare 建立 WireGuard 连接,并在用户态网络栈中终结。它不需要 TUN 设备、root、`NET_ADMIN` 或修改路由表,但宿主机(或容器)必须能向 Cloudflare 端点发送 UDP(端口 `2408`)。注册与 `warp=on` 的 trace 探测在启动时完成;WARP 无法初始化时启动直接失败,不会静默回退到代理。通过 WebUI 启用同样采用失败即拒绝:参数错误会返回错误,旧运行时继续服务。 - -`warp.pool_size`(1–32,默认 `2`)是**上限**而不是固定数量。第一个出口同步注册、决定服务是否 ready;之后池子在后台预注册上限的一半(至少 1 个),突发流量可以直接拿到预热出口而不用等注册。活跃出口再按并发调整:每个在途请求一个出口,另加一个备用,最多不超过上限;空闲 60 秒的多余出口会被回收。出口第一次收到上游 429 或 403 即被淘汰,由预注册的出口立刻顶上——免费模型请求会持续切换到其他出口,直到用完 `retry.max_attempts` 次才把最后一个 429 返回客户端;被淘汰的出口马上在后台重新注册。注册仍然串行,节流改由 Cloudflare 的 429 / Retry-After 决定,而不是固定间隔。若机房能给出的不同出口网段少于预注册目标,池子会退避而不是无限注册;自动免费模型探测在没有备用出口时跳过,并在一轮探测淘汰出口后停止本轮。`warp.stack` 默认 `ipv6`,可选 `ipv4` 或 `dual`。 - -上游的免费额度按**出口网段**计算,所以只有替换出口能拿到不同网段时轮换才有意义:IPv6 出口按 `/64` 去重并冷却 30 分钟,IPv4 出口按 `/32`。Cloudflare WARP 的 IPv4 出口通常是同一个共享 NAT 地址,常被其他用户用尽;IPv6 网络栈的出口则由外层 WireGuard 源地址决定。把 `warp.source_ipv6` 设为路由到本机的 IPv6 前缀(通常是 `/64`,`warp.stack` 默认已是 `ipv6`),每个出口就会从该前缀绑定自己的源地址。Linux 下该地址通过 `IPV6_FREEBIND` 绑定(网关已自动设置),或要求地址已分配到网卡。不会预先探测地址族:握手先尝试 IPv6 端点,全部失败时自动回退到 IPv4 端点(此时出口为共享地址)。留空则共用本机默认源地址。某些网络的 WARP 出口池本身已被用尽,此时每个新出口也会返回 429,网关会持续轮换出口,但仍会在尝试次数用尽后返回 429。`/healthz` 会返回 `warp` 状态块;启用 WARP 但没有任何活跃出口时返回 503。只有 WARP 关闭或存在 Go Key 需要代理时,`no_healthy_proxies` 才会阻塞就绪。诊断请求会占用出口,但不会轮换或淘汰它。关闭 WARP 后,免费通道恢复使用代理。 - -### 官方系统提示词 - -每个经过整形的免费模型请求都会携带 OpenCode CLI 自身的系统提示词——基础指令、`` 环境块和内置 skill 列表——因为免费层级会校验请求是否具有 agent 形态。v1 `/zen` 使用 1.x 工具名,`/inference` 与 `/zen/go` 使用 2.x 工具名。环境块包含请求的模型、网关工作目录、平台和 UTC 日期。 - -远程客户端可通过可选的 `upstream.prompt_environment` 替换注入的环境值,不删除字段、不改变顺序,也不修改官方基础提示词: - ```json -{ - "upstream": { - "prompt_environment": { - "working_directory": "/workspace", - "workspace_root": "/workspace", - "platform": "linux", - "is_git_repo": true - } - } -} +{"model":"MODEL_ID","max_tokens":512,"messages":[{"role":"user","content":"你好"}]} ``` -这是需要合并到现有 `upstream` 对象中的配置片段,不是完整配置。省略或设置为空对象时保持原有宿主机行为。非空 `working_directory` 同时作为默认 workspace root,除非另设 `workspace_root`;其他省略值保持旧默认,包括 `is_git_repo: true`。平台支持 `linux`、`darwin`、`win32`,其中 `windows` 会规范化为 `win32`;显式平台也会同步选择 shell 工具描述,但网关不会执行或转换客户端命令。路径仅作为文本使用,不解析、不访问;控制字符、行分隔符和尖括号会被拒绝。这些值由运维人员指定,不代表自动识别了客户端环境;需要不同环境的客户端应使用独立网关配置。请求模型和 UTC 日期保持不变。任意覆写值(包括 macOS 描述)是否通过上游校验仍需验证。 +Anthropic 客户端还可发送 `anthropic-version: 2023-06-01`。流式请求添加 `"stream": true`,用 `curl -N` 或能即时消费 SSE 的客户端。HTTP 200 后仍可能发生流错误,需检查错误事件与最终结果。 -注入按协议处理:Chat 的系统与 developer 消息会合并为一条位于最前的 `system` 消息;Anthropic 写入 `system`(字符串,或调用方提供块列表时在最前插入文本块);Responses 写入 `instructions`。如果系统内容中已包含标记 `You are opencode, an interactive CLI tool`,请求会原样通过,因此已经发送官方提示词的客户端不会被重复注入。通过 Zen 或 Go Key 提供的免费模型也会接受同样的整形,只是仍然从对应 Tier 的代理出网。 - -覆写仅作用于网关注入的环境块,不修改客户端已有的官方提示词;匿名、认证、WARP 和探测请求共用该设置。通过 WebUI 保存其他设置时会保留这些值;修改请编辑 JSON 配置并重新加载,目前没有独立的 WebUI 输入字段。 - -### 工具整形 - -每个经过整形的免费模型请求中,网关会把客户端声明的每个具名工具改名为不透明的线上名称:命名空间前缀加上客户端名称 SHA-256 的前 12 个十六进制字符(冲突时追加 `_2`、`_3` 等后缀),并追加该通道的完整官方工具集:`/zen` 使用 1.x 定义(`bash`、`edit`、`glob`、`grep`、`read`、`skill`、`task`、`todowrite`、`webfetch`、`websearch`、`write`),`/inference` 与 `/zen/go` 使用 13 个工具的 2.x 定义。没有 `tools`、`tools` 为空数组或使用旧版 `functions` 数组的请求同样会补全官方工具集;`tool_choice`、旧版 `function_call` 和工具调用历史会同步改写。Responses 内置工具和 Anthropic 服务端工具保持不变。 - -响应(包括流式与非流式,以及拆分到多个 Chat 分块中的工具名)会恢复为客户端声明的名称。只有在客户端声明了等价工具时,官方工具名才会映射到客户端名称;否则响应中的名称保持原样。整形请求历史时,未知工具调用以及没有客户端等价工具的官方调用会连同配对的结果一起移除;若具名 `tool_choice` 指向被移除的工具,也会一并移除。 - -旧版 `functions` 定义与现代工具使用同一次重命名,确保定义、具名选择、历史引用和响应名称还原保持一致。 - -### 免费模型可用性 - -只探测 ID 含 `free`(不区分大小写),或元数据输入、输出价格均为零且未弃用的模型,按模型原生协议发送简短探测请求。先尝试已启用的匿名通道,再尝试一个配置的 Zen Key;启用 `warp.enabled` 时,每条探测通道都改走 WARP 而不是代理,无法取得出口时结果为 `warp_unavailable`,视为不确定。任一通道返回完整有效响应即视为可用,只有所有实际尝试的通道都明确返回模型不存在或已下架时才自动禁用,从模型列表与路由中移除。认证失败、429、超时、网络错误、5xx 和响应格式异常均视为结果不确定,不新增禁用,1 小时后复测。探测不修改生产 Key / 代理的冷却状态,也不计入请求统计,但仍会访问上游并可能消耗免费额度。 - -System One 使用原生 `noul` 类型询问“1+1 是否等于 2”,不注入聊天或工具字段。模型列表标明 `native_protocol` 和 `supported_endpoints`;仅在配置 Go Key 且有可用模型时展示轮转别名。升级时解除 v1.3.6 旧探测生成的禁用并立即安排复测,避免非法会话 ID 造成的误判继续保留。 - -周期硬编码:正常模型每 **1 小时**探测,明确失效模型每 **24 小时**复测。已禁用模型到期复测遇到临时错误时,保留原禁用原因并在 24 小时后重试;复测成功自动恢复。也可在 WebUI「免费模型可用性」页立即恢复启用,进入手动控制:保持启用且不再自动探测,也不会被在途或后续探测结果覆盖;如需回到自动探测,在同一页面按「切回自动」,下一轮调度即安排探测。旧版本留下的 `manually_enabled` 记录在启动时自动迁移为手动控制。没有可用 Zen / 匿名通道,或推理协议不支持探测时跳过,不自动禁用。 - -手动控制也会暂停 `reasoning.effort=auto` 的档位探测;已验证档位超过 2 小时后不再强制下发。切回自动后可重新探测档位。 - -状态保存在 `config.json.<上游地址指纹>.availability.json`,重启后保留,按 Zen 上游 URL 隔离。后台每分钟检查到期项,跳过手动控制的模型,串行探测其余模型,每条通道最多等待 60 秒。 - -管理接口:`GET /api/models/availability` 查看状态;`POST /api/models/probe` 将所有自动探测的免费模型标记为到期并立即开始一轮探测,WebUI「刷新状态」按钮即调用它(真正的重新探测,而不是只重载缓存视图);`POST /api/models/restore` 携带 `{"model":"MODEL_ID"}` 恢复并进入手动控制;`POST /api/models/manual` 携带 `{"model":"MODEL_ID","manual":true|false}` 在手动与自动之间切换。均需管理登录,写入接口还需 CSRF 校验。 - -### 会话与代理 - -Key 初始化时均衡分配到代理。真实流量可以触发代理检查、Key 重新绑定和失败冷却。已经标记异常的代理,每 15 分钟通过 Cloudflare trace 复查一次。 - -服务使用稳定会话哈希选择首选 Key 或匿名代理。建议通过 `x-session-id` 区分独立会话,同时支持 `x-opencode-session`、`x-session-affinity`、`session_id`、`conversation-id`、`conversation_id` 请求头,请求体中的 `conversation_id`、`metadata.session_id`,以及 Claude Code `metadata.user_id` 中的会话 ID。 - -网关自行生成的会话与项目标识按调用方的服务端 Key 隔离,不同 Key 不会共享上游会话、首选 Key 或匿名代理;客户端自带的官方 OpenCode 会话(`ses_…`)原样保留;网关自行派生的会话标识按进程加盐,重启网关后会用新的标识,而不会沿用上一轮进程的上游会话。没有显式会话 ID 时,使用系统提示词和第一条用户消息生成会话标识,因此同一 Key 下系统提示词和开场内容都相同的会话仍可能共享亲和性。需要互相隔离的用户应各自使用独立的服务端 Key。调整 Key 或代理池成员后,原有会话选择的节点可能变化。 - -失败冷却按指数增长,最高为 `performance.failure_cooldown_seconds` 的八倍;如果上游的 `Retry-After` 更长,则使用更长时间。所有认证 Key 都处于冷却时,路由仍可能尝试最早结束冷却的 Key;仍在冷却的匿名节点会被跳过。 - -## 配置参考 - -起始配置见 [config.example.json](config.example.json),启动前须添加上游凭证。配置文件读取器支持非标准 JSON 的 `//` 和 `/* ... */` 注释;管理接口请求体仍须使用标准 JSON。未知字段(包括 `_comment`)和无效取值会被拒绝。 - -### Key、监听地址与路由 - -| 字段 | 默认值或要求 | -| --------------------------- | ------------------------------------------------------------------------------------- | -| `listen` | `127.0.0.1:8080`。 | -| `server_keys` | 至少一个本地 Key。 | -| `zen_keys`、`go_keys` | 未明确启用匿名模式时,至少需要一个上游 Key 或已有的 `go_subscription` 连接。 | -| `anonymous` | `false`;须主动开启,上游封堵可能使其不可用,优先使用 Zen API Key。 | -| `warp.enabled` | `false`;免费通道流量通过 Cloudflare WARP 出口,不使用代理。 | -| `warp.pool_size` | `2`;WARP 出口上限(后台预注册一半,活跃出口按并发调整),1–32。 | -| `warp.stack` | `ipv6`;可选 `ipv6`、`ipv4`、`dual`。 | -| `warp.source_ipv6` | 空;每个出口绑定的外层 IPv6 源前缀(`/64`),要求 `stack = "ipv6"`。 | -| `prefer` | `go`;可选 `go`、`zen`。 | -| `upstream.zen` | `https://opencode.ai/zen`。 | -| `upstream.go` | `https://opencode.ai/zen/go`。 | -| `upstream.anonymous` | `https://opencode.ai/inference`;匿名通道仅使用此地址,已停用 v1 `/zen` 回退。 | -| `proxies` | 两个代理来源都为空时,使用 `["direct"]`。 | -| `proxyfile` | 可选;相对路径基于配置文件所在目录解析。 | -| `models.refresh_seconds` | `300`;最小为 1。 | -| `models.protocols` | `{}`;按模型 ID 覆盖原生协议。 | -| `models.free_only` | `false`;即使配置了 Zen / Go Key,也只暴露和路由免费模型。 | -| `models.active_probes` | `false`;关闭时通过实际请求被动追踪模型可用性,不主动发起测试请求。设为 `true` 开启主动探测。 | -| `models.anonymous_backoff` | 缺省关闭;`{threshold, base_hours, max_hours}`,默认 6、1、24。 | -| `reasoning.effort` | 空(关闭);可选 `auto`、`minimal`、`low`、`medium`、`high`、`xhigh`、`max`、`none`。 | -| `reasoning.effort_by_model` | `{}`;按模型 ID 覆盖 `reasoning.effort`。 | - -### 强制思考强度 - -`reasoning.effort` 在请求自身没有指定思考强度时,指定发往上游的强度; -`reasoning.effort_by_model` 按模型 ID 覆盖它。它对三种协议、两个转换方向都生效, -对跨协议请求尤其重要:Anthropic 的 `thinking.budget_tokens` 只能被 Chat 与 -Responses 近似表达,而强制指定的强度可以到达单独靠预算表达不出的档位。 +System One 要求选择 `native_protocol` 为 `systemone` 的模型,例如: ```json -{ - "reasoning": { - "effort": "high", - "effort_by_model": { "claude-opus-5": "max" } - } -} +{"model":"SYSTEM_ONE_MODEL_ID","state":"1 + 1 = 2","questions":{"arithmetic":{"type":"noul","instructions":"Is 1 + 1 equal to 2?"}}} ``` -客户端显式关闭始终优先。Anthropic 原生 `thinking.type="disabled"` 和 Chat/Responses 的 effort -`"none"` 都会在协议转换后保持关闭,不会被配置的默认强度重新开启。 +网关直接转发决策请求与答案。消息接口也能识别 System One 模型的这种决策结构,但普通聊天内容无法转换成决策问题。上游 System One 流式响应直接透传,不提供流重置恢复。 -两个方向的强度都会如实保留:显式的 `output_config.effort` 不会再被 `thinking` -块遮蔽,`budget_tokens` 保持其档位(`8192` 为 `high`,`32000` 为 `xhigh`, -两者可区分),发往 Responses 时强度会以 `reasoning.effort` 形式传递而不再丢失。 +### 兼容边界 -WebUI 的配置中心也提供默认强度和按模型覆盖。管理 API 的 `GET /api/config` -会返回 `reasoning`,`PUT /api/config` 接受同名对象;省略该字段会保留现有值, -发送空对象则会清除它。 +三种消息协议支持文本、可表达的图片/文件内容、reasoning、函数定义、工具调用、工具结果和流式响应。原生请求保留未被网关主动整形的供应商字段;跨协议只转换已有对应表示的内容,例如 Chat `seed` 和 JSON 输出约束不转换为 Anthropic 参数。不支持的内容或工具可能返回校验错误。 -代理支持 `direct`、`http://`、`https://`、`socks5://` 和 `socks5h://`,URL 可包含认证信息。配置内代理先加载,再追加 `proxyfile` 内容,并按首次出现的顺序去重。 +Responses 历史中的 assistant reasoning、文本和函数调用会合并为 assistant 轮次;用户消息和工具结果分隔轮次。转换到 Chat Completions 时,缺失或不匹配的工具结果仍会报错。 -代理文件每行一个地址,允许空行和注释: +网关不实现 embeddings、文件上传、图片生成、Responses 检索或取消,也不替客户端保存会话历史。请求需携带所需历史;上游可能提供的有状态功能不代表网关具有本地会话存储。 -```text -# 首选代理 -http://user:password@127.0.0.1:7890 -socks5://127.0.0.1:1080 # 备用代理 -direct -``` +## 配置与路由 -支持 `#`、`;`、`//` 注释标记,标记需要位于行首或空白字符之后。 +从 [config.example.json](config.example.json) 开始配置。文件支持 `//` 和 `/* ... */` 注释,管理 API 请求体须使用标准 JSON。未知字段、无效值、重复顶层字段及同一 OAuth 方案的新旧字段冲突会被拒绝。保存会规范化配置并去掉注释。 -#### 轮换代理池 +| 配置项 | 默认值 / 含义 | +| --- | --- | +| `server_keys` | 必须保留至少一个启用的本地 Key。 | +| `zen_keys`、`go_keys` | 独立上游 Key 池;示例均为空。 | +| `prefer` | `go`;也可设为 `zen`,决定可用认证通道的首选顺序。 | +| `anonymous` | `false`;为符合条件的免费模型启用上游 `public` 凭证。 | +| `upstream.zen` | 手动 Zen Key 默认使用 `https://opencode.ai/zen`。 | +| `upstream.go` | 手动 Go Key 及其额度接口默认使用 `https://opencode.ai/zen/go`。 | +| `upstream.anonymous` | 匿名通道默认使用 `https://opencode.ai/inference`。 | +| `models.refresh_seconds` | `300`;模型发现间隔。 | +| `models.protocols` | 按模型覆盖原生协议:`chat`、`responses`、`anthropic`、`systemone`。 | +| `models.free_only` | `false`;发现与路由均仅允许免费模型。 | +| `models.active_probes` | `false`;可选的免费模型合成推理探测。 | +| `reasoning.effort` | 内置默认未设置;示例设为 `high`。 | +| `reasoning.effort_by_model` | 按模型覆盖默认思考强度。 | -在条目末尾追加 `#pool`(或在开头加 `pool+`)即可声明该地址是轮换代理池(例如 [Resin](https://github.com/Resinat/Resin)),每次新建 TCP 连接都会从不同出口 IP 发出: +### 模型与通道选择 -```text -http://127.0.0.1:7890#pool -socks5://127.0.0.1:1080#pool -pool+http://127.0.0.1:7891 -``` +模型发现结合上游目录与 `https://models.opencode.ai/api.json` 的 OpenCode 能力和价格目录,按 Tier 保存原生协议,并通过 `/v1/models` 提供已知的上下文/Token 上限、价格、`native_protocol`、`supported_endpoints` 与 reasoning 信息。价格及弃用元数据每 24 小时刷新,失败保留已有数据;价格元数据不是账单估算或账户余额。 -代理池条目的处理方式与静态代理完全不同: +使用手动 Key 时,明确开启匿名后,符合条件的免费模型可先尝试匿名通道,再按 `prefer` 尝试可用 Key 池;匿名关闭时使用已配置 Key。模型 ID 不区分大小写包含 `free`,或元数据表明未弃用且输入/输出价格均为零,即可判为免费,但不保证上游接受。付费模型需要适当的认证通道。`models.free_only` 同时限制轮转组成员。 -| 行为 | 静态代理 | `#pool` 条目 | -| ------------ | ------------------------------------------- | --------------------------------------------------------- | -| 连接复用 | Keep-alive + HTTP/2 多路复用(`performance.*` 连接池参数) | 每次请求新建 TCP + CONNECT 隧道(`DisableKeepAlives`,禁用 HTTP/2) | -| 失败冷却 | 15s–120s 指数退避,并受 `Retry-After` 影响 | 无冷却:下一次请求直接换一个新出口 IP | -| 可用性剔除 | 标记不可用、迁移 Key、每 15 分钟复检 | 永不剔除,完全跳过健康检查 | -| 匿名通道重试 | 每个出口最多访问一次,最多 `performance.max_anonymous_exits` 个出口 | 最多尝试 `retry.max_attempts` 次,循环该池条目 | +OAuth 另有规则:请求选择 OAuth 路由后,只使用该 Tier 已确认的路由,不因失败改走匿名、手动 Key 或其他 Tier。Go OAuth 授权失败、额度耗尽或返回 429,均不会触发 PAYG 请求。两类通道都能服务同一模型时,明确选择 `prefer: "zen"` 允许使用已连接的 Zen PAYG 通道。 -当 URL 背后的服务本身就在做轮换、而池内出口 IP 会被单独限流或不稳定时使用它:网关会把每次尝试都当作新出口,而不是把整个会话固定在某个出口上。只要一条 `#pool` 条目即可,无需再罗列几十个出口。静态条目仍然保留下文的连接池行为。 +### 超时、代理与会话亲和 -### 超时与连接池 +| 配置项 | 默认值 | 含义 | +| --- | --- | --- | +| `retry.max_attempts` | `3` | Key 重试循环预算;匿名与轮转有各自选择规则。 | +| `retry.timeout_seconds` | `300` | 整个推理请求预算,含流式消费。 | +| `performance.attempt_timeout_seconds` | `0` | 可选的较短单次尝试上限;零沿用请求超时。 | +| `performance.first_event_timeout_seconds` | `0` | 可选的首事件等待上限;零关闭。 | +| `performance.connect_timeout_seconds` | `5` | 建立连接超时。 | +| `performance.failure_cooldown_seconds` | `15` | 失败后的基础冷却时间。 | +| `performance.max_anonymous_exits` | 有效值 `8` | 单次匿名请求的不同静态出口上限;零使用内置值。 | +| `performance.free_tier_block_seconds` | 有效值 `900` | 免费通道出口封锁冷却时间;零使用内置值。 | +| `performance.max_idle_conns` | `2048` | 每个 transport 的空闲连接上限。 | +| `performance.max_idle_conns_per_host` | `256` | 每个 host/transport 的空闲连接上限。 | +| `performance.max_conns_per_host` | `0` | 连接数上限;零表示不限。 | +| `performance.idle_conn_timeout_seconds` | `120` | 空闲连接寿命。 | -| 字段 | 默认值 | 含义 | -| --------------------------------------- | ------ | ------------------------------------------------ | -| `retry.max_attempts` | `3` | 每个认证 Tier 的尝试次数,包含首次请求。 | -| `retry.timeout_seconds` | `300` | 推理请求总超时,包含流式响应读取。 | -| `performance.attempt_timeout_seconds` | `0` | 单次尝试的总超时;0 表示使用请求总超时。 | -| `performance.max_anonymous_exits` | `8` | 每个匿名请求最多尝试的静态代理出口数。 | -| `performance.free_tier_block_seconds` | `900` | 被免费层标记的出口冷却时长。 | -| `performance.connect_timeout_seconds` | `5` | 建立连接的超时。 | -| `performance.failure_cooldown_seconds` | `15` | 失败冷却基数。 | -| `performance.max_idle_conns` | `2048` | 每个代理 Transport 的空闲连接上限。 | -| `performance.max_idle_conns_per_host` | `256` | 每个 Transport 对单个主机的空闲连接上限。 | -| `performance.max_conns_per_host` | `0` | 单个主机的连接上限;0 表示不限制。 | -| `performance.idle_conn_timeout_seconds` | `120` | 空闲连接保留时间。 | +`proxies` 支持 `direct`、HTTP、HTTPS、SOCKS5、SOCKS5H URL。`proxyfile` 从配置目录相对路径读取,每个非空行一个代理,合并后去重;最终为空时使用直连。行首或空白后的 `#`、`;`、`//` 表示注释。代理 URL 中的账号密码属于敏感信息。 -单次响应头超时不会超过请求总超时。希望慢节点仍能留出回退时间时,可以将它设为小于总超时的值。请求上下文过期后会停止后续尝试,不会惩罚尚未实际使用的 Key 或代理。 +供应商负责轮换出口时,可写成 `pool+https://proxy.example:8443` 或 `https://proxy.example:8443#pool`。每次尝试新建连接,不复用 keep-alive/HTTP/2,也不采用静态节点的冷却和健康淘汰。实际出口轮换由供应商提供。静态代理保留连接复用、健康跟踪与 Key 绑定;`proxy_bindings` 可按 Key 指纹绑定已配置代理。 -### 日志与管理端 +建议为独立会话发送 `x-session-id`。同时支持 OpenCode 会话头和既有 conversation 字段;未指定时使用初始 system/user 内容生成种子。网关生成的身份按本地 API Key 与进程生命周期隔离,有效的官方 OpenCode 会话 ID 原样保留。同一 Key 下相同开头可能共享亲和性,需要用户隔离时使用独立 Key。 -| 字段 | 默认值或要求 | -| ----------------------------- | ----------------------------------------------- | -| `logging.level` | `info`;可选 `debug`、`info`、`warn`、`error`。 | -| `logging.ring_size` | `2000`;范围为 100–50,000。 | -| `logging.dump_request_bodies` | `false`;配合 `debug` 日志级别输出上游请求体。 | -| `webui.enabled` | 省略时为 `false`;示例配置设置为 `true`。 | -| `webui.listen` | `0.0.0.0:8081`。 | -| `webui.username` | 启用 WebUI 时必填;示例为 `admin`。 | -| `webui.password` | 首次初始化密码,最小长度为 10。 | -| `webui.password_hash` | 自动生成的 Argon2id 哈希,用于替代明文密码。 | -| `webui.session_ttl_minutes` | `720`;范围为 5–10,080。 | +可选 `models.anonymous_backoff` 在连续失败后暂停整个匿名通道,默认阈值 `6` 次、基础 `1` 小时、最大 `24` 小时;不配置此对象则关闭该通道级熔断。 -启动时会将初始密码哈希化,并从配置中删除明文;包含初始明文密码的备份也会删除。配置和备份仍包含运行所需的上游 Key、代理凭据,应限制文件访问权限。 +### 免费模型整形与 reasoning -请求体日志默认关闭,每份准备好的上游请求体最多输出 64 KiB。已配置的敏感值会脱敏,但对话内容本身仍可能包含敏感信息。 +免费模型兼容逻辑会按需注入官方 OpenCode 系统提示词和工具定义,改写线上工具名,并在响应中还原客户端名称。使用 Key 的免费模型也可能经过整形。网关只转发工具调用,不会在本机执行工具;System One 不经过消息/工具整形。 -## WebUI 与诊断 - -管理监听端口提供 WebUI 和 `/api/*` 接口。认证使用单一管理员账号、服务端 Session、HttpOnly / SameSite Cookie、写操作 CSRF 校验及登录限速。 - -| 管理接口 | 用途 | -| ------------------------------------------------ | ----------------------------------------------- | -| `POST /api/auth/login` | 登录,获取 Session Cookie 和 CSRF Token。 | -| `GET /api/auth/session`、`POST /api/auth/logout` | 查看或结束当前 Session。 | -| `GET /api/config`、`PUT /api/config` | 读取脱敏配置或应用修改。 | -| `POST /api/config/reload` | 从磁盘重载配置。 | -| `POST /api/config/reveal` | 验证密码后查看配置中的敏感值。 | -| `PUT /api/account` | 验证密码后修改账号,修改后使已有 Session 失效。 | -| `GET /api/monitor` | 请求、Token、上游和资源统计。 | -| `GET /api/debug/models` | 模型路由、Key 指纹和 metadata 诊断。 | -| `POST /api/debug/inference` | 执行 Playground 请求。 | -| `POST /api/proxies/check` | 检查一个已保存或草稿代理到 Zen 上游的连通性。 | -| `GET /api/logs`、`GET /api/logs/stream` | 最近日志或 SSE 实时订阅。 | - -Playground 需要已登录的 Session 和 `X-CSRF-Token`,每个客户端 IP 每分钟最多 12 次: +注入提示词包含目录、工作区、平台、模型与 UTC 日期,默认描述网关主机。远程客户端可配置兼容文本: ```json -{ - "protocol": "chat", - "key": { "mode": "auto" }, - "request": { - "model": "MODEL_ID", - "messages": [{ "role": "user", "content": "Hello" }] - } -} +{"working_directory":"C:\\work\\project","workspace_root":"C:\\work\\project","platform":"windows","is_git_repo":true} ``` -服务端强制设置 `stream: false`。需要指定 Key 时,使用 `{"mode":"selected","tier":"zen","id":"KEY_FINGERPRINT"}`,其中指纹来自 `/api/debug/models`。指定 Key 的诊断最多执行一次上游尝试,不进入匿名通道,不轮换 Key,不切换 Tier,也不重放 reasoning 请求。 +将此对象合并到 `upstream.prompt_environment`。目录仅作为文本使用,不会由此访问;`windows` 规范为 `win32`,还支持 `linux`、`darwin`。客户端已提供的官方提示词不被覆盖。界面没有这些高级字段,需编辑配置并重载;任意环境覆盖值尚未经过真实上游校验。 -**自动模式和指定 Key 模式都不会改变生产 Key 的冷却、失败次数,以及代理的健康状态和绑定关系。** 诊断仍会真实访问上游,可能消耗供应商配额,并会计入监控。 +思考强度接受 `minimal`、`low`、`medium`、`high`、`xhigh`、`max`、`none`、`auto` 或空值,客户端明确指定的强度优先。`none` 移除 reasoning 设置。`auto` 仅使用近期为免费 Zen/匿名模型验证的强度上限,不扩大探测范围;自动发现需开启主动探测,可能发送多次消耗额度的请求,结果两小时后过期。Go/付费模型及未验证强度不会被推算。 -执行后,管理接口返回 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 状态。 +默认从真实流量学习可用性。只有 `models.active_probes: true` 才执行合成检查;管理端探测按钮仅安排检查,不绕过此开关。只有明确的模型下架/不存在证据才禁用模型,限流、认证失败、普通错误和超时不能证明下架。手动恢复会保持启用并退出自动探测,直到恢复自动控制。 -### 批量代理管理 +### WARP -WebUI 支持批量导入内联代理、检查选中条目和暂存批量移除。检查逐条调用 `POST /api/proxies/check`,需要管理登录和 `X-CSRF-Token`;请求体二选一:`{"id":"SAVED_PROXY_ID"}`(`GET /api/config` 返回的已保存代理 ID)或 `{"value":"https://proxy.example:8443"}`(草稿地址)。前端最多四个并发,后端最多八个,超出立即拒绝、不排队;每次检查限时 20 秒。 +`warp.enabled` 默认 `false`。开启后,免费匿名/手动 Zen 流量及其目录/探测路径使用进程内 Cloudflare WARP 隧道;Go、付费及 OAuth 路由继续使用配置的代理。需要向 Cloudflare `2408` 端口发送 UDP,无需 TUN 设备或修改路由表。初始化失败会拒绝启动或候选配置。 -**仅检查代理到 Zen 的连通性,不验证推理、Key 或额度。** 请求通过指定代理的独立 Bun 客户端向配置的 `upstream.zen` 加 `/v1/models` 发送无认证 GET,不带 Zen/Go Key、`public` 或 OAuth 凭证,不发推理、不跟随重定向、不走 WARP,也不修改正式健康、冷却或绑定状态。`anonymous: false` 时仍可检查,不会擅自启用匿名推理。 +`warp.pool_size` 是随并发调整的出口上限,范围 1–32,默认 2。`warp.stack` 为 `ipv6`(默认)、`ipv4` 或 `dual`。替换出口不保证获得新的上游额度。可选 `warp.source_ipv6` 要求 IPv6 堆栈及 `/64` 或更短前缀;Windows 下实际选择的源地址必须已分配到网卡,程序不会配置主机网络。 -成功执行检查后返回 HTTP 200,结果包含 `ok`、`state`、`reason`,以及可用时的 `status`、`latency_ms`。`available` 表示上游返回 200–399 或 401(401 仅表示到站后需要认证);`unavailable` 仅限本次确认的代理端拒绝连接、DNS 失败或代理 407;429 为 `limited`,上游 403 等错误为 `rejected`,超时及其他不能定位的错误为 `inconclusive`。后三种状态不得当作确认损坏代理批量清理;本次不可用也不代表永久故障。 +## 管理与 OAuth -移除只暂存在页面中,仍须通过 `PUT /api/config` 保存完整配置后才生效,检查本身不会删除代理。`proxyfile` 提供的代理在来源文件管理,不加入内联代理表格。 +WebUI 包含概览、诊断/Playground/日志、接入、API Key、模型与额度、轮转、配置、账号页面,提供简中、英语、越南语及意大利语。语言与主题选择保存在浏览器。完整操作与端点见[管理指南](docs/management.zh-CN.md)。 -### Go 订阅登录 +管理端使用管理员 Session Cookie、写操作 CSRF 和登录限流;修改管理员凭证会使 Session 失效。本地 API Key 不授予管理权限。`GET /api/config` 隐藏敏感值;再次验证密码后可显示手动 Key/代理值,但不会显示 OAuth Token。 -在「模型与额度」页面(`/#model-quotas`)点击「浏览器登录 Go 订阅」,打开页面显示的 OpenCode 官方 Device OAuth 链接,输入显示的 `user_code`。确认这是自己发起的授权后完成登录;WebUI 按间隔请求后端轮询并完成授权交换,无需手贴 Token、导入本机凭证文件或提交回调 URL。账号关联多个组织时,在 WebUI 选择 Go 订阅所在的组织。 +在「模型与额度」启动 Device OAuth。自行打开页面显示的官方验证地址,输入 `user_code`,批准自己发起的请求,并按需选择组织/工作区。后端负责轮询和刷新;不使用粘贴 Token、导入本机凭证文件或提交回调 URL 的流程。 -- 后端按需自动刷新访问凭证,并将连接保存到本地配置的 `go_subscription`。其中包含访问和刷新凭证,属于敏感信息,请保护配置文件及备份;WebUI 不接收这些凭证。 -- 「断开 Go 订阅登录」仅移除网关保存的连接,不撤销 OpenCode 官方会话。手动配置的 `go_keys` 仍保留,但 OAuth 连接期间不作备用通道;断开后恢复原有手动 Key 路由。登录失效时应重新登录,而非依赖手动 Key 回退。 -- OAuth 只使用已确认的官方 Go 订阅路由,不回退到按量付费(PAYG)通道。OAuth 额度当前显示为「未知」,不根据模型或请求结果推算;手动 Go Key 仍可使用原有额度查询接口。 +| 连接 | 范围与限制 | +| --- | --- | +| Go OAuth | 仅官方 Go 订阅路由;额度显示未知。 | +| Zen OAuth | 使用 Console 工作区 credits 的 PAYG;开始前必须明确确认,余额显示未知。 | -实现参考上游源码快照:[v2 `4617210822bdbb31e5749751afbfb4584ccedac8`](https://github.com/anomalyco/opencode/tree/4617210822bdbb31e5749751afbfb4584ccedac8)、[dev `7745079647b65036fe142e09ccd8623b25be1878`](https://github.com/anomalyco/opencode/tree/7745079647b65036fe142e09ccd8623b25be1878)。源码对比和本地检查不代表已通过真实订阅登录验证,上游授权或路由仍可能变化。生命周期和管理接口见[管理控制台说明](docs/management.zh-CN.md)。 +两类连接的待完成登录、凭证、刷新和断开分别管理。离开/隐藏页面停止自动轮询,返回可继续未过期登录。退出管理 Session 取消该 Session 的待完成登录,保留已完成连接;取消待完成登录不会断开已有账号。 -### 界面语言 +连接以 `go_oauth`、`zen_oauth` 保存于配置,包含访问/刷新凭证,配置与备份均需保护。对应 OAuth 存在期间,手动 Key 保留但不作备用,即使需要重新登录也一样。断开仅删除本地连接,在重新发现后恢复手动路由,不撤销官方 Session。匿名关闭时,断开最后连接前先保留其他凭证。 -WebUI 从 `webui/js/i18n.js` 加载翻译,内置 **简体中文**(默认)、**English**、**Tiếng Việt** 和 **Italiano**。原始简体中文文案保留在 `index.html` 和 `webui/js/` 中,并始终作为缺少翻译时的回退,因此新增语言不会覆盖原文。 +只接受已认证官方远程配置中通过方案 URL 与 SDK 校验的路由,不从 Go 地址推导 PAYG,也不引入任意远程请求头。普通配置保存保留后端管理的 OAuth 凭证。旧 `go_subscription`/`zen_subscription` 加载时迁移;同一方案同时提供新旧字段会被拒绝。 -- 语言选择器位于顶部工具栏右侧,登录卡片上也有一个。 -- 选择结果保存在 `localStorage`,键名为 `opencode2api.ui.lang`。 -- 切换语言会同时重绘静态文案(`data-i18n`、`data-i18n-attr`)和 JavaScript 生成的文案,无需刷新页面。 -- 日期时间格式跟随所选语言。 +实现依据管理指南列出的上游源码快照;此处说明代码行为,不代表所有账号的真实授权与推理已通过验证,上游权限和路由格式可能变化。 -新增语言时,在 `webui/js/i18n.js` 的 `DICTIONARY` 中增加一个语言块,并在 `SUPPORTED`、`LABELS`、`FLAGS` 和 `DATE_LOCALES` 中登记其代码,同时加入 `browserLocale` 检测链。 +### 本地 Key、额度与轮转 -### 保存与重载 +API Key 页面支持创建、命名、启用、停用、删除。自动 Key 使用 192 位随机数;自定义 Key 为 16–256 位字母、数字、`.`、`_`、`-`,名称 1–80 字符,最多 200 个,至少一个启用。新请求立即使用变更;未实现按 Key 模型权限、消费上限或过期时间。 -服务先验证候选配置并创建新的 Gateway,然后保存配置并切换实例。验证或保存失败时,当前 Gateway 继续处理请求;已经开始的请求继续使用原有实例。 +手动 Go Key 额度来自已配置 Go 上游的 `/v1/usage`,是共享滚动/每周/每月百分比窗口,不是逐模型余额。多个 Key 可能共享同一套餐,不能相加。成功缓存 60 秒、失败 15 秒,旧数据标记历史。OAuth 额度/credits 未知,不根据手动 Key 或成功请求推算。 -Key、代理、上游地址、重试、模型、日志和路由偏好立即对新请求生效。`listen`、`webui.listen`、`webui.enabled` 的修改需要重启进程。保存后的 JSON 会规范化,不保留原有注释。 +轮转别名 `sota`、`sweet` 使用 Go 模型,支持三种消息接口和流式输出。每组共享当前模型,成功保持,失败推进。SOTA 固定包含 `deepseek-v4.1-flash`、`glm-5.3`、`grok-4.6`、`kimi-k3`、`qwen3.8-max`;Sweet 收集其他合适的 Go 模型。能否调用以实际发现为准。可在 `/#rotation` 调整别名、顺序和首输出超时。 -## 监控与持久化 +普通错误预算为三个模型、每模型最多三次;额度/限流直接跳过,轮换不产生额外共享额度。流式内容提交后,错误结束当前答案并让下一请求使用后续模型。响应 `model` 保留请求别名,`X-Resolved-Model` 标记实际模型。状态保存于配置旁。 -请求结果以完整推理过程为准。即使 HTTP 200 已经发出,SSE 错误事件或异常断流仍会计为失败,并标记 `stream_error`;客户端取消标记为 `client_canceled`。WebUI 会将这些结果与 HTTP 状态一起显示。 +## 运行与安全 -上游**尝试记录**统计的是收到响应头为止的 HTTP 交互,其成功状态和耗时与完整 JSON 响应或流的最终完成情况分开计算。 +配置保存先校验并构建替代运行时,校验或持久化失败保留当前运行时。Key、代理、路由、模型与日志设置对新请求生效;监听地址和 WebUI 开关需要重启。手动编辑文件后执行 UI 重载或 `POST /api/config/reload`,没有自动文件监视器。 -Token 统计仅使用上游报告的 usage。输入 Token 包含缓存读取和写入,缓存 Token 单独统计缓存读取量。缺失 usage 时不估算 Token,覆盖率表示已经建立路由的推理请求中有多少报告了 usage。`usage.server_keys` 按调用方认证所用的本地 server key(指纹,与 `/api/api-keys` 的 ID 一致)拆分请求数和 Token;Playground 流量计入 `playground`。 +| 数据 | 存储位置 | +| --- | --- | +| 配置及上一版本 | `config.json`、`config.json.bak`。 | +| 模型及元数据缓存 | `config.json.models.catalog.json`、`config.json.models.dev.json`。 | +| 可用性及轮转 | `config.json..availability.json`、`config.json.rotation.json`。 | +| Session、用量、近期请求/尝试、日志环形缓冲、最近 Playground 结果 | 内存,进程重启清空。 | +| 结构化日志 | stdout JSON,需外部收集才能长期保存。 | -| 数据 | 保存位置或保留规则 | -| ----------------------------------------------- | ------------------------------------------------------------------------- | -| Session、指标、Token 累计、最近 Playground 结果 | 进程内存;重启清空。 | -| 请求与尝试明细 | 最近一小时,最多 10,000 个请求和 20,000 次尝试;API 分别最多返回 500 条。 | -| 实时日志环形缓冲 | 进程内存,大小由 `logging.ring_size` 指定。 | -| 结构化日志 | stdout JSON;需要长期保留时由外部系统收集。 | -| 当前配置与上一版本 | `config.json`、`config.json.bak`。 | -| 模型目录缓存 | `config.json.models.catalog.json`。 | -| 成本与弃用信息缓存 | `config.json.models.dev.json`。 | +文件名以实际配置路径为前缀。监控保留跨热重载数据,不跨进程共享;Token 只统计上游报告值,不估算缺失用量。完整请求结果与收到响应头为止的尝试指标是不同口径。Playground 用量单独归类。最近一小时最多保留 10,000 请求/20,000 尝试,接口各返回最多 500 条。 -缓存文件名基于实际配置路径生成。lifetime 仅表示当前进程运行期间的累计,各实例之间不共享 Session 或监控状态。 +`GET /healthz` 不发送上游请求、无需 Key。目录未就绪/为空、WARP 不可用或必要代理全部不健康时返回 503。可用但过期目录可返回 200 及 `status: "degraded"`;过期阈值为两倍刷新间隔,最低 60 秒。就绪不保证 Key 有效、额度充足或推理成功;公开响应只含计数与状态,不含凭证或代理地址。 -### 健康检查 +本地使用将 API 与管理监听在 loopback。网络访问须使用 HTTPS 并限制管理入口;可信反向代理应正确设置 `X-Forwarded-Proto`。限流使用直连对端地址,同一反向代理后的客户端共享限制。可执行文件本身提供 HTTP。 -`/healthz` 不增加监控计数,也不触发网络请求;返回资源数量,不包含 Key 或代理地址。 +配置和备份包含上游 Key、代理密码、OAuth Token,密码哈希不加密这些内容。限制文件权限,Windows 使用 ACL,分享源码时排除运行文件。`logging.dump_request_bodies` 默认关闭且需 debug 才输出,即使截断与脱敏仍可能暴露对话内容。Playground 和主动可用性探测会发送真实上游请求,可能消耗额度或 credits。 -- HTTP 503:模型目录尚未就绪、当前配置下没有可路由模型,或没有健康代理。 -- HTTP 200:服务就绪。可用目录缓存过期时仍返回 200,同时模型状态为 `stale`,整体状态为 `degraded`。 +## 本地开发与核对 -过期阈值为 `models.refresh_seconds` 的两倍,且不低于 60 秒。就绪状态检查目录和资源,不会实际验证某个上游 Key 能否完成下一次推理。 +`cmd/opencode2api` 启动服务;`internal/admin` 负责管理,`gateway` 负责路由/运行时,`protocol` 负责 JSON/SSE 转换,`models` 负责发现,`oauth` 负责官方授权,`config` 负责校验/持久化,`telemetry` 负责监控/日志。静态资源位于 `webui`,无需安装前端依赖。 -## 开发 - -Go 源码按职责拆分为独立包。程序入口负责组装服务,具体实现放在 `internal/` 中。 - -```text -cmd/ - opencode2api/main.go 命令行参数、启动与优雅退出 -internal/ - admin/ 管理 API、登录会话与 Playground - buildinfo/ 健康检查和管理接口共享的版本信息 - config/ 配置解析、持久化、密码与脱敏 - gateway/ HTTP 路由、重试、资源池、刷新与运行时 - httpx/ 通用 HTTP 响应、响应体处理与请求头 - identity/ 请求标识与会话亲和性 - jsonutil/ JSON 取值与解码辅助函数 - models/ 模型目录、能力、价格与缓存 - protocol/ 请求和响应转换、SSE 解析与输出 - telemetry/ 请求跟踪、指标、日志与异常恢复 -webui/ - embed.go 将静态资源内嵌到可执行文件 - index.html 页面结构 - css/ 设计 token、基础样式、组件与页面布局 - js/ ES 模块:外壳、i18n、共享辅助与每页一个模块 -``` - -建议阅读顺序: - -1. [程序入口](cmd/opencode2api/main.go) → [运行时管理](internal/gateway/runtime.go) → [HTTP 处理](internal/gateway/gateway.go)。 -2. [上游请求](internal/gateway/upstream.go)和[模型路由](internal/models/catalog.go)说明请求如何选择并到达上游。 -3. [请求转换](internal/protocol/request.go)、[响应转换](internal/protocol/response.go)和[流式传输](internal/protocol/stream.go)说明协议处理过程。 -4. [管理路由](internal/admin/server.go)和 [WebUI 交互](webui/js/main.js)说明配置编辑与诊断功能。 - -执行 Go 格式化、静态分析和程序构建: +常规开发环境可运行以下原生 Go 命令;需要工作区内缓存时,将 `GOCACHE`、`GOMODCACHE` 设为项目内持久目录: ```bash -gofmt -w cmd internal webui go vet ./... -go build -o opencode2api ./cmd/opencode2api +go build -trimpath -o opencode2api ./cmd/opencode2api ``` -开发时可以直接运行 `go run ./cmd/opencode2api -config config.json`。发布构建仍通过 `-ldflags "-X main.version=vX.Y.Z"` 注入版本号。 - -Node.js 仅用于 WebUI 的 JavaScript 语法检查: +Node.js 仅用于可选的 JavaScript 语法核对,无需安装包。在 Bash 执行,Windows 可用 Git Bash: ```bash -for f in webui/js/*.js webui/js/pages/*.js; do node --input-type=module --check < "$f"; done +for file in webui/js/*.js webui/js/pages/*.js; do + node --input-type=module --check < "$file" || exit 1 +done ``` -项目通过 `.editorconfig`、`.gitattributes` 和 Go 格式化统一格式。CI 覆盖 Linux / Windows 上的 Go 1.24 与稳定版 Go 的 `go vet` 和构建,以及 Go 格式、WebUI 语法和容器入口脚本语法检查。发布压缩包包含四份 README。 +在 Bash 中执行以上命令(Windows 可用 Git Bash)。部署前检查见[验证与维护](docs/management.zh-CN.md#验证与维护)。发行版本可通过 `-ldflags "-X main.version=vX.Y.Z"` 注入。 -## 常见问题 +| 现象 | 核对内容 | +| --- | --- | +| API 401 | 本地 Key、启用状态与请求头。 | +| 启动提示缺少凭证 | 配置上游 Key/已有 OAuth,或明确启用匿名。 | +| 无模型 / health 503 | 目录状态、原生协议支持、凭证配置和资源可用性。 | +| OAuth 请求失败 | 安全账号状态与重登提示,不会自动转 PAYG。 | +| HTTP 200 但生成失败 | SSE 错误事件、请求结果及 `x-request-id` 日志。 | +| 修改无效 | 保存/重载实际配置;监听变化需重启。 | +| Compose 中宿主配置修改无效 | 实际配置位于状态卷,重新导入或使用 WebUI。 | +| 重启后用量清零 | 计数器仅在内存,日志需另外保存。 | -| 现象 | 排查方向 | -| ----------------------------- | -------------------------------------------------- | -| API 返回 401 | 使用配置中的本地 `server_keys`。 | -| 健康检查一直为 `starting` | 查看目录刷新日志和网络连通性,必要时补充协议覆盖。 | -| 模型列表为空 | 检查配置的 Tier、匿名资格和原生协议是否受支持。 | -| 请求返回 502 / 504 | 查看上游尝试、凭据、代理以及请求总超时和单次超时。 | -| HTTP 200 但生成失败 | 查看 SSE 错误事件和请求结果,不能只看 HTTP 状态。 | -| Docker 中宿主机配置修改不生效 | 当前配置在状态卷中;重新导入,或通过 WebUI 修改。 | -| 无法通过容器端口访问 | 检查监听地址、端口映射和状态卷中的实际配置。 | -| 重启后监控消失 | 监控仅保存在内存,需要外部收集 stdout 日志。 | +升级前安全备份程序、配置及状态,停止进程后再替换可执行文件。回退时恢复相互匹配的程序、配置与状态。 ## 致谢 感谢 [LINUX DO](https://linux.do) 社区的支持。 -### 自适应思考强度 - -将 `reasoning.effort` 或按模型覆盖值设置为 `auto`,即可使用免费模型探测实际验证过的最高可用档。已有具体档位语义不变,客户端显式指定的强度始终优先,不维护模型名称白名单。 - -基础请求成功后,对能力目录标记支持 reasoning 的模型依次验证 `max`、`xhigh`、`high`、`medium`、`low`、`minimal`。只有明确的思考参数不支持错误才尝试下一档;429、超时等临时失败会停止搜索,不能据此判断模型档位上限。全部档位均被拒绝时,不注入思考覆盖。 - -结果按上游 URL、模型与原生协议持久化,在可用性页展示,最多使用两小时内的验证结果。主动探测仍只覆盖免费 Zen/匿名模型;Go/付费模型、能力未知或尚未验证的模型不猜测档位。开启 `auto` 不扩大探测范围,也不能证明上游一定执行了所有接受的字段;每个模型可能增加数次简短请求并消耗上游额度。 - ## 许可证 -SPDX-License-Identifier: GPL-3.0-or-later - -本项目是自由软件,采用自由软件基金会发布的 GNU 通用公共许可证第 3 版或(由你选择的)任何后续版本。你可以按该许可证重新分发和修改本项目;本项目不提供任何担保。完整条款见 [LICENSE](LICENSE)。 +SPDX-License-Identifier: GPL-3.0-or-later。完整条款见 [LICENSE](LICENSE),本软件不提供担保。 diff --git a/cmd/opencode2api/main.go b/cmd/opencode2api/main.go index 9a5e0aa..c98cfe3 100644 --- a/cmd/opencode2api/main.go +++ b/cmd/opencode2api/main.go @@ -32,7 +32,9 @@ func main() { cfg, err := config.Load(*configPath) if err != nil { - slog.Error("configuration error", "error", err) + // No validated configuration exists to seed the redactor yet. Parse + // errors can quote credential-bearing input, so keep this log generic. + slog.Error("configuration could not be loaded; check JSON, required fields, and file permissions") os.Exit(1) } if *listen != "" { diff --git a/docs/management.it.md b/docs/management.it.md new file mode 100644 index 0000000..5f431b0 --- /dev/null +++ b/docs/management.it.md @@ -0,0 +1,265 @@ +# Console di gestione e guida operativa + +[English](management.md) | [简体中文](management.zh-CN.md) | [Tiếng Việt](management.vi.md) | Italiano + +Questa guida descrive le funzioni di gestione attualmente implementate, OAuth, quote, rotazione dei modelli, diagnostica e persistenza. Per avvio del servizio ed esempi delle API di inferenza consulta il [README in italiano](../README.it.md); il punto di partenza per la configurazione completa è [config.example.json](../config.example.json). La gestione e le API di inferenza usano listener distinti; tutte le rotte `/api/*` riportate qui appartengono alla gestione. + +## Avvio e accesso + +Su Linux usa Go 1.24 o successivo e compila nella directory del progetto con Bash: + +```bash +if [ ! -f config.json ]; then + cp config.example.json config.json +fi +export GOCACHE="$PWD/.local/go-cache" +export GOMODCACHE="$PWD/.local/go-modules" +go build -trimpath -o opencode2api ./cmd/opencode2api +``` + +Prima dell'avvio modifica la configurazione localmente: sostituisci `server_keys` e `webui.password`, poi imposta `zen_keys` o `go_keys`. Per la gestione locale è consigliato `webui.listen: "127.0.0.1:8081"`; il valore di esempio `0.0.0.0:8081` ascolta su tutte le interfacce. La password deve avere almeno 10 caratteri; il nome amministratore di esempio è `admin`. + +```bash +./opencode2api -config config.json +``` + +Su Windows puoi compilare in modalità nativa con `go build -trimpath -o opencode2api.exe ./cmd/opencode2api`, poi eseguire `.\opencode2api.exe -config .\config.json` in PowerShell. Per inizializzazione dei volumi, importazione dei file, porte e immagini Docker/Compose consulta il README. Le operazioni di gestione devono riferirsi alla configurazione effettivamente in uso: modificare una copia sull'host senza importarla nuovamente non aggiorna il servizio. + +Il canale anonimo `anonymous` è disabilitato per impostazione predefinita. Per avviare il servizio occorre almeno una chiave upstream, una connessione Go/Zen OAuth già salvata oppure l'abilitazione esplicita dell'accesso anonimo. Non è possibile avviare senza credenziali e completare soltanto dopo il primo OAuth dalla WebUI. L'upstream può bloccare il traffico anonimo; non abilitare l'inferenza anonima soltanto per controllare i proxy. + +La directory della configurazione deve essere scrivibile. Al primo avvio il servizio migra `webui.password` in `password_hash` Argon2id e tenta di eliminare il backup che contiene la password iniziale in chiaro. Questa operazione non cifra le altre credenziali. + +## Pagine e autenticazione amministrativa + +| Pagina | Indirizzo | Funzione | +| --- | --- | --- | +| Panoramica | `/#overview` | Richieste, token, tentativi upstream e risorse operative. | +| Diagnostica | `/#diagnostics` | Instradamento dei modelli, Playground e log in tempo reale. | +| Guida all'accesso | `/#access` | Parametri di connessione dei client. | +| Gestione chiavi API | `/#api-keys` | Ciclo di vita e utilizzo delle chiavi locali. | +| Modelli e quota | `/#model-quotas` | Catalogo Go, quote condivise, due tipi di OAuth e disponibilità dei modelli gratuiti. | +| Rotazione dei modelli | `/#rotation` | Ordine dei gruppi, posizione corrente, pause e cronologia dei tentativi. | +| Configurazione | `/#config` | Chiavi, proxy, timeout, instradamento, WARP e log. | +| Sicurezza account | `/#account` | Modifica di nome e password dell'amministratore. | + +L'interfaccia supporta cinese semplificato, inglese, vietnamita e italiano; lingua e tema sono memorizzati nel browser. I vecchi collegamenti `#playground` e `#logs` aprono Diagnostica; `#availability` apre Modelli e quota. + +L'amministratore accede con nome utente e password e riceve un cookie di sessione `HttpOnly`, `SameSite=Strict`. Tutte le API di gestione tranne il login richiedono una sessione valida; le scritture richiedono anche `X-CSRF-Token`. Se presente, `Origin` deve corrispondere all'origine del servizio. Le risposte di login/sessione forniscono `csrf_token`. Le chiavi locali `server_keys` non sostituiscono il login amministrativo. + +La sessione dura 720 minuti per impostazione predefinita, con intervallo consentito di 5–10.080 minuti. Modificare le credenziali amministrative o riavviare il processo invalida le sessioni esistenti; l'endpoint di modifica dell'account richiede nuovamente la password corrente. Il login ha un limite di frequenza; il Playground consente al massimo 12 richieste al minuto per client connesso direttamente. Il servizio non considera attendibile `X-Forwarded-For`, quindi i client dietro un reverse proxy condividono il limite del peer. Un reverse proxy HTTPS deve impostare correttamente `X-Forwarded-Proto`, usato per il flag Secure del cookie e per il controllo dell'origine. + +## Salvataggio e ricarica della configurazione + +`GET /api/config` restituisce la configurazione operativa, ID sicuri/valori mascherati, listener effettivi e campi che richiedono un riavvio. Per aggiornare chiavi e proxy usa una delle seguenti rappresentazioni: + +```json +{"id":"EXISTING_FINGERPRINT"} +``` + +```json +{"value":"NEW_VALUE"} +``` + +`PUT /api/config` accetta il modulo completo di configurazione, non un PATCH parziale; le liste di chiavi/proxy omesse possono essere considerate vuote. Per conservare un valore esistente invia il suo ID. Il salvataggio dalla pagina conserva le opzioni avanzate non modificate nel modulo. Credenziali OAuth, rotazione e password amministrativa sono gestite dagli endpoint dedicati; il salvataggio ordinario non accetta né sovrascrive token OAuth inviati dal browser. + +Il salvataggio esegue, nell'ordine, validazione, costruzione del runtime candidato, persistenza e sostituzione del runtime. Se la validazione o la persistenza della configurazione falliscono, il runtime precedente continua a servire le richieste. Il file ammette commenti `//` e `/* ... */`, mentre le richieste API devono essere JSON standard. Campi sconosciuti, campi duplicati al primo livello, valori non validi e presenza simultanea dei campi OAuth vecchi e nuovi per lo stesso piano vengono rifiutati. Il salvataggio normalizza il file ed elimina i commenti. + +Chiavi, proxy, upstream, timeout, modelli, preferenza, reasoning e log vengono applicati alle nuove richieste senza riavvio. `listen`, `webui.listen` e `webui.enabled` richiedono un riavvio; la pagina mostra sia i valori configurati sia i listener effettivi. Dopo una modifica manuale del file usa «Ricarica da disco» o `POST /api/config/reload`: il programma non sorveglia automaticamente il file. + +`POST /api/config/reveal` richiede sessione amministrativa, CSRF e una nuova verifica della password. Può restituire chiavi manuali e valori dei proxy, ma non password, hash della password o token OAuth. Usalo soltanto quando occorre copiarli, evitando di scrivere il risultato nei log o condividerlo. + +Valori predefiniti comuni per la gestione: + +| Impostazione | Valore predefinito / intervallo | +| --- | --- | +| `webui.enabled` | Disabilitata nei valori incorporati; abilitata nell'esempio. | +| `webui.listen` | `0.0.0.0:8081`. | +| `logging.level` | `info`; supporta `debug`, `info`, `warn`, `error`. | +| `logging.ring_size` | `2000`; intervallo 100–50.000. | +| `logging.dump_request_bodies` | `false`; richiede anche debug, con un massimo di 64 KiB per corpo preparato. | +| `models.active_probes` | `false`; il traffico reale fornisce le osservazioni predefinite sulla disponibilità. | + +## Go OAuth e Zen PAYG OAuth + +«Modelli e quota» contiene due pannelli indipendenti. Go usa le rotte dell'abbonamento; Zen usa la fatturazione a consumo (PAYG) del workspace Console: **l'inferenza consuma i credits di quel workspace**. Accedere a Go non concede autorizzazioni o saldo Zen e non collega automaticamente PAYG. + +Procedura: + +1. Avvia il login nel pannello corrispondente; Zen richiede prima una conferma esplicita di PAYG. +2. Apri personalmente il collegamento ufficiale di verifica OpenCode Device OAuth, inserisci il `user_code` mostrato e conferma che l'autorizzazione sia stata richiesta da te. La pagina non reindirizza automaticamente. +3. Il backend effettua il polling all'intervallo restituito. Se sono presenti più organizzazioni, sospende il completamento automatico: scegli quella a cui appartengono abbonamento/credits e collega l'organizzazione selezionata. Sono ammesse soltanto le organizzazioni autorizzate da quel login. +4. Dopo il successo si aggiornano configurazione e vista dei modelli. In caso di errore o scadenza puoi annullare e ricominciare. + +Non occorre incollare token, leggere file locali di credenziali o inviare URL di callback. Uscire dalla pagina o nascondere il browser interrompe il polling automatico; al ritorno viene riletto lo stato e un login non scaduto può proseguire. I login in attesa sono isolati per sessione amministrativa e piano: un ID non può essere riutilizzato tra piani. L'annullamento rimuove soltanto il login in attesa corrispondente; il logout amministrativo annulla i login in attesa di quella sessione, conservando le connessioni salvate. + +| Operazione | Endpoint Go | Endpoint Zen | Corpo | +| --- | --- | --- | --- | +| Stato sicuro | `GET /api/go/auth` | `GET /api/zen/auth` | Nessuno. | +| Avvio del login | `POST /api/go/auth/start` | `POST /api/zen/auth/start` | Go: `{}`; Zen: `{"acknowledge_payg":true}`. | +| Polling / scelta organizzazione | `POST /api/go/auth/poll` | `POST /api/zen/auth/poll` | `{"id":"LOGIN_ID"}`; aggiungi `organization_id` per scegliere l'organizzazione. | +| Annullamento login in attesa | `DELETE /api/go/auth` | `DELETE /api/zen/auth` | Nessuno. | +| Disconnessione salvata | `DELETE /api/go/connection` | `DELETE /api/zen/connection` | Nessuno. | + +Tutti gli endpoint richiedono una sessione, e le scritture richiedono CSRF. Login, stato, configurazione e reveal non restituiscono credenziali OAuth di accesso o rinnovo. + +Le connessioni sono salvate rispettivamente in `go_oauth` e `zen_oauth`; il backend le rinnova e persiste quando necessario. Configurazione e backup contengono quindi credenziali sensibili di accesso/rinnovo: limita i permessi di lettura. I vecchi `go_subscription`/`zen_subscription` sono soltanto alias di migrazione al caricamento; il salvataggio usa i nuovi campi. La presenza dei campi vecchi e nuovi per lo stesso piano viene rifiutata. + +Limiti dell'instradamento: + +- Sono accettati soltanto i modelli effettivamente forniti dalla configurazione remota ufficiale autenticata e validati per host/percorso del piano e SDK supportato. Non si deduce PAYG eliminando `/go` dall'URL Go e non si accettano header di autenticazione remoti arbitrari. Le vecchie rotte `/zen` sono ammesse soltanto se fornite esplicitamente dalla configurazione remota. +- Credenziali, origine dei modelli e rinnovi di Go e Zen sono indipendenti. `prefer` decide il primo canale disponibile per lo stesso modello; scegliere `zen` consente alla connessione Zen OAuth di consumare credits. +- Una volta selezionato OAuth viene usato soltanto quel tier. Autorizzazione Go scaduta, quota esaurita, 429 o altri errori non causano un ripiego automatico su Zen PAYG, chiavi manuali o canale anonimo. +- `go_keys`/`zen_keys` manuali sono conservate ma non fungono da riserva finché esiste l'OAuth corrispondente, anche se occorre un nuovo login o non sono disponibili rotte. +- La disconnessione rimuove soltanto la connessione locale corrispondente, senza revocare la sessione ufficiale o influire sull'altra connessione. Seguono un nuovo rilevamento dei modelli manuali di quel tier e il rifiuto di dedurre rotte finché il rilevamento non è concluso. Con accesso anonimo disabilitato non puoi scollegare l'unica credenziale upstream rimasta: configura prima un'altra chiave/connessione. +- Quota residua OAuth dell'abbonamento e credits sono attualmente sconosciuti. Non vengono riutilizzate le quote delle chiavi manuali né dedotte disponibilità dal numero di modelli o dalle richieste riuscite. + +L'implementazione si basa su snapshot del sorgente fissati: per Go, [v2 `4617210822bdbb31e5749751afbfb4584ccedac8`](https://github.com/anomalyco/opencode/tree/4617210822bdbb31e5749751afbfb4584ccedac8) e [dev `7745079647b65036fe142e09ccd8623b25be1878`](https://github.com/anomalyco/opencode/tree/7745079647b65036fe142e09ccd8623b25be1878); per Console/PAYG, [dev `03d848f7b8d71d31d3e56f2abd8b337efbc1bc32`](https://github.com/anomalyco/opencode/tree/03d848f7b8d71d31d3e56f2abd8b337efbc1bc32). La compatibilità del sorgente non certifica autorizzazione e inferenza reali. Cambiamenti di permessi, workspace o formato upstream possono richiedere un nuovo login o un aggiornamento dell'implementazione. + +## Modelli, quote e disponibilità + +`GET /api/model-quotas` restituisce modelli Go e riepilogo delle quote; i modelli seguono il catalogo del gateway. Per le chiavi Go manuali la query usa `upstream.go` configurato con `/v1/usage`, per impostazione predefinita `https://opencode.ai/zen/go/v1/usage`. Il browser non riceve la chiave upstream. + +- Sono fornite finestre percentuali condivise su 5 ore mobili, settimana e mese, con orari di ripristino. Non sono disponibili saldi, importi o conteggi di richieste per singolo modello. +- Più chiavi possono condividere lo stesso piano: le quote non si sommano. La precisione delle percentuali dipende dall'upstream. +- I successi restano in cache 60 secondi, gli errori 15. In caso di errore si conserva l'ultimo valore riuscito, segnalato come storico; senza dati precedenti la quota resta sconosciuta. +- La pagina interroga ogni 60 secondi mentre è visibile; il polling periodico si ferma quando viene nascosta o abbandonata. Anche l'aggiornamento manuale rispetta la cache. +- Se esiste Go OAuth non vengono presi in prestito i dati delle chiavi Go manuali; quota OAuth e credits Zen restano sconosciuti. + +Il formato della quota segue il [sorgente usage upstream](https://github.com/anomalyco/opencode/blob/dev/packages/console/app/src/routes/zen/go/v1/usage.ts). Non è una garanzia di interfaccia pubblica stabile: un cambiamento di formato produce uno stato sconosciuto/errore, senza inventare saldi. + +La disponibilità dei modelli gratuiti deriva normalmente dalle richieste reali. Solo errori espliciti di modello inesistente o ritirato possono disabilitarlo; 401, 403, 429, errori generici 4xx/5xx, timeout, problemi di connessione e risposte malformate non bastano a dimostrare un ritiro. Il ripristino manuale mantiene il modello instradabile e lo esclude dai test automatici; la pianificazione riprende soltanto tornando al controllo automatico. + +L'inferenza sintetica in background richiede `models.active_probes: true`. Lo scheduler controlla ogni minuto gli elementi da verificare ed esegue i test per modello e canale. I modelli normali/non determinabili sono in genere ricontrollati ogni ora, quelli confermati non disponibili ogni 24 ore; ogni canale ha un timeout di 60 secondi. La richiesta usa prima il canale anonimo già abilitato, poi le chiavi Zen disponibili; se WARP è attivo ne usa le uscite. Senza un canale adatto il controllo viene saltato. I test attivi consumano quota reale ma non modificano cooldown di chiavi/proxy o statistiche delle richieste di produzione. + +| Endpoint di gestione | Scopo | +| --- | --- | +| `GET /api/models/availability` | Legge stato dei modelli gratuiti e risultati dei test reasoning. | +| `POST /api/models/probe` | Segna come da verificare i modelli a controllo automatico e risveglia lo scheduler; non aggira `active_probes`. | +| `POST /api/models/restore` | `{"model":"MODEL_ID"}`: ripristina il modello e lo assegna al controllo manuale. | +| `POST /api/models/manual` | `{"model":"MODEL_ID","manual":true}`; `false` ripristina il controllo automatico. | + +`reasoning.effort: "auto"` usa il massimo livello per Zen gratuito/anonimo verificato recentemente con successo. Con test attivi disabilitati non apprende nuovi limiti; anche il controllo manuale sospende i test automatici. Le osservazioni scadono dopo due ore. Non vengono dedotti livelli per Go, modelli a pagamento o capacità sconosciute; un effort esplicito del client ha sempre precedenza. + +## Chiavi API locali + +La gestione riguarda le `server_keys` del gateway, separate dalle chiavi upstream OpenCode. L'endpoint di creazione restituisce la nuova chiave completa; la lista restituisce soltanto impronta, nome, maschera, stato, data e utilizzo. Dopo la creazione la pagina permette di copiare chiave e variabili d'ambiente del client. + +| Endpoint | Richiesta e risultato | +| --- | --- | +| `GET /api/api-keys` | Lista sicura. | +| `POST /api/api-keys` | `{"name":"client-a"}` genera una chiave; `value` consente un valore personalizzato. Successo: 201. | +| `PATCH /api/api-keys/{id}` | `{"name":"client-b","enabled":false}`; puoi inviare soltanto i campi da modificare. | +| `DELETE /api/api-keys/{id}` | Elimina la chiave locale. | + +Le chiavi automatiche usano 192 bit casuali. Quelle personalizzate hanno lunghezza 16–256 e ammettono lettere, cifre, `.`, `_`, `-`; i nomi hanno 1–80 caratteri e la creazione ammette al massimo 200 chiavi. Deve restare almeno una chiave abilitata. Disabilitazione/eliminazione restituiscono immediatamente 401 alle nuove richieste; quelle in corso potrebbero aver già completato l'autenticazione. + +`server_key_metadata` memorizza per impronta nome, stato di abilitazione e data di creazione; le vecchie `server_keys` restano compatibili automaticamente. L'utilizzo mostra ultima ora e totale del processo corrente, classificando richieste e token per chiave usata nell'autenticazione. Il Playground è registrato separatamente come `playground`, senza addebito alla chiave locale presa in prestito. Le statistiche sopravvivono alla ricarica a caldo e si azzerano al riavvio; non forniscono quote indipendenti, autorizzazioni per modello o scadenze. + +## Proxy e WARP + +La configurazione supporta importazione multipla di proxy inline, controlli individuali e rimozioni in bozza. Il contenuto di `proxyfile` va gestito nel file di origine; i percorsi relativi sono risolti rispetto alla directory di configurazione. La rimozione rimane una bozza e diventa effettiva solo salvando la configurazione completa. + +`POST /api/proxies/check` richiede sessione e CSRF; scegli esattamente una delle due richieste: + +```json +{"id":"SAVED_PROXY_ID"} +``` + +```json +{"value":"https://proxy.example:8443"} +``` + +L'ID del proxy salvato proviene da `GET /api/config`; `value` serve per le bozze. Ogni controllo ha un timeout di 20 secondi. La pagina consente al massimo quattro controlli concorrenti, il server otto; oltre il limite restituisce 429 senza accodare. Un controllo completato restituisce HTTP 200 con `ok`, `state`, `reason`, `latency_ms` e, se disponibile, `status`; errori di autenticazione, CSRF o formato usano i rispettivi stati HTTP. + +Il controllo verifica soltanto se il proxy selezionato raggiunge l'upstream Zen configurato. Un client isolato invia attraverso quel proxy una GET non autenticata a `upstream.zen` con `/v1/models`: non invia chiavi Zen/Go, `public` o OAuth, non esegue inferenza, non segue redirect, non usa WARP e non modifica salute di produzione, cooldown delle chiavi o binding. Funziona anche con accesso anonimo disabilitato. + +| `state` | Interpretazione | +| --- | --- | +| `available` | Upstream 200–399 oppure 401; `authentication_required` su 401 prova solo l'arrivo a destinazione, non la validità della chiave. | +| `unavailable` | Connessione rifiutata dal proxy/DNS inesistente confermati nel controllo (`proxy_unreachable`), oppure 407 del tunnel proxy (`proxy_authentication_required`). | +| `limited` | 429: non dimostra un proxy guasto. | +| `rejected` | Altro rifiuto upstream o del tunnel; un 407 upstream non equivale a un errore di autenticazione del proxy. | +| `inconclusive` | Timeout, errore di trasporto non localizzabile o prerequisiti mancanti: non dimostra un guasto. | + +Per la pulizia in blocco considera confermata soltanto l'indisponibilità `unavailable` di quel controllo; non trattare limiti, rifiuti e timeout come guasti permanenti. L'inferenza reale può comunque essere limitata da modello, autenticazione, quota o policy. + +WARP è disabilitato per impostazione predefinita. Quando è attivo, richieste gratuite anonime/Zen manuali e relativi cataloghi/test usano il tunnel del processo; Go, modelli a pagamento e OAuth mantengono l'instradamento proxy. Serve UDP Cloudflare `2408`, senza TUN o modifiche alla tabella di routing. `warp.pool_size` limita le uscite concorrenti a 1–32 (predefinito 2); `warp.stack` è `ipv6` per impostazione predefinita, con alternative `ipv4`/`dual`. Un errore di inizializzazione rifiuta l'avvio o la configurazione candidata, senza passare silenziosamente ai proxy. + +Un 403/429 su un'uscita può causarne ritiro e sostituzione; i tentativi restano limitati dal budget e un'altra uscita non garantisce quota aggiuntiva. Le uscite IPv6 `/64` e IPv4 `/32` vengono deduplicate e messe in cooldown per sottorete. `warp.source_ipv6` richiede stack IPv6 e prefisso `/64` o più corto; Linux usa `IPV6_FREEBIND`, mentre su Windows gli indirizzi sorgente selezionati devono essere già assegnati. Questa impostazione non configura la rete host. `/healthz` espone solo stato/conteggi WARP; `resources.warp` in `/api/monitor` include anche informazioni sulle uscite. + +## Rotazione SOTA / Sweet + +I client mantengono API Base URL, chiave e i tre endpoint di messaggistica, cambiando solo `model` nell'alias `sota` o `sweet`. Gli alias sono modificabili e compaiono in `/v1/models` quando disponibili; le chiamate ai modelli reali restano compatibili. La rotazione usa solo Go (chiavi manuali o Go OAuth), senza ripiego PAYG tra tier; System One non partecipa alla rotazione. + +I membri fissi di SOTA sono `deepseek-v4.1-flash`, `glm-5.3`, `grok-4.6`, `kimi-k3`, `qwen3.8-max`. Sweet comprende gli altri modelli Go di messaggistica disponibili, inizialmente con precedenza a `glm-5.3-flash`, poi in ordine alfabetico; i nuovi modelli vengono aggiunti in coda. Quelli ritirati restano nella lista ma non sono selezionabili. La disponibilità effettiva dipende da catalogo e rotte, non è garantita dal nome fisso. + +Ogni gruppo condivide una posizione corrente: la conserva dopo un successo e avanza dopo un errore. Un numero di versione impedisce che un errore concorrente precedente ripristini una posizione vecchia; una selezione manuale non interrompe la risposta in corso. Ogni richiesta visita un modello al massimo una volta. + +- Gli errori ordinari consentono al massimo tre tentativi per modello e consumano il budget di al massimo tre modelli con errori ordinari. Un modello esaurito viene sospeso per 15 secondi. +- Un 429/errore esplicito di quota passa direttamente al modello successivo; la pausa segue `Retry-After`, altrimenti 60 secondi, senza aggiungere consumo al budget degli errori ordinari. Gli errori ordinari precedenti continuano a contare. +- Non si applicano tentativi ordinari delle chiavi tra tier o reinvii stale-reasoning; il guasto di un modello non sospende l'intera chiave Go. Una quota condivisa può rendere indisponibile tutto il gruppo. +- Il budget complessivo è `retry.timeout_seconds`; `rotation.first_output_seconds` limita l'attesa di output effettivo per tentativo, con predefinito 30 secondi e intervallo 1–300. Per risposte non streaming occorre leggere la risposta valida completa entro questa scadenza. +- Gli eventi iniziali dello stream restano in memoria fino a output effettivo/termine normale. Prima dell'invio è possibile ritentare; dopo l'invio un errore conserva il contenuto già ricevuto, invia un errore SSE nel protocollo e termina. Non si concatenano risposte alternative in uno stream. L'annullamento del client non provoca cambi di modello o pause. +- `model` nella risposta mantiene l'alias richiesto; `X-Resolved-Model` indica il modello effettivo, cui sono attribuiti i token. Le registrazioni contengono la classificazione della causa, non corpi delle richieste, chiavi o testo degli errori upstream. + +| Endpoint di gestione | Contenuto | +| --- | --- | +| `GET /api/rotation` | Ordine/alias dei due gruppi, modello corrente, pause, stato di persistenza, ultimi 100 tentativi e 30 cambi per gruppo. | +| `PUT /api/rotation` | Invia `alias`, `order` e `first_output_seconds` completi per `sota`/`sweet`; si può riordinare all'interno del gruppo senza omettere membri. | +| `POST /api/rotation/current` | `{"group":"sota","model":"glm-5.3"}`: cambia modello e ne elimina la pausa. | + +Gli alias ammettono 1–64 lettere, cifre, `.`, `_`, `-`, devono iniziare con una lettera/cifra e non possono coincidere tra loro o con modelli reali. Se un cambiamento del catalogo rende incompatibili i membri inviati, aggiorna la pagina prima di riordinarli. + +La configurazione è in `rotation`, lo stato operativo in `config.json.rotation.json`. La ricarica a caldo condivide lo stato; l'impossibilità iniziale di leggerlo/scriverlo rifiuta l'avvio, mentre errori di scrittura successivi sono segnalati nella gestione. + +## Playground, log e monitoraggio + +Il Playground invoca nello stesso processo il medesimo gateway tramite `POST /api/debug/inference`, forzando risposte non streaming. Esempio di instradamento automatico: + +```json +{"protocol":"chat","key":{"mode":"auto"},"request":{"model":"MODEL_ID","messages":[{"role":"user","content":"Hello"}]}} +``` + +Per una chiave specifica sostituisci `key` con `{"mode":"selected","tier":"zen","id":"KEY_FINGERPRINT"}`; l'ID proviene da `GET /api/debug/models`. La chiave selezionata esegue un solo tentativo upstream, senza anonimo, cambio chiave, cambio tier o reinvio reasoning. L'opzione `relay` seleziona un proxy con un indice noto, per esempio `{"index":0}`; l'indice deve provenire dal catalogo diagnostico corrente. + +La diagnostica non modifica cooldown delle chiavi, conteggi degli errori, salute dei proxy o binding di produzione, ma invia richieste reali, consuma quota/credits ed entra nel monitoraggio. La risposta di gestione valida è incapsulata in HTTP 200, con `ok`, `http_status`, `request_id`, `route`, `response` che descrivono l'esito effettivo. Le chiavi selezionate aggiungono `selected_key` e `key_test`, con valori come `usable`, `rejected`, `rate_limited`, `transport_error`, `upstream_error`, `request_error`, `unavailable`. Errori di formato, autenticazione o limite usano comunque lo stato HTTP corrispondente. + +I log sono disponibili su `GET /api/logs?after=SEQUENCE&limit=COUNT` e `GET /api/logs/stream`. SSE consente la ripresa con `Last-Event-ID` o `after`; gli eventi scaduti/persi producono `gap`, ma i dati già eliminati non sono recuperabili. Il server termina lo stream dei log quando la sessione diventa invalida. + +`GET /api/monitor` fornisce aggregati di richieste, token, tentativi upstream e risorse. `GET /api/debug/models` fornisce rotte, impronte delle chiavi, metadati dei modelli, proxy e ultimo risultato diagnostico. I token sono soltanto quelli dichiarati dall'upstream, senza stime dei valori mancanti; l'input include letture e scritture della cache, mentre cached indica separatamente le letture. `usage.server_keys` raggruppa per chiave locale e distingue `playground`. + +Il risultato della richiesta riguarda l'inferenza completa: un errore dello stream è `stream_error` anche con HTTP 200, l'annullamento del chiamante è `client_canceled`. I tentativi upstream misurano solo lo scambio fino agli header: percentuale di successo e latenza non equivalgono al successo della risposta completa. + +## Persistenza, salute e sicurezza + +| Dati | Posizione e ciclo di vita | +| --- | --- | +| Configurazione / versione precedente | `config.json`, `config.json.bak`, con informazioni sensibili. | +| Cache modelli/prezzi | `config.json.models.catalog.json`, `config.json.models.dev.json`. | +| Disponibilità gratuita | `config.json..availability.json`, isolata per upstream. | +| Stato della rotazione | `config.json.rotation.json`. | +| Sessioni, token cumulativi, buffer circolare dei log, ultimo Playground | Memoria del processo; azzerati al riavvio. | +| Dettagli di richieste/tentativi | Ultima ora, al massimo 10.000/20.000 elementi; gli endpoint restituiscono fino a 500 elementi ciascuno. | +| Log a lungo termine | JSON su stdout, da raccogliere e conservare in sicurezza. | + +Il prefisso dei file dipende dal percorso effettivo di `-config`. Più processi non condividono sessioni, monitoraggio o contatori in memoria; evita modifiche concorrenti allo stesso file di stato. + +`GET /healthz` si trova sulla porta di inferenza, non richiede autenticazione e non attiva controlli upstream o conteggi di monitoraggio. Catalogo non pronto/vuoto, WARP senza uscite attive o proxy necessari senza nodi sani producono 503. Un catalogo obsoleto ma utilizzabile può restituire 200, `degraded`; la soglia di obsolescenza è due volte l'intervallo di aggiornamento, con minimo di 60 secondi. La necessità di un nuovo login OAuth compare negli issues, ma lo stato pronto non garantisce la prossima inferenza. Le informazioni pubbliche riguardano stato e conteggi, senza chiavi o indirizzi dei proxy. + +Per uso locale limita l'accesso a loopback; per gestione in rete usa HTTPS e restrizioni d'accesso. Il programma non termina TLS. Configurazione/backup contengono chiavi manuali, password dei proxy e token OAuth: limita i permessi dei file o le ACL Windows ed escludili dalla condivisione del sorgente. I corpi di debug, pur mascherati e troncati, possono contenere conversazioni private: abilitali brevemente solo quando necessario. Non allegare configurazioni complete, risultati reveal, cookie, header di autorizzazione o contenuti reali dell'inferenza per la risoluzione dei problemi. + +## Verifica e manutenzione + +Controlli di sviluppo locale: + +```bash +go vet ./... +go build -trimpath -o opencode2api ./cmd/opencode2api +for file in webui/js/*.js webui/js/pages/*.js; do + node --input-type=module --check < "$file" || exit 1 +done +``` + +La verifica di una distribuzione normale deve coprire login amministrativo e CSRF, disabilitazione/ripristino delle chiavi, salvataggio della configurazione e riavvio dei listener, rilevamento dei modelli, tre protocolli di messaggistica ed errori SSE, stato della rotazione e funzioni reali OAuth/upstream necessarie. Inferenza reale, OAuth, WARP e query di quota possono dipendere dai permessi dell'account e consumare quota; i controlli statici non sostituiscono queste verifiche. + +Prima di aggiornare salva in sicurezza programma, configurazione effettiva e stato; arresta il processo prima di sostituire l'eseguibile. Per tornare indietro ripristina configurazione e stato compatibili. Con Compose conserva i file effettivi nel volume. Non aggiungere credenziali, log, stato operativo o artefatti locali di verifica al sorgente. diff --git a/docs/management.md b/docs/management.md new file mode 100644 index 0000000..d4bd640 --- /dev/null +++ b/docs/management.md @@ -0,0 +1,265 @@ +# Management console and operations guide + +[English](management.md) | [简体中文](management.zh-CN.md) | [Tiếng Việt](management.vi.md) | [Italiano](management.it.md) + +This guide covers the implemented management features, OAuth, quota, model rotation, diagnostics, and persistence. See the [English README](../README.md) for startup and inference API examples, and [config.example.json](../config.example.json) for a configuration starting point. Management and inference use separate listeners; every `/api/*` route below belongs to the management listener. + +## Startup and access + +On Linux, use Go 1.24 or later and build with Bash from the project directory: + +```bash +if [ ! -f config.json ]; then + cp config.example.json config.json +fi +export GOCACHE="$PWD/.local/go-cache" +export GOMODCACHE="$PWD/.local/go-modules" +go build -trimpath -o opencode2api ./cmd/opencode2api +``` + +Before starting, edit the configuration locally: replace `server_keys` and `webui.password`, and supply `zen_keys` or `go_keys`. For local management, use `webui.listen: "127.0.0.1:8081"`; the example's `0.0.0.0:8081` listens on all interfaces. The password must contain at least 10 characters; the example administrator name is `admin`. + +```bash +./opencode2api -config config.json +``` + +On native Windows, build with `go build -trimpath -o opencode2api.exe ./cmd/opencode2api`, then run `.\opencode2api.exe -config .\config.json` in PowerShell. The README documents Docker/Compose volume initialization, configuration imports, ports, and images. Manage the configuration actually used by the running service; editing a host copy without importing it again does not change the active volume configuration. + +The anonymous lane, `anonymous`, is disabled by default. Startup requires at least one upstream key, a saved Go/Zen OAuth connection, or explicitly enabled anonymous access. You cannot start with all credentials empty just to complete the first OAuth login in the WebUI. Anonymous traffic may be blocked upstream; do not enable anonymous inference just to check proxies. + +The configuration directory must be writable. On first startup, `webui.password` is migrated to an Argon2id `password_hash`, and the program attempts to remove the backup containing the bootstrap plaintext password. Other credentials are not encrypted by this migration. + +## Pages and management authentication + +| Page | Address | Purpose | +| --- | --- | --- | +| Overview | `/#overview` | Requests, tokens, upstream attempts, and runtime resources. | +| Diagnostics | `/#diagnostics` | Model routes, Playground, and live logs. | +| Client access | `/#access` | Client connection settings. | +| API key management | `/#api-keys` | Local key lifecycle and usage. | +| Models and quota | `/#model-quotas` | Go catalog, shared quota, both OAuth plans, and free-model availability. | +| Model rotation | `/#rotation` | Group order, current selection, pauses, and attempt history. | +| Configuration | `/#config` | Keys, proxies, timeouts, routes, WARP, and logging. | +| Account security | `/#account` | Change the administrator username and password. | + +The UI supports Simplified Chinese, English, Vietnamese, and Italian. Language and theme choices are stored in the browser. The old `#playground` and `#logs` links open Diagnostics; `#availability` opens Models and quota. + +Administrators log in with a username and password and receive an `HttpOnly`, `SameSite=Strict` session cookie. Every management API except login requires a valid session. Writes also require `X-CSRF-Token`; when an `Origin` header is present, it must match the service's origin. Login and session responses provide `csrf_token`. Local `server_keys` do not grant management access. + +Sessions default to 720 minutes, with a range of 5–10,080 minutes. Changing administrator credentials or restarting the process invalidates existing sessions; the account update endpoint requires the current password again. Login is throttled. Playground allows at most 12 requests per direct client per minute. The service does not trust `X-Forwarded-For`, so clients behind a reverse proxy share its limits. An HTTPS reverse proxy must set `X-Forwarded-Proto` correctly because it affects the cookie's Secure flag and origin checks. + +## Saving and reloading configuration + +`GET /api/config` returns the runtime configuration, safe IDs/masked values, effective listeners, and fields requiring restart. A key/proxy update uses one of these representations: + +```json +{"id":"EXISTING_FINGERPRINT"} +``` + +```json +{"value":"NEW_VALUE"} +``` + +`PUT /api/config` accepts a complete configuration form rather than a partial PATCH. Omitted key/proxy lists may be treated as empty. Submit the existing value's ID to retain it. Saving through the UI preserves advanced configuration that the form does not edit. OAuth credentials, rotation, and administrator passwords have dedicated endpoints; ordinary configuration saves do not accept browser-supplied OAuth tokens or overwrite the saved credentials with them. + +Saving validates the candidate, builds its runtime, persists the configuration, and switches to it. If validation or configuration persistence fails, the existing runtime continues serving. Configuration files allow `//` and `/* ... */` comments; API bodies require standard JSON. Unknown fields, repeated top-level fields, invalid values, and old/new OAuth fields for the same plan are rejected. Saving normalizes the file and removes comments. + +Keys, proxies, upstreams, timeouts, models, preferences, reasoning, and logging apply to new requests without a restart. Changes to `listen`, `webui.listen`, or `webui.enabled` require restart; the UI shows configured and effective listeners. After editing the file manually, select the disk reload action or call `POST /api/config/reload`. The program does not watch the file automatically. + +`POST /api/config/reveal` requires a management session, CSRF, and password verification again. It can return manual keys and proxy values, but never the password, password hash, or OAuth tokens. Use it only when copying a value is necessary, and keep its output out of logs and shared material. + +Common management defaults: + +| Setting | Default / range | +| --- | --- | +| `webui.enabled` | Disabled in built-in defaults; enabled in the example. | +| `webui.listen` | `0.0.0.0:8081`. | +| `logging.level` | `info`; supports `debug`, `info`, `warn`, and `error`. | +| `logging.ring_size` | `2000`; range 100–50,000. | +| `logging.dump_request_bodies` | `false`; also requires debug logging, capped at 64 KiB per prepared body. | +| `models.active_probes` | `false`; real traffic supplies default availability observations. | + +## Go OAuth and Zen PAYG OAuth + +Models and quota contains two separate panels. Go uses subscription routes; Zen uses Console workspace pay-as-you-go billing (PAYG), and **inference consumes that workspace's credits**. Signing in to Go does not establish Zen permissions or balance, or automatically connect PAYG. + +Sign-in steps: + +1. Start login in the appropriate panel. Zen requires explicit PAYG acknowledgement first. +2. Open the official OpenCode Device OAuth verification link yourself, enter the displayed `user_code`, and confirm that you initiated the authorization. The page does not redirect automatically. +3. The backend polls at the returned interval. When several organizations are available, automatic completion pauses. Select the organization holding the subscription/credits and connect it; only organizations allowed by this authorization can be selected. +4. On success, configuration and model views refresh. Cancel and start again if login fails or expires. + +No token pasting, local credential-file import, or callback-URL submission is required. Leaving the page or hiding the browser stops automatic polling; returning reads the status again and can resume an unexpired login. Pending logins are scoped to the management session and plan; login IDs cannot be used across plans. Canceling clears only the corresponding pending login. Logging out cancels that session's pending logins while retaining saved connections. + +| Action | Go endpoint | Zen endpoint | Body | +| --- | --- | --- | --- | +| Safe status | `GET /api/go/auth` | `GET /api/zen/auth` | None. | +| Start login | `POST /api/go/auth/start` | `POST /api/zen/auth/start` | Go: `{}`; Zen: `{"acknowledge_payg":true}`. | +| Poll/select organization | `POST /api/go/auth/poll` | `POST /api/zen/auth/poll` | `{"id":"LOGIN_ID"}`; add `organization_id` when selecting an organization. | +| Cancel pending login | `DELETE /api/go/auth` | `DELETE /api/zen/auth` | None. | +| Disconnect saved account | `DELETE /api/go/connection` | `DELETE /api/zen/connection` | None. | + +All endpoints require a session, and writes require CSRF. Login, status, configuration, and reveal responses never return OAuth access/refresh credentials. + +Connections are saved as `go_oauth` and `zen_oauth` in the configuration. The backend refreshes credentials when needed and persists them. Configuration and backups therefore contain sensitive access/refresh credentials and need restricted read permissions. Legacy `go_subscription`/`zen_subscription` fields are accepted only as load-time migration aliases; saves use the new fields. Supplying both old and new fields for one plan is rejected. + +Routing boundaries: + +- Only models actually supplied by authenticated official remote configuration and accepted by the plan-specific host/path and supported-SDK checks are used. PAYG URLs are not guessed by removing `/go` from Go URLs, and arbitrary remote authentication headers are not imported. Legacy `/zen` routes are accepted only when explicitly provided by remote configuration. +- Go and Zen credentials, model sources, and refresh state are separate. `prefer` selects the preferred available route for a model; choosing `zen` permits the connected Zen OAuth account to consume credits. +- Once OAuth is selected, only that tier serves the request. Go authorization failure, quota exhaustion, 429, or other errors do not automatically switch to Zen PAYG, manual keys, or anonymous access. +- Manual `go_keys`/`zen_keys` remain saved but are not fallback routes while the corresponding OAuth connection exists, including when a new login is needed or no usable route is available. +- Disconnecting removes only the corresponding local connection, without revoking the official session or affecting the other plan. Manual models for that tier are then rediscovered; routing is not guessed while discovery is pending. With anonymous access disabled, the last remaining upstream credential cannot be disconnected until another key/connection is configured. +- OAuth subscription allowance and credits are currently unknown. Manual-key quota, model counts, and successful requests are not used to infer them. + +The implementation references fixed upstream source snapshots: Go [v2 `4617210822bdbb31e5749751afbfb4584ccedac8`](https://github.com/anomalyco/opencode/tree/4617210822bdbb31e5749751afbfb4584ccedac8) and [dev `7745079647b65036fe142e09ccd8623b25be1878`](https://github.com/anomalyco/opencode/tree/7745079647b65036fe142e09ccd8623b25be1878), and Console/PAYG [dev `03d848f7b8d71d31d3e56f2abd8b337efbc1bc32`](https://github.com/anomalyco/opencode/tree/03d848f7b8d71d31d3e56f2abd8b337efbc1bc32). Source compatibility does not establish successful live authorization or inference. Changes to upstream permissions, workspaces, or configuration formats may require signing in again or updating the implementation. + +## Models, quota, and availability + +`GET /api/model-quotas` returns Go models and a quota summary, using the gateway catalog as the model source. Manual Go-key quota is queried at configured `upstream.go` plus `/v1/usage`, defaulting to `https://opencode.ai/zen/go/v1/usage`. Upstream keys are not sent to the browser. + +- The response provides shared percentages and reset times for rolling five-hour, weekly, and monthly windows, not individual model balances, monetary amounts, or remaining request counts. +- Several keys may share one subscription; their allowances must not be added. Percentage precision is determined by the upstream. +- Successful results cache for 60 seconds, failures for 15. Failures retain previous successful data and label it stale; without history, quota is unknown. +- While visible, the page polls every 60 seconds. Hiding or leaving it stops periodic queries. Manual refresh also respects the server cache. +- When Go OAuth is connected, manual Go-key data is not reused. OAuth allowance and Zen credits remain unknown. + +The format follows the [upstream usage implementation](https://github.com/anomalyco/opencode/blob/dev/packages/console/app/src/routes/zen/go/v1/usage.ts). This is not a promise of a stable public interface. Format changes produce unknown/error states rather than invented balances. + +Free-model availability is learned from real requests by default. Only explicit model-not-found/retired evidence can disable a model. Statuses 401, 403, 429, generic 4xx/5xx, timeouts, transport errors, and malformed replies alone do not establish retirement. Manual restore keeps a model routable and excludes it from automatic probes until automatic control is restored. + +Background synthetic inference requires `models.active_probes: true`. The scheduler checks due records every minute and processes models and lanes sequentially. Healthy/inconclusive models are normally checked after one hour; confirmed unavailable models after 24 hours. Each lane has a 60-second timeout. Probes try the enabled anonymous lane, then an available Zen key, using WARP exits when enabled; models without a suitable lane are skipped. Active probes use real upstream allowance without changing production key/proxy cooldowns or request statistics. + +| Management endpoint | Purpose | +| --- | --- | +| `GET /api/models/availability` | Free-model state and reasoning-probe results. | +| `POST /api/models/probe` | Mark automatically controlled models due and wake the scheduler; does not override `active_probes`. | +| `POST /api/models/restore` | `{"model":"MODEL_ID"}` restores a model and puts it under manual control. | +| `POST /api/models/manual` | `{"model":"MODEL_ID","manual":true}`; `false` restores automatic control. | + +`reasoning.effort: "auto"` uses a recently validated effort ceiling for free Zen/anonymous models. New ceilings are not actively learned with active probes disabled; manual control also pauses automatic probes. Observations expire after two hours. Levels are not inferred for Go/paid models or unknown capabilities. Explicit client effort always takes precedence. + +## Local API keys + +These endpoints manage the gateway's `server_keys`, separately from OpenCode upstream keys. Creation returns the complete new key; lists contain only fingerprint, name, masked value, state, timestamps, and usage. The UI can copy the key and client environment variables after creation. + +| Endpoint | Request and result | +| --- | --- | +| `GET /api/api-keys` | Safe key list. | +| `POST /api/api-keys` | `{"name":"client-a"}` generates a key; add `value` for a custom key. Returns 201 on success. | +| `PATCH /api/api-keys/{id}` | `{"name":"client-b","enabled":false}`; only fields being changed are required. | +| `DELETE /api/api-keys/{id}` | Delete a local key. | + +Generated keys contain 192 random bits. Custom keys accept 16–256 letters, digits, `.`, `_`, or `-`. Names accept 1–80 characters, and the creation endpoint allows at most 200 keys. At least one key must remain enabled. Disabled/deleted keys receive 401 on new requests; in-flight requests may already have authenticated. + +`server_key_metadata` stores names, enabled state, and creation times by fingerprint. Existing `server_keys` remain compatible. Usage shows the last hour and process lifetime, attributing requests and tokens to the key that authenticated them. Playground is recorded separately under `playground`, without charging its borrowed local key. Statistics survive hot reloads and reset on restart. There are no per-key quotas, model permissions, or expiration dates. + +## Proxies and WARP + +Configuration supports bulk import of inline proxies, individual checks, and staged removal. Manage `proxyfile` entries in their source file; relative paths are resolved against the configuration directory. Removal remains a draft until the complete configuration is saved. + +`POST /api/proxies/check` requires a session and CSRF. Submit exactly one of these requests: + +```json +{"id":"SAVED_PROXY_ID"} +``` + +```json +{"value":"https://proxy.example:8443"} +``` + +Saved proxy IDs come from `GET /api/config`; `value` is for drafts. Each check times out after 20 seconds. The UI runs at most four concurrently; the server accepts at most eight and returns 429 for excess checks without queuing. A completed check returns HTTP 200 with `ok`, `state`, `reason`, `latency_ms`, and `status` when available. Authentication, CSRF, and input errors use their corresponding HTTP statuses. + +A check only determines whether the selected proxy can reach the configured Zen upstream. An isolated client sends an unauthenticated GET through that proxy to `upstream.zen` plus `/v1/models`. It sends no Zen/Go key, `public` credential, or OAuth token; performs no inference; follows no redirects; does not use WARP; and does not change production health, key cooldowns, or bindings. It works with anonymous access disabled. + +| `state` | Meaning | +| --- | --- | +| `available` | Upstream 200–399 or 401. For 401, `authentication_required` proves reachability without validating a key. | +| `unavailable` | Confirmed proxy-side connection refusal/DNS-not-found (`proxy_unreachable`) or proxy tunnel 407 (`proxy_authentication_required`) on this check. | +| `limited` | 429; does not establish a broken proxy. | +| `rejected` | Other upstream refusal or proxy tunnel rejection. An origin 407 is not a proxy-authentication failure. | +| `inconclusive` | Timeout, unlocalized transport failure, or missing prerequisites; not proof of a broken proxy. | + +For bulk cleanup, only `unavailable` is a confirmed-unavailable filter for that check. Rate limits, rejections, and timeouts do not establish permanent failure. Production inference can still fail because of model, authentication, allowance, or policy constraints. + +WARP is disabled by default. When enabled, free anonymous/manual-Zen requests and their discovery/probe paths use an in-process tunnel. Go, paid, and OAuth routes retain proxy routing. It needs outbound Cloudflare UDP on port `2408`, without TUN or routing-table changes. `warp.pool_size` is a concurrency-driven exit ceiling of 1–32 (default 2). `warp.stack` defaults to `ipv6`, with `ipv4`/`dual` also available. Initialization failure rejects startup or the candidate configuration without silently falling back to proxies. + +Exit statuses 403/429 can trigger retirement and replacement, with retries still bounded by their budget. A new exit does not guarantee additional quota. IPv6 `/64` and IPv4 `/32` egress blocks are deduplicated/cooled. `warp.source_ipv6` requires the IPv6 stack and a prefix of `/64` or shorter. Linux uses `IPV6_FREEBIND`; Windows requires the selected source addresses to be assigned already. This setting does not configure host networking. `/healthz` reports WARP state/counts only; `resources.warp` in `/api/monitor` also contains exit information. + +## SOTA / Sweet rotation + +Clients keep the same API base URL, key, and three message endpoints, changing only `model` to the `sota` or `sweet` alias. Aliases are editable and appear in `/v1/models` when eligible. Direct model calls remain compatible. Rotation uses only Go (manual keys or Go OAuth), never cross-tier PAYG fallback; System One does not join rotation. + +SOTA contains the fixed models `deepseek-v4.1-flash`, `glm-5.3`, `grok-4.6`, `kimi-k3`, and `qwen3.8-max`. Sweet includes other available Go message models, initially prioritizing `glm-5.3-flash`, then sorting by name. New models are appended; retired members stay listed but cannot be selected. Availability comes from the catalog and routes, rather than being guaranteed by the fixed names. + +Each group has a shared current position. Success keeps it; failure advances it. A generation prevents an older concurrent failure from reverting a newer position. Manual selection does not interrupt an answer in progress. A request does not revisit the same model. + +- Ordinary errors allow up to three attempts per model and at most three ordinary-error models. A model that exhausts its attempts pauses for 15 seconds. +- A 429/explicit quota failure immediately advances to the next model. The pause follows `Retry-After`, defaulting to 60 seconds. It does not add to the ordinary-error model budget, although earlier ordinary errors still count. +- Rotation does not use regular-key cross-tier retries or stale-reasoning replay. A single-model failure does not pause the entire Go key. Shared quota may leave the whole group unavailable. +- The total budget is `retry.timeout_seconds`. `rotation.first_output_seconds` bounds each wait for useful output, defaults to 30 seconds, and accepts 1–300 seconds. A non-streaming response must be fully read and valid within that limit. +- Stream prelude events are held until useful output or normal completion. Errors before commitment can retry; errors after commitment preserve emitted content, send the protocol's SSE error, and end the response. Replacement answers are never spliced into one stream. Client cancellation does not trigger a switch or pause. +- Response `model` keeps the requested alias; `X-Resolved-Model` identifies the actual model. Tokens are attributed to that model. Records contain classified reasons, without request bodies, keys, or upstream error bodies. + +| Management endpoint | Content | +| --- | --- | +| `GET /api/rotation` | Both groups' order/aliases, current models, pauses, persistence state, last 100 attempts, and last 30 switches per group. | +| `PUT /api/rotation` | Full `alias`/`order` for `sota` and `sweet`, plus `first_output_seconds`; reorder within groups without dropping members. | +| `POST /api/rotation/current` | `{"group":"sota","model":"glm-5.3"}` selects a model and clears its pause. | + +Aliases accept 1–64 letters, digits, `.`, `_`, and `-`, beginning with a letter/digit. They must be distinct and cannot conflict with actual model IDs. If catalog changes cause a member mismatch on save, refresh before reordering. + +Configuration is stored under `rotation`; runtime state is `config.json.rotation.json`. Hot reloads share that state. Initial state read/write failure prevents startup; subsequent persistence failures are shown in the management page. + +## Playground, logs, and monitoring + +Playground invokes the same gateway in-process through `POST /api/debug/inference`, forcing non-streaming output. Automatic routing example: + +```json +{"protocol":"chat","key":{"mode":"auto"},"request":{"model":"MODEL_ID","messages":[{"role":"user","content":"Hello"}]}} +``` + +For a selected key, replace `key` with `{"mode":"selected","tier":"zen","id":"KEY_FINGERPRINT"}`; obtain its ID from `GET /api/debug/models`. A selected-key check makes one upstream attempt without anonymous access, key switching, cross-tier fallback, or reasoning replay. Optional `relay` pins a known proxy index, for example `{"index":0}`. Use an index from the current diagnostic catalog. + +Diagnostics preserve production key cooldowns, failure counts, proxy health, and bindings. They still make real requests, consume allowance/credits, and appear in monitoring. A completed management call wraps the result in HTTP 200, with the actual outcome in `ok`, `http_status`, `request_id`, `route`, and `response`. Selected-key results also include `selected_key` and `key_test`, such as `usable`, `rejected`, `rate_limited`, `transport_error`, `upstream_error`, `request_error`, or `unavailable`. Input, authentication, and throttling errors keep their corresponding HTTP statuses. + +Logs are available at `GET /api/logs?after=SEQUENCE&limit=COUNT` and `GET /api/logs/stream`. SSE resumes using `Last-Event-ID` or `after`; expired/missed events produce `gap`, and evicted data cannot be replayed. The server ends a log stream when its session becomes invalid. + +`GET /api/monitor` provides aggregate requests, tokens, upstream attempts, and resources. `GET /api/debug/models` provides routes, key fingerprints, model metadata, proxies, and the latest diagnostic result. Tokens use only upstream-reported usage, without estimating missing values. Input includes cache reads/writes; cached tokens separately count reads. `usage.server_keys` groups local-key usage, with `playground` separate. + +Request outcomes describe the complete inference. Failed streams count as `stream_error` even after HTTP 200; client cancellation is `client_canceled`. An upstream attempt measures the exchange only until response headers arrive, so its success rate and latency are not the success rate and latency of the complete answer. + +## Persistence, health, and security + +| Data | Location and lifecycle | +| --- | --- | +| Configuration/previous version | `config.json`, `config.json.bak`; contain sensitive information. | +| Model/price caches | `config.json.models.catalog.json`, `config.json.models.dev.json`. | +| Free-model availability | `config.json..availability.json`, isolated by upstream. | +| Rotation state | `config.json.rotation.json`. | +| Sessions, token totals, log ring, latest Playground | Process memory; cleared on restart. | +| Request/attempt details | Last hour, capped at 10,000/20,000 records; APIs return at most 500 of each. | +| Durable logs | JSON on stdout; collect and retain securely yourself. | + +Prefixes use the actual `-config` path. Processes do not share sessions, monitoring, or in-memory counters. Avoid concurrent writes to the same state files. + +`GET /healthz` is on the inference port, requires no authentication, and triggers no upstream check or monitoring count. It returns 503 while the catalog is pending/empty, WARP has no active exit, or required proxies have no healthy node. A usable stale catalog may return 200 with `degraded`; staleness means twice the refresh interval, at least 60 seconds. OAuth reauthorization needs appear in issues, but readiness does not guarantee the next inference. Public information includes state/counts, without keys or proxy addresses. + +Restrict local use to loopback. Network management needs HTTPS and access controls; the program does not terminate TLS itself. Configuration/backups contain manual keys, proxy passwords, and OAuth tokens: limit filesystem permissions or Windows ACLs and exclude them from source sharing. Even redacted, truncated request-body dumps can contain private conversations; enable them only briefly when needed. Do not attach full configuration, reveal output, cookies, authentication headers, or real inference content to troubleshooting reports. + +## Verification and maintenance + +Local development checks: + +```bash +go vet ./... +go build -trimpath -o opencode2api ./cmd/opencode2api +for file in webui/js/*.js webui/js/pages/*.js; do + node --input-type=module --check < "$file" || exit 1 +done +``` + +Normal deployment acceptance should verify management login and CSRF, key disable/restore, configuration saves and listener restarts, model discovery, the three message protocols and SSE errors, rotation state, and required live OAuth/upstream features. Real inference, OAuth, WARP, and quota queries may depend on account permissions and consume allowance. Static checks do not replace them. + +Before upgrading, securely back up the executable, active configuration, and state. Stop the process before replacing the executable; rollback needs compatible configuration and state. Compose users must preserve the actual files in the volume. Keep credentials, logs, runtime state, and local verification artifacts out of source control. diff --git a/docs/management.vi.md b/docs/management.vi.md new file mode 100644 index 0000000..a9d49e1 --- /dev/null +++ b/docs/management.vi.md @@ -0,0 +1,265 @@ +# Hướng dẫn quản trị và vận hành + +[English](management.md) | [简体中文](management.zh-CN.md) | Tiếng Việt | [Italiano](management.it.md) + +Tài liệu này mô tả các chức năng quản trị hiện có, OAuth, hạn mức, luân chuyển mô hình, chẩn đoán và lưu trữ trạng thái. Cách khởi động dịch vụ và ví dụ API suy luận có trong [README tiếng Việt](../README.vi.md); cấu hình mẫu đầy đủ nằm ở [config.example.json](../config.example.json). Giao diện quản trị và API suy luận dùng địa chỉ lắng nghe riêng; mọi đường dẫn `/api/*` bên dưới đều thuộc cổng quản trị. + +## Khởi động và truy cập + +Trên Linux, dùng Go 1.24 trở lên và Bash để biên dịch trong thư mục dự án: + +```bash +if [ ! -f config.json ]; then + cp config.example.json config.json +fi +export GOCACHE="$PWD/.local/go-cache" +export GOMODCACHE="$PWD/.local/go-modules" +go build -trimpath -o opencode2api ./cmd/opencode2api +``` + +Trước khi chạy, chỉnh cấu hình trên máy: thay `server_keys` và `webui.password`, rồi điền `zen_keys` hoặc `go_keys`. Khi chỉ quản trị cục bộ, nên dùng `webui.listen: "127.0.0.1:8081"`; giá trị mẫu `0.0.0.0:8081` lắng nghe trên mọi giao diện. Mật khẩu phải có ít nhất 10 ký tự; tên quản trị viên trong cấu hình mẫu là `admin`. + +```bash +./opencode2api -config config.json +``` + +Trên Windows, biên dịch bằng `go build -trimpath -o opencode2api.exe ./cmd/opencode2api`, sau đó chạy `.\opencode2api.exe -config .\config.json` trong PowerShell. Hướng dẫn khởi tạo volume, nhập tệp, cổng và image cho Docker/Compose có trong README. Khi quản trị, phải dùng cấu hình đang chạy thực tế; chỉ sửa bản sao trên máy chủ mà chưa nhập lại sẽ không thay đổi cấu hình trong container. + +Kênh ẩn danh `anonymous` mặc định tắt. Muốn khởi động, phải có ít nhất một key thượng nguồn, kết nối Go/Zen OAuth đã lưu, hoặc chủ động bật ẩn danh. Không thể khởi động khi mọi thông tin xác thực đều trống rồi vào WebUI để đăng nhập OAuth lần đầu. Thượng nguồn có thể chặn lưu lượng ẩn danh; không nên bật suy luận ẩn danh chỉ để kiểm tra proxy. + +Thư mục cấu hình phải ghi được. Lần chạy đầu chuyển `webui.password` thành `password_hash` Argon2id và cố xóa bản sao lưu chứa mật khẩu khởi tạo dạng rõ; thao tác này không mã hóa các thông tin xác thực khác. + +## Các trang và xác thực quản trị + +| Trang | Địa chỉ | Chức năng | +| --- | --- | --- | +| Tổng quan | `/#overview` | Yêu cầu, token, lần thử thượng nguồn và tài nguyên đang chạy. | +| Chẩn đoán | `/#diagnostics` | Định tuyến mô hình, Playground và nhật ký trực tiếp. | +| Hướng dẫn kết nối | `/#access` | Thông số kết nối cho client. | +| Quản lý API key | `/#api-keys` | Vòng đời và mức sử dụng key cục bộ. | +| Mô hình và hạn mức | `/#model-quotas` | Danh mục Go, hạn mức dùng chung, hai loại OAuth và tính khả dụng của mô hình miễn phí. | +| Luân chuyển mô hình | `/#rotation` | Thứ tự nhóm, vị trí hiện tại, tạm dừng và lịch sử thử. | +| Trung tâm cấu hình | `/#config` | Key, proxy, thời gian chờ, định tuyến, WARP và nhật ký. | +| Bảo mật tài khoản | `/#account` | Đổi tên quản trị viên và mật khẩu. | + +Giao diện hỗ trợ tiếng Trung giản thể, Anh, Việt và Ý; ngôn ngữ và giao diện được lưu trong trình duyệt. Các địa chỉ cũ `#playground`, `#logs` mở trang chẩn đoán; `#availability` mở trang mô hình và hạn mức. + +Quản trị viên đăng nhập bằng tên và mật khẩu để nhận cookie phiên có `HttpOnly` và `SameSite=Strict`. Mọi API quản trị, trừ đăng nhập, đều cần phiên hợp lệ; thao tác ghi còn cần `X-CSRF-Token`. Nếu có header `Origin`, giá trị phải trùng với nguồn của dịch vụ. Phản hồi đăng nhập/phiên cung cấp `csrf_token`. `server_keys` cục bộ không thay thế được đăng nhập quản trị. + +Phiên mặc định kéo dài 720 phút, cho phép cấu hình từ 5 đến 10.080 phút. Đổi thông tin xác thực quản trị hoặc khởi động lại tiến trình làm các phiên hiện có mất hiệu lực; API đổi tài khoản yêu cầu xác minh lại mật khẩu hiện tại. Đăng nhập có giới hạn tần suất; Playground cho phép tối đa 12 lần mỗi phút trên mỗi client kết nối trực tiếp. Dịch vụ không tin cậy `X-Forwarded-For`, nên các client sau reverse proxy dùng chung giới hạn của đầu kết nối. Reverse proxy HTTPS phải đặt đúng `X-Forwarded-Proto` vì header này tham gia xác định cờ Secure của cookie và kiểm tra nguồn. + +## Lưu và nạp lại cấu hình + +`GET /api/config` trả về cấu hình đang chạy, ID/mặt nạ an toàn, địa chỉ lắng nghe thực tế và những trường cần khởi động lại. Khi cập nhật key/proxy, dùng một trong hai dạng sau: + +```json +{"id":"EXISTING_FINGERPRINT"} +``` + +```json +{"value":"NEW_VALUE"} +``` + +`PUT /api/config` nhận toàn bộ biểu mẫu cấu hình, không phải PATCH từng phần; danh sách key/proxy bị bỏ qua có thể được coi là danh sách rỗng. Muốn giữ giá trị hiện có, gửi ID của giá trị đó. Lưu bằng giao diện có thể giữ các cấu hình nâng cao chưa được sửa trong biểu mẫu. Thông tin xác thực OAuth, luân chuyển và mật khẩu quản trị được quản lý qua API riêng; thao tác lưu thông thường không nhận hoặc ghi đè token OAuth do trình duyệt gửi lên. + +Thứ tự lưu là kiểm tra, tạo runtime ứng viên, ghi xuống đĩa rồi chuyển sang runtime mới. Nếu kiểm tra hoặc ghi cấu hình thất bại, runtime cũ tiếp tục phục vụ. Tệp cấu hình cho phép chú thích `//` và `/* ... */`, còn yêu cầu API phải là JSON chuẩn. Trường không xác định, trường cấp cao nhất bị lặp, giá trị không hợp lệ và việc dùng đồng thời trường OAuth cũ/mới cho cùng một gói đều bị từ chối. Sau khi lưu, tệp được chuẩn hóa và mất các chú thích. + +Các thiết lập key, proxy, thượng nguồn, thời gian chờ, mô hình, ưu tiên, reasoning và nhật ký áp dụng ngay cho yêu cầu mới. `listen`, `webui.listen`, `webui.enabled` cần khởi động lại; giao diện hiển thị cả giá trị cấu hình lẫn địa chỉ lắng nghe thực tế. Sau khi sửa tệp thủ công, phải chọn “Nạp lại từ đĩa” hoặc gọi `POST /api/config/reload`; chương trình không tự theo dõi thay đổi tệp. + +`POST /api/config/reveal` yêu cầu phiên quản trị, CSRF và xác minh lại mật khẩu; API có thể trả về giá trị key thủ công và proxy, nhưng không trả mật khẩu, hash mật khẩu hoặc token OAuth. Chỉ dùng khi thực sự cần sao chép, tránh ghi kết quả vào nhật ký hoặc chia sẻ. + +Các giá trị mặc định quản trị thường dùng: + +| Cấu hình | Mặc định / phạm vi | +| --- | --- | +| `webui.enabled` | Mặc định tích hợp là tắt; cấu hình mẫu bật. | +| `webui.listen` | `0.0.0.0:8081`. | +| `logging.level` | `info`; hỗ trợ `debug`, `info`, `warn`, `error`. | +| `logging.ring_size` | `2000`; phạm vi 100–50.000. | +| `logging.dump_request_bodies` | `false`; cần thêm mức debug để xuất, tối đa 64 KiB cho mỗi nội dung yêu cầu đã chuẩn bị. | +| `models.active_probes` | `false`; tính khả dụng mặc định được quan sát từ lưu lượng thực. | + +## Go OAuth và Zen PAYG OAuth + +Trang “Mô hình và hạn mức” có hai bảng độc lập. Go dùng định tuyến thuê bao; Zen tính phí theo mức sử dụng (PAYG) của workspace Console, **suy luận sẽ tiêu thụ credits của workspace đó**. Đăng nhập Go không cấp quyền hoặc số dư Zen và không tự kết nối PAYG. + +Quy trình: + +1. Bắt đầu đăng nhập trong bảng tương ứng; với Zen, phải xác nhận rõ việc dùng PAYG trước. +2. Tự mở liên kết xác minh OpenCode Device OAuth chính thức, nhập `user_code` hiển thị và xác nhận đây là yêu cầu cấp quyền do mình khởi tạo. Trang không tự chuyển hướng. +3. Backend thăm dò theo khoảng thời gian được trả về. Nếu có nhiều tổ chức, quá trình tự hoàn tất tạm dừng để chọn tổ chức sở hữu thuê bao/credits rồi kết nối tổ chức đó; chỉ được chọn tổ chức mà lần cấp quyền này cho phép. +4. Khi thành công, làm mới cấu hình và danh sách mô hình. Nếu thất bại hoặc hết hạn, có thể hủy rồi bắt đầu lại. + +Không cần dán token, đọc tệp xác thực trên máy hoặc gửi URL callback. Rời trang hoặc ẩn trình duyệt sẽ dừng thăm dò tự động; khi quay lại, trang đọc lại trạng thái và có thể tiếp tục lần đăng nhập chưa hết hạn. Hai loại đăng nhập chờ được tách theo phiên quản trị và gói; không thể dùng ID đăng nhập của gói này cho gói khác. Hủy chỉ xóa lần đăng nhập chờ tương ứng; đăng xuất phiên quản trị hủy các lần đăng nhập chờ của phiên đó nhưng giữ các kết nối đã lưu. + +| Thao tác | API Go | API Zen | Nội dung yêu cầu | +| --- | --- | --- | --- | +| Trạng thái an toàn | `GET /api/go/auth` | `GET /api/zen/auth` | Không có. | +| Bắt đầu đăng nhập | `POST /api/go/auth/start` | `POST /api/zen/auth/start` | Go dùng `{}`; Zen dùng `{"acknowledge_payg":true}`. | +| Thăm dò/chọn tổ chức | `POST /api/go/auth/poll` | `POST /api/zen/auth/poll` | `{"id":"LOGIN_ID"}`; thêm `organization_id` khi chọn tổ chức. | +| Hủy đăng nhập chờ | `DELETE /api/go/auth` | `DELETE /api/zen/auth` | Không có. | +| Ngắt kết nối đã lưu | `DELETE /api/go/connection` | `DELETE /api/zen/connection` | Không có. | + +Tất cả API đều cần phiên; thao tác ghi cần CSRF. Phản hồi đăng nhập, trạng thái, cấu hình và reveal đều không trả thông tin xác thực truy cập/làm mới OAuth. + +Hai kết nối được lưu riêng trong `go_oauth` và `zen_oauth`; backend làm mới và lưu khi cần. Vì vậy, cấu hình và bản sao lưu chứa thông tin xác thực truy cập/làm mới nhạy cảm và cần giới hạn quyền đọc. `go_subscription`/`zen_subscription` cũ chỉ là bí danh để chuyển đổi khi nạp; khi lưu sẽ dùng trường mới. Dùng đồng thời trường cũ và mới cho cùng một gói sẽ bị từ chối. + +Giới hạn định tuyến: + +- Chỉ chấp nhận mô hình do cấu hình từ xa chính thức đã xác thực cung cấp, vượt qua kiểm tra host/đường dẫn của gói tương ứng và SDK được hỗ trợ. Không xóa `/go` khỏi URL Go để đoán PAYG, cũng không chấp nhận header xác thực từ xa tùy ý. Định tuyến `/zen` cũ chỉ được chấp nhận khi cấu hình từ xa cung cấp rõ ràng. +- Go và Zen có thông tin xác thực, nguồn mô hình và quy trình làm mới độc lập. `prefer` quyết định lựa chọn ưu tiên khi cùng một mô hình có nhiều đường đi; chọn `zen` cho phép Zen OAuth đã kết nối tiêu thụ credits. +- Sau khi chọn OAuth, chỉ dùng tier đó. Go mất hiệu lực, hết hạn mức, nhận 429 hoặc gặp lỗi khác sẽ không tự chuyển sang Zen PAYG, key thủ công hay kênh ẩn danh. +- `go_keys`/`zen_keys` thủ công vẫn được giữ nhưng không làm dự phòng khi OAuth tương ứng tồn tại, kể cả khi cần đăng nhập lại hoặc không có định tuyến khả dụng. +- Ngắt kết nối chỉ xóa kết nối cục bộ tương ứng, không thu hồi phiên chính thức và không ảnh hưởng kết nối còn lại. Sau đó, gateway khám phá lại mô hình thủ công của tier đó và từ chối đoán định tuyến khi quá trình chưa xong. Khi ẩn danh tắt, không thể ngắt thông tin xác thực thượng nguồn duy nhất còn lại; cần cấu hình key/kết nối khác trước. +- Dung lượng thuê bao OAuth và credits hiện chưa biết; không dùng lại hạn mức của key thủ công hoặc suy ra từ số mô hình hay yêu cầu thành công. + +Triển khai tham chiếu các snapshot mã nguồn cố định: Go dùng [v2 `4617210822bdbb31e5749751afbfb4584ccedac8`](https://github.com/anomalyco/opencode/tree/4617210822bdbb31e5749751afbfb4584ccedac8) và [dev `7745079647b65036fe142e09ccd8623b25be1878`](https://github.com/anomalyco/opencode/tree/7745079647b65036fe142e09ccd8623b25be1878); Console/PAYG dùng [dev `03d848f7b8d71d31d3e56f2abd8b337efbc1bc32`](https://github.com/anomalyco/opencode/tree/03d848f7b8d71d31d3e56f2abd8b337efbc1bc32). Tương thích mã nguồn không có nghĩa đã xác minh cấp quyền và suy luận thực tế. Khi quyền, workspace hoặc định dạng cấu hình thượng nguồn thay đổi, có thể cần đăng nhập lại hoặc cập nhật triển khai. + +## Mô hình, hạn mức và tính khả dụng + +`GET /api/model-quotas` trả về mô hình Go và tóm tắt hạn mức; danh sách mô hình lấy theo danh mục gateway. Với key Go thủ công, gateway truy vấn `upstream.go` đã cấu hình cộng `/v1/usage`, mặc định là `https://opencode.ai/zen/go/v1/usage`; trình duyệt không nhận key thượng nguồn. + +- Cung cấp các cửa sổ phần trăm dùng chung trong 5 giờ cuốn chiếu, theo tuần và theo tháng cùng thời điểm đặt lại; không cung cấp số dư từng mô hình, số tiền hoặc số lần dùng còn lại. +- Nhiều key có thể dùng chung gói, nên không được cộng các giá trị. Độ chính xác phần trăm do thượng nguồn quyết định. +- Lưu cache thành công 60 giây, thất bại 15 giây. Khi thất bại, giữ giá trị thành công gần nhất và đánh dấu là lịch sử; nếu không có lịch sử thì hiển thị chưa biết. +- Trang truy vấn mỗi 60 giây khi đang hiển thị; dừng truy vấn định kỳ khi bị ẩn hoặc rời trang. Làm mới thủ công cũng chịu giới hạn cache. +- Khi có Go OAuth, không mượn dữ liệu của key Go thủ công; hạn mức OAuth và credits Zen vẫn là chưa biết. + +Định dạng hạn mức dựa trên [mã nguồn usage thượng nguồn](https://github.com/anomalyco/opencode/blob/dev/packages/console/app/src/routes/zen/go/v1/usage.ts). Đây không phải cam kết về một API công khai ổn định. Nếu định dạng thay đổi, trang báo chưa biết/bất thường và không tự tạo số dư. + +Tính khả dụng miễn phí mặc định lấy từ yêu cầu thực. Chỉ lỗi rõ ràng rằng mô hình không tồn tại/đã bị gỡ mới có thể vô hiệu hóa mô hình. Riêng 401, 403, 429, 4xx/5xx thông thường, hết thời gian chờ, lỗi kết nối và phản hồi sai định dạng không chứng minh mô hình bị gỡ. Khôi phục thủ công giữ mô hình có thể định tuyến và đưa mô hình ra khỏi thăm dò tự động; chỉ lập lịch lại sau khi bật lại điều khiển tự động. + +Chỉ `models.active_probes: true` mới bật suy luận tổng hợp ở nền. Bộ lập lịch kiểm tra các mục đến hạn mỗi phút, lần lượt theo mô hình và kênh. Mô hình bình thường/chưa thể kết luận thường được kiểm tra lại sau một giờ; mô hình đã xác nhận không khả dụng sau 24 giờ. Mỗi kênh có thời gian chờ 60 giây. Yêu cầu đi qua kênh ẩn danh đã bật trước, sau đó thử key Zen khả dụng; nếu bật WARP thì dùng lối ra WARP. Không có kênh phù hợp sẽ bỏ qua. Thăm dò chủ động tiêu thụ hạn mức thực nhưng không đổi thời gian chờ phục hồi của key/proxy sản xuất hoặc thống kê yêu cầu. + +| API quản trị | Mục đích | +| --- | --- | +| `GET /api/models/availability` | Đọc trạng thái mô hình miễn phí và kết quả thăm dò reasoning. | +| `POST /api/models/probe` | Đánh dấu mô hình điều khiển tự động là đến hạn và đánh thức bộ lập lịch; không bỏ qua công tắc `active_probes`. | +| `POST /api/models/restore` | `{"model":"MODEL_ID"}`: khôi phục và chuyển sang điều khiển thủ công. | +| `POST /api/models/manual` | `{"model":"MODEL_ID","manual":true}`; `false` bật lại điều khiển tự động. | + +`reasoning.effort: "auto"` dùng mức reasoning cao nhất của Zen miễn phí/ẩn danh đã được xác minh thành công gần đây. Khi thăm dò chủ động tắt, gateway không chủ động học mức trần mới; điều khiển thủ công cũng tạm dừng thăm dò tự động. Kết quả quan sát hết hiệu lực sau hai giờ. Không suy ra mức cho Go/mô hình trả phí hoặc mô hình chưa biết năng lực; effort do client chỉ định rõ luôn được ưu tiên. + +## API key cục bộ + +Đối tượng quản lý là `server_keys` của gateway, tách biệt với key thượng nguồn OpenCode. API tạo key trả toàn bộ key mới trong phản hồi; danh sách chỉ trả dấu vân tay, tên, mặt nạ, trạng thái, thời gian và mức sử dụng. Giao diện hỗ trợ sao chép key và biến môi trường cho client sau khi tạo. + +| API | Yêu cầu và kết quả | +| --- | --- | +| `GET /api/api-keys` | Danh sách an toàn. | +| `POST /api/api-keys` | `{"name":"client-a"}` tạo tự động; có thể thêm `value` để tùy chọn giá trị; thành công trả 201. | +| `PATCH /api/api-keys/{id}` | `{"name":"client-b","enabled":false}`; chỉ cần gửi các trường muốn đổi. | +| `DELETE /api/api-keys/{id}` | Xóa key cục bộ. | + +Key tự động dùng 192 bit ngẫu nhiên. Key tùy chọn dài 16–256 ký tự, gồm chữ cái, chữ số, `.`, `_`, `-`; tên dài 1–80 ký tự. API tạo cho phép tối đa 200 key. Phải giữ ít nhất một key đang bật. Tắt/xóa khiến yêu cầu mới nhận 401 ngay; yêu cầu đang xử lý có thể đã xác thực xong. + +`server_key_metadata` lưu tên, trạng thái bật và thời điểm tạo theo dấu vân tay, tự tương thích với `server_keys` cũ. Mức sử dụng gồm một giờ gần nhất và tổng của tiến trình hiện tại; yêu cầu và token được phân loại theo key đã xác thực thành công. Playground được ghi riêng là `playground`, không tính vào key cục bộ mượn để xác thực. Thống kê giữ qua nạp lại nóng và xóa khi khởi động lại; không cung cấp hạn mức riêng, quyền mô hình hoặc ngày hết hạn cho từng key. + +## Proxy và WARP + +Trung tâm cấu hình hỗ trợ nhập hàng loạt proxy nội tuyến, kiểm tra từng mục và đánh dấu xóa trong bản nháp. Nội dung tệp proxy `proxyfile` cần được quản lý tại tệp nguồn; đường dẫn tương đối tính từ thư mục cấu hình. Xóa ở giao diện chỉ là bản nháp và có hiệu lực sau khi lưu toàn bộ cấu hình. + +`POST /api/proxies/check` yêu cầu phiên và CSRF; chỉ được chọn một trong hai dạng yêu cầu sau: + +```json +{"id":"SAVED_PROXY_ID"} +``` + +```json +{"value":"https://proxy.example:8443"} +``` + +ID của proxy đã lưu lấy từ `GET /api/config`; `value` dùng cho bản nháp. Mỗi lần kiểm tra có thời gian chờ 20 giây. Giao diện cho tối đa bốn kiểm tra đồng thời, máy chủ tối đa tám; vượt giới hạn trả 429, không xếp hàng. Khi hoàn tất bình thường, phản hồi HTTP 200 có `ok`, `state`, `reason`, `latency_ms` và `status` nếu có. Lỗi xác thực, CSRF và định dạng dùng trạng thái HTTP tương ứng. + +Kiểm tra chỉ xác minh proxy được chọn có kết nối được đến Zen thượng nguồn đã cấu hình hay không: client riêng gửi GET không xác thực qua proxy tới `upstream.zen` cộng `/v1/models`. Không gửi key Zen/Go, `public` hoặc OAuth; không suy luận, không theo redirect, không dùng WARP và không thay đổi trạng thái khỏe, thời gian chờ phục hồi hay liên kết của key trong lưu lượng sản xuất. Vẫn dùng được khi ẩn danh tắt. + +| `state` | Ý nghĩa | +| --- | --- | +| `available` | Thượng nguồn trả 200–399 hoặc 401; `authentication_required` của 401 chỉ chứng minh đã tới đích, chưa xác minh key. | +| `unavailable` | Lần kiểm tra này xác nhận phía proxy từ chối kết nối/DNS không tồn tại (`proxy_unreachable`), hoặc đường hầm proxy trả 407 (`proxy_authentication_required`). | +| `limited` | 429; không chứng minh proxy bị hỏng. | +| `rejected` | Từ chối khác từ thượng nguồn hoặc đường hầm proxy; 407 từ thượng nguồn không đồng nghĩa xác thực proxy thất bại. | +| `inconclusive` | Hết thời gian chờ, lỗi truyền tải không xác định được nguồn hoặc thiếu điều kiện; không thể kết luận proxy bị hỏng. | + +Khi dọn hàng loạt, chỉ nên coi `unavailable` trong lần kiểm tra này là xác nhận không khả dụng. Không coi mọi trường hợp giới hạn tần suất, từ chối hay hết thời gian chờ là hỏng vĩnh viễn. Suy luận thực vẫn có thể chịu giới hạn của mô hình, xác thực, hạn mức và chính sách. + +WARP mặc định tắt. Khi bật, yêu cầu miễn phí ẩn danh/Zen thủ công và các truy vấn danh mục/thăm dò tương ứng dùng đường hầm trong tiến trình; Go, mô hình trả phí và OAuth vẫn đi qua proxy. Cần UDP `2408` tới Cloudflare, không cần TUN hoặc sửa bảng định tuyến. `warp.pool_size` là giới hạn 1–32 lối ra đồng thời, mặc định 2; `warp.stack` mặc định `ipv6`, cũng hỗ trợ `ipv4`/`dual`. Khởi tạo thất bại sẽ từ chối khởi động hoặc cấu hình ứng viên, không âm thầm chuyển sang proxy. + +403/429 ở lối ra có thể kích hoạt loại bỏ và bổ sung lối ra, nhưng thử lại vẫn chịu giới hạn thời gian/số lần. Đổi lối ra không bảo đảm có thêm hạn mức. Lối ra IPv6 `/64`, IPv4 `/32` được chống trùng và chờ phục hồi theo dải mạng. `warp.source_ipv6` yêu cầu stack IPv6 và prefix `/64` hoặc ngắn hơn. Linux dùng `IPV6_FREEBIND`; Windows phải được gán sẵn địa chỉ nguồn đã chọn. Thiết lập này không cấu hình mạng của máy. `/healthz` chỉ cung cấp trạng thái/số lượng WARP; `resources.warp` trong `/api/monitor` còn có thông tin lối ra. + +## Luân chuyển SOTA / Sweet + +Client tiếp tục dùng API Base URL, key và ba API thông điệp hiện tại, chỉ đổi `model` thành bí danh `sota` hoặc `sweet`. Có thể đổi bí danh; khi đủ điều kiện, bí danh xuất hiện trong `/v1/models`, còn lệnh gọi mô hình thực vẫn tương thích. Luân chuyển chỉ dùng Go, qua key thủ công hoặc Go OAuth; không chuyển dự phòng sang PAYG giữa các tier. System One không tham gia luân chuyển. + +Các thành viên SOTA cố định là `deepseek-v4.1-flash`, `glm-5.3`, `grok-4.6`, `kimi-k3`, `qwen3.8-max`. Sweet gồm các mô hình thông điệp Go khả dụng còn lại, ban đầu ưu tiên `glm-5.3-flash`, sau đó sắp theo tên và thêm mô hình mới ở cuối. Thành viên đã bị gỡ vẫn nằm trong danh sách nhưng không chọn được. Tính khả dụng thực lấy từ danh mục và định tuyến; tên cố định không bảo đảm gọi được. + +Mỗi nhóm dùng chung một vị trí hiện tại, giữ nguyên sau thành công và chuyển tiếp sau thất bại. Số thế hệ ngăn lỗi từ yêu cầu đồng thời cũ ghi đè vị trí mới; chọn thủ công không ngắt câu trả lời đang chạy. Một yêu cầu không ghé lại cùng mô hình. + +- Lỗi thông thường được thử tối đa ba lần mỗi mô hình, với ngân sách tối đa ba mô hình gặp lỗi thông thường; mô hình đã dùng hết số lần được tạm dừng 15 giây. +- 429/lỗi hạn mức rõ ràng chuyển ngay sang mô hình tiếp theo và tạm dừng theo `Retry-After`, mặc định 60 giây. Trường hợp này không tăng số mô hình tính vào ngân sách lỗi thông thường; lỗi thông thường đã xảy ra vẫn được tính. +- Không dùng cơ chế thử lại key thông thường giữa các tier hoặc gửi lại để sửa stale reasoning; lỗi của một mô hình không tạm dừng cả key Go. Hạn mức dùng chung có thể khiến toàn nhóm không dùng được. +- Tổng thời gian giới hạn bởi `retry.timeout_seconds`. `rotation.first_output_seconds` giới hạn mỗi lần đợi đầu ra có hiệu lực, mặc định 30 giây, phạm vi 1–300 giây. Với phản hồi không streaming, phải đọc xong phản hồi hợp lệ trong thời gian này. +- Các sự kiện mở đầu của stream được giữ lại đến khi có đầu ra thực/kết thúc bình thường mới gửi cho client. Trước đó có thể thử lại; sau khi đã gửi, lỗi giữ nguyên nội dung đã có, gửi lỗi SSE của giao thức rồi kết thúc. Không ghép câu trả lời thay thế vào một stream. Client hủy không kích hoạt chuyển mô hình hoặc tạm dừng. +- `model` trong phản hồi giữ bí danh được yêu cầu; `X-Resolved-Model` chỉ mô hình thực, token được tính cho mô hình thực. Bản ghi giữ nguyên nhân đã phân loại, không lưu nội dung yêu cầu, key hay nội dung lỗi thượng nguồn. + +| API quản trị | Nội dung | +| --- | --- | +| `GET /api/rotation` | Thứ tự/bí danh hai nhóm, mô hình hiện tại, thời gian tạm dừng, trạng thái lưu trữ, 100 lần thử gần nhất và 30 lần chuyển của mỗi nhóm. | +| `PUT /api/rotation` | Gửi toàn bộ `alias`, `order` của `sota`/`sweet` cùng `first_output_seconds`; chỉ được sắp lại trong nhóm, không bỏ thành viên. | +| `POST /api/rotation/current` | `{"group":"sota","model":"glm-5.3"}`: chuyển mô hình và xóa thời gian tạm dừng của mô hình đó. | + +Bí danh dài 1–64 ký tự gồm chữ cái, chữ số, `.`, `_`, `-`; ký tự đầu phải là chữ cái/chữ số. Bí danh không được trùng nhau hoặc xung đột với mô hình thực. Nếu danh mục thay đổi khiến thành viên gửi lên không khớp, hãy làm mới rồi sắp xếp lại. + +Cấu hình nằm trong `rotation`, trạng thái runtime ở `config.json.rotation.json`. Các lần nạp lại nóng dùng chung trạng thái. Nếu không thể đọc/ghi trạng thái lúc khởi động đầu tiên, dịch vụ từ chối khởi động; lỗi ghi về sau được báo trên trang quản trị. + +## Playground, nhật ký và giám sát + +Playground gọi cùng gateway trong tiến trình qua `POST /api/debug/inference` và bắt buộc dùng phản hồi không streaming. Ví dụ định tuyến tự động: + +```json +{"protocol":"chat","key":{"mode":"auto"},"request":{"model":"MODEL_ID","messages":[{"role":"user","content":"Hello"}]}} +``` + +Muốn chỉ định key, thay `key` bằng `{"mode":"selected","tier":"zen","id":"KEY_FINGERPRINT"}`; ID lấy từ `GET /api/debug/models`. Key được chọn chỉ thực hiện một lần thử thượng nguồn, không ẩn danh, không đổi key, không chuyển tier và không phát lại reasoning. Có thể thêm `relay` với chỉ mục đã biết để chọn proxy, ví dụ `{"index":0}`. Chỉ mục phải lấy từ danh mục chẩn đoán hiện tại. + +Chẩn đoán không thay đổi thời gian chờ phục hồi, số lỗi, trạng thái khỏe hoặc liên kết của key/proxy sản xuất, nhưng vẫn gửi yêu cầu thực, tiêu thụ hạn mức/credits và được ghi vào giám sát. Khi lớp bao phản hồi quản trị thành công, API trả HTTP 200; `ok`, `http_status`, `request_id`, `route`, `response` biểu thị kết quả thực. Với key được chọn còn có `selected_key`, `key_test`, chẳng hạn `usable`, `rejected`, `rate_limited`, `transport_error`, `upstream_error`, `request_error`, `unavailable`. Lỗi định dạng/xác thực/giới hạn tần suất vẫn dùng trạng thái HTTP tương ứng. + +Nhật ký có tại `GET /api/logs?after=SEQUENCE&limit=COUNT` và `GET /api/logs/stream`. SSE hỗ trợ nối tiếp bằng `Last-Event-ID` hoặc `after`; sự kiện hết hạn/bị mất được báo bằng `gap`, và dữ liệu đã loại khỏi bộ đệm không thể khôi phục. Máy chủ kết thúc stream nhật ký khi phiên mất hiệu lực. + +`GET /api/monitor` cung cấp tổng hợp yêu cầu, token, lần thử thượng nguồn và tài nguyên. `GET /api/debug/models` cung cấp định tuyến, dấu vân tay key, metadata mô hình, proxy và kết quả chẩn đoán gần nhất. Token chỉ dùng số thượng nguồn báo cáo, không ước tính phần thiếu; đầu vào gồm cả cache đọc/ghi, còn cached ghi riêng cache đọc. `usage.server_keys` nhóm theo key cục bộ và ghi riêng `playground`. + +Kết quả yêu cầu phản ánh toàn bộ quá trình suy luận: stream thất bại vẫn được ghi `stream_error` dù HTTP là 200; bên gọi hủy được ghi `client_canceled`. Lần thử thượng nguồn chỉ đo trao đổi đến lúc nhận header phản hồi, nên không thể coi tỷ lệ thành công và độ trễ đó là tỷ lệ thành công của toàn bộ câu trả lời. + +## Lưu trữ, trạng thái khỏe và bảo mật + +| Dữ liệu | Vị trí và vòng đời | +| --- | --- | +| Cấu hình/phiên bản trước | `config.json`, `config.json.bak`, có thông tin nhạy cảm. | +| Cache mô hình/giá | `config.json.models.catalog.json`, `config.json.models.dev.json`. | +| Tính khả dụng miễn phí | `config.json..availability.json`, tách theo thượng nguồn. | +| Trạng thái luân chuyển | `config.json.rotation.json`. | +| Phiên, token tích lũy, bộ đệm nhật ký vòng, Playground gần đây | Bộ nhớ tiến trình; xóa khi khởi động lại. | +| Chi tiết yêu cầu/lần thử | Một giờ gần nhất, tối đa 10.000/20.000 bản ghi; mỗi API trả tối đa 500 bản ghi. | +| Nhật ký dài hạn | JSON trên stdout; cần tự thu thập và lưu giữ an toàn. | + +Tiền tố tệp phụ thuộc đường dẫn `-config` thực tế. Nhiều tiến trình không dùng chung phiên, giám sát hay bộ đếm trong bộ nhớ; tránh để chúng đồng thời sửa cùng một tệp trạng thái. + +`GET /healthz` nằm trên cổng suy luận, không cần xác thực và không kích hoạt kiểm tra thượng nguồn hoặc đếm giám sát. API trả 503 khi danh mục chưa sẵn sàng/rỗng, WARP không có lối ra hoạt động hoặc proxy bắt buộc không có nút khỏe. Danh mục còn dùng được nhưng quá hạn có thể trả 200 với `degraded`; ngưỡng quá hạn là hai lần khoảng làm mới và ít nhất 60 giây. Nhu cầu đăng nhập lại OAuth xuất hiện trong issues, nhưng trạng thái sẵn sàng không bảo đảm lần suy luận tiếp theo thành công. Thông tin công khai chỉ gồm trạng thái và số lượng, không lộ key/địa chỉ proxy. + +Khi dùng cục bộ, nên giới hạn ở loopback; quản trị qua mạng cần HTTPS và giới hạn truy cập. Chương trình không tự xử lý kết thúc TLS. Cấu hình/bản sao lưu chứa key thủ công, mật khẩu proxy và token OAuth; cần hạn chế bằng quyền tệp hoặc Windows ACL và loại khỏi phần mã nguồn chia sẻ. Nội dung yêu cầu debug đã che bí mật và cắt ngắn vẫn có thể chứa hội thoại riêng tư, nên chỉ bật khi cần trong thời gian ngắn. Không dùng cấu hình đầy đủ, kết quả reveal, cookie, header xác thực hoặc nội dung suy luận thực làm tệp đính kèm để tìm lỗi. + +## Kiểm tra và bảo trì + +Kiểm tra khi phát triển cục bộ: + +```bash +go vet ./... +go build -trimpath -o opencode2api ./cmd/opencode2api +for file in webui/js/*.js webui/js/pages/*.js; do + node --input-type=module --check < "$file" || exit 1 +done +``` + +Nghiệm thu triển khai thông thường cần xác minh đăng nhập quản trị và CSRF, tắt/khôi phục key, lưu cấu hình và khởi động lại để đổi địa chỉ lắng nghe, khám phá mô hình, ba giao thức thông điệp và lỗi SSE, trạng thái luân chuyển, cùng các chức năng OAuth/thượng nguồn thực cần dùng. Suy luận thực, OAuth, WARP và truy vấn hạn mức có thể phụ thuộc quyền tài khoản và tiêu thụ hạn mức; kiểm tra tĩnh không thay thế các bước này. + +Trước khi nâng cấp, sao lưu an toàn chương trình, cấu hình thực tế và trạng thái, dừng tiến trình rồi thay chương trình. Quay về phiên bản cũ cần khôi phục cấu hình và trạng thái tương thích. Người dùng Compose cần lưu đúng các tệp thực trong volume. Không thêm thông tin xác thực, nhật ký, trạng thái runtime hoặc sản phẩm xác minh cục bộ vào mã nguồn. diff --git a/docs/management.zh-CN.md b/docs/management.zh-CN.md index 78b51c3..3453c89 100644 --- a/docs/management.zh-CN.md +++ b/docs/management.zh-CN.md @@ -1,16 +1,165 @@ -# 管理控制台:模型轮转、Go 额度、API Key 与代理 +# 管理控制台与运行指南 -本文说明管理页面的使用方式、配置和错误处理。 +[English](management.md) | 简体中文 | [Tiếng Việt](management.vi.md) | [Italiano](management.it.md) -## 匿名通道默认关闭 +本文说明当前实现的管理功能、OAuth、额度、模型轮转、诊断与持久化。服务启动及推理 API 示例见[简体中文 README](../README.zh-CN.md),完整配置起点为 [config.example.json](../config.example.json)。管理端与推理 API 使用不同监听地址;下文 `/api/*` 都是管理端路由。 -**匿名通道可能已被上游重点封堵,优先使用 Zen API Key。** 配置和 WebUI 默认 `anonymous: false`;已有配置中明确设置的 `true` 保持不变,不会被自动关闭。示例的上游 Key 数组为空,启动前应先填入 Zen API Key(推荐)或 Go Key;已有的 Go 订阅连接也可满足上游凭证要求。不要为了检查代理而开启匿名推理。 +## 启动与访问 -## 批量代理管理 +Linux 下使用 Go 1.24 或以上版本,在项目目录以 Bash 编译运行: -「Proxy 节点」页可批量导入内联代理、检查选中条目和暂存批量移除。代理文件 `proxyfile` 的条目在来源文件管理,不加入内联代理表格。移除不会立即修改运行时,仍需保存完整配置(`PUT /api/config`);检查本身不删除任何条目。 +```bash +if [ ! -f config.json ]; then + cp config.example.json config.json +fi +export GOCACHE="$PWD/.local/go-cache" +export GOMODCACHE="$PWD/.local/go-modules" +go build -trimpath -o opencode2api ./cmd/opencode2api +``` -检查接口为 `POST /api/proxies/check`,需要管理 Session 与 `X-CSRF-Token`,请求体二选一: +启动前在本机编辑配置:替换 `server_keys` 和 `webui.password`,填入 `zen_keys` 或 `go_keys`。本地管理建议 `webui.listen: "127.0.0.1:8081"`;示例的 `0.0.0.0:8081` 会监听所有接口。密码至少 10 字符,示例管理员名为 `admin`。 + +```bash +./opencode2api -config config.json +``` + +Windows 原生方式为 `go build -trimpath -o opencode2api.exe ./cmd/opencode2api`,然后在 PowerShell 执行 `.\opencode2api.exe -config .\config.json`。Docker/Compose 的卷初始化、文件导入、端口与镜像指引见 README;管理操作需使用实际运行配置,而非仅编辑未重新导入的宿主副本。 + +匿名通道 `anonymous` 默认关闭。至少一个上游 Key、已保存 Go/Zen OAuth 或明确开启匿名才满足启动条件;不能凭证全空先启动,再进入 WebUI 做首次 OAuth。匿名流量可能被上游封堵,不应为检查代理而开启匿名推理。 + +配置目录须可写。首次启动会把 `webui.password` 迁移为 Argon2id `password_hash` 并尝试删除包含引导明文密码的备份;这不会加密其他凭证。 + +## 页面与管理认证 + +| 页面 | 地址 | 功能 | +| --- | --- | --- | +| 概览 | `/#overview` | 请求、Token、上游尝试和运行资源。 | +| 诊断 | `/#diagnostics` | 模型路由、Playground、实时日志。 | +| 接入指南 | `/#access` | 客户端连接参数。 | +| API Key 管理 | `/#api-keys` | 本地 Key 生命周期与用量。 | +| 模型与额度 | `/#model-quotas` | Go 目录、共享额度、两类 OAuth、免费模型可用性。 | +| 模型轮转 | `/#rotation` | 分组顺序、当前位置、暂停与尝试记录。 | +| 配置中心 | `/#config` | Key、代理、超时、路由、WARP 与日志设置。 | +| 账号安全 | `/#account` | 修改管理员账号和密码。 | + +界面支持简中、英语、越南语、意大利语,语言与主题保存在浏览器。旧 `#playground`、`#logs` 会进入诊断,`#availability` 进入模型与额度。 + +管理员通过用户名/密码登录,获得 `HttpOnly`、`SameSite=Strict` Session Cookie。所有管理 API 除登录均需有效 Session;写操作另需 `X-CSRF-Token`,带 `Origin` 时须与服务来源一致。登录/Session 响应提供 `csrf_token`。本地 `server_keys` 不能代替管理登录。 + +Session 默认 720 分钟,范围 5–10,080 分钟。修改管理员凭证或重启进程会使现有 Session 失效;改账号接口要求再次验证当前密码。登录有限流;Playground 每直连客户端每分钟最多 12 次。服务不信任 `X-Forwarded-For`,反向代理后的客户端会共享对端限制。HTTPS 反向代理须正确设置 `X-Forwarded-Proto`,它参与 Cookie Secure 标记与来源校验。 + +## 配置保存与重载 + +`GET /api/config` 返回运行配置、安全 ID/掩码、实际监听地址及需重启字段。Key/代理更新使用以下一种表示: + +```json +{"id":"EXISTING_FINGERPRINT"} +``` + +```json +{"value":"NEW_VALUE"} +``` + +`PUT /api/config` 接收完整配置表单,不是局部 PATCH;遗漏的 Key/代理列表可能被视为空列表。保留已有值时提交其 ID。使用页面保存可以保留未在表单中编辑的高级配置。OAuth 凭证、轮转和管理员密码由各自专用接口管理;普通保存不会接收或覆盖浏览器提交的 OAuth Token。 + +保存顺序为校验、构建候选运行时、持久化、切换。校验或配置持久化失败时旧运行时继续服务。配置文件允许 `//`、`/* ... */` 注释,API 请求必须是标准 JSON;未知字段、重复顶层字段、非法值及同一方案新旧 OAuth 字段并存会被拒绝。保存后文件规范化,注释消失。 + +Key、代理、上游、超时、模型、偏好、reasoning 和日志设置热应用到新请求。`listen`、`webui.listen`、`webui.enabled` 必须重启;页面同时显示已配置值和实际监听。文件手动修改后须执行「从磁盘重载」或 `POST /api/config/reload`,程序不自动监视文件。 + +`POST /api/config/reveal` 要求管理 Session、CSRF 及再次验证密码,可返回手动 Key 与代理值;不会返回密码、密码哈希或 OAuth Token。只在确实需要复制时使用,避免把结果写进日志或分享。 + +常用管理默认值: + +| 配置 | 默认 / 范围 | +| --- | --- | +| `webui.enabled` | 内置默认关闭,示例开启。 | +| `webui.listen` | `0.0.0.0:8081`。 | +| `logging.level` | `info`;支持 `debug`、`info`、`warn`、`error`。 | +| `logging.ring_size` | `2000`;范围 100–50,000。 | +| `logging.dump_request_bodies` | `false`;还需 debug 才输出,每个准备好的请求体最多 64 KiB。 | +| `models.active_probes` | `false`;真实流量提供默认可用性观察。 | + +## Go OAuth 与 Zen PAYG OAuth + +「模型与额度」有两个独立面板。Go 使用订阅路由;Zen 使用 Console 工作区按量计费(PAYG),**推理会消耗该工作区 credits**。Go 登录不代表获得 Zen 权限或余额,不会自动连接 PAYG。 + +操作流程: + +1. 在对应面板开始登录;Zen 必须先明确确认 PAYG。 +2. 自行打开官方 OpenCode Device OAuth 验证链接,输入显示的 `user_code`,确认这是自己发起的授权。页面不自动跳转。 +3. 后端按返回的间隔轮询。存在多个组织时暂停自动完成,选择订阅/credits 所属组织,再连接所选组织;只能选择本次授权允许的组织。 +4. 成功后刷新配置与模型视图。失败或过期可取消并重新开始。 + +不需要粘贴 Token、读取本机凭证文件或提交回调 URL。离开页面或隐藏浏览器停止自动轮询;返回后重新读取状态,未过期登录可继续。两类待完成登录按管理 Session 和方案隔离,不能跨方案使用登录 ID。取消只清除对应待完成登录;退出管理 Session 取消该 Session 的待完成登录,保留已保存连接。 + +| 操作 | Go 接口 | Zen 接口 | 请求体 | +| --- | --- | --- | --- | +| 安全状态 | `GET /api/go/auth` | `GET /api/zen/auth` | 无。 | +| 开始登录 | `POST /api/go/auth/start` | `POST /api/zen/auth/start` | Go 为 `{}`;Zen 为 `{"acknowledge_payg":true}`。 | +| 轮询/选组织 | `POST /api/go/auth/poll` | `POST /api/zen/auth/poll` | `{"id":"LOGIN_ID"}`;选组织另加 `organization_id`。 | +| 取消待完成登录 | `DELETE /api/go/auth` | `DELETE /api/zen/auth` | 无。 | +| 断开已存连接 | `DELETE /api/go/connection` | `DELETE /api/zen/connection` | 无。 | + +全部接口要求 Session,写操作要求 CSRF。登录、状态、配置与 reveal 响应都不返回 OAuth 访问/刷新凭证。 + +连接分别存为配置的 `go_oauth`、`zen_oauth`,后端按需刷新并持久化。配置及备份因此包含敏感访问/刷新凭证,应限制读取权限。旧 `go_subscription`/`zen_subscription` 仅作为加载迁移别名,保存使用新字段;同一方案的新旧字段同时出现会被拒绝。 + +路由边界: + +- 只接纳已认证官方远程配置实际提供、通过对应方案主机/路径及支持 SDK 校验的模型。不从 Go URL 删除 `/go` 来猜测 PAYG,也不接纳任意远程认证头。旧 `/zen` 路由仅在远程配置明确提供时接受。 +- Go 与 Zen 的凭证、模型来源及刷新独立。`prefer` 决定同一模型的可用首选;选择 `zen` 允许已连接 Zen OAuth 消耗 credits。 +- 选定 OAuth 后只使用该 Tier。Go 授权失效、额度耗尽、429 或其他错误不会自动转入 Zen PAYG、手动 Key 或匿名通道。 +- 手动 `go_keys`/`zen_keys` 保留,但对应 OAuth 存在期间不作备用,即使需要重新登录或没有可用路由也如此。 +- 断开仅移除对应本地连接,不撤销官方 Session、不影响另一连接;随后重新发现该 Tier 的手动模型,发现未完成时拒绝猜测路由。匿名关闭时,不能断开唯一剩余上游凭证,需先配置其他 Key/连接。 +- OAuth 订阅余量和 credits 当前未知,不复用手动 Key 额度,不根据模型数量或成功请求推算。 + +实现参考固定源码快照:Go 的 [v2 `4617210822bdbb31e5749751afbfb4584ccedac8`](https://github.com/anomalyco/opencode/tree/4617210822bdbb31e5749751afbfb4584ccedac8)、[dev `7745079647b65036fe142e09ccd8623b25be1878`](https://github.com/anomalyco/opencode/tree/7745079647b65036fe142e09ccd8623b25be1878),Console/PAYG 的 [dev `03d848f7b8d71d31d3e56f2abd8b337efbc1bc32`](https://github.com/anomalyco/opencode/tree/03d848f7b8d71d31d3e56f2abd8b337efbc1bc32)。源码兼容不等于真实授权和推理已验证;上游权限、工作区或配置格式改变时,可能需要重登或更新实现。 + +## 模型、额度与可用性 + +`GET /api/model-quotas` 返回 Go 模型与额度摘要,模型以网关目录为准。手动 Go Key 从已配置 `upstream.go` 加 `/v1/usage` 查询,默认是 `https://opencode.ai/zen/go/v1/usage`,浏览器不接收上游 Key。 + +- 提供 5 小时滚动、每周、每月的共享百分比窗口和重置时间,不提供逐模型余额、金额或可用次数。 +- 多个 Key 可能共用套餐,不能相加。百分比精度由上游决定。 +- 成功缓存 60 秒,失败 15 秒;失败保留上次成功值并标记历史,没有历史则未知。 +- 页面显示时每 60 秒查询;隐藏或离开时停止周期查询。手动刷新也受缓存限制。 +- Go OAuth 存在时不借用手动 Go Key 数据;OAuth 额度和 Zen credits 保持未知。 + +额度格式依据[上游 usage 源码](https://github.com/anomalyco/opencode/blob/dev/packages/console/app/src/routes/zen/go/v1/usage.ts)。这不是稳定公开接口的保证,格式改变会报告未知/异常,不虚构余额。 + +免费可用性默认来自真实请求。明确的模型不存在/下架错误才可禁用;401、403、429、普通 4xx/5xx、超时、连接错误和畸形响应不能单独证明模型下架。手动恢复保持模型可路由并退出自动探测,恢复自动控制后才重新排程。 + +`models.active_probes: true` 才启用后台合成推理,调度器每分钟检查到期项,逐模型、逐通道执行。正常/无法判断的模型通常一小时复查,确认不可用的模型 24 小时复查;单通道超时 60 秒。请求先走已开启匿名通道,再尝试可用 Zen Key,WARP 开启时使用其出口;没有合适通道就跳过。主动探测会消耗实际额度,不改变生产 Key/代理冷却及请求统计。 + +| 管理接口 | 用途 | +| --- | --- | +| `GET /api/models/availability` | 读取免费模型状态和 reasoning 探测结果。 | +| `POST /api/models/probe` | 将自动控制模型标为到期并唤醒调度;不绕过 `active_probes` 开关。 | +| `POST /api/models/restore` | `{"model":"MODEL_ID"}`,恢复并交给手动控制。 | +| `POST /api/models/manual` | `{"model":"MODEL_ID","manual":true}`;`false` 恢复自动控制。 | + +`reasoning.effort: "auto"` 使用近期成功验证的免费 Zen/匿名强度上限。主动探测关闭时不会主动学习新上限;手动控制也暂停自动探测。观测结果两小时后失效。Go/付费或能力未知模型不推算;客户端明确 effort 始终优先。 + +## 本地 API Key + +管理对象是网关 `server_keys`,与 OpenCode 上游 Key 分开。创建接口在响应中返回完整新 Key,列表只返回指纹、名称、掩码、状态、时间和用量。页面支持创建后复制 Key 与客户端环境变量。 + +| 接口 | 请求与结果 | +| --- | --- | +| `GET /api/api-keys` | 安全列表。 | +| `POST /api/api-keys` | `{"name":"client-a"}` 自动生成;可另带 `value` 自定义,成功 201。 | +| `PATCH /api/api-keys/{id}` | `{"name":"client-b","enabled":false}`,可只提交需要修改的字段。 | +| `DELETE /api/api-keys/{id}` | 删除本地 Key。 | + +自动 Key 使用 192 位随机数。自定义 Key 长度 16–256,字符为字母、数字、`.`、`_`、`-`;名称 1–80 字符,创建接口最多允许 200 个 Key。至少保留一个启用 Key。停用/删除对新请求立即返回 401,在途请求可能已完成认证。 + +`server_key_metadata` 按指纹保存名称、启用状态和创建时间,旧 `server_keys` 自动兼容。用量显示近一小时与当前进程累计,请求与 Token 按认证命中的 Key 归类。Playground 单独记为 `playground`,不计入借用的本地 Key。统计跨热重载保留、重启清零,不提供独立配额、模型权限或到期日。 + +## 代理与 WARP + +配置中心支持批量导入内联代理、逐项检查及暂存移除。代理文件 `proxyfile` 的内容应在来源文件管理;相对路径以配置目录为准。移除仅为草稿,保存完整配置后才生效。 + +`POST /api/proxies/check` 要求 Session、CSRF,以下两种请求只能选一种: ```json {"id":"SAVED_PROXY_ID"} @@ -20,126 +169,97 @@ {"value":"https://proxy.example:8443"} ``` -`id` 使用 `GET /api/config` 返回的已保存代理 ID;`value` 用于草稿地址。前端最多四个并发,服务端最多八个,超出立即拒绝、不排队;单次检查限时 20 秒。检查正常执行时返回 HTTP 200,包含 `ok`、`state`、`reason` 及可用时的 `status`、`latency_ms`;请求格式、认证、CSRF 和并发限制错误使用各自的 HTTP 错误状态。 +已保存代理的 ID 来自 `GET /api/config`,`value` 用于草稿。单次超时 20 秒;页面最多四并发,服务端最多八并发,超出返回 429、不排队。正常完成返回 HTTP 200,包含 `ok`、`state`、`reason`、`latency_ms` 及可用时的 `status`;认证、CSRF 和格式错误使用各自 HTTP 状态。 -**只检查代理到配置的 Zen 上游的连通性,不验证推理、Key 或额度。** 独立 Bun 客户端仅通过选中代理向 `upstream.zen` 加 `/v1/models` 发送无认证 GET,不带任何 Zen/Go Key、`public` 或 OAuth 凭证,不发推理、不跟随重定向、不走 WARP,也不改变正式代理健康、Key 冷却或绑定。匿名关闭时仍可检查,不会私自启用匿名推理。 +检查只验证所选代理能否连接已配置 Zen 上游:隔离客户端通过该代理向 `upstream.zen` 加 `/v1/models` 发无认证 GET,不发送 Zen/Go Key、`public` 或 OAuth,不推理、不跟随重定向、不用 WARP,也不更改生产健康、Key 冷却或绑定。匿名关闭时仍可使用。 -| `state` | 含义与清理建议 | -| ------- | -------------- | -| `available` | 上游返回 200–399 或 401。401 的 `authentication_required` 表示已到站、需要认证,不代表验证了 Key。 | -| `unavailable` | 仅本次可确认的代理端拒绝连接、DNS 失败(`proxy_unreachable`)或代理 407(`proxy_authentication_required`),可加入不可用筛选,不代表永久故障。 | -| `limited` | 上游返回 429,不等于代理损坏。 | -| `rejected` | 上游返回 403 等错误,不等于代理损坏。 | -| `inconclusive` | 超时、其他不能定位的传输错误或检查前提不满足,不能确认代理损坏。 | +| `state` | 解读 | +| --- | --- | +| `available` | 上游 200–399 或 401;401 的 `authentication_required` 只证明到站,未验证 Key。 | +| `unavailable` | 本次确认代理侧拒绝连接/DNS 不存在(`proxy_unreachable`),或代理隧道 407(`proxy_authentication_required`)。 | +| `limited` | 429,不证明代理损坏。 | +| `rejected` | 上游其他拒绝或代理隧道拒绝;上游 407 不等于代理认证失败。 | +| `inconclusive` | 超时、无法定位的传输错误或前提缺失,不能认定损坏。 | -只允许将 `unavailable` 作为本次确认不可用的清理筛选;不要把 `limited`、`rejected` 或 `inconclusive` 一并选为损坏代理。正式推理仍可能因模型、凭证、额度或上游策略失败。 +批量清理只应把本次 `unavailable` 作为确认不可用筛选,不能把限流、拒绝、超时都当成永久损坏;正式推理仍可能受模型、认证、额度和策略限制。 -## 模型与额度 +WARP 默认关闭。开启后免费匿名/手动 Zen 请求及对应目录/探测使用进程内隧道;Go、付费与 OAuth 保持代理路由。需要 Cloudflare UDP `2408`,不需要 TUN 或改路由表。`warp.pool_size` 为 1–32 的并发出口上限(默认 2),`warp.stack` 默认为 `ipv6`,也可 `ipv4`/`dual`。初始化失败拒绝启动或候选配置,不静默改走代理。 -管理页面 `/#model-quotas`,登录后读取 `GET /api/model-quotas`。 +出口 403/429 可触发退役与补充,重试仍受预算限制;更换出口不保证额外额度。IPv6 `/64`、IPv4 `/32` 出口按网段去重/冷却。`warp.source_ipv6` 要求 IPv6 堆栈、`/64` 或更短前缀;Linux 使用 `IPV6_FREEBIND`,Windows 必须已分配所选源地址。该设置不会配置主机网络。`/healthz` 只提供 WARP 状态/数量,`/api/monitor` 的 `resources.warp` 另含出口信息。 -- 模型来自网关同步的 OpenCode Go 目录,支持搜索和复制模型 ID。 -- 手动 Go Key 的额度由网关查询 `https://opencode.ai/zen/go/v1/usage`。浏览器不会收到上游 Key;OAuth 订阅账户的额度当前不可查询,显示未知,不复用其他 Key 的数据。 -- 显示 5 小时、每周、每月窗口的剩余百分比和重置时间。接口只提供共享套餐窗口,不提供独立的逐模型余额,不推算金额或可用次数。多个 Key 的额度不相加。 -- 成功响应缓存 60 秒,失败缓存 15 秒;失败时保留上次成功结果并明确标记历史数据。没有成功数据时显示未知。 -- 页面打开期间每 60 秒查询一次;离开页面或隐藏浏览器时停止周期查询。手动刷新也受服务端缓存约束。 +## SOTA / Sweet 轮转 -依据:[OpenCode 官方额度接口源码](https://github.com/anomalyco/opencode/blob/dev/packages/console/app/src/routes/zen/go/v1/usage.ts)。该接口未列入正式 API 文档,若响应格式变化,会显示查询异常而非虚构额度。 +客户端继续使用原 API Base URL、Key 和三种消息接口,只把 `model` 改为别名 `sota` 或 `sweet`。别名可修改,满足条件时列入 `/v1/models`;实际模型调用保持兼容。轮转只走 Go(手动 Key 或 Go OAuth),不跨 Tier 回退 PAYG,System One 不加入轮转。 -## Go 订阅登录(Device OAuth) +SOTA 固定成员为 `deepseek-v4.1-flash`、`glm-5.3`、`grok-4.6`、`kimi-k3`、`qwen3.8-max`。Sweet 为其余可用 Go 消息模型,初始优先 `glm-5.3-flash`,之后按名称排序,新模型追加;下架成员保留列表但不可选用。实际可用性来自目录和路由,不因固定名称而保证可调用。 -在同一页面的「Go 订阅登录」卡片点击「浏览器登录 Go 订阅」。页面显示官方 OpenCode 验证链接和 `user_code`;自行打开链接、输入代码,并确认这是自己发起的授权。浏览器不自动跳转,也不要求粘贴 Token、读取本机凭证文件或提交回调 URL。WebUI 按服务端给出的间隔请求后端轮询,授权交换和凭证刷新均由后端完成。 +每组共享一个当前位置,成功后保持,失败后推进。版本号阻止较早的并发失败把新位置改回去;手动选择不打断正在进行的回答。每请求不重复访问同一模型。 -- 多个组织可选时,自动轮询暂停,选择订阅所在组织并点击「连接所选组织」。授权失败或过期可重新开始;「取消本次登录」只清除待完成的登录,不断开已保存的连接。 -- 离开页面或隐藏浏览器时停止自动轮询,返回页面后重新读取状态;未过期的待完成登录可继续。退出管理 Session 会取消该 Session 的待完成登录,但不删除已保存的订阅连接。 -- 成功连接后,配置与模型视图自动刷新。连接存于本地配置的 `go_subscription`,包含访问凭证及刷新凭证,后端按需自动刷新并持久化。配置及其备份包含敏感信息,应限制访问,不要上传或放入日志;WebUI 仅显示安全账户状态,不显示这些凭证。需重新登录时页面会提示,不把保留的连接误标为健康。 -- 「断开 Go 订阅登录」仅删除本地保存的连接,不撤销 OpenCode 官方会话。手动 `go_keys` 始终保留,但 OAuth 连接存在期间不作备用通道,包括授权失效或订阅路由不可用时;断开后恢复原有手动 Key 路由。 -- OAuth 只接入已确认的官方 Go 订阅路由,不自动改用余额或按量付费(PAYG)通道。OAuth 额度显示未知,不根据模型数量、成功响应或其他 Key 的共享窗口推算剩余量。 +- 普通错误每模型最多三次,最多消耗三个普通错误模型预算;耗尽的模型暂停 15 秒。 +- 429/明确额度错误直接跳到下一个模型,暂停取 `Retry-After`,缺省 60 秒,不新增普通错误预算;已发生普通错误仍计数。 +- 不使用普通 Key 跨 Tier 重试或 stale-reasoning 补发;单模型故障不暂停整个 Go Key。共享额度可能让整组都不可用。 +- 总预算为 `retry.timeout_seconds`,`rotation.first_output_seconds` 限制每次等待有效输出,默认 30 秒、范围 1–300 秒。非流式需在此期限内读完有效响应。 +- 流式前导事件暂存到有实际输出/正常结束后才提交;提交前可重试,提交后错误保留内容、发送协议 SSE 错误并终止。不会在一条流拼接替代答案。客户端取消不触发切换或暂停。 +- 响应 `model` 保持请求别名,`X-Resolved-Model` 指实际模型;Token 归实际模型。记录保存分类原因,不保存请求体、Key 或上游错误正文。 -管理接口均要求现有管理 Session,写操作还需 CSRF:`GET /api/go/auth` 读取安全状态,`POST /api/go/auth/start` 开始登录,`POST /api/go/auth/poll` 携带登录 `id`(选组织时另带 `organization_id`)检查或完成授权,`DELETE /api/go/auth` 取消待完成登录,`DELETE /api/go/connection` 移除本地连接。这些接口不向浏览器返回访问或刷新凭证。 +| 管理接口 | 内容 | +| --- | --- | +| `GET /api/rotation` | 两组顺序/别名、当前模型、暂停、持久化状态、最近 100 次尝试及每组 30 次切换。 | +| `PUT /api/rotation` | 提交 `sota`/`sweet` 的完整 `alias`、`order` 和 `first_output_seconds`;只能组内排序,不可丢成员。 | +| `POST /api/rotation/current` | `{"group":"sota","model":"glm-5.3"}`,切换并清除该模型暂停。 | -协议参考上游固定源码快照:[v2 `4617210822bdbb31e5749751afbfb4584ccedac8`](https://github.com/anomalyco/opencode/tree/4617210822bdbb31e5749751afbfb4584ccedac8)、[dev `7745079647b65036fe142e09ccd8623b25be1878`](https://github.com/anomalyco/opencode/tree/7745079647b65036fe142e09ccd8623b25be1878)。源码对比与本地模拟检查不代表真实订阅授权或真实推理已经验证;上游授权流程、组织权限及可用路由变化时,可能需要重新登录或更新实现。 +别名 1–64 位字母、数字、`.`、`_`、`-`,首位为字母/数字,不得重复或与真实模型冲突。目录变化导致提交成员不匹配时,先刷新再排序。 -## API Key 管理 +配置存于 `rotation`,运行状态为 `config.json.rotation.json`。热重载共享状态;首次无法读取/写入状态会拒绝启动,后续写入失败在管理页面提示。 -管理页面 `/#api-keys`,支持列表、生成、自定义、重命名、启用、停用、删除和创建后复制环境变量。 +## Playground、日志与监控 -- 管理的是网关的 `server_keys`,不修改 OpenCode Go 的上游 Key。 -- 自动生成 192 位随机密钥;自定义密钥为 16–256 位英文字母、数字、`-`、`_` 或 `.`。 -- 列表只显示名称、尾码、状态、用量和创建时间。创建后可复制完整密钥及环境变量。 -- 用量按认证命中的 Key 统计请求数和 token,分近 1 小时和累计两个窗口;`GET /api/monitor` 的 `usage.server_keys` 给出同一份数据,各项之和等于聚合口径。Playground 调试流量单独归入 `playground`,不计入任何 Key。与其他监控数据一样只存于内存:热重载保留,进程重启后清零。 -- 变更热应用;停用和删除后,新请求返回 401。在途请求可以完成。至少保留一个启用的 Key。 -- 所有管理接口需要登录,写操作需要 CSRF Token。 -- 元数据以 `server_key_metadata` 保存在原配置中,按 Key 指纹关联;已有 `server_keys` 自动兼容。 -- 当前未实现按 Key 单独分配模型权限、用量配额或过期时间。 +Playground 通过 `POST /api/debug/inference` 在进程内调用同一网关,强制非流式。以下为自动路由示例: -## WARP 免费模型出口 - -WebUI「Proxy 节点」页底部新增 WARP 开关,对应配置 `warp.enabled`(默认关闭)、`warp.pool_size`(1–32,默认 2;出口数量上限,活跃出口按并发动态调整)、`warp.stack`(默认 `ipv6`,可选 `ipv4` 或 `dual`)和 `warp.source_ipv6`(外层 IPv6 源前缀,需配合 `stack = "ipv6"`)。开启后,匿名通道、免费模型的 Zen Key 回退、免费模型可用性探测和匿名模型目录刷新都通过用户态 Cloudflare WARP 出网,不再使用任何代理;Go 套餐 Key 与付费模型保持原有代理绑定。 - -- 主机或容器必须能向 Cloudflare 端点发送 UDP(端口 `2408`);不需要 TUN 设备、root、`NET_ADMIN` 或修改路由表。 -- 出口第一次收到上游 429/403 即被淘汰并立刻在后台重新注册;免费模型请求会持续切换到其他出口,用完 `retry.max_attempts` 次后才把最后一个 429 返回客户端。活跃出口数按并发动态调整(每个在途请求一个,另留一个备用,上限为 `warp.pool_size`),空闲 60 秒的多余出口自动回收。免费额度按出口网段计算:IPv6 出口按 `/64`、IPv4 出口按 `/32` 去重并冷却 30 分钟。Cloudflare WARP 的共享 IPv4 出口通常已被用尽,`warp.stack` 默认 `ipv6`,配合 `warp.source_ipv6`(路由到本机的 `/64`,Linux 下通过 `IPV6_FREEBIND` 绑定)让每个出口使用独立源地址时,替换出口才会获得新的公网地址。 -- WARP 无法初始化时启动直接失败;通过 WebUI 启用时参数错误会返回错误,旧运行时继续服务,不会静默回退到代理。 -- `/healthz` 的 `warp` 块与 `/api/monitor` 的 `resources.warp` 显示堆栈、出口数量、活跃/备用/冷却数量和出口地址;启用 WARP 但无活跃出口时健康检查返回 503,此时若没有 Go Key,`no_healthy_proxies` 不再阻塞就绪。 - -## 验证和构建 - -```bash -go test ./... -go test -race ./... -go vet ./... -for f in webui/js/*.js webui/js/pages/*.js; do node --input-type=module --check < "$f"; done -go build -trimpath -o opencode2api ./cmd/opencode2api +```json +{"protocol":"chat","key":{"mode":"auto"},"request":{"model":"MODEL_ID","messages":[{"role":"user","content":"Hello"}]}} ``` -升级前请备份程序、配置及轮转状态,再停止服务并替换可执行文件。旧版本不认识新增的 `server_key_metadata` 和 `rotation` 字段;回退时应同时恢复旧程序和旧配置。 +指定 Key 时用 `{"mode":"selected","tier":"zen","id":"KEY_FINGERPRINT"}` 替换 `key`,ID 来自 `GET /api/debug/models`。选定 Key 只做一次上游尝试,不匿名、不换 Key、不跨 Tier、不 reasoning 重放。可选 `relay` 用已知索引指定代理,例如 `{"index":0}`。索引必须来自当前诊断目录。 -## SOTA / 甜点模型轮转 +诊断不修改生产 Key 冷却、失败计数、代理健康或绑定,但会发真实请求、消耗额度/credits 并进入监控。管理响应成功封装为 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`;格式/认证/限流错误仍使用对应 HTTP 状态。 -管理页:`/#rotation`。调用时继续使用 网关的 Base URL(默认 -`http://127.0.0.1:8080/v1`)和已有 API Key,将 `model` 设为 `sota` 或 -`sweet`。两个别名列入 `/v1/models`,支持 Chat Completions、Responses 和 -Messages,以及这三种协议的流式输出。真实模型 ID 的原有调用路径保持不变。 +日志位于 `GET /api/logs?after=SEQUENCE&limit=COUNT` 与 `GET /api/logs/stream`。SSE 支持 `Last-Event-ID` 或 `after` 续接;过期/丢失事件会有 `gap`,无法补回已淘汰数据。Session 失效后服务端结束日志流。 -- SOTA 固定成员:`deepseek-v4.1-flash`、`glm-5.3`、`grok-4.6`、`kimi-k3`、 - `qwen3.8-max`,默认按上述顺序。 -- 甜点组包含其余 Go 可用模型,初次以 `glm-5.3-flash` 为首,随后按名称排序。 - 新模型追加在末尾;下架或协议不受支持的模型保留在列表,但不参与调用。 -- 每组共享一个当前模型。成功后保持位置;失败切换后,下次从新位置开始。 - 并发请求通过位置版本号避免旧请求把游标移回去;手动切换不打断在途回答。 -- 普通错误每模型最多 3 次(包含首次),每请求最多消耗 3 个普通错误模型预算。 - 模型耗尽重试后暂停 15 秒。分组请求不使用原有 Key 重试、跨 Tier 降级、 - 自动重定向或 stale-reasoning 补发,也不因单个模型故障暂停整个 Go Key。 -- 429 或明确额度错误直接跳到下一模型,不新增普通错误模型计数;已经发生的 - 普通错误仍计数。允许遍历整组,同一请求不重复模型。暂停时间采用 Retry-After, - 未提供时为 60 秒。共享套餐额度只用于展示,不能保证换模型后就有余额。 -- 整体超时沿用 `retry.timeout_seconds`。`rotation.first_output_seconds` 默认 - 30 秒,限制每次等待首个有效输出的时间,不限制已经开始的正常流式回答。 -- 流式 start/role/usage 前导事件会等到有效输出或正常结束后再提交。提交前错误 - 可重试;提交后中断会保留已输出内容、追加协议对应的 SSE 错误并结束,随后 - 推进当前位置,下一次请求使用下一个模型。不会在同一响应里拼接替代答案。 - 调用方取消不会触发暂停或切换。 -- 响应 JSON / SSE 的 `model` 保持请求别名,`X-Resolved-Model` 标记实际模型。 - 用量按实际上游模型记录。轮转日志与管理页面仅保留分类后的错误原因, - 不记录上游错误正文、请求正文或密钥。最近保留 100 条尝试和每组 30 条切换。 +`GET /api/monitor` 提供聚合请求、Token、上游尝试与资源。`GET /api/debug/models` 提供路由、Key 指纹、模型元数据、代理和最近诊断结果。Token 只使用上游报告,不估算缺失值;输入包括缓存读写,cached 单列缓存读。`usage.server_keys` 以本地 Key 分组,`playground` 单列。 -配置保存于 `config.json` 的 `rotation` 字段:`sota` / `sweet` 各有 `alias` -和 `order`;状态单独原子写入 `config.json.rotation.json`(0600),包括当前 -位置、版本、动态追加的顺序、暂停期限和最近记录。修改 Key 或其他配置时 -沿用同一个轮转状态管理器。页面展示状态写入失败提示,首次无法写入则拒绝启动。 +请求结果表示完整推理:流失败即使 HTTP 200 也记为 `stream_error`,调用方取消为 `client_canceled`。上游 attempt 只测量收到响应头为止的交换,成功率和延迟不可当成整条回答成功率。 -管理接口均需要现有管理 Session,写入另需 CSRF: +## 持久化、健康与安全 -- `GET /api/rotation`:分组配置、可用状态、暂停期限、切换和尝试记录。 -- `PUT /api/rotation`:提交 `sota` / `sweet` 的 `alias`、完整 `order`,以及 - `first_output_seconds`;别名不得重复或与真实模型 ID 冲突,成员不得跨组。 -- `POST /api/rotation/current`:`{"group":"sota","model":"glm-5.3"}`;立即 - 修改当前模型并解除该模型的临时暂停。 +| 数据 | 位置与生命周期 | +| --- | --- | +| 配置/上一版本 | `config.json`、`config.json.bak`,包含敏感信息。 | +| 模型/价格缓存 | `config.json.models.catalog.json`、`config.json.models.dev.json`。 | +| 免费可用性 | `config.json..availability.json`,按上游隔离。 | +| 轮转状态 | `config.json.rotation.json`。 | +| Session、Token 累计、日志环、最近 Playground | 进程内存,重启清空。 | +| 请求/尝试详情 | 最近一小时,最多 10,000/20,000 条,接口各最多返回 500 条。 | +| 长期日志 | stdout JSON,须自行安全收集与保留。 | -验证:`go test -race ./...`、`go vet ./...`、`for f in webui/js/*.js webui/js/pages/*.js; do node --input-type=module --check < "$f"; done`。 -模拟上游测试覆盖 9 次普通错误上限、超过 3 个额度跳过、混合错误预算、 -Retry-After、单个模型故障不影响 Key、三种入口协议的跨协议转换、成功保持、 -别名发现与用量归属、畸形响应、输出前错误、首个输出超时、输出后故障、 -调用方取消、在途回答不受手动切换影响、并发版本保护、下架和重启恢复。 -上线前建议使用独立配置及端口验证管理登录、CSRF、页面排序与保存、别名冲突、 -Key 配置热更新和真实 Go 请求。测试与正式配置、凭证、日志及运行状态不应提交到仓库。 +文件前缀以实际 `-config` 路径为准。多个进程不共享 Session、监控或内存计数,避免并发修改同一状态文件。 + +`GET /healthz` 位于推理端口,无需认证,不触发上游检查或监控计数。目录未就绪/为空、WARP 无活跃出口、必要代理无健康节点时返回 503;可用但过期的目录可返回 200、`degraded`,过期阈值为两倍刷新间隔且至少 60 秒。OAuth 重登需求会体现在 issues,但就绪不等于下次推理一定成功。公开信息为状态和计数,不暴露 Key/代理地址。 + +本地使用应限制为 loopback;网络管理须用 HTTPS 和访问限制。程序自身不终止 TLS。配置/备份含手动 Key、代理密码与 OAuth Token,须用文件权限或 Windows ACL 限制,分享源码时排除。调试请求体输出虽脱敏且截断,仍可能含私人对话,应按需短时开启。不要把完整配置、reveal、Cookie、授权头或真实推理内容作为排错附件。 + +## 验证与维护 + +本地开发检查: + +```bash +go vet ./... +go build -trimpath -o opencode2api ./cmd/opencode2api +for file in webui/js/*.js webui/js/pages/*.js; do + node --input-type=module --check < "$file" || exit 1 +done +``` + +正常部署验收需核实管理登录与 CSRF、Key 停用/恢复、配置保存与监听重启、模型发现、三种消息协议和 SSE 错误、轮转状态,以及所需的真实 OAuth/上游功能。真实推理、OAuth、WARP 和额度查询可能依赖账号权限并消耗额度;静态核对不能替代这些验证。 + +升级前安全备份程序、实际配置和状态,停止进程后替换程序;回退需恢复兼容的配置与状态。Compose 用户注意保存卷中的实际文件。不要把凭证、日志、运行状态或本地验证产物加入源码。 diff --git a/internal/admin/auth.go b/internal/admin/auth.go index 7f4d053..77cf21f 100644 --- a/internal/admin/auth.go +++ b/internal/admin/auth.go @@ -32,7 +32,7 @@ type adminSession struct { } // loginWindow is a fixed-window counter for one client: Started is when the -// window opened and Count the events in it. Login failures use a five-minute +// window opened and Count the events in it. Login attempts use a five-minute // window, Playground requests a one-minute one. type loginWindow struct { Started time.Time @@ -44,10 +44,6 @@ type loginWindow struct { // cookie. A successful login clears that client's failure window. func (a *Server) handleLogin(w http.ResponseWriter, r *http.Request) { client := clientIP(r) - if !a.allowLogin(client) { - writeAdminError(w, http.StatusTooManyRequests, "rate_limited", "too many login attempts; try again later") - return - } var input struct { Username string `json:"username"` Password string `json:"password"` @@ -56,11 +52,15 @@ func (a *Server) handleLogin(w http.ResponseWriter, r *http.Request) { writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error()) return } + if !a.reserveLoginCheck(client) { + writeAdminError(w, http.StatusTooManyRequests, "rate_limited", "too many login attempts; try again later") + return + } + defer a.releaseLoginCheck() cfg := a.manager.Config() usernameMatch := len(input.Username) == len(cfg.WebUI.Username) && subtle.ConstantTimeCompare([]byte(input.Username), []byte(cfg.WebUI.Username)) == 1 passwordMatch := config.VerifyPassword(cfg.WebUI.PasswordHash, input.Password) if !usernameMatch || !passwordMatch { - a.recordLoginFailure(client) a.logger.Warn("admin login failed", "component", "auth", "event", "login_failed", "client_ip", client) writeAdminError(w, http.StatusUnauthorized, "invalid_credentials", "invalid username or password") return @@ -106,7 +106,7 @@ func (a *Server) handleLogout(w http.ResponseWriter, r *http.Request) { a.mu.Lock() delete(a.sessions, tokenDigest(cookie.Value)) a.mu.Unlock() - a.cancelGoAuth(tokenDigest(cookie.Value)) + a.cancelOAuth(tokenDigest(cookie.Value)) } http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: "", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1, Secure: requestIsSecure(r)}) w.WriteHeader(http.StatusNoContent) @@ -197,7 +197,7 @@ func (a *Server) handleAccount(w http.ResponseWriter, r *http.Request) { return } _, err := a.manager.Update(func(latest *config.Config) error { - if !a.goAuthSessionValid(goAuthOwner(r), *latest) || !config.VerifyPassword(latest.WebUI.PasswordHash, input.CurrentPassword) { + if !a.sessionValid(sessionID(r), *latest) || !config.VerifyPassword(latest.WebUI.PasswordHash, input.CurrentPassword) { return errors.New("management account changed; sign in again") } if username := strings.TrimSpace(input.Username); username != "" { @@ -215,18 +215,22 @@ func (a *Server) handleAccount(w http.ResponseWriter, r *http.Request) { a.mu.Lock() a.sessions = make(map[string]adminSession) a.mu.Unlock() - a.cancelGoAuth("") + a.cancelOAuth("") http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: "", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1, Secure: requestIsSecure(r)}) a.logger.Info("admin account updated", "component", "auth", "event", "account_updated", "client_ip", clientIP(r)) httpx.WriteJSON(w, http.StatusOK, map[string]any{"updated": true, "reauthenticate": true}) } -// allowLogin reports whether client may try to log in: at most five failures -// per five-minute window. Once more than 1024 clients are tracked it also -// drops windows older than five minutes and evicts the oldest window at capacity. -func (a *Server) allowLogin(client string) bool { +// reserveLoginCheck counts an attempt before password verification, so +// concurrent requests cannot all pass the same failure count. Four active +// checks bound the memory used by the deliberately expensive Argon2 hashes; +// each client gets at most five attempts until a successful login clears them. +func (a *Server) reserveLoginCheck(client string) bool { a.mu.Lock() defer a.mu.Unlock() + if a.loginChecks >= 4 { + return false + } now := time.Now() if len(a.attempts) > 1024 { for address, candidate := range a.attempts { @@ -235,31 +239,26 @@ func (a *Server) allowLogin(client string) bool { } } } - if _, exists := a.attempts[client]; !exists && len(a.attempts) >= 4096 { - a.removeOldestLoginWindowLocked() - } - window := a.attempts[client] - if window.Started.IsZero() || now.Sub(window.Started) > 5*time.Minute { - return true - } - return window.Count < 5 -} - -// recordLoginFailure adds one failure for client, starting a new window when -// the previous one is older than five minutes. -func (a *Server) recordLoginFailure(client string) { - a.mu.Lock() - defer a.mu.Unlock() - now := time.Now() window := a.attempts[client] if window.Started.IsZero() || now.Sub(window.Started) > 5*time.Minute { window = loginWindow{Started: now} } + if window.Count >= 5 { + return false + } if _, exists := a.attempts[client]; !exists && len(a.attempts) >= 4096 { a.removeOldestLoginWindowLocked() } window.Count++ a.attempts[client] = window + a.loginChecks++ + return true +} + +func (a *Server) releaseLoginCheck() { + a.mu.Lock() + a.loginChecks-- + a.mu.Unlock() } // removeOldestLoginWindowLocked evicts one window so inserting a new client @@ -318,6 +317,23 @@ func tokenDigest(token string) string { return hex.EncodeToString(sum[:]) } +func sessionID(r *http.Request) string { + cookie, err := r.Cookie(adminCookieName) + if err != nil || cookie.Value == "" { + return "" + } + return tokenDigest(cookie.Value) +} + +// sessionValid checks the current account as well as the expiry, so requests +// waiting on upstream work cannot persist changes after a password change. +func (a *Server) sessionValid(id string, cfg config.Config) bool { + a.mu.Lock() + session, ok := a.sessions[id] + a.mu.Unlock() + return ok && time.Now().Before(session.Expires) && session.Username == cfg.WebUI.Username && session.AuthVersion == config.Fingerprint(cfg.WebUI.PasswordHash) +} + // clientIP returns the IP address of the direct peer, without the port. It // deliberately ignores X-Forwarded-For: the header is client-controlled, so // trusting it would let anyone escape the login and Playground rate limits by diff --git a/internal/admin/go_auth.go b/internal/admin/go_auth.go deleted file mode 100644 index c1461d3..0000000 --- a/internal/admin/go_auth.go +++ /dev/null @@ -1,382 +0,0 @@ -package admin - -import ( - "context" - "errors" - "net/http" - "slices" - "time" - - "opencode2api/internal/config" - "opencode2api/internal/goauth" - "opencode2api/internal/httpx" -) - -type goAuthAttempt struct { - ID string - Owner string - Status string - Device goauth.Device - Credential *goauth.Credential - Organizations []goauth.Organization - Expires time.Time - NextPoll time.Time - Busy bool - Cancel context.CancelFunc - Error string -} - -type goAuthPendingView struct { - ID string `json:"id"` - Status string `json:"status"` - VerificationURL string `json:"verification_url,omitempty"` - UserCode string `json:"user_code,omitempty"` - ExpiresAt time.Time `json:"expires_at"` - IntervalSeconds int `json:"interval_seconds"` - RetryAfterSeconds int `json:"retry_after_seconds"` - Organizations []goauth.Organization `json:"organizations,omitempty"` - Error string `json:"error,omitempty"` -} - -type goAccountView struct { - Email string `json:"email"` - Organization string `json:"organization"` - ExpiresAt time.Time `json:"expires_at"` - Models int `json:"models"` - NeedsLogin bool `json:"needs_login"` - Error string `json:"error,omitempty"` -} - -type goAuthView struct { - Connected bool `json:"connected"` - Account *goAccountView `json:"account,omitempty"` - Pending *goAuthPendingView `json:"pending,omitempty"` -} - -func goAuthOwner(r *http.Request) string { - cookie, err := r.Cookie(adminCookieName) - if err != nil || cookie.Value == "" { - return "" - } - return tokenDigest(cookie.Value) -} - -func (a *Server) goAuthSessionValid(owner string, cfg config.Config) bool { - a.mu.Lock() - session, ok := a.sessions[owner] - a.mu.Unlock() - return ok && time.Now().Before(session.Expires) && session.Username == cfg.WebUI.Username && session.AuthVersion == config.Fingerprint(cfg.WebUI.PasswordHash) -} - -func (a *Server) cleanupGoAuthLocked() { - now := time.Now() - cfg := a.manager.Config() - for owner, attempt := range a.goAuth { - if !now.Before(attempt.Expires) || !a.goAuthSessionValid(owner, cfg) { - if attempt.Cancel != nil { - attempt.Cancel() - } - delete(a.goAuth, owner) - } - } -} - -func (a *Server) cancelGoAuth(owner string) { - a.goAuthMu.Lock() - defer a.goAuthMu.Unlock() - for candidate, attempt := range a.goAuth { - if owner != "" && candidate != owner { - continue - } - if attempt.Cancel != nil { - attempt.Cancel() - } - delete(a.goAuth, candidate) - } -} - -func (a *Server) goAuthViewLocked(owner string) goAuthView { - view := goAuthView{} - connection := a.manager.Config().GoSubscription - if connection != nil { - view.Connected = true - view.Account = &goAccountView{ - Email: connection.Credential.Email, Organization: connection.Credential.OrganizationName, - ExpiresAt: connection.Credential.ExpiresAt, Models: len(connection.Routes), NeedsLogin: connection.NeedsLogin, - } - if connection.NeedsLogin { - view.Account.Error = "Go 订阅授权已失效或组织发生变化,请重新登录。" - } - } - if attempt := a.goAuth[owner]; attempt != nil { - wait := max(0, int(time.Until(attempt.NextPoll).Seconds()+0.999)) - view.Pending = &goAuthPendingView{ - ID: attempt.ID, Status: attempt.Status, ExpiresAt: attempt.Expires, - VerificationURL: attempt.Device.VerificationURI, UserCode: attempt.Device.UserCode, - IntervalSeconds: max(1, int(attempt.Device.Interval.Seconds())), RetryAfterSeconds: wait, - Organizations: append([]goauth.Organization(nil), attempt.Organizations...), Error: attempt.Error, - } - } - return view -} - -func (a *Server) handleGoAuthStatus(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "no-store") - a.goAuthMu.Lock() - a.cleanupGoAuthLocked() - view := a.goAuthViewLocked(goAuthOwner(r)) - a.goAuthMu.Unlock() - httpx.WriteJSON(w, http.StatusOK, view) -} - -func (a *Server) handleGoAuthStart(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "no-store") - var input struct{} - if err := decodeAdminJSON(w, r, &input); err != nil { - writeAdminError(w, http.StatusBadRequest, "invalid_request", "登录请求格式无效") - return - } - owner := goAuthOwner(r) - session, ok := sessionFromContext(r) - if !ok || owner == "" { - writeAdminError(w, http.StatusUnauthorized, "authentication_required", "login required") - return - } - id, err := randomToken(24) - if err != nil { - writeAdminError(w, http.StatusInternalServerError, "internal_error", "无法创建订阅登录") - return - } - ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) - defer cancel() - a.goAuthMu.Lock() - a.cleanupGoAuthLocked() - if existing := a.goAuth[owner]; existing != nil && existing.Status != "failed" { - view := a.goAuthViewLocked(owner) - a.goAuthMu.Unlock() - httpx.WriteJSON(w, http.StatusOK, view) - return - } - if len(a.goAuth) >= 32 && a.goAuth[owner] == nil { - a.goAuthMu.Unlock() - writeAdminError(w, http.StatusTooManyRequests, "login_capacity", "待完成的订阅登录过多,请稍后重试") - return - } - attempt := &goAuthAttempt{ID: id, Owner: owner, Status: "starting", Expires: minTime(session.Expires, time.Now().Add(15*time.Minute)), Busy: true, Cancel: cancel} - if a.goAuth == nil { - a.goAuth = make(map[string]*goAuthAttempt) - } - a.goAuth[owner] = attempt - a.goAuthMu.Unlock() - device, err := a.goAuthClient.Start(ctx) - a.goAuthMu.Lock() - if a.goAuth[owner] != attempt || !time.Now().Before(attempt.Expires) || !a.goAuthSessionValid(owner, a.manager.Config()) { - a.goAuthMu.Unlock() - writeAdminError(w, http.StatusConflict, "login_canceled", "订阅登录已取消或管理会话已失效") - return - } - attempt.Busy, attempt.Cancel = false, nil - if err != nil { - attempt.Status, attempt.Error = "failed", safeGoAuthError(err) - } else { - attempt.Device, attempt.Status = device, "pending" - attempt.Expires = minTime(attempt.Expires, device.ExpiresAt) - attempt.NextPoll = time.Now().Add(device.Interval) - } - view := a.goAuthViewLocked(owner) - a.goAuthMu.Unlock() - httpx.WriteJSON(w, http.StatusOK, view) -} - -func (a *Server) handleGoAuthPoll(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "no-store") - var input struct { - ID string `json:"id"` - OrganizationID string `json:"organization_id,omitempty"` - } - if err := decodeAdminJSON(w, r, &input); err != nil || input.ID == "" { - writeAdminError(w, http.StatusBadRequest, "invalid_request", "登录请求格式无效") - return - } - owner := goAuthOwner(r) - ctx, cancel := context.WithTimeout(r.Context(), 45*time.Second) - defer cancel() - a.goAuthMu.Lock() - a.cleanupGoAuthLocked() - attempt := a.goAuth[owner] - if attempt == nil || attempt.ID != input.ID { - a.goAuthMu.Unlock() - writeAdminError(w, http.StatusNotFound, "login_not_found", "订阅登录已过期或不存在,请重新开始") - return - } - if attempt.Busy || attempt.Status == "failed" || time.Now().Before(attempt.NextPoll) { - view := a.goAuthViewLocked(owner) - a.goAuthMu.Unlock() - httpx.WriteJSON(w, http.StatusOK, view) - return - } - if input.OrganizationID != "" && !slices.ContainsFunc(attempt.Organizations, func(org goauth.Organization) bool { return org.ID == input.OrganizationID }) { - a.goAuthMu.Unlock() - writeAdminError(w, http.StatusBadRequest, "invalid_organization", "只能选择本次授权允许的组织") - return - } - if attempt.Status == "choosing_org" && input.OrganizationID == "" { - view := a.goAuthViewLocked(owner) - a.goAuthMu.Unlock() - httpx.WriteJSON(w, http.StatusOK, view) - return - } - var credential *goauth.Credential - if attempt.Credential != nil { - copied := *attempt.Credential - credential = &copied - } - organizations := append([]goauth.Organization(nil), attempt.Organizations...) - deviceCode := attempt.Device.DeviceCode - attempt.Busy, attempt.Cancel, attempt.Status = true, cancel, "authorizing" - a.goAuthMu.Unlock() - var err error - if credential == nil { - var token goauth.Token - token, err = a.goAuthClient.Poll(ctx, deviceCode) - if err == nil { - var user goauth.User - user, organizations, err = a.goAuthClient.Identify(ctx, token) - if err == nil { - credential = &goauth.Credential{ - AccessToken: token.AccessToken, RefreshToken: token.RefreshToken, ExpiresAt: token.ExpiresAt, - AccountID: user.ID, Email: user.Email, OrganizationID: token.OrganizationID, - } - } - } - } - if err == nil && credential.OrganizationID == "" { - switch { - case input.OrganizationID != "": - credential.OrganizationID = input.OrganizationID - case len(organizations) == 1: - credential.OrganizationID = organizations[0].ID - case len(organizations) > 1: - a.goAuthMu.Lock() - if a.goAuth[owner] == attempt && time.Now().Before(attempt.Expires) && a.goAuthSessionValid(owner, a.manager.Config()) { - attempt.Credential, attempt.Organizations = credential, organizations - attempt.Expires = minTime(attempt.Expires, credential.ExpiresAt) - attempt.Status, attempt.Busy, attempt.Cancel = "choosing_org", false, nil - attempt.NextPoll = time.Time{} - view := a.goAuthViewLocked(owner) - a.goAuthMu.Unlock() - httpx.WriteJSON(w, http.StatusOK, view) - } else { - a.goAuthMu.Unlock() - writeAdminError(w, http.StatusConflict, "login_canceled", "订阅登录已取消") - } - return - } - } - if credential != nil { - for _, organization := range organizations { - if organization.ID == credential.OrganizationID { - credential.OrganizationName = organization.Name - break - } - } - } - var routes map[string]goauth.Route - if err == nil { - routes, err = a.goAuthClient.Discover(ctx, *credential) - } - a.goAuthMu.Lock() - if a.goAuth[owner] != attempt || !time.Now().Before(attempt.Expires) || !a.goAuthSessionValid(owner, a.manager.Config()) { - a.goAuthMu.Unlock() - writeAdminError(w, http.StatusConflict, "login_canceled", "订阅登录已取消或管理会话已失效") - return - } - attempt.Busy, attempt.Cancel = false, nil - if err != nil { - var oauthError *goauth.OAuthError - if errors.As(err, &oauthError) && (oauthError.Code == "authorization_pending" || oauthError.Code == "slow_down") { - if oauthError.Code == "slow_down" { - attempt.Device.Interval = min(attempt.Device.Interval+5*time.Second, 5*time.Minute) - } - attempt.Status = "pending" - attempt.NextPoll = time.Now().Add(attempt.Device.Interval) - } else { - attempt.Status, attempt.Error, attempt.Credential = "failed", safeGoAuthError(err), nil - attempt.Device.DeviceCode = "" - } - view := a.goAuthViewLocked(owner) - a.goAuthMu.Unlock() - httpx.WriteJSON(w, http.StatusOK, view) - return - } - connection := &goauth.Connection{Credential: *credential, Routes: routes} - _, err = a.manager.Update(func(cfg *config.Config) error { - if ctx.Err() != nil || !time.Now().Before(attempt.Expires) || !time.Now().Before(credential.ExpiresAt) || !a.goAuthSessionValid(owner, *cfg) { - return errors.New("subscription login is no longer active") - } - if cfg.GoSubscription != nil { - connection.Proxy = cfg.GoSubscription.Proxy - } - cfg.GoSubscription = connection - return nil - }) - if err != nil { - attempt.Status, attempt.Error, attempt.Credential = "failed", "无法安全保存订阅登录,请检查配置后重新登录。", nil - attempt.Device.DeviceCode = "" - } else { - delete(a.goAuth, owner) - a.logger.Info("Go subscription connected", "component", "auth", "event", "go_subscription_connected") - } - view := a.goAuthViewLocked(owner) - a.goAuthMu.Unlock() - httpx.WriteJSON(w, http.StatusOK, view) -} - -func (a *Server) handleGoAuthCancel(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "no-store") - a.cancelGoAuth(goAuthOwner(r)) - a.handleGoAuthStatus(w, r) -} - -func (a *Server) handleGoDisconnect(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "no-store") - owner := goAuthOwner(r) - a.goAuthMu.Lock() - _, err := a.manager.Update(func(cfg *config.Config) error { - if !a.goAuthSessionValid(owner, *cfg) { - return errors.New("management session is no longer active") - } - cfg.GoSubscription = nil - return nil - }) - if err != nil { - a.goAuthMu.Unlock() - writeAdminError(w, http.StatusBadRequest, "disconnect_failed", "无法断开订阅;请确保保留至少一个上游 Key 或启用匿名通道。") - return - } - for candidate, attempt := range a.goAuth { - if attempt.Cancel != nil { - attempt.Cancel() - } - delete(a.goAuth, candidate) - } - a.logger.Info("Go subscription disconnected locally", "component", "auth", "event", "go_subscription_disconnected") - view := a.goAuthViewLocked(owner) - a.goAuthMu.Unlock() - httpx.WriteJSON(w, http.StatusOK, view) -} - -func safeGoAuthError(err error) string { - var oauthError *goauth.OAuthError - if errors.As(err, &oauthError) { - return oauthError.Error() - } - return "订阅授权未完成或请求已取消,请重新开始。" -} - -func minTime(first, second time.Time) time.Time { - if first.Before(second) { - return first - } - return second -} diff --git a/internal/admin/model_quotas.go b/internal/admin/model_quotas.go index c196b10..3349bb6 100644 --- a/internal/admin/model_quotas.go +++ b/internal/admin/model_quotas.go @@ -147,10 +147,10 @@ func (a *Server) handleModelQuotas(w http.ResponseWriter, r *http.Request) { cfg := a.manager.Config() endpoint := strings.TrimRight(cfg.Upstream.Go, "/") + "/v1/usage" accounts := make([]quotaAccount, len(cfg.GoKeys)) - if connection := cfg.GoSubscription; connection != nil { + if connection := cfg.GoOAuth; connection != nil { accounts = []quotaAccount{{ ID: config.Fingerprint(connection.Credential.AccountID + "\x00" + connection.Credential.OrganizationID), - Display: "Go subscription (OAuth)", Status: "unavailable", CheckedAt: time.Now().UTC(), + Display: "Go OAuth", Status: "unavailable", CheckedAt: time.Now().UTC(), Error: "OpenCode 未提供已验证的 OAuth 订阅额度接口,额度保持未知。", }} endpoint = "" @@ -162,7 +162,7 @@ func (a *Server) handleModelQuotas(w http.ResponseWriter, r *http.Request) { a.quotaCache = map[string]quotaCacheEntry{} } keys := cfg.GoKeys - if cfg.GoSubscription != nil { + if cfg.GoOAuth != nil { keys = nil } entries := make([]quotaCacheEntry, len(keys)) @@ -209,7 +209,7 @@ func (a *Server) handleModelQuotas(w http.ResponseWriter, r *http.Request) { } } note := "OpenCode 返回套餐共享额度,未提供逐模型独立余额;多个 Go Key 可能属于同一套餐,不能相加。百分比由上游取整。" - if cfg.GoSubscription != nil { + if cfg.GoOAuth != nil { note = "OAuth 订阅使用官方 Go 推理路由;未提供已验证的订阅额度接口,不查询手动 Go Key 或按量计费余额。" } httpx.WriteJSON(w, 200, map[string]any{ diff --git a/internal/admin/oauth.go b/internal/admin/oauth.go new file mode 100644 index 0000000..8f2d556 --- /dev/null +++ b/internal/admin/oauth.go @@ -0,0 +1,446 @@ +package admin + +import ( + "context" + "errors" + "net/http" + "slices" + "time" + + "opencode2api/internal/config" + "opencode2api/internal/httpx" + "opencode2api/internal/oauth" +) + +type oauthKey struct { + Owner string + Plan oauth.Plan +} + +type oauthAttempt struct { + ID string + Status string + Device oauth.Device + Credential *oauth.Credential + Organizations []oauth.Organization + Expires time.Time + NextPoll time.Time + Busy bool + Cancel context.CancelFunc + Error string +} + +type oauthPendingView struct { + ID string `json:"id"` + Status string `json:"status"` + VerificationURL string `json:"verification_url,omitempty"` + UserCode string `json:"user_code,omitempty"` + ExpiresAt time.Time `json:"expires_at"` + IntervalSeconds int `json:"interval_seconds"` + RetryAfterSeconds int `json:"retry_after_seconds"` + Organizations []oauth.Organization `json:"organizations,omitempty"` + Error string `json:"error,omitempty"` +} + +type oauthAccountView struct { + Email string `json:"email"` + Organization string `json:"organization"` + ExpiresAt time.Time `json:"expires_at"` + Models int `json:"models"` + NeedsLogin bool `json:"needs_login"` + Error string `json:"error,omitempty"` +} + +type oauthView struct { + Connected bool `json:"connected"` + Account *oauthAccountView `json:"account,omitempty"` + Pending *oauthPendingView `json:"pending,omitempty"` +} + +func (a *Server) cleanupOAuthLocked() { + now := time.Now() + cfg := a.manager.Config() + for key, attempt := range a.oauth { + if !now.Before(attempt.Expires) || !a.sessionValid(key.Owner, cfg) { + if attempt.Cancel != nil { + attempt.Cancel() + } + delete(a.oauth, key) + } + } +} + +func (a *Server) cancelOAuth(owner string) { + a.oauthMu.Lock() + defer a.oauthMu.Unlock() + a.cancelOAuthLocked(owner, "") +} + +func (a *Server) cancelOAuthLocked(owner string, plan oauth.Plan) { + for key, attempt := range a.oauth { + if (owner != "" && key.Owner != owner) || (plan != "" && key.Plan != plan) { + continue + } + if attempt.Cancel != nil { + attempt.Cancel() + } + delete(a.oauth, key) + } +} + +func (a *Server) oauthViewLocked(owner string, plan oauth.Plan) oauthView { + view := oauthView{} + cfg := a.manager.Config() + connection := cfg.GoOAuth + if plan == oauth.PlanZen { + connection = cfg.ZenOAuth + } + if connection != nil { + view.Connected = true + view.Account = &oauthAccountView{ + Email: connection.Credential.Email, Organization: connection.Credential.OrganizationName, + ExpiresAt: connection.Credential.ExpiresAt, Models: len(connection.Routes), NeedsLogin: connection.NeedsLogin, + } + if connection.NeedsLogin { + view.Account.Error = "OpenCode 授权已失效或组织发生变化,请重新登录。" + } + } + if attempt := a.oauth[oauthKey{Owner: owner, Plan: plan}]; attempt != nil { + wait := max(0, int(time.Until(attempt.NextPoll).Seconds()+0.999)) + view.Pending = &oauthPendingView{ + ID: attempt.ID, Status: attempt.Status, ExpiresAt: attempt.Expires, + VerificationURL: attempt.Device.VerificationURI, UserCode: attempt.Device.UserCode, + IntervalSeconds: max(1, int(attempt.Device.Interval.Seconds())), RetryAfterSeconds: wait, + Organizations: append([]oauth.Organization(nil), attempt.Organizations...), Error: attempt.Error, + } + } + return view +} + +func (a *Server) handleGoOAuthStatus(w http.ResponseWriter, r *http.Request) { + a.handleOAuthStatus(w, r, oauth.PlanGo) +} + +func (a *Server) handleZenOAuthStatus(w http.ResponseWriter, r *http.Request) { + a.handleOAuthStatus(w, r, oauth.PlanZen) +} + +func (a *Server) handleOAuthStatus(w http.ResponseWriter, r *http.Request, plan oauth.Plan) { + w.Header().Set("Cache-Control", "no-store") + a.oauthMu.Lock() + a.cleanupOAuthLocked() + view := a.oauthViewLocked(sessionID(r), plan) + a.oauthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) +} + +func (a *Server) handleGoOAuthStart(w http.ResponseWriter, r *http.Request) { + a.handleOAuthStart(w, r, oauth.PlanGo) +} + +func (a *Server) handleZenOAuthStart(w http.ResponseWriter, r *http.Request) { + a.handleOAuthStart(w, r, oauth.PlanZen) +} + +func (a *Server) handleOAuthStart(w http.ResponseWriter, r *http.Request, plan oauth.Plan) { + w.Header().Set("Cache-Control", "no-store") + if plan == oauth.PlanZen { + var input struct { + AcknowledgePAYG bool `json:"acknowledge_payg"` + } + if err := decodeAdminJSON(w, r, &input); err != nil { + writeAdminError(w, http.StatusBadRequest, "invalid_request", "登录请求格式无效") + return + } + if !input.AcknowledgePAYG { + writeAdminError(w, http.StatusBadRequest, "payg_acknowledgement_required", "Zen 按 credits 用量计费,与 Go 订阅额度独立;请明确确认 acknowledge_payg 为 true 后再连接。") + return + } + } else { + var input struct{} + if err := decodeAdminJSON(w, r, &input); err != nil { + writeAdminError(w, http.StatusBadRequest, "invalid_request", "登录请求格式无效") + return + } + } + owner := sessionID(r) + key := oauthKey{Owner: owner, Plan: plan} + session, ok := sessionFromContext(r) + if !ok || owner == "" { + writeAdminError(w, http.StatusUnauthorized, "authentication_required", "login required") + return + } + id, err := randomToken(24) + if err != nil { + writeAdminError(w, http.StatusInternalServerError, "internal_error", "无法创建 OAuth 登录") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + a.oauthMu.Lock() + a.cleanupOAuthLocked() + if existing := a.oauth[key]; existing != nil && existing.Status != "failed" { + view := a.oauthViewLocked(owner, plan) + a.oauthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) + return + } + if len(a.oauth) >= 32 && a.oauth[key] == nil { + a.oauthMu.Unlock() + writeAdminError(w, http.StatusTooManyRequests, "login_capacity", "待完成的 OAuth 登录过多,请稍后重试") + return + } + attempt := &oauthAttempt{ID: id, Status: "starting", Expires: minTime(session.Expires, time.Now().Add(15*time.Minute)), Busy: true, Cancel: cancel} + if a.oauth == nil { + a.oauth = make(map[oauthKey]*oauthAttempt) + } + a.oauth[key] = attempt + a.oauthMu.Unlock() + device, err := a.oauthClient.Start(ctx) + a.oauthMu.Lock() + if a.oauth[key] != attempt || !time.Now().Before(attempt.Expires) || !a.sessionValid(owner, a.manager.Config()) { + a.oauthMu.Unlock() + writeAdminError(w, http.StatusConflict, "login_canceled", "OAuth 登录已取消或管理会话已失效") + return + } + attempt.Busy, attempt.Cancel = false, nil + if err != nil { + attempt.Status, attempt.Error = "failed", safeOAuthError(err) + } else { + attempt.Device, attempt.Status = device, "pending" + attempt.Expires = minTime(attempt.Expires, device.ExpiresAt) + attempt.NextPoll = time.Now().Add(device.Interval) + } + view := a.oauthViewLocked(owner, plan) + a.oauthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) +} + +func (a *Server) handleGoOAuthPoll(w http.ResponseWriter, r *http.Request) { + a.handleOAuthPoll(w, r, oauth.PlanGo) +} + +func (a *Server) handleZenOAuthPoll(w http.ResponseWriter, r *http.Request) { + a.handleOAuthPoll(w, r, oauth.PlanZen) +} + +func (a *Server) handleOAuthPoll(w http.ResponseWriter, r *http.Request, plan oauth.Plan) { + w.Header().Set("Cache-Control", "no-store") + var input struct { + ID string `json:"id"` + OrganizationID string `json:"organization_id,omitempty"` + } + if err := decodeAdminJSON(w, r, &input); err != nil || input.ID == "" { + writeAdminError(w, http.StatusBadRequest, "invalid_request", "登录请求格式无效") + return + } + owner := sessionID(r) + key := oauthKey{Owner: owner, Plan: plan} + ctx, cancel := context.WithTimeout(r.Context(), 45*time.Second) + defer cancel() + a.oauthMu.Lock() + a.cleanupOAuthLocked() + attempt := a.oauth[key] + if attempt == nil || attempt.ID != input.ID { + a.oauthMu.Unlock() + writeAdminError(w, http.StatusNotFound, "login_not_found", "OAuth 登录已过期或不存在,请重新开始") + return + } + if attempt.Busy || attempt.Status == "failed" || time.Now().Before(attempt.NextPoll) { + view := a.oauthViewLocked(owner, plan) + a.oauthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) + return + } + if input.OrganizationID != "" && !slices.ContainsFunc(attempt.Organizations, func(org oauth.Organization) bool { return org.ID == input.OrganizationID }) { + a.oauthMu.Unlock() + writeAdminError(w, http.StatusBadRequest, "invalid_organization", "只能选择本次授权允许的组织") + return + } + if attempt.Status == "choosing_org" && input.OrganizationID == "" { + view := a.oauthViewLocked(owner, plan) + a.oauthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) + return + } + var credential *oauth.Credential + if attempt.Credential != nil { + copied := *attempt.Credential + credential = &copied + } + organizations := append([]oauth.Organization(nil), attempt.Organizations...) + deviceCode := attempt.Device.DeviceCode + attempt.Busy, attempt.Cancel, attempt.Status = true, cancel, "authorizing" + a.oauthMu.Unlock() + var err error + if credential == nil { + var token oauth.Token + token, err = a.oauthClient.Poll(ctx, deviceCode) + if err == nil { + var user oauth.User + user, organizations, err = a.oauthClient.Identify(ctx, token) + if err == nil { + credential = &oauth.Credential{ + AccessToken: token.AccessToken, RefreshToken: token.RefreshToken, ExpiresAt: token.ExpiresAt, + AccountID: user.ID, Email: user.Email, OrganizationID: token.OrganizationID, + } + } + } + } + if err == nil && credential.OrganizationID == "" { + switch { + case input.OrganizationID != "": + credential.OrganizationID = input.OrganizationID + case len(organizations) == 1: + credential.OrganizationID = organizations[0].ID + case len(organizations) > 1: + a.oauthMu.Lock() + if a.oauth[key] == attempt && time.Now().Before(attempt.Expires) && a.sessionValid(owner, a.manager.Config()) { + attempt.Credential, attempt.Organizations = credential, organizations + attempt.Expires = minTime(attempt.Expires, credential.ExpiresAt) + attempt.Status, attempt.Busy, attempt.Cancel = "choosing_org", false, nil + attempt.NextPoll = time.Time{} + view := a.oauthViewLocked(owner, plan) + a.oauthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) + } else { + a.oauthMu.Unlock() + writeAdminError(w, http.StatusConflict, "login_canceled", "OAuth 登录已取消") + } + return + } + } + if credential != nil { + for _, organization := range organizations { + if organization.ID == credential.OrganizationID { + credential.OrganizationName = organization.Name + break + } + } + } + var routes map[string]oauth.Route + if err == nil { + routes, err = a.oauthClient.DiscoverForPlan(ctx, *credential, plan) + } + a.oauthMu.Lock() + if a.oauth[key] != attempt || !time.Now().Before(attempt.Expires) || !a.sessionValid(owner, a.manager.Config()) { + a.oauthMu.Unlock() + writeAdminError(w, http.StatusConflict, "login_canceled", "OAuth 登录已取消或管理会话已失效") + return + } + attempt.Busy, attempt.Cancel = false, nil + if err != nil { + var oauthError *oauth.OAuthError + if errors.As(err, &oauthError) && (oauthError.Code == "authorization_pending" || oauthError.Code == "slow_down") { + if oauthError.Code == "slow_down" { + attempt.Device.Interval = min(attempt.Device.Interval+5*time.Second, 5*time.Minute) + } + attempt.Status = "pending" + attempt.NextPoll = time.Now().Add(attempt.Device.Interval) + } else { + attempt.Status, attempt.Error, attempt.Credential = "failed", safeOAuthError(err), nil + attempt.Device.DeviceCode = "" + } + view := a.oauthViewLocked(owner, plan) + a.oauthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) + return + } + connection := &oauth.Connection{Credential: *credential, Routes: routes} + _, err = a.manager.Update(func(cfg *config.Config) error { + if ctx.Err() != nil || a.oauth[key] != attempt || !time.Now().Before(attempt.Expires) || !time.Now().Before(credential.ExpiresAt) || !a.sessionValid(owner, *cfg) { + return errors.New("OAuth login is no longer active") + } + if plan == oauth.PlanZen { + if cfg.ZenOAuth != nil { + connection.Proxy = cfg.ZenOAuth.Proxy + } + cfg.ZenOAuth = connection + } else { + if cfg.GoOAuth != nil { + connection.Proxy = cfg.GoOAuth.Proxy + } + cfg.GoOAuth = connection + } + return nil + }) + if err != nil { + attempt.Status, attempt.Error, attempt.Credential = "failed", "无法安全保存 OAuth 登录,请检查配置后重新登录。", nil + attempt.Device.DeviceCode = "" + } else { + delete(a.oauth, key) + a.logger.Info("OpenCode account connected", "component", "auth", "event", string(plan)+"_oauth_connected", "tier", plan) + } + view := a.oauthViewLocked(owner, plan) + a.oauthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) +} + +func (a *Server) handleGoOAuthCancel(w http.ResponseWriter, r *http.Request) { + a.handleOAuthCancel(w, r, oauth.PlanGo) +} + +func (a *Server) handleZenOAuthCancel(w http.ResponseWriter, r *http.Request) { + a.handleOAuthCancel(w, r, oauth.PlanZen) +} + +func (a *Server) handleOAuthCancel(w http.ResponseWriter, r *http.Request, plan oauth.Plan) { + w.Header().Set("Cache-Control", "no-store") + owner := sessionID(r) + a.oauthMu.Lock() + a.cancelOAuthLocked(owner, plan) + a.cleanupOAuthLocked() + view := a.oauthViewLocked(owner, plan) + a.oauthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) +} + +func (a *Server) handleGoOAuthDisconnect(w http.ResponseWriter, r *http.Request) { + a.handleOAuthDisconnect(w, r, oauth.PlanGo) +} + +func (a *Server) handleZenOAuthDisconnect(w http.ResponseWriter, r *http.Request) { + a.handleOAuthDisconnect(w, r, oauth.PlanZen) +} + +func (a *Server) handleOAuthDisconnect(w http.ResponseWriter, r *http.Request, plan oauth.Plan) { + w.Header().Set("Cache-Control", "no-store") + owner := sessionID(r) + a.oauthMu.Lock() + _, err := a.manager.Update(func(cfg *config.Config) error { + if !a.sessionValid(owner, *cfg) { + return errors.New("management session is no longer active") + } + if plan == oauth.PlanZen { + cfg.ZenOAuth = nil + } else { + cfg.GoOAuth = nil + } + return nil + }) + if err != nil { + a.oauthMu.Unlock() + writeAdminError(w, http.StatusBadRequest, "disconnect_failed", "无法断开登录;请确保保留至少一个上游 Key、另一个 OpenCode 连接或已启用的匿名通道。") + return + } + a.cancelOAuthLocked("", plan) + a.logger.Info("OpenCode account disconnected locally", "component", "auth", "event", string(plan)+"_oauth_disconnected", "tier", plan) + view := a.oauthViewLocked(owner, plan) + a.oauthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) +} + +func safeOAuthError(err error) string { + var oauthError *oauth.OAuthError + if errors.As(err, &oauthError) { + return oauthError.Error() + } + return "OpenCode 授权未完成或请求已取消,请重新开始。" +} + +func minTime(first, second time.Time) time.Time { + if first.Before(second) { + return first + } + return second +} diff --git a/internal/admin/server.go b/internal/admin/server.go index 833873a..6cbf4e2 100644 --- a/internal/admin/server.go +++ b/internal/admin/server.go @@ -17,8 +17,8 @@ import ( "opencode2api/internal/buildinfo" "opencode2api/internal/config" "opencode2api/internal/gateway" - "opencode2api/internal/goauth" "opencode2api/internal/httpx" + "opencode2api/internal/oauth" "opencode2api/internal/telemetry" "opencode2api/webui" ) @@ -34,13 +34,14 @@ type Server struct { mu sync.Mutex sessions map[string]adminSession attempts map[string]loginWindow + loginChecks int debugAttempts map[string]loginWindow lastInference *DebugInferenceResult quotaMu sync.Mutex quotaCache map[string]quotaCacheEntry - goAuthMu sync.Mutex - goAuth map[string]*goAuthAttempt - goAuthClient *goauth.Client + oauthMu sync.Mutex + oauth map[oauthKey]*oauthAttempt + oauthClient *oauth.Client proxyChecks chan struct{} } @@ -49,7 +50,7 @@ func New(manager *gateway.RuntimeController, monitor *telemetry.Metrics, logs *t return &Server{ manager: manager, monitor: monitor, logs: logs, logger: logger, sessions: make(map[string]adminSession), attempts: make(map[string]loginWindow), debugAttempts: make(map[string]loginWindow), - goAuth: make(map[string]*goAuthAttempt), goAuthClient: goauth.NewClient(nil), + oauth: make(map[oauthKey]*oauthAttempt), oauthClient: oauth.NewClient(nil), proxyChecks: make(chan struct{}, 8), } } @@ -80,11 +81,16 @@ func (a *Server) Handler() http.Handler { mux.Handle("PUT /api/rotation", a.authenticate(a.csrf(http.HandlerFunc(a.handleSaveRotation)))) mux.Handle("POST /api/rotation/current", a.authenticate(a.csrf(http.HandlerFunc(a.handleSelectRotation)))) mux.Handle("GET /api/model-quotas", a.authenticate(http.HandlerFunc(a.handleModelQuotas))) - mux.Handle("GET /api/go/auth", a.authenticate(http.HandlerFunc(a.handleGoAuthStatus))) - mux.Handle("POST /api/go/auth/start", a.authenticate(a.csrf(http.HandlerFunc(a.handleGoAuthStart)))) - mux.Handle("POST /api/go/auth/poll", a.authenticate(a.csrf(http.HandlerFunc(a.handleGoAuthPoll)))) - mux.Handle("DELETE /api/go/auth", a.authenticate(a.csrf(http.HandlerFunc(a.handleGoAuthCancel)))) - mux.Handle("DELETE /api/go/connection", a.authenticate(a.csrf(http.HandlerFunc(a.handleGoDisconnect)))) + mux.Handle("GET /api/go/auth", a.authenticate(http.HandlerFunc(a.handleGoOAuthStatus))) + mux.Handle("POST /api/go/auth/start", a.authenticate(a.csrf(http.HandlerFunc(a.handleGoOAuthStart)))) + mux.Handle("POST /api/go/auth/poll", a.authenticate(a.csrf(http.HandlerFunc(a.handleGoOAuthPoll)))) + mux.Handle("DELETE /api/go/auth", a.authenticate(a.csrf(http.HandlerFunc(a.handleGoOAuthCancel)))) + mux.Handle("DELETE /api/go/connection", a.authenticate(a.csrf(http.HandlerFunc(a.handleGoOAuthDisconnect)))) + mux.Handle("GET /api/zen/auth", a.authenticate(http.HandlerFunc(a.handleZenOAuthStatus))) + mux.Handle("POST /api/zen/auth/start", a.authenticate(a.csrf(http.HandlerFunc(a.handleZenOAuthStart)))) + 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/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)))) @@ -267,7 +273,8 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { candidate := config.Config{ ServerKeyMetadata: current.ServerKeyMetadata, Rotation: current.Rotation, - GoSubscription: current.GoSubscription, + GoOAuth: current.GoOAuth, + 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, @@ -275,10 +282,11 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes}, } result, err := a.manager.Update(func(latest *config.Config) error { - if !a.goAuthSessionValid(goAuthOwner(r), *latest) { + if !a.sessionValid(sessionID(r), *latest) { return errors.New("management session is no longer active") } - candidate.GoSubscription = latest.GoSubscription + candidate.GoOAuth = latest.GoOAuth + candidate.ZenOAuth = latest.ZenOAuth candidate.ServerKeyMetadata = latest.ServerKeyMetadata candidate.Rotation = latest.Rotation candidate.WebUI.Username = latest.WebUI.Username @@ -288,6 +296,23 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { } if update.ProxyBindings == nil { candidate.ProxyBindings = latest.ProxyBindings + } else { + for key, proxy := range candidate.ProxyBindings { + if existing, ok := latest.ProxyBindings[key]; ok && proxy == config.RedactURL(existing) { + candidate.ProxyBindings[key] = existing + } + } + } + // A masked URL returned by GET must preserve its original userinfo + // when an operator edits unrelated settings. + if candidate.Upstream.Zen == config.RedactURL(latest.Upstream.Zen) { + candidate.Upstream.Zen = latest.Upstream.Zen + } + if candidate.Upstream.Go == config.RedactURL(latest.Upstream.Go) { + candidate.Upstream.Go = latest.Upstream.Go + } + if candidate.Upstream.Anonymous == config.RedactURL(latest.Upstream.Anonymous) { + candidate.Upstream.Anonymous = latest.Upstream.Anonymous } *latest = candidate return nil @@ -367,6 +392,10 @@ func (a *Server) handleLogStream(w http.ResponseWriter, r *http.Request) { if queryAfter, err := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64); err == nil && queryAfter > after { after = queryAfter } + // Subscribe before taking the snapshot so an event published during replay + // is queued. The live loop skips events already included in the snapshot. + stream, unsubscribe := a.logs.Subscribe() + defer unsubscribe() recent, gap := a.logs.Recent(after, 2000) if gap { _ = httpx.WriteSSE(w, "gap", 0, map[string]any{"message": "older log events have expired"}) @@ -378,8 +407,6 @@ func (a *Server) handleLogStream(w http.ResponseWriter, r *http.Request) { after = event.Sequence } flusher.Flush() - stream, unsubscribe := a.logs.Subscribe() - defer unsubscribe() cookie, _ := r.Cookie(adminCookieName) keepAlive := time.NewTicker(20 * time.Second) defer keepAlive.Stop() @@ -388,6 +415,12 @@ func (a *Server) handleLogStream(w http.ResponseWriter, r *http.Request) { case <-r.Context().Done(): return case event := <-stream: + if event.Sequence <= after { + continue + } + if cookie == nil || !a.sessionTokenValid(cookie.Value) { + return + } if after > 0 && event.Sequence > after+1 { _ = httpx.WriteSSE(w, "gap", 0, map[string]any{"message": "slow client missed log events", "after": after, "next": event.Sequence}) } @@ -409,27 +442,24 @@ func (a *Server) handleLogStream(w http.ResponseWriter, r *http.Request) { // sessionTokenValid reports whether token still names a live session that // belongs to the current username and password hash. func (a *Server) sessionTokenValid(token string) bool { - a.mu.Lock() - session, ok := a.sessions[tokenDigest(token)] - if ok && time.Now().After(session.Expires) { - delete(a.sessions, tokenDigest(token)) - ok = false - } - a.mu.Unlock() - if !ok { - return false - } - cfg := a.manager.Config() - return session.Username == cfg.WebUI.Username && session.AuthVersion == config.Fingerprint(cfg.WebUI.PasswordHash) + return a.sessionValid(tokenDigest(token), a.manager.Config()) } // configView builds the masked view of the current configuration. func (a *Server) configView() ConfigView { cfg := a.manager.Config() effective, restart := a.manager.RestartStatus() + proxyBindings := make(map[string]string, len(cfg.ProxyBindings)) + for key, proxy := range cfg.ProxyBindings { + proxyBindings[key] = config.RedactURL(proxy) + } + upstream := cfg.Upstream + upstream.Zen = config.RedactURL(upstream.Zen) + upstream.Go = config.RedactURL(upstream.Go) + upstream.Anonymous = config.RedactURL(upstream.Anonymous) return ConfigView{ Listen: cfg.Listen, ServerKeys: maskSecrets(cfg.ServerKeys, false), ZenKeys: maskSecrets(cfg.ZenKeys, false), GoKeys: maskSecrets(cfg.GoKeys, false), Anonymous: cfg.Anonymous, Warp: cfg.Warp, - Proxies: maskSecrets(cfg.Proxies, true), ProxyFile: cfg.ProxyFile, ProxyBindings: cfg.ProxyBindings, Upstream: cfg.Upstream, Retry: cfg.Retry, Models: cfg.Models, + Proxies: maskSecrets(cfg.Proxies, true), ProxyFile: cfg.ProxyFile, ProxyBindings: proxyBindings, Upstream: upstream, Retry: cfg.Retry, Models: cfg.Models, Performance: cfg.Performance, Logging: cfg.Logging, Prefer: cfg.Prefer, Reasoning: cfg.Reasoning, WebUI: WebUIView{Enabled: cfg.WebUI.Enabled, Listen: cfg.WebUI.Listen, Username: cfg.WebUI.Username, SessionTTLMinutes: cfg.WebUI.SessionTTLMinutes}, Effective: EffectiveView{Listen: effective.API, WebUIListen: effective.WebUI, WebUIEnabled: effective.WebUIEnabled}, diff --git a/internal/config/config.go b/internal/config/config.go index f64a173..49cbb28 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -13,8 +13,8 @@ import ( "time" "unicode" - "opencode2api/internal/goauth" "opencode2api/internal/jsonutil" + "opencode2api/internal/oauth" wire "opencode2api/internal/protocol" "opencode2api/internal/warp" ) @@ -34,7 +34,8 @@ type Config struct { ServerKeyMetadata map[string]ServerKeyMetadata `json:"server_key_metadata,omitempty"` ZenKeys []string `json:"zen_keys"` GoKeys []string `json:"go_keys"` - GoSubscription *goauth.Connection `json:"go_subscription,omitempty"` + GoOAuth *oauth.Connection `json:"go_oauth,omitempty"` + ZenOAuth *oauth.Connection `json:"zen_oauth,omitempty"` Anonymous bool `json:"anonymous"` Warp WarpConfig `json:"warp"` Proxies []string `json:"proxies"` @@ -334,6 +335,10 @@ func Load(path string) (Config, error) { if err != nil { return Config{}, fmt.Errorf("parse %s: %w", path, err) } + data, err = migrateOAuthFields(data) + if err != nil { + return Config{}, fmt.Errorf("parse %s: %w", path, err) + } cfg := Config{ Listen: "127.0.0.1:8080", Anonymous: false, @@ -380,10 +385,20 @@ func Normalize(path string, cfg Config) (Config, error) { if err := resolveProxyFiles(path, &cfg); err != nil { return Config{}, err } - if cfg.GoSubscription != nil { - connection := cloneGoSubscription(cfg.GoSubscription) - if err := connection.Validate(); err != nil { - return Config{}, errors.New("go_subscription contains an invalid credential or unsupported subscription route") + for _, account := range []struct { + name string + plan oauth.Plan + connection **oauth.Connection + }{ + {"go_oauth", oauth.PlanGo, &cfg.GoOAuth}, + {"zen_oauth", oauth.PlanZen, &cfg.ZenOAuth}, + } { + if *account.connection == nil { + continue + } + connection := cloneOAuth(*account.connection) + if err := connection.ValidateForPlan(account.plan); err != nil { + return Config{}, fmt.Errorf("%s contains an invalid credential or unsupported OAuth route", account.name) } connection.Proxy = strings.TrimSpace(connection.Proxy) if connection.Proxy != "" { @@ -395,10 +410,10 @@ func Normalize(path string, cfg Config) (Config, error) { } } if !matched { - return Config{}, errors.New("go_subscription.proxy must name a configured proxy") + return Config{}, fmt.Errorf("%s.proxy must name a configured proxy", account.name) } } - cfg.GoSubscription = connection + *account.connection = connection } if cfg.Prefer != TierZen && cfg.Prefer != TierGo { return Config{}, errors.New("prefer must be \"zen\" or \"go\"") @@ -435,8 +450,8 @@ func Normalize(path string, cfg Config) (Config, error) { if cfg.FirstEnabledServerKey() == "" { return Config{}, errors.New("at least one server key must remain enabled") } - if !cfg.Anonymous && len(cfg.ZenKeys) == 0 && len(cfg.GoKeys) == 0 && cfg.GoSubscription == nil { - return Config{}, errors.New("configure a Zen API Key (zen_keys), a Go key (go_keys), or a Go subscription (go_subscription); anonymous access is disabled by default and may be blocked upstream") + if !cfg.Anonymous && len(cfg.ZenKeys) == 0 && len(cfg.GoKeys) == 0 && cfg.GoOAuth == nil && cfg.ZenOAuth == nil { + return Config{}, errors.New("configure a Zen API Key (zen_keys), a Go key (go_keys), or a saved Go/Zen OAuth connection; anonymous access is disabled by default and may be blocked upstream") } if cfg.Retry.MaxAttempts < 1 { return Config{}, errors.New("retry.max_attempts must be at least 1") @@ -556,6 +571,9 @@ func normalizeReasoning(cfg *Config) error { if err := validateEffort(fmt.Sprintf("reasoning.effort_by_model[%q]", key), level); err != nil { return err } + if existing, exists := normalized[key]; exists && existing != level { + return errors.New("reasoning.effort_by_model contains conflicting entries for the same model ID") + } normalized[key] = level } cfg.Reasoning.EffortByModel = normalized @@ -598,15 +616,6 @@ func (cfg Config) RuntimeProxies() []string { return []string{"direct"} } -// PasswordForSave clears the resolved proxy list (the proxies plus proxyfile -// entries that RuntimeProxies returns), leaving only Config.Proxies; despite -// its name it does not touch the WebUI password. SaveAtomic calls it on its -// own copy before encoding. The field is unexported and so never encoded -// anyway, which makes the call a guard rather than a requirement. -func (cfg *Config) PasswordForSave() { - cfg.effectiveProxies = nil -} - // Clone returns a copy of cfg whose slices and maps, including the rotation // orders and the resolved proxy list, no longer share storage with cfg. func Clone(cfg Config) Config { @@ -620,7 +629,8 @@ func Clone(cfg Config) Config { cfg.ServerKeyMetadata = metadata cfg.ZenKeys = append([]string(nil), cfg.ZenKeys...) cfg.GoKeys = append([]string(nil), cfg.GoKeys...) - cfg.GoSubscription = cloneGoSubscription(cfg.GoSubscription) + cfg.GoOAuth = cloneOAuth(cfg.GoOAuth) + cfg.ZenOAuth = cloneOAuth(cfg.ZenOAuth) cfg.Proxies = append([]string(nil), cfg.Proxies...) cfg.effectiveProxies = append([]string(nil), cfg.effectiveProxies...) if cfg.Upstream.PromptEnvironment != nil { @@ -655,12 +665,12 @@ func Clone(cfg Config) Config { return cfg } -func cloneGoSubscription(source *goauth.Connection) *goauth.Connection { +func cloneOAuth(source *oauth.Connection) *oauth.Connection { if source == nil { return nil } connection := *source - connection.Routes = make(map[string]goauth.Route, len(source.Routes)) + connection.Routes = make(map[string]oauth.Route, len(source.Routes)) for model, route := range source.Routes { connection.Routes[model] = route } @@ -680,24 +690,27 @@ func normalizeProxyBindings(cfg *Config) error { return nil } keyMap := make(map[string]string, len(cfg.ZenKeys)+len(cfg.GoKeys)) - for _, k := range cfg.ZenKeys { - fp := Fingerprint(k) - keyMap[k] = fp - keyMap[fp] = fp + for _, key := range cfg.ZenKeys { + fingerprint := Fingerprint(key) + keyMap[key] = fingerprint + keyMap[fingerprint] = fingerprint } - for _, k := range cfg.GoKeys { - fp := Fingerprint(k) - keyMap[k] = fp - keyMap[fp] = fp + for _, key := range cfg.GoKeys { + fingerprint := Fingerprint(key) + keyMap[key] = fingerprint + keyMap[fingerprint] = fingerprint } knownProxies := make(map[string]string) for _, raw := range cfg.RuntimeProxies() { - clean, _ := ParseProxyEntry(raw) knownProxies[raw] = raw - knownProxies[clean] = raw - if clean == "direct" { - knownProxies["direct"] = "direct" + } + for _, raw := range cfg.RuntimeProxies() { + clean, _ := ParseProxyEntry(raw) + // An explicitly configured static route wins over the clean alias of + // a pool route that happens to dial the same endpoint. + if _, exists := knownProxies[clean]; !exists { + knownProxies[clean] = raw } } @@ -705,7 +718,7 @@ func normalizeProxyBindings(cfg *Config) error { for keyRef, proxyRef := range cfg.ProxyBindings { trimmedKey := strings.TrimSpace(keyRef) trimmedProxy := strings.TrimSpace(proxyRef) - fp, ok := keyMap[trimmedKey] + fingerprint, ok := keyMap[trimmedKey] if !ok { return fmt.Errorf("proxy_bindings contains reference to unknown key %q", MaskValue(trimmedKey)) } @@ -713,7 +726,10 @@ func normalizeProxyBindings(cfg *Config) error { if !ok { return fmt.Errorf("proxy_bindings references unknown proxy %q", RedactURL(trimmedProxy)) } - normalized[fp] = canonicalProxy + if existing, exists := normalized[fingerprint]; exists && existing != canonicalProxy { + return errors.New("proxy_bindings contains conflicting entries for the same key") + } + normalized[fingerprint] = canonicalProxy } cfg.ProxyBindings = normalized return nil diff --git a/internal/config/json.go b/internal/config/json.go index 11526d3..e19ca7f 100644 --- a/internal/config/json.go +++ b/internal/config/json.go @@ -2,9 +2,64 @@ package config import ( "bytes" + "encoding/json" "errors" + "io" + "strings" ) +// migrateOAuthFields preserves legacy account settings while rejecting +// aliases that would otherwise overwrite each other during JSON decoding. +func migrateOAuthFields(data []byte) ([]byte, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + opening, err := decoder.Token() + if err != nil || opening != json.Delim('{') { + return nil, errors.New("configuration must be a JSON object") + } + fields := make(map[string]json.RawMessage) + seen := make(map[string]bool) + changed := false + for decoder.More() { + token, err := decoder.Token() + name, ok := token.(string) + if err != nil || !ok { + return nil, errors.New("invalid configuration JSON") + } + folded := strings.ToLower(name) + if seen[folded] { + return nil, errors.New("configuration fields must not be repeated") + } + seen[folded] = true + canonical := name + for _, names := range [][2]string{{"go_subscription", "go_oauth"}, {"zen_subscription", "zen_oauth"}} { + if strings.EqualFold(name, names[0]) || strings.EqualFold(name, names[1]) { + canonical = names[1] + changed = changed || canonical != name + break + } + } + if _, exists := fields[canonical]; exists { + return nil, errors.New("legacy and current OAuth configuration fields must not be combined") + } + var value json.RawMessage + if err := decoder.Decode(&value); err != nil { + return nil, errors.New("invalid configuration JSON") + } + fields[canonical] = value + } + if closing, err := decoder.Token(); err != nil || closing != json.Delim('}') { + return nil, errors.New("invalid configuration JSON") + } + var extra any + if decoder.Decode(&extra) != io.EOF { + return nil, errors.New("configuration must contain one JSON object") + } + if !changed { + return data, nil + } + return json.Marshal(fields) +} + // stripJSONComments removes // and /* */ comments by overwriting each comment // byte with a space but keeping newlines, so a position in the result is on // the same line as in config.json. Comment markers inside JSON strings (for diff --git a/internal/config/persistence.go b/internal/config/persistence.go index 1dc75e1..2e5b0c3 100644 --- a/internal/config/persistence.go +++ b/internal/config/persistence.go @@ -10,8 +10,8 @@ import ( "runtime" ) -// SaveAtomic writes cfg to path as indented JSON, after clearing the resolved -// proxy list (see PasswordForSave). It does not normalize cfg; callers pass a +// SaveAtomic writes cfg to path as indented JSON. The unexported runtime proxy +// list is never encoded. It does not normalize cfg; callers pass a // config that Normalize already accepted. An existing file is kept as // path+".bak". // @@ -23,7 +23,6 @@ import ( // replacement is renamed into place. If the replacement fails, the original // is restored and both replacement and rollback errors are returned. func SaveAtomic(path string, cfg Config) error { - cfg.PasswordForSave() data, err := json.MarshalIndent(cfg, "", " ") if err != nil { return fmt.Errorf("encode config: %w", err) diff --git a/internal/config/secrets.go b/internal/config/secrets.go index 8137b82..f961d88 100644 --- a/internal/config/secrets.go +++ b/internal/config/secrets.go @@ -7,6 +7,8 @@ import ( "sort" "strings" "sync/atomic" + + "opencode2api/internal/oauth" ) // MaskValue hides a secret for display: "••••" followed by its last five @@ -44,14 +46,14 @@ func RedactURL(raw string) string { // messages. It is safe for concurrent use: Replace swaps the whole secret set // atomically. type Redactor struct { - values atomic.Value + replacer atomic.Value } // SecretRedactor returns a Redactor with no secrets loaded; Replace loads // them. func SecretRedactor() *Redactor { r := &Redactor{} - r.values.Store([]string(nil)) + r.replacer.Store(strings.NewReplacer()) return r } @@ -66,10 +68,13 @@ func (r *Redactor) Replace(cfg Config) { values = append(values, cfg.ServerKeys...) values = append(values, cfg.ZenKeys...) values = append(values, cfg.GoKeys...) - if cfg.GoSubscription != nil { - values = append(values, cfg.GoSubscription.Credential.AccessToken, cfg.GoSubscription.Credential.RefreshToken) - if cfg.GoSubscription.Proxy != "" { - values = append(values, cfg.GoSubscription.Proxy) + for _, connection := range []*oauth.Connection{cfg.GoOAuth, cfg.ZenOAuth} { + if connection == nil { + continue + } + values = append(values, connection.Credential.AccessToken, connection.Credential.RefreshToken) + if connection.Proxy != "" { + values = append(values, connection.Proxy) } } if cfg.WebUI.Password != "" { @@ -96,18 +101,26 @@ func (r *Redactor) Replace(cfg Config) { } } sort.Slice(values, func(i, j int) bool { return len(values[i]) > len(values[j]) }) - r.values.Store(values) + replacements := make([]string, 0, 2*len(values)) + seen := make(map[string]bool, len(values)) + for _, value := range values { + if value == "" || seen[value] { + continue + } + seen[value] = true + replacements = append(replacements, value, "***") + } + r.replacer.Store(strings.NewReplacer(replacements...)) } -// String returns value with every loaded secret of at least four bytes -// replaced by "***". +// String replaces every non-empty configured secret. One pass prevents a +// short secret from rewriting masking text produced for another secret. func (r *Redactor) String(value string) string { - for _, secret := range r.values.Load().([]string) { - if len(secret) >= 4 { - value = strings.ReplaceAll(value, secret, "***") - } + replacer, _ := r.replacer.Load().(*strings.Replacer) + if replacer == nil { + return value } - return value + return replacer.Replace(value) } // Fingerprint returns the first 16 hex digits of the SHA-256 of value. It is @@ -120,14 +133,15 @@ func Fingerprint(value string) string { return hex.EncodeToString(sum[:])[:16] } -// KeyDisplayID returns the last five characters of value, or the whole value -// when it has five characters or fewer. It is intentionally separate from +// KeyDisplayID returns the last five characters of value, or its fingerprint +// when it has five characters or fewer so a short key is never disclosed in +// full. It is intentionally separate from // Fingerprint: it is meant to be read by a person, and it is the key_id of an // upstream key in logs, request telemetry and the key status list. func KeyDisplayID(value string) string { runes := []rune(value) if len(runes) <= 5 { - return string(runes) + return Fingerprint(value) } return string(runes[len(runes)-5:]) } diff --git a/internal/gateway/availability.go b/internal/gateway/availability.go index ad5a8b6..03c6837 100644 --- a/internal/gateway/availability.go +++ b/internal/gateway/availability.go @@ -2,9 +2,7 @@ package gateway import ( "context" - "errors" - "time" "opencode2api/internal/models" diff --git a/internal/gateway/first_event.go b/internal/gateway/first_event.go index 14c5f69..ea1b57a 100644 --- a/internal/gateway/first_event.go +++ b/internal/gateway/first_event.go @@ -83,9 +83,6 @@ func (e *phasedError) Unwrap() error { return e.err } // client gets a proxy error instead of a generic bad gateway. var errProxyUnavailable = errors.New("proxy unavailable") -// proxyUnavailableError is an attempt error that asProxyUnavailable attributed -// to the proxy route. It matches both errProxyUnavailable and the original -// error under errors.Is and errors.As. // timeoutStatus classifies an exhausted request budget for the client. // // A write-phase failure means the upstream never finished reading the request @@ -134,6 +131,8 @@ func isPayloadTooLarge(err error, budgetAlive bool) bool { return errors.Is(err, errAttemptTimeout) || errors.Is(err, context.DeadlineExceeded) } +// proxyUnavailableError attributes an attempt failure to its proxy route while +// preserving both the proxy-unavailable marker and the original error. type proxyUnavailableError struct { proxy string err error diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index f7fe982..c676685 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -9,8 +9,7 @@ // and, on the free tier, the 1.x toolset. The v2 lane is the /inference // origin (upstream.anonymous) and the Go plan's /zen/go origin, which expect // the OpenCode 2.x CLI shape. The anonymous free tier uses the configured v2 -// /inference origin only; the retired v1 fallback is kept in -// anonymousUpstreams but commented out. +// /inference origin only. package gateway import ( @@ -28,11 +27,11 @@ import ( "time" "opencode2api/internal/config" - "opencode2api/internal/goauth" "opencode2api/internal/httpx" "opencode2api/internal/identity" "opencode2api/internal/jsonutil" "opencode2api/internal/models" + "opencode2api/internal/oauth" wire "opencode2api/internal/protocol" "opencode2api/internal/rotation" "opencode2api/internal/telemetry" @@ -76,6 +75,7 @@ type Gateway struct { rotation *rotation.Manager cfg config.Config logger *slog.Logger + redactor *config.Redactor transports *proxyTransports zenNodes *upstreamNodes goNodes *upstreamNodes @@ -96,9 +96,11 @@ type Gateway struct { // anonymous cursor. Zero uses freeTierBlockTTL. freeTierBlock time.Duration // refreshMu prevents overlapping catalog refreshes across concurrent or scheduled callers. - refreshMu sync.Mutex - resolveGoSubscription func(context.Context) (*goauth.Connection, error) - onGoSubscriptionUnauthorized func(context.Context, goauth.Credential) + refreshMu sync.Mutex + resolveGoOAuth func(context.Context) (*oauth.Connection, error) + onGoOAuthUnauthorized func(context.Context, oauth.Credential) + resolveZenOAuth func(context.Context) (*oauth.Connection, error) + onZenOAuthUnauthorized func(context.Context, oauth.Credential) } // New builds a Gateway for cfg: one proxy transport per runtime proxy (a @@ -120,12 +122,16 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, war return nil, err } cooldown := time.Duration(cfg.Performance.FailureCooldownSeconds) * time.Second - zenNodes, err := nodePool(cfg.ZenKeys, transports, cooldown, cfg.ProxyBindings) + zenKeys := cfg.ZenKeys + if cfg.ZenOAuth != nil { + zenKeys = nil + } + zenNodes, err := nodePool(zenKeys, transports, cooldown, cfg.ProxyBindings) if err != nil { return nil, fmt.Errorf("zen node pool: %w", err) } goKeys := cfg.GoKeys - if cfg.GoSubscription != nil { + if cfg.GoOAuth != nil { goKeys = nil } goNodes, err := nodePool(goKeys, transports, cooldown, cfg.ProxyBindings) @@ -135,10 +141,13 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, war catalog := models.Catalog(cfg.Prefer, cfg.Models.Protocols) catalog.SetRefreshInterval(time.Duration(cfg.Models.RefreshSeconds) * time.Second) catalog.SetFreeOnly(cfg.Models.FreeOnly) + redactor := config.SecretRedactor() + redactor.Replace(cfg) gateway := &Gateway{ cfg: cfg, rotation: rotationManager, logger: logger, + redactor: redactor, transports: transports, zenNodes: zenNodes, goNodes: goNodes, @@ -149,7 +158,7 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, war attemptTimeout: attemptDeadline(cfg), freeTierBlock: time.Duration(cfg.Performance.FreeTierBlockSeconds) * time.Second, } - gateway.restoreGoSubscriptionCatalog() + gateway.restoreOAuthCatalog() return gateway, nil } @@ -285,11 +294,14 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { g.handleRotation(w, r, external, payload, id, model) return } - subscriptionModel := false - if g.cfg.GoSubscription != nil { - _, subscriptionModel = g.cfg.GoSubscription.Routes[model] + oauthModel := false + for _, connection := range []*oauth.Connection{g.cfg.GoOAuth, g.cfg.ZenOAuth} { + if connection != nil { + _, included := connection.Routes[model] + oauthModel = oauthModel || included + } } - if !subscriptionModel && !g.catalog.Supported(model) { + if !oauthModel && !g.catalog.Supported(model) { // A model the catalog has never heard of is a bad model NAME: 404 // tells a client to pick a different model. A model the catalog // knows but cannot serve is a capability or routing problem, and @@ -312,9 +324,9 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { route, err = g.routeForModel(model, override.Tier) } if err != nil { - var oauthError *goauth.OAuthError + var oauthError *oauth.OAuthError if errors.As(err, &oauthError) { - wire.WriteError(w, external, http.StatusServiceUnavailable, oauthError.Error(), "subscription_auth_error", "") + wire.WriteError(w, external, http.StatusServiceUnavailable, oauthError.Error(), "oauth_auth_error", "") return } wire.WriteError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "model") @@ -399,9 +411,9 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { wire.WriteError(w, external, status, message, code, ids.Request) return } - var subscriptionError *goauth.OAuthError - if errors.As(err, &subscriptionError) { - wire.WriteError(w, external, http.StatusServiceUnavailable, subscriptionError.Error(), "subscription_auth_error", ids.Request) + var oauthError *oauth.OAuthError + if errors.As(err, &oauthError) { + wire.WriteError(w, external, http.StatusServiceUnavailable, oauthError.Error(), "oauth_auth_error", ids.Request) return } // Every exit this request could use is under the free tier's IP @@ -429,7 +441,7 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { } w.Header().Set("x-request-id", ids.Request) if resp.StatusCode/100 != 2 { - copyErrorResponse(w, external, resp, ids.Request) + g.copyErrorResponse(w, external, resp, ids.Request) return } shape := requestShapeFrom(r.Context()) @@ -445,13 +457,17 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("X-Accel-Buffering", "no") - w.WriteHeader(resp.StatusCode) streamBody := wire.RenameStreamReader(resp.Body, upstreamRoute.Protocol, toolRenames) var usage wire.Usage var usageReported bool if external == upstreamRoute.Protocol { - usage, usageReported, err = wire.ForwardStream(r.Context(), w, streamBody, upstreamRoute.Protocol, model) + streamWriter := w + if flusher, ok := w.(http.Flusher); ok { + streamWriter = &deferredStreamWriter{ResponseWriter: w, flusher: flusher, status: resp.StatusCode} + } + usage, usageReported, err = wire.ForwardStream(r.Context(), streamWriter, streamBody, upstreamRoute.Protocol, model) } else { + w.WriteHeader(resp.StatusCode) usage, usageReported, err = wire.TranscodeStream(r.Context(), w, streamBody, upstreamRoute.Protocol, external, model) } if meta != nil { @@ -468,11 +484,15 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { } return } - responseBody, err := io.ReadAll(io.LimitReader(resp.Body, 64<<20)) + responseBody, err := io.ReadAll(io.LimitReader(resp.Body, (64<<20)+1)) if err != nil { wire.WriteError(w, external, http.StatusBadGateway, "failed to read upstream response", "upstream_error", ids.Request) return } + if len(responseBody) > 64<<20 { + wire.WriteError(w, external, http.StatusBadGateway, "upstream response exceeds 64 MiB", "upstream_error", ids.Request) + return + } if upstreamRoute.Anonymous || shape.shaped { // The anonymous lane, and a key-tier request shaped like it, is // force-streamed upstream (see prepareAnonymousBody); collapse @@ -504,6 +524,32 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { } } +// deferredStreamWriter keeps the upstream success status pending while the +// first SSE frame is validated, allowing an invalid prelude to become a 502. +type deferredStreamWriter struct { + http.ResponseWriter + flusher http.Flusher + status int + committed bool +} + +func (w *deferredStreamWriter) WriteHeader(status int) { + if !w.committed { + w.committed = true + w.ResponseWriter.WriteHeader(status) + } +} + +func (w *deferredStreamWriter) Write(body []byte) (int, error) { + w.WriteHeader(w.status) + return w.ResponseWriter.Write(body) +} + +func (w *deferredStreamWriter) Flush() { + w.WriteHeader(w.status) + w.flusher.Flush() +} + // handleSystemOne serves System One decision requests on their own endpoint. // Only models whose upstream protocol is System One can be served here; a chat // or responses model belongs on its own endpoint, where the bridge can convert @@ -618,7 +664,7 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body } w.Header().Set("x-request-id", ids.Request) if resp.StatusCode/100 != 2 { - copyErrorResponse(w, wire.SystemOne, resp, ids.Request) + g.copyErrorResponse(w, wire.SystemOne, resp, ids.Request) return } if contentType := resp.Header.Get("Content-Type"); strings.HasPrefix(contentType, "text/event-stream") { @@ -631,11 +677,15 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body _, _ = io.Copy(w, resp.Body) return } - responseBody, err := io.ReadAll(io.LimitReader(resp.Body, 64<<20)) + responseBody, err := io.ReadAll(io.LimitReader(resp.Body, (64<<20)+1)) if err != nil { wire.WriteError(w, wire.SystemOne, http.StatusBadGateway, "failed to read upstream response", "upstream_error", ids.Request) return } + if len(responseBody) > 64<<20 { + wire.WriteError(w, wire.SystemOne, http.StatusBadGateway, "upstream response exceeds 64 MiB", "upstream_error", ids.Request) + return + } if usage, reported := wire.ResponseUsage(upstreamRoute.Protocol, responseBody); meta != nil { meta.Usage, meta.UsageReported = usage, reported } @@ -672,13 +722,13 @@ func (g *Gateway) prepareRouteBodies(from wire.Protocol, route models.Route, inp baseURL := g.cfg.Upstream.Zen if tier == config.TierGo { baseURL = g.cfg.Upstream.Go - if g.cfg.GoSubscription != nil { - subscriptionRoute, ok := g.cfg.GoSubscription.Routes[route.ID] - if !ok { - return nil, errors.New("model is not included in the connected Go subscription") - } - baseURL = subscriptionRoute.BaseURL + } + if connection := g.tierOAuth(tier); connection != nil && !route.Anonymous { + oauthRoute, ok := connection.Routes[route.ID] + if !ok { + return nil, errors.New("model is not included in the connected OAuth plan") } + baseURL = oauthRoute.BaseURL } upstreamPayload, err := wire.PrepareRequest(from, protocol, input, baseURL) if err != nil { @@ -708,15 +758,17 @@ func (g *Gateway) prepareRouteBodies(from wire.Protocol, route models.Route, inp // client's protocol. It keeps the status and any Retry-After, and takes the // message from a JSON body's error.message or message, falling back to the // status text. -func copyErrorResponse(w http.ResponseWriter, protocol wire.Protocol, resp *http.Response, requestID string) { +func (g *Gateway) copyErrorResponse(w http.ResponseWriter, protocol wire.Protocol, resp *http.Response, requestID string) { body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) if retryAfter := resp.Header.Get("Retry-After"); retryAfter != "" { - w.Header().Set("Retry-After", retryAfter) + w.Header().Set("Retry-After", g.redactor.String(retryAfter)) } message := http.StatusText(resp.StatusCode) var value map[string]any if json.Unmarshal(body, &value) == nil { message = jsonutil.FirstString(jsonutil.StringAt(value, "error", "message"), jsonutil.StringAt(value, "message"), message) } - wire.WriteError(w, protocol, resp.StatusCode, message, "upstream_error", requestID) + // Error bodies may echo the credential that the upstream rejected. Decode + // first so escaped JSON strings receive the same redaction as plain text. + wire.WriteError(w, protocol, resp.StatusCode, g.redactor.String(message), "upstream_error", requestID) } diff --git a/internal/gateway/gosubscription.go b/internal/gateway/gosubscription.go deleted file mode 100644 index 2d3d9b9..0000000 --- a/internal/gateway/gosubscription.go +++ /dev/null @@ -1,372 +0,0 @@ -package gateway - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/binary" - "encoding/json" - "errors" - "io" - "net/http" - "sort" - "strconv" - "strings" - "time" - - "opencode2api/internal/config" - "opencode2api/internal/goauth" - "opencode2api/internal/httpx" - "opencode2api/internal/identity" - "opencode2api/internal/models" - wire "opencode2api/internal/protocol" - "opencode2api/internal/telemetry" -) - -func (g *Gateway) goAvailable() bool { - return g.cfg.GoSubscription != nil || g.goNodes.Len() > 0 -} - -func (g *Gateway) routeForModel(model string, tier config.Tier) (models.Route, error) { - if connection := g.cfg.GoSubscription; connection != nil { - if subscriptionRoute, ok := connection.Routes[model]; ok && (tier == "" || tier == config.TierGo) { - if connection.NeedsLogin { - return models.Route{}, &goauth.OAuthError{Code: "invalid_grant"} - } - if g.cfg.Models.FreeOnly && !g.catalog.IsFreeModel(model) { - return models.Route{}, errors.New("this subscription model is excluded by models.free_only") - } - return models.Route{ - ID: model, Tier: config.TierGo, Protocol: subscriptionRoute.Protocol, - Protocols: map[config.Tier]wire.Protocol{config.TierGo: subscriptionRoute.Protocol}, - KeyTiers: []config.Tier{config.TierGo}, - }, nil - } - if tier == config.TierGo { - return models.Route{}, errors.New("model is not included in the connected Go subscription") - } - } - if tier != "" { - return g.catalog.RouteForTier(model, tier, g.zenNodes.Len() > 0, g.goAvailable()) - } - return g.catalog.Route(model, g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous) -} - -func (g *Gateway) seedGoSubscriptionCatalog(capabilities *models.Capabilities) []string { - connection := g.cfg.GoSubscription - if connection == nil { - return nil - } - if capabilities.Protocols == nil { - capabilities.Protocols = map[config.Tier]map[string]wire.Protocol{} - } - if capabilities.Unsupported == nil { - capabilities.Unsupported = map[config.Tier]map[string]bool{} - } - protocols := make(map[string]wire.Protocol, len(connection.Routes)) - modelIDs := make([]string, 0, len(connection.Routes)) - for model, route := range connection.Routes { - modelIDs = append(modelIDs, model) - protocols[model] = route.Protocol - } - sort.Strings(modelIDs) - capabilities.Protocols[config.TierGo] = protocols - capabilities.Unsupported[config.TierGo] = map[string]bool{} - return modelIDs -} - -func (g *Gateway) restoreGoSubscriptionCatalog() { - if g.cfg.GoSubscription == nil { - return - } - capabilities := models.Capabilities{} - modelIDs := g.seedGoSubscriptionCatalog(&capabilities) - g.catalog.ReplaceWithCapabilities(nil, modelIDs, capabilities.Protocols, capabilities.Unsupported, nil) -} - -func (g *Gateway) subscriptionConnection(ctx context.Context) (*goauth.Connection, error) { - snapshot := g.cfg.GoSubscription - if snapshot == nil { - return nil, errors.New("Go subscription is not connected") - } - connection := snapshot - if g.resolveGoSubscription != nil { - resolved, err := g.resolveGoSubscription(ctx) - if err != nil { - return nil, err - } - connection = resolved - } - if connection == nil || connection.Credential.AccountID != snapshot.Credential.AccountID || connection.Credential.OrganizationID != snapshot.Credential.OrganizationID || connection.Proxy != snapshot.Proxy { - return nil, errors.New("Go subscription connection changed; retry with the current configuration") - } - if connection.NeedsLogin { - return nil, &goauth.OAuthError{Code: "invalid_grant"} - } - if err := connection.Validate(); err != nil { - return nil, err - } - if !time.Now().Before(connection.Credential.ExpiresAt) { - return nil, &goauth.OAuthError{Code: "expired_token"} - } - return connection, nil -} - -func subscriptionAccountID(connection *goauth.Connection) string { - return config.Fingerprint(connection.Credential.AccountID + "\x00" + connection.Credential.OrganizationID) -} - -func (g *Gateway) subscriptionProxy(ctx context.Context, connection *goauth.Connection, affinity string, offset int) (*proxyTransport, error) { - if g.transports == nil || len(g.transports.items) == 0 { - return nil, errProxyUnavailable - } - var pinned *proxyTransport - if selection, selected := relayOverrideFrom(ctx); selected { - var found bool - pinned, found = g.RelayProxy(selection) - if !found { - return nil, errRelayNotFound - } - } - if connection.Proxy != "" { - for _, proxy := range g.transports.items { - if proxy == nil || proxy.name != connection.Proxy { - continue - } - if pinned != nil && pinned != proxy { - return nil, errors.New("the selected relay conflicts with the Go subscription proxy binding") - } - if !proxy.healthy.Load() && !isDiagnosticRequest(ctx) { - return nil, errProxyUnavailable - } - return proxy, nil - } - return nil, errProxyUnavailable - } - if pinned != nil { - return pinned, nil - } - digest := sha256.Sum256([]byte(subscriptionAccountID(connection) + "\x00" + affinity)) - start := int(binary.LittleEndian.Uint64(digest[:8]) % uint64(len(g.transports.items))) - for step := range len(g.transports.items) { - proxy := g.transports.items[(start+offset+step)%len(g.transports.items)] - if proxy != nil && proxy.healthy.Load() { - return proxy, nil - } - } - return nil, errProxyUnavailable -} - -func (g *Gateway) goSubscriptionAttempt(ctx context.Context, route models.Route, body []byte, ids identity.RequestIDs, attempt, offset int, firstEventTimeout time.Duration) (*http.Response, error) { - connection, err := g.subscriptionConnection(ctx) - if err != nil { - return nil, err - } - subscriptionRoute, ok := connection.Routes[route.ID] - if !ok || subscriptionRoute.Protocol != route.Protocol || subscriptionRoute != g.cfg.GoSubscription.Routes[route.ID] { - return nil, errors.New("Go subscription route changed; retry with the current configuration") - } - var payload map[string]json.RawMessage - if err := json.Unmarshal(body, &payload); err != nil || payload == nil { - return nil, errors.New("invalid Go subscription request body") - } - payload["model"], err = json.Marshal(subscriptionRoute.ModelID) - if err != nil { - return nil, errors.New("invalid Go subscription model") - } - body, err = json.Marshal(payload) - if err != nil { - return nil, errors.New("invalid Go subscription request body") - } - proxy, err := g.subscriptionProxy(ctx, connection, ids.Session, offset) - if err != nil { - return nil, err - } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(subscriptionRoute.BaseURL, "/")+wire.Path(subscriptionRoute.Protocol), bytes.NewReader(body)) - if err != nil { - return nil, errors.New("invalid Go subscription endpoint") - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", "Bearer "+connection.Credential.AccessToken) - req.Header.Set("x-opencode-session", ids.Session) - req.Header.Set("User-Agent", httpx.V2UserAgent()) - if connection.Credential.OrganizationID != "" { - req.Header.Set("x-org-id", connection.Credential.OrganizationID) - } - if route.Protocol == wire.Anthropic { - req.Header.Set("anthropic-version", "2023-06-01") - } - req.GetBody = nil - if proxy.pool { - req.Close = true - } - client := *proxy.client - client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } - accountID := subscriptionAccountID(connection) - setRequestCredential(ctx, config.TierGo, accountID, "subscription", false, proxy) - setRequestShape(ctx, false, nil) - if meta := telemetry.MetaFromContext(ctx); meta != nil { - meta.Attempts = attempt - meta.Tier = string(config.TierGo) - } - started := time.Now() - resp, err := doInferenceAttempt(&client, req, firstEventTimeout, g.attemptTimeout) - if resp != nil { - sanitizeGoSubscriptionResponse(resp, connection.Credential) - if resp.StatusCode == http.StatusUnauthorized && g.onGoSubscriptionUnauthorized != nil { - g.onGoSubscriptionUnauthorized(ctx, connection.Credential) - } - } - if err != nil { - err = &goSubscriptionError{cause: err, message: redactGoSubscriptionValue(err.Error(), connection.Credential)} - } - if ctx.Err() == nil && !isDiagnosticRequest(ctx) { - g.syncProxyResult(ctx, proxy, upstreamStatus(resp), err) - } - g.recordUpstreamAttempt(ctx, route, ids, attempt, accountID, "subscription", false, proxy, resp, err, time.Since(started)) - if err != nil { - return resp, asProxyUnavailable(proxy, err) - } - return resp, nil -} - -type goSubscriptionError struct { - cause error - message string -} - -func (err *goSubscriptionError) Error() string { return err.message } -func (err *goSubscriptionError) Unwrap() error { return err.cause } - -func redactGoSubscriptionValue(value string, credential goauth.Credential) string { - secrets := []string{credential.AccessToken, credential.RefreshToken} - if len(secrets[1]) > len(secrets[0]) { - secrets[0], secrets[1] = secrets[1], secrets[0] - } - for _, secret := range secrets { - if secret == "" { - continue - } - value = strings.ReplaceAll(value, secret, "***") - encoded, _ := json.Marshal(secret) - value = strings.ReplaceAll(value, string(encoded[1:len(encoded)-1]), "***") - } - return value -} - -func sanitizeGoSubscriptionResponse(response *http.Response, credential goauth.Credential) { - if response.Header == nil { - response.Header = make(http.Header) - } - response.Request = nil - response.Status = redactGoSubscriptionValue(response.Status, credential) - if response.StatusCode/100 != 2 { - var body []byte - var readErr error - if response.Body != nil { - body, readErr = io.ReadAll(io.LimitReader(response.Body, 1<<20)) - response.Body.Close() - } - if readErr != nil || len(body) >= 1<<20 { - body = []byte(`{"error":{"message":"Go subscription upstream request was rejected"}}`) - response.Header.Set("Content-Type", "application/json") - response.Header.Del("Content-Encoding") - } else { - body = []byte(redactGoSubscriptionValue(string(body), credential)) - } - response.Body = io.NopCloser(bytes.NewReader(body)) - response.ContentLength = int64(len(body)) - response.TransferEncoding = nil - response.Header.Set("Content-Length", strconv.Itoa(len(body))) - } - for _, header := range []http.Header{response.Header, response.Trailer} { - for name, values := range header { - for index, value := range values { - values[index] = redactGoSubscriptionValue(value, credential) - } - safeName := redactGoSubscriptionValue(name, credential) - if safeName != name { - delete(header, name) - header[safeName] = append(header[safeName], values...) - } - } - } -} - -func (g *Gateway) doGoSubscriptionUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (response *http.Response, resultErr error, resultAttempts int) { - body := bodies[config.TierGo] - if len(body) == 0 { - return nil, errors.New("no prepared Go subscription request body"), 0 - } - limit := max(g.cfg.Retry.MaxAttempts, 1) - if isDiagnosticRequest(ctx) { - limit = 1 - } - var lastResponse *http.Response - var lastErr error - defer func() { - if lastResponse != nil && lastResponse != response { - httpx.DrainAndClose(lastResponse.Body) - } - }() - for attempts := 0; attempts < limit; attempts++ { - if ctx.Err() != nil { - lastErr = ctx.Err() - break - } - bufferRetryResponse(lastResponse) - resp, err := g.goSubscriptionAttempt(ctx, route, body, ids, attemptOffset+attempts+1, attempts, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second) - resultAttempts = attempts + 1 - lastResponse = replaceRetryResponse(lastResponse, resp) - lastErr = err - if ctx.Err() != nil { - break - } - var authorizationError *goauth.OAuthError - if errors.As(err, &authorizationError) { - return nil, err, resultAttempts - } - if resp != nil && (err == nil && resp.StatusCode/100 == 2 || resp.StatusCode < 500) { - return resp, err, resultAttempts - } - } - if errors.Is(ctx.Err(), context.Canceled) { - return nil, ctx.Err(), resultAttempts - } - if lastResponse != nil { - return lastResponse, nil, resultAttempts - } - if lastErr == nil { - lastErr = errors.New("Go subscription request could not be completed") - } - return nil, lastErr, resultAttempts -} - -func (g *Gateway) routeDiagnostic(model string, requested wire.Protocol) models.RouteDiagnostic { - diagnostic := g.catalog.Diagnostic(model, requested, g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous) - subscriptionModel := false - if connection := g.cfg.GoSubscription; connection != nil { - subscriptionRoute, included := connection.Routes[model] - subscriptionModel, diagnostic.AvailableGo = included, included - if included { - diagnostic.NativeProtocol = subscriptionRoute.Protocol - diagnostic.NativeProtocols = map[config.Tier]wire.Protocol{config.TierGo: subscriptionRoute.Protocol} - diagnostic.ProtocolSource = "go_subscription" - diagnostic.Channel = "subscription" - diagnostic.KeyID = subscriptionAccountID(connection) - } - } - route, err := g.routeForModel(model, "") - if err != nil { - diagnostic.RouteError = err.Error() - if subscriptionModel { - diagnostic.Tier, diagnostic.Anonymous, diagnostic.KeyTiers = "", false, nil - } - return diagnostic - } - diagnostic.RouteError = "" - diagnostic.Tier, diagnostic.Anonymous = route.Tier, route.Anonymous - diagnostic.KeyTiers = route.KeyTiers - diagnostic.NativeProtocol, diagnostic.NativeProtocols = route.Protocol, route.Protocols - return diagnostic -} diff --git a/internal/gateway/gosubscription_refresh.go b/internal/gateway/gosubscription_refresh.go deleted file mode 100644 index edded27..0000000 --- a/internal/gateway/gosubscription_refresh.go +++ /dev/null @@ -1,149 +0,0 @@ -package gateway - -import ( - "context" - "errors" - "time" - - "opencode2api/internal/config" - "opencode2api/internal/goauth" -) - -type goSubscriptionRefresh struct { - credential goauth.Credential - done chan struct{} - err error - retryAt time.Time -} - -func (m *RuntimeController) ResolveGoSubscription(ctx context.Context) (*goauth.Connection, error) { - for { - if err := ctx.Err(); err != nil { - return nil, err - } - m.goSubscriptionMu.Lock() - connection := m.Config().GoSubscription - if connection == nil { - m.goSubscriptionMu.Unlock() - return nil, errors.New("Go subscription is not connected") - } - if connection.NeedsLogin { - m.goSubscriptionMu.Unlock() - return nil, &goauth.OAuthError{Code: "invalid_grant"} - } - if err := connection.Validate(); err != nil { - m.goSubscriptionMu.Unlock() - return nil, err - } - if time.Until(connection.Credential.ExpiresAt) >= 5*time.Minute { - m.goSubscriptionMu.Unlock() - return connection, nil - } - refresh := m.goRefresh - if refresh == nil || refresh.done == nil && (refresh.credential != connection.Credential || !time.Now().Before(refresh.retryAt)) { - refresh = &goSubscriptionRefresh{credential: connection.Credential, done: make(chan struct{})} - m.goRefresh = refresh - go m.refreshGoSubscription(connection, refresh) - } - if refresh.done == nil { - err := refresh.err - m.goSubscriptionMu.Unlock() - if err != nil { - return nil, err - } - if !time.Now().Before(connection.Credential.ExpiresAt) { - return nil, &goauth.OAuthError{Code: "expired_token"} - } - return connection, nil - } - done := refresh.done - m.goSubscriptionMu.Unlock() - select { - case <-ctx.Done(): - return nil, ctx.Err() - case <-done: - } - } -} - -func (m *RuntimeController) refreshGoSubscription(connection *goauth.Connection, refresh *goSubscriptionRefresh) { - root := m.root - if root == nil { - root = context.Background() - } - ctx, cancel := context.WithTimeout(root, 20*time.Second) - defer cancel() - client := m.goAuthClient - if client == nil { - client = goauth.NewClient(nil) - } - credential, err := client.Refresh(ctx, connection.Credential) - if err != nil { - var oauthError *goauth.OAuthError - if errors.As(err, &oauthError) { - switch oauthError.Code { - case "invalid_grant", "expired_token", "unauthorized", "access_denied", "sso_required": - if saveErr := m.saveGoSubscriptionCredential(connection, connection.Credential, true); saveErr != nil { - err = saveErr - } - } - } else { - err = errors.New("Go subscription authorization could not be refreshed") - } - } else { - needsLogin := credential.OrganizationID != connection.Credential.OrganizationID - err = m.saveGoSubscriptionCredential(connection, credential, needsLogin) - if err == nil && needsLogin { - err = &goauth.OAuthError{Code: "invalid_grant"} - } - } - m.goSubscriptionMu.Lock() - defer m.goSubscriptionMu.Unlock() - refresh.err = err - refresh.retryAt = time.Now().Add(15 * time.Second) - if err == nil { - refresh.credential = credential - refresh.retryAt = time.Now().Add(min(30*time.Second, max(time.Millisecond, time.Until(credential.ExpiresAt)/2))) - } - close(refresh.done) - refresh.done = nil -} - -func (m *RuntimeController) saveGoSubscriptionCredential(previous *goauth.Connection, credential goauth.Credential, needsLogin bool) error { - changed := false - _, err := m.Update(func(cfg *config.Config) error { - connection := cfg.GoSubscription - if connection == nil || connection.Credential != previous.Credential || connection.NeedsLogin != previous.NeedsLogin { - changed = true - return errors.New("Go subscription connection changed") - } - connection.Credential = credential - connection.NeedsLogin = needsLogin - return nil - }) - if changed { - return errors.New("Go subscription connection changed; retry with the current configuration") - } - if err != nil { - return errors.New("Go subscription authorization could not be saved safely; sign in again") - } - return nil -} - -func (m *RuntimeController) invalidateGoSubscription(ctx context.Context, credential goauth.Credential) { - if ctx.Err() != nil { - return - } - unchanged := errors.New("Go subscription authorization is no longer current") - _, err := m.Update(func(cfg *config.Config) error { - connection := cfg.GoSubscription - if connection == nil || connection.Credential != credential || connection.NeedsLogin { - return unchanged - } - connection.NeedsLogin = true - return nil - }) - if err != nil && !errors.Is(err, unchanged) && m.logger != nil { - m.logger.Warn("Go subscription authorization could not be marked for reconnect", "component", "auth", "event", "go_subscription_reconnect_save_failed") - } -} diff --git a/internal/gateway/health.go b/internal/gateway/health.go index ac3bf7e..98e0667 100644 --- a/internal/gateway/health.go +++ b/internal/gateway/health.go @@ -9,6 +9,7 @@ import ( "opencode2api/internal/config" "opencode2api/internal/httpx" modelcatalog "opencode2api/internal/models" + "opencode2api/internal/oauth" wire "opencode2api/internal/protocol" ) @@ -70,7 +71,10 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { _, models := g.availableModels() proxyTotal, proxyHealthy := g.transports.healthCounts() zenKeys, goKeys := g.zenNodes.Len(), g.goNodes.Len() - if g.cfg.GoSubscription != nil { + if g.cfg.ZenOAuth != nil { + zenKeys = 1 + } + if g.cfg.GoOAuth != nil { goKeys = 1 } staleAfter := max(2*time.Duration(g.cfg.Models.RefreshSeconds)*time.Second, time.Minute) @@ -96,8 +100,11 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { modelStatus := "ready" var lastRefresh *time.Time issues := make([]string, 0, 3) - if g.cfg.GoSubscription != nil && g.cfg.GoSubscription.NeedsLogin { - issues = append(issues, "go_subscription_authorization_required") + if g.cfg.GoOAuth != nil && g.cfg.GoOAuth.NeedsLogin { + issues = append(issues, "go_oauth_authorization_required") + } + if g.cfg.ZenOAuth != nil && g.cfg.ZenOAuth.NeedsLogin { + issues = append(issues, "zen_oauth_authorization_required") } if models.UpdatedAt.IsZero() { modelStatus = "pending" @@ -122,7 +129,7 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { } // Proxies carry Go-tier traffic whenever Go keys exist, and every lane // while WARP is off; free-model traffic alone does not need them. - proxyBlocking := proxyHealthy == 0 && (g.warp == nil || goKeys > 0) + proxyBlocking := proxyHealthy == 0 && (g.warp == nil || goKeys > 0 || g.cfg.ZenOAuth != nil) if proxyHealthy == 0 { issues = append(issues, "no_healthy_proxies") } @@ -167,17 +174,23 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { } func (g *Gateway) availableModels() ([]modelcatalog.Route, modelcatalog.CatalogSnapshot) { - if g.cfg.GoSubscription == nil { + if g.cfg.GoOAuth == nil && g.cfg.ZenOAuth == nil && !g.catalog.TierPending(config.TierGo) && !g.catalog.TierPending(config.TierZen) { return g.catalog.AvailableModels(g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous) } modelIDs := g.catalog.List() - seen := make(map[string]bool, len(modelIDs)+len(g.cfg.GoSubscription.Routes)) + seen := make(map[string]bool, len(modelIDs)) for _, model := range modelIDs { seen[model] = true } - for model := range g.cfg.GoSubscription.Routes { - if !seen[model] { - modelIDs = append(modelIDs, model) + for _, connection := range []*oauth.Connection{g.cfg.GoOAuth, g.cfg.ZenOAuth} { + if connection == nil { + continue + } + for model := range connection.Routes { + if !seen[model] { + modelIDs = append(modelIDs, model) + seen[model] = true + } } } slices.Sort(modelIDs) diff --git a/internal/gateway/oauth.go b/internal/gateway/oauth.go new file mode 100644 index 0000000..0f72186 --- /dev/null +++ b/internal/gateway/oauth.go @@ -0,0 +1,487 @@ +package gateway + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/binary" + "encoding/json" + "errors" + "io" + "net/http" + "sort" + "strconv" + "strings" + "time" + + "opencode2api/internal/config" + "opencode2api/internal/httpx" + "opencode2api/internal/identity" + "opencode2api/internal/models" + "opencode2api/internal/oauth" + wire "opencode2api/internal/protocol" + "opencode2api/internal/telemetry" +) + +func (g *Gateway) goAvailable() bool { + return g.cfg.GoOAuth != nil || g.goNodes.Len() > 0 +} + +func (g *Gateway) tierOAuth(tier config.Tier) *oauth.Connection { + if tier == config.TierZen { + return g.cfg.ZenOAuth + } + if tier == config.TierGo { + return g.cfg.GoOAuth + } + return nil +} + +func (g *Gateway) routeForModel(model string, tier config.Tier) (models.Route, error) { + if g.cfg.GoOAuth == nil && g.cfg.ZenOAuth == nil && !g.catalog.TierPending(config.TierGo) && !g.catalog.TierPending(config.TierZen) { + if tier != "" { + return g.catalog.RouteForTier(model, tier, g.zenNodes.Len() > 0, g.goNodes.Len() > 0) + } + return g.catalog.Route(model, g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous) + } + tiers := []config.Tier{config.TierGo, config.TierZen} + if g.cfg.Prefer == config.TierZen { + tiers = []config.Tier{config.TierZen, config.TierGo} + } + if tier != "" { + tiers = []config.Tier{tier} + } + manualRoute, manualErr := g.catalog.Route(model, g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous) + for _, candidate := range tiers { + connection := g.tierOAuth(candidate) + if connection == nil { + hasKeys := g.zenNodes.Len() > 0 + if candidate == config.TierGo { + hasKeys = g.goNodes.Len() > 0 + } + if hasKeys && g.catalog.TierPending(candidate) { + return models.Route{}, errors.New("manual key model discovery is pending after OAuth disconnect; retry after catalog refresh") + } + if route, err := g.catalog.RouteForTier(model, candidate, g.zenNodes.Len() > 0, g.goNodes.Len() > 0); err == nil { + if tier != "" { + return route, nil + } + return manualRoute, manualErr + } + continue + } + if oauthRoute, ok := connection.Routes[model]; ok { + if connection.NeedsLogin { + return models.Route{}, &oauth.OAuthError{Code: "invalid_grant"} + } + if g.cfg.Models.FreeOnly && !g.catalog.IsFreeModel(model) { + return models.Route{}, errors.New("this OAuth model is excluded by models.free_only") + } + return models.Route{ + ID: model, Tier: candidate, Protocol: oauthRoute.Protocol, + Protocols: map[config.Tier]wire.Protocol{candidate: oauthRoute.Protocol}, + KeyTiers: []config.Tier{candidate}, + }, nil + } + if tier != "" { + return models.Route{}, errors.New("model is not included in the connected Console plan") + } + } + if tier != "" { + return g.catalog.RouteForTier(model, tier, g.zenNodes.Len() > 0, g.goNodes.Len() > 0) + } + return manualRoute, manualErr +} + +func (g *Gateway) seedOAuthCatalog(capabilities *models.Capabilities, tier config.Tier) []string { + connection := g.tierOAuth(tier) + if connection == nil { + return nil + } + if capabilities.Protocols == nil { + capabilities.Protocols = map[config.Tier]map[string]wire.Protocol{} + } + if capabilities.Unsupported == nil { + capabilities.Unsupported = map[config.Tier]map[string]bool{} + } + protocols := make(map[string]wire.Protocol, len(connection.Routes)) + modelIDs := make([]string, 0, len(connection.Routes)) + for model, route := range connection.Routes { + modelIDs = append(modelIDs, model) + protocols[model] = route.Protocol + } + sort.Strings(modelIDs) + capabilities.Protocols[tier] = protocols + capabilities.Unsupported[tier] = map[string]bool{} + return modelIDs +} + +func (g *Gateway) restoreOAuthCatalog() { + for _, tier := range []config.Tier{config.TierGo, config.TierZen} { + if g.tierOAuth(tier) == nil { + g.catalog.ClearOAuthTier(tier) + } + } + if g.cfg.GoOAuth == nil && g.cfg.ZenOAuth == nil { + return + } + capabilities := models.Capabilities{} + goModels := g.seedOAuthCatalog(&capabilities, config.TierGo) + zenModels := g.seedOAuthCatalog(&capabilities, config.TierZen) + g.catalog.ReplaceWithCapabilities(zenModels, goModels, capabilities.Protocols, capabilities.Unsupported, nil, g.oauthTiers()...) +} + +func (g *Gateway) oauthTiers() []config.Tier { + var tiers []config.Tier + for _, tier := range []config.Tier{config.TierGo, config.TierZen} { + if g.tierOAuth(tier) != nil { + tiers = append(tiers, tier) + } + } + return tiers +} + +func (g *Gateway) oauthConnection(ctx context.Context, tier config.Tier) (*oauth.Connection, error) { + snapshot := g.tierOAuth(tier) + if snapshot == nil { + return nil, errors.New("Console plan is not connected") + } + connection := snapshot + resolve := g.resolveGoOAuth + if tier == config.TierZen { + resolve = g.resolveZenOAuth + } + if resolve != nil { + resolved, err := resolve(ctx) + if err != nil { + return nil, err + } + connection = resolved + } + if connection == nil || connection.Credential.AccountID != snapshot.Credential.AccountID || connection.Credential.OrganizationID != snapshot.Credential.OrganizationID || connection.Proxy != snapshot.Proxy { + return nil, errors.New("Console plan connection changed; retry with the current configuration") + } + if connection.NeedsLogin { + return nil, &oauth.OAuthError{Code: "invalid_grant"} + } + if err := connection.ValidateForPlan(oauth.Plan(tier)); err != nil { + return nil, err + } + if !time.Now().Before(connection.Credential.ExpiresAt) { + return nil, &oauth.OAuthError{Code: "expired_token"} + } + return connection, nil +} + +func oauthAccountID(connection *oauth.Connection) string { + return config.Fingerprint(connection.Credential.AccountID + "\x00" + connection.Credential.OrganizationID) +} + +func (g *Gateway) oauthProxy(ctx context.Context, connection *oauth.Connection, affinity string, offset int) (*proxyTransport, error) { + if g.transports == nil || len(g.transports.items) == 0 { + return nil, errProxyUnavailable + } + var pinned *proxyTransport + if selection, selected := relayOverrideFrom(ctx); selected { + var found bool + pinned, found = g.RelayProxy(selection) + if !found { + return nil, errRelayNotFound + } + } + if connection.Proxy != "" { + for _, proxy := range g.transports.items { + if proxy == nil || proxy.name != connection.Proxy { + continue + } + if pinned != nil && pinned != proxy { + return nil, errors.New("the selected relay conflicts with the OAuth proxy binding") + } + if !proxy.healthy.Load() && !isDiagnosticRequest(ctx) { + return nil, errProxyUnavailable + } + return proxy, nil + } + return nil, errProxyUnavailable + } + if pinned != nil { + return pinned, nil + } + digest := sha256.Sum256([]byte(oauthAccountID(connection) + "\x00" + affinity)) + start := int(binary.LittleEndian.Uint64(digest[:8]) % uint64(len(g.transports.items))) + for step := range len(g.transports.items) { + proxy := g.transports.items[(start+offset+step)%len(g.transports.items)] + if proxy != nil && proxy.healthy.Load() { + return proxy, nil + } + } + return nil, errProxyUnavailable +} + +func (g *Gateway) oauthAttempt(ctx context.Context, route models.Route, body []byte, ids identity.RequestIDs, attempt, offset int, firstEventTimeout time.Duration) (*http.Response, error) { + connection, err := g.oauthConnection(ctx, route.Tier) + if err != nil { + return nil, err + } + oauthRoute, ok := connection.Routes[route.ID] + if !ok || oauthRoute.Protocol != route.Protocol || oauthRoute != g.tierOAuth(route.Tier).Routes[route.ID] { + return nil, errors.New("Console plan route changed; retry with the current configuration") + } + var payload map[string]json.RawMessage + if err := json.Unmarshal(body, &payload); err != nil || payload == nil { + return nil, errors.New("invalid OAuth request body") + } + payload["model"], err = json.Marshal(oauthRoute.ModelID) + if err != nil { + return nil, errors.New("invalid OAuth model") + } + body, err = json.Marshal(payload) + if err != nil { + return nil, errors.New("invalid OAuth request body") + } + proxy, err := g.oauthProxy(ctx, connection, ids.Session, offset) + if err != nil { + return nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(oauthRoute.BaseURL, "/")+wire.Path(oauthRoute.Protocol), bytes.NewReader(body)) + if err != nil { + return nil, errors.New("invalid OAuth endpoint") + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+connection.Credential.AccessToken) + req.Header.Set("x-opencode-session", ids.Session) + req.Header.Set("User-Agent", httpx.V2UserAgent()) + if connection.Credential.OrganizationID != "" { + req.Header.Set("x-org-id", connection.Credential.OrganizationID) + } + if route.Protocol == wire.Anthropic { + req.Header.Set("anthropic-version", "2023-06-01") + } + req.GetBody = nil + if proxy.pool { + req.Close = true + } + client := *proxy.client + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + accountID := oauthAccountID(connection) + setRequestCredential(ctx, route.Tier, accountID, "oauth", false, proxy) + setRequestShape(ctx, false, nil) + if meta := telemetry.MetaFromContext(ctx); meta != nil { + meta.Attempts = attempt + meta.Tier = string(route.Tier) + } + started := time.Now() + resp, err := doInferenceAttempt(&client, req, firstEventTimeout, g.attemptTimeout) + if resp != nil { + sanitizeOAuthResponse(resp, connection.Credential) + invalidate := g.onGoOAuthUnauthorized + if route.Tier == config.TierZen { + invalidate = g.onZenOAuthUnauthorized + } + if resp.StatusCode == http.StatusUnauthorized && invalidate != nil { + invalidate(ctx, connection.Credential) + } + } + if err != nil { + err = &oauthError{cause: err, message: redactOAuthValue(err.Error(), connection.Credential)} + } + if ctx.Err() == nil && !isDiagnosticRequest(ctx) { + g.syncProxyResult(ctx, proxy, upstreamStatus(resp), err) + } + g.recordUpstreamAttempt(ctx, route, ids, attempt, accountID, "oauth", false, proxy, resp, err, time.Since(started)) + if err != nil { + return resp, asProxyUnavailable(proxy, err) + } + return resp, nil +} + +type oauthError struct { + cause error + message string +} + +func (err *oauthError) Error() string { return err.message } +func (err *oauthError) Unwrap() error { return err.cause } + +func redactOAuthValue(value string, credential oauth.Credential) string { + secrets := []string{credential.AccessToken, credential.RefreshToken} + if len(secrets[1]) > len(secrets[0]) { + secrets[0], secrets[1] = secrets[1], secrets[0] + } + for _, secret := range secrets { + if secret == "" { + continue + } + value = strings.ReplaceAll(value, secret, "***") + encoded, _ := json.Marshal(secret) + value = strings.ReplaceAll(value, string(encoded[1:len(encoded)-1]), "***") + } + return value +} + +func sanitizeOAuthResponse(response *http.Response, credential oauth.Credential) { + if response.Header == nil { + response.Header = make(http.Header) + } + response.Request = nil + response.Status = redactOAuthValue(response.Status, credential) + if response.StatusCode/100 != 2 { + var body []byte + var readErr error + if response.Body != nil { + body, readErr = io.ReadAll(io.LimitReader(response.Body, 1<<20)) + response.Body.Close() + } + if readErr != nil || len(body) >= 1<<20 { + body = []byte(`{"error":{"message":"OAuth upstream request was rejected"}}`) + response.Header.Set("Content-Type", "application/json") + response.Header.Del("Content-Encoding") + } else { + var value any + if json.Unmarshal(body, &value) == nil { + // Decode before scrubbing so a JSON escape cannot hide a token + // that a rejected request echoed in its error message. + body, _ = json.Marshal(redactOAuthJSON(value, credential)) + } else { + body = []byte(redactOAuthValue(string(body), credential)) + } + } + response.Body = io.NopCloser(bytes.NewReader(body)) + response.ContentLength = int64(len(body)) + response.TransferEncoding = nil + response.Header.Set("Content-Length", strconv.Itoa(len(body))) + } + for _, header := range []http.Header{response.Header, response.Trailer} { + for name, values := range header { + for index, value := range values { + values[index] = redactOAuthValue(value, credential) + } + safeName := redactOAuthValue(name, credential) + if safeName != name { + delete(header, name) + header[safeName] = append(header[safeName], values...) + } + } + } +} + +func redactOAuthJSON(value any, credential oauth.Credential) any { + switch typed := value.(type) { + case string: + return redactOAuthValue(typed, credential) + case []any: + for index, item := range typed { + typed[index] = redactOAuthJSON(item, credential) + } + case map[string]any: + redacted := make(map[string]any, len(typed)) + for name, item := range typed { + redacted[redactOAuthValue(name, credential)] = redactOAuthJSON(item, credential) + } + return redacted + } + return value +} + +func (g *Gateway) doOAuthUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (response *http.Response, resultErr error, resultAttempts int) { + body := bodies[route.Tier] + if len(body) == 0 { + return nil, errors.New("no prepared OAuth request body"), 0 + } + limit := max(g.cfg.Retry.MaxAttempts, 1) + if isDiagnosticRequest(ctx) { + limit = 1 + } + var lastResponse *http.Response + var lastErr error + defer func() { + if lastResponse != nil && lastResponse != response { + httpx.DrainAndClose(lastResponse.Body) + } + }() + for attempts := 0; attempts < limit; attempts++ { + if ctx.Err() != nil { + lastErr = ctx.Err() + break + } + bufferRetryResponse(lastResponse) + resp, err := g.oauthAttempt(ctx, route, body, ids, attemptOffset+attempts+1, attempts, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second) + resultAttempts = attempts + 1 + lastResponse = replaceRetryResponse(lastResponse, resp) + lastErr = err + if ctx.Err() != nil { + break + } + var authorizationError *oauth.OAuthError + if errors.As(err, &authorizationError) { + return nil, err, resultAttempts + } + if resp != nil && (err == nil && resp.StatusCode/100 == 2 || resp.StatusCode < 500) { + return resp, err, resultAttempts + } + } + if errors.Is(ctx.Err(), context.Canceled) { + return nil, ctx.Err(), resultAttempts + } + if lastResponse != nil { + return lastResponse, nil, resultAttempts + } + if lastErr == nil { + lastErr = errors.New("OAuth request could not be completed") + } + return nil, lastErr, resultAttempts +} + +func (g *Gateway) routeDiagnostic(model string, requested wire.Protocol) models.RouteDiagnostic { + diagnostic := g.catalog.Diagnostic(model, requested, g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous) + oauthModel := false + for _, tier := range []config.Tier{config.TierGo, config.TierZen} { + if connection := g.tierOAuth(tier); connection != nil { + _, included := connection.Routes[model] + oauthModel = oauthModel || included + if tier == config.TierGo { + diagnostic.AvailableGo = included + } else { + diagnostic.AvailableZen = included + } + } + } + route, err := g.routeForModel(model, "") + if err != nil { + diagnostic.RouteError = err.Error() + if oauthModel { + diagnostic.Tier, diagnostic.Anonymous, diagnostic.KeyTiers = "", false, nil + var authorizationError *oauth.OAuthError + if errors.As(err, &authorizationError) { + tiers := []config.Tier{config.TierGo, config.TierZen} + if g.cfg.Prefer == config.TierZen { + tiers = []config.Tier{config.TierZen, config.TierGo} + } + for _, tier := range tiers { + connection := g.tierOAuth(tier) + if connection == nil { + continue + } + if oauthRoute, included := connection.Routes[model]; included { + diagnostic.ProtocolSource = string(tier) + "_oauth" + diagnostic.Channel, diagnostic.KeyID = "oauth", oauthAccountID(connection) + diagnostic.NativeProtocol = oauthRoute.Protocol + diagnostic.NativeProtocols = map[config.Tier]wire.Protocol{tier: oauthRoute.Protocol} + break + } + } + } + } + return diagnostic + } + diagnostic.RouteError = "" + diagnostic.Tier, diagnostic.Anonymous = route.Tier, route.Anonymous + diagnostic.KeyTiers = route.KeyTiers + diagnostic.NativeProtocol, diagnostic.NativeProtocols = route.Protocol, route.Protocols + if connection := g.tierOAuth(route.Tier); connection != nil && !route.Anonymous { + diagnostic.ProtocolSource = string(route.Tier) + "_oauth" + diagnostic.Channel = "oauth" + diagnostic.KeyID = oauthAccountID(connection) + } + return diagnostic +} diff --git a/internal/gateway/oauth_refresh.go b/internal/gateway/oauth_refresh.go new file mode 100644 index 0000000..81f3cb2 --- /dev/null +++ b/internal/gateway/oauth_refresh.go @@ -0,0 +1,171 @@ +package gateway + +import ( + "context" + "errors" + "time" + + "opencode2api/internal/config" + "opencode2api/internal/oauth" +) + +type oauthRefresh struct { + credential oauth.Credential + done chan struct{} + err error + retryAt time.Time +} + +func (m *RuntimeController) ResolveOAuth(ctx context.Context, tiers ...config.Tier) (*oauth.Connection, error) { + tier := config.TierGo + if len(tiers) > 0 { + tier = tiers[0] + } + if tier != config.TierGo && tier != config.TierZen { + return nil, errors.New("invalid Console plan") + } + for { + if err := ctx.Err(); err != nil { + return nil, err + } + m.oauthMu.Lock() + connection := m.Config().GoOAuth + refreshSlot := &m.goRefresh + if tier == config.TierZen { + connection = m.Config().ZenOAuth + refreshSlot = &m.zenRefresh + } + if connection == nil { + m.oauthMu.Unlock() + return nil, errors.New("Console plan is not connected") + } + if connection.NeedsLogin { + m.oauthMu.Unlock() + return nil, &oauth.OAuthError{Code: "invalid_grant"} + } + if err := connection.ValidateForPlan(oauth.Plan(tier)); err != nil { + m.oauthMu.Unlock() + return nil, err + } + if time.Until(connection.Credential.ExpiresAt) >= 5*time.Minute { + m.oauthMu.Unlock() + return connection, nil + } + refresh := *refreshSlot + if refresh == nil || refresh.done == nil && (refresh.credential != connection.Credential || !time.Now().Before(refresh.retryAt)) { + refresh = &oauthRefresh{credential: connection.Credential, done: make(chan struct{})} + *refreshSlot = refresh + go m.refreshOAuth(connection, refresh, tier) + } + if refresh.done == nil { + err := refresh.err + m.oauthMu.Unlock() + if err != nil { + return nil, err + } + if !time.Now().Before(connection.Credential.ExpiresAt) { + return nil, &oauth.OAuthError{Code: "expired_token"} + } + return connection, nil + } + done := refresh.done + m.oauthMu.Unlock() + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-done: + } + } +} + +func (m *RuntimeController) refreshOAuth(connection *oauth.Connection, refresh *oauthRefresh, tier config.Tier) { + root := m.root + if root == nil { + root = context.Background() + } + ctx, cancel := context.WithTimeout(root, 20*time.Second) + defer cancel() + client := m.oauthClient + if client == nil { + client = oauth.NewClient(nil) + } + credential, err := client.Refresh(ctx, connection.Credential) + if err != nil { + var oauthError *oauth.OAuthError + if errors.As(err, &oauthError) { + switch oauthError.Code { + case "invalid_grant", "expired_token", "unauthorized", "access_denied", "sso_required": + if saveErr := m.saveOAuthCredential(connection, connection.Credential, true, tier); saveErr != nil { + err = saveErr + } + } + } else { + err = errors.New("Console authorization could not be refreshed") + } + } else { + needsLogin := credential.OrganizationID != connection.Credential.OrganizationID + err = m.saveOAuthCredential(connection, credential, needsLogin, tier) + if err == nil && needsLogin { + err = &oauth.OAuthError{Code: "invalid_grant"} + } + } + m.oauthMu.Lock() + defer m.oauthMu.Unlock() + refresh.err = err + refresh.retryAt = time.Now().Add(15 * time.Second) + if err == nil { + refresh.credential = credential + refresh.retryAt = time.Now().Add(min(30*time.Second, max(time.Millisecond, time.Until(credential.ExpiresAt)/2))) + } + close(refresh.done) + refresh.done = nil +} + +func (m *RuntimeController) saveOAuthCredential(previous *oauth.Connection, credential oauth.Credential, needsLogin bool, tier config.Tier) error { + changed := false + _, err := m.Update(func(cfg *config.Config) error { + connection := cfg.GoOAuth + if tier == config.TierZen { + connection = cfg.ZenOAuth + } + if connection == nil || connection.Credential != previous.Credential || connection.NeedsLogin != previous.NeedsLogin { + changed = true + return errors.New("Console plan connection changed") + } + connection.Credential = credential + connection.NeedsLogin = needsLogin + return nil + }) + if changed { + return errors.New("Console plan connection changed; retry with the current configuration") + } + if err != nil { + return errors.New("Console authorization could not be saved safely; sign in again") + } + return nil +} + +func (m *RuntimeController) invalidateOAuth(ctx context.Context, credential oauth.Credential, tiers ...config.Tier) { + tier := config.TierGo + if len(tiers) > 0 { + tier = tiers[0] + } + if ctx.Err() != nil { + return + } + unchanged := errors.New("Console authorization is no longer current") + _, err := m.Update(func(cfg *config.Config) error { + connection := cfg.GoOAuth + if tier == config.TierZen { + connection = cfg.ZenOAuth + } + if connection == nil || connection.Credential != credential || connection.NeedsLogin { + return unchanged + } + connection.NeedsLogin = true + return nil + }) + if err != nil && !errors.Is(err, unchanged) && m.logger != nil { + m.logger.Warn("Console authorization could not be marked for reconnect", "component", "auth", "event", "oauth_reconnect_save_failed", "tier", tier) + } +} diff --git a/internal/gateway/pool.go b/internal/gateway/pool.go index 26dd47a..6b2a83e 100644 --- a/internal/gateway/pool.go +++ b/internal/gateway/pool.go @@ -151,18 +151,16 @@ func (p *anonymousNodes) HasPool() bool { return p != nil && p.hasPool } -// CursorFor returns a cursor whose first node is stable for a non-empty -// affinity key, keeping a conversation on one exit; an empty affinity rotates -// the starting node round-robin. // CursorForProxy returns a cursor whose first Next hands back the node that // uses proxy and whose second returns nil, so a relay-pinned diagnostic // attempts exactly one exit. A proxy outside the pool yields the same // single-shot cursor over no node, which the caller reports as an error. func (p *anonymousNodes) CursorForProxy(proxy *proxyTransport) anonymousCursor { - c := anonymousCursor{pool: p, offset: len(p.nodes), single: true} + c := anonymousCursor{pool: p, start: -1, single: true} if p == nil || proxy == nil { return c } + c.offset = len(p.nodes) for i, node := range p.nodes { if node.proxy == proxy { c.start = i @@ -172,6 +170,9 @@ func (p *anonymousNodes) CursorForProxy(proxy *proxyTransport) anonymousCursor { return c } +// CursorFor returns a cursor whose first node is stable for a non-empty +// affinity key, keeping a conversation on one exit; an empty affinity rotates +// the starting node round-robin. func (p *anonymousNodes) CursorFor(affinity string) anonymousCursor { if p == nil || len(p.nodes) == 0 { return anonymousCursor{pool: p} @@ -323,8 +324,7 @@ func (c *anonymousCursor) Next() *anonymousNode { } if c.single { index := c.start - c.single = false - c.offset = n + c.start = -1 if index < 0 || index >= n { return nil } @@ -530,7 +530,14 @@ func transportPool(proxies []string, cfg config.PerformanceConfig, responseHeade if err != nil { return nil, fmt.Errorf("proxy %s: %w", config.RedactURL(raw), err) } - proxy := &proxyTransport{index: len(p.items), name: raw, pool: isPool, client: &http.Client{Transport: transport}, bun: &http.Client{Transport: bun}} + // Redirects can forward x-api-key and replay an inference body to a + // different origin. The configured endpoint owns the request directly. + rejectRedirect := func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + proxy := &proxyTransport{ + index: len(p.items), name: raw, pool: isPool, + client: &http.Client{Transport: transport, CheckRedirect: rejectRedirect}, + bun: &http.Client{Transport: bun, CheckRedirect: rejectRedirect}, + } proxy.healthy.Store(true) p.items = append(p.items, proxy) } diff --git a/internal/gateway/probe.go b/internal/gateway/probe.go index a8eb9d1..bac5611 100644 --- a/internal/gateway/probe.go +++ b/internal/gateway/probe.go @@ -310,8 +310,13 @@ func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, base if !result.success { result.reason = "invalid_or_incomplete_response" if err != nil { - result.effortRejected = isEffortRejection(400, err.Error()) - if IsModelUnavailable(400, err.Error()) { + message := err.Error() + var failure *wire.StreamFailure + if errors.As(err, &failure) { + message = failure.Type + " " + failure.Message + } + result.effortRejected = isEffortRejection(400, message) + if IsModelUnavailable(400, message) { result.reason = "model_unavailable" } } diff --git a/internal/gateway/refresh.go b/internal/gateway/refresh.go index b0e78c4..3e284e5 100644 --- a/internal/gateway/refresh.go +++ b/internal/gateway/refresh.go @@ -175,10 +175,15 @@ func (g *Gateway) RefreshCatalog(ctx context.Context) { var capabilitiesErr error var wg sync.WaitGroup wg.Add(3) - go func() { defer wg.Done(); zen = g.refreshZen(ctx) }() go func() { defer wg.Done() - if g.cfg.GoSubscription == nil { + if g.cfg.ZenOAuth == nil { + zen = g.refreshZen(ctx) + } + }() + go func() { + defer wg.Done() + if g.cfg.GoOAuth == nil { goModels = g.refreshTier(ctx, g.cfg.Upstream.Go, g.goNodes) } }() @@ -195,11 +200,14 @@ func (g *Gateway) RefreshCatalog(ctx context.Context) { if capabilitiesErr != nil { g.logger.Warn("OpenCode capability catalog refresh failed", "component", "models", "event", "capability_refresh_failed", "error", capabilitiesErr) } - if g.cfg.GoSubscription != nil { - goModels = g.seedGoSubscriptionCatalog(&capabilities) + if g.cfg.GoOAuth != nil { + goModels = g.seedOAuthCatalog(&capabilities, config.TierGo) + } + if g.cfg.ZenOAuth != nil { + zen = g.seedOAuthCatalog(&capabilities, config.TierZen) } if zen != nil || goModels != nil { - g.catalog.ReplaceWithCapabilities(zen, goModels, capabilities.Protocols, capabilities.Unsupported, capabilities.Metadata) + g.catalog.ReplaceWithCapabilities(zen, goModels, capabilities.Protocols, capabilities.Unsupported, capabilities.Metadata, g.oauthTiers()...) g.syncRotation() if ctx.Err() == nil { if err := g.catalog.SaveCache(); err != nil { diff --git a/internal/gateway/rotation.go b/internal/gateway/rotation.go index 32a538a..6e519e4 100644 --- a/internal/gateway/rotation.go +++ b/internal/gateway/rotation.go @@ -12,10 +12,10 @@ import ( "time" "opencode2api/internal/config" - "opencode2api/internal/goauth" "opencode2api/internal/identity" "opencode2api/internal/jsonutil" "opencode2api/internal/models" + "opencode2api/internal/oauth" wire "opencode2api/internal/protocol" "opencode2api/internal/rotation" "opencode2api/internal/telemetry" @@ -102,8 +102,8 @@ func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, externa meta.Session = ids.Session meta.ModelAlias = alias } - if g.cfg.GoSubscription != nil && g.cfg.GoSubscription.NeedsLogin { - wire.WriteError(w, external, http.StatusServiceUnavailable, (&goauth.OAuthError{Code: "invalid_grant"}).Error(), "subscription_auth_error", ids.Request) + if g.cfg.GoOAuth != nil && g.cfg.GoOAuth.NeedsLogin { + wire.WriteError(w, external, http.StatusServiceUnavailable, (&oauth.OAuthError{Code: "invalid_grant"}).Error(), "oauth_auth_error", ids.Request) return } visited := map[string]bool{} @@ -116,9 +116,9 @@ func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, externa visited[token.Model] = true route, err := g.routeForModel(token.Model, config.TierGo) if err != nil { - var oauthError *goauth.OAuthError + var oauthError *oauth.OAuthError if errors.As(err, &oauthError) { - wire.WriteError(w, external, http.StatusServiceUnavailable, oauthError.Error(), "subscription_auth_error", ids.Request) + wire.WriteError(w, external, http.StatusServiceUnavailable, oauthError.Error(), "oauth_auth_error", ids.Request) return } continue @@ -158,12 +158,12 @@ func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, externa if result.err == nil { return } - var oauthError *goauth.OAuthError + var oauthError *oauth.OAuthError if errors.As(result.err, &oauthError) { - wire.WriteError(w, external, http.StatusServiceUnavailable, oauthError.Error(), "subscription_auth_error", ids.Request) + wire.WriteError(w, external, http.StatusServiceUnavailable, oauthError.Error(), "oauth_auth_error", ids.Request) return } - if g.cfg.GoSubscription != nil && result.reason == "subscription_auth_error" { + if g.cfg.GoOAuth != nil && result.reason == "oauth_auth_error" { return } if result.committed { @@ -235,8 +235,8 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter, var resp *http.Response var toolRenames *wire.ToolRenames shaped := false - if g.cfg.GoSubscription != nil { - resp, err = g.goSubscriptionAttempt(ctx, route, bodies[config.TierGo], ids, attempt, attempt-1, 0) + if g.cfg.GoOAuth != nil { + resp, err = g.oauthAttempt(ctx, route, bodies[config.TierGo], ids, attempt, attempt-1, 0) } else { var body []byte body, toolRenames, shaped = g.shapeKeyBody(bodies[config.TierGo], route, config.TierGo) @@ -285,19 +285,19 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter, } if err != nil { result.err = err - var oauthError *goauth.OAuthError + var oauthError *oauth.OAuthError if errors.As(err, &oauthError) { - result.reason = "subscription_auth_error" + result.reason = "oauth_auth_error" } else if errors.Is(err, errFirstEventTimeout) || ctx.Err() != nil { result.reason = "first_output_timeout" } return result } - if g.cfg.GoSubscription != nil && resp.StatusCode == http.StatusUnauthorized { + if g.cfg.GoOAuth != nil && resp.StatusCode == http.StatusUnauthorized { w.Header().Set("x-request-id", ids.Request) - copyErrorResponse(w, external, resp, ids.Request) - result.err = errors.New("Go subscription authorization was rejected") - result.reason = "subscription_auth_error" + g.copyErrorResponse(w, external, resp, ids.Request) + result.err = errors.New("Go OAuth authorization was rejected") + result.reason = "oauth_auth_error" result.committed = true return result } diff --git a/internal/gateway/runtime.go b/internal/gateway/runtime.go index 26308fb..7d31e24 100644 --- a/internal/gateway/runtime.go +++ b/internal/gateway/runtime.go @@ -14,8 +14,8 @@ import ( "time" "opencode2api/internal/config" - "opencode2api/internal/goauth" modelcatalog "opencode2api/internal/models" + "opencode2api/internal/oauth" "opencode2api/internal/protocol" "opencode2api/internal/rotation" "opencode2api/internal/telemetry" @@ -64,9 +64,10 @@ type RuntimeController struct { level *slog.LevelVar current atomic.Pointer[gatewayRuntime] updateMu sync.Mutex - goSubscriptionMu sync.Mutex - goAuthClient *goauth.Client - goRefresh *goSubscriptionRefresh + oauthMu sync.Mutex + oauthClient *oauth.Client + goRefresh *oauthRefresh + zenRefresh *oauthRefresh effective EffectiveListeners metadata *modelcatalog.PricingRegistry availabilityCancel context.CancelFunc @@ -144,7 +145,7 @@ func RuntimeManager(root context.Context, configPath string, cfg config.Config, manager.logger.Warn("model catalog cache ignored", "component", "models", "event", "catalog_cache_load_failed", "path", modelcatalog.CatalogCachePath(configPath), "error", err) } } - runtime.gateway.restoreGoSubscriptionCatalog() + runtime.gateway.restoreOAuthCatalog() if err := cfg.Rotation.Validate(runtime.gateway.catalog.List()); err != nil { if runtime.warpCreated && runtime.warpPool != nil { runtime.warpPool.Close() @@ -203,14 +204,29 @@ func (m *RuntimeController) build(cfg config.Config) (*gatewayRuntime, error) { return nil, err } gateway.rotation = m.rotation - gateway.onGoSubscriptionUnauthorized = m.invalidateGoSubscription - gateway.resolveGoSubscription = func(ctx context.Context) (*goauth.Connection, error) { - connection, err := m.ResolveGoSubscription(ctx) + gateway.onGoOAuthUnauthorized = func(ctx context.Context, credential oauth.Credential) { + m.invalidateOAuth(ctx, credential) + } + gateway.resolveGoOAuth = func(ctx context.Context) (*oauth.Connection, error) { + connection, err := m.ResolveOAuth(ctx) if err != nil { return nil, err } if !slices.Equal(cfg.RuntimeProxies(), m.Config().RuntimeProxies()) { - return nil, errors.New("Go subscription proxy configuration changed; retry with the current configuration") + return nil, errors.New("Go OAuth proxy configuration changed; retry with the current configuration") + } + return connection, nil + } + gateway.onZenOAuthUnauthorized = func(ctx context.Context, credential oauth.Credential) { + m.invalidateOAuth(ctx, credential, config.TierZen) + } + gateway.resolveZenOAuth = func(ctx context.Context) (*oauth.Connection, error) { + connection, err := m.ResolveOAuth(ctx, config.TierZen) + if err != nil { + return nil, err + } + if !slices.Equal(cfg.RuntimeProxies(), m.Config().RuntimeProxies()) { + return nil, errors.New("Zen OAuth proxy configuration changed; retry with the current configuration") } return connection, nil } @@ -388,7 +404,7 @@ func (m *RuntimeController) applyLocked(candidate config.Config, persist bool) ( if current != nil { next.gateway.catalog.CopyState(current.gateway.catalog) } - next.gateway.restoreGoSubscriptionCatalog() + next.gateway.restoreOAuthCatalog() if err := normalized.Rotation.Validate(next.gateway.catalog.List()); err != nil { if next.warpCreated && next.warpPool != nil { next.warpPool.Close() @@ -540,8 +556,8 @@ func (m *RuntimeController) Resources() ResourceSnapshot { result := ResourceSnapshot{Models: models, Anonymous: gateway.cfg.Anonymous} result.Metadata = gateway.catalog.MetadataSnapshot() result.Keys = append(result.Keys, keyStatuses("zen", gateway.zenNodes)...) - if connection := gateway.cfg.GoSubscription; connection != nil { - status := KeyStatus{ID: subscriptionAccountID(connection), Tier: string(config.TierGo), ProxyIndex: -1, Bound: connection.Proxy != ""} + if connection := gateway.cfg.GoOAuth; connection != nil { + status := KeyStatus{ID: oauthAccountID(connection), Tier: string(config.TierGo), ProxyIndex: -1, Bound: connection.Proxy != ""} for _, proxy := range gateway.transports.items { if connection.Proxy != "" && proxy.name == connection.Proxy { status.ProxyIndex = proxy.index @@ -552,6 +568,16 @@ func (m *RuntimeController) Resources() ResourceSnapshot { } else { result.Keys = append(result.Keys, keyStatuses("go", gateway.goNodes)...) } + if connection := gateway.cfg.ZenOAuth; connection != nil { + status := KeyStatus{ID: oauthAccountID(connection), Tier: string(config.TierZen), ProxyIndex: -1, Bound: connection.Proxy != ""} + for _, proxy := range gateway.transports.items { + if connection.Proxy != "" && proxy.name == connection.Proxy { + status.ProxyIndex = proxy.index + break + } + } + result.Keys = append(result.Keys, status) + } gateway.zenNodes.bindingsMu.Lock() zenBindings := append([]int(nil), gateway.zenNodes.bindingCount...) gateway.zenNodes.bindingsMu.Unlock() @@ -566,9 +592,12 @@ func (m *RuntimeController) Resources() ResourceSnapshot { if proxy.index < len(goBindings) { status.GoKeys = goBindings[proxy.index] } - if gateway.cfg.GoSubscription != nil && gateway.cfg.GoSubscription.Proxy == proxy.name { + if gateway.cfg.GoOAuth != nil && gateway.cfg.GoOAuth.Proxy == proxy.name { status.GoKeys = 1 } + if gateway.cfg.ZenOAuth != nil && gateway.cfg.ZenOAuth.Proxy == proxy.name { + status.ZenKeys = 1 + } result.Proxies = append(result.Proxies, status) } if gateway.warp != nil { @@ -651,9 +680,13 @@ func (m *RuntimeController) DebugKeys() map[string][]DebugKeyView { result[string(tier)] = append(result[string(tier)], view) } } - appendKeys(config.TierZen, runtime.gateway.zenNodes.nodes) - if connection := runtime.config.GoSubscription; connection != nil { - result["go"] = append(result["go"], DebugKeyView{ID: subscriptionAccountID(connection), Tier: config.TierGo, Display: "Go subscription"}) + if connection := runtime.config.ZenOAuth; connection != nil { + result["zen"] = append(result["zen"], DebugKeyView{ID: oauthAccountID(connection), Tier: config.TierZen, Display: "Zen PAYG (OAuth)"}) + } else { + appendKeys(config.TierZen, runtime.gateway.zenNodes.nodes) + } + if connection := runtime.config.GoOAuth; connection != nil { + result["go"] = append(result["go"], DebugKeyView{ID: oauthAccountID(connection), Tier: config.TierGo, Display: "Go OAuth"}) } else { appendKeys(config.TierGo, runtime.gateway.goNodes.nodes) } @@ -689,9 +722,12 @@ func (m *RuntimeController) DebugRouteForTier(model string, tier config.Tier) (m diagnostic.Tier, diagnostic.Anonymous = route.Tier, false diagnostic.KeyTiers = []config.Tier{tier} diagnostic.NativeProtocol, diagnostic.NativeProtocols = route.Protocol, route.Protocols - if tier != config.TierGo { + if connection := gateway.tierOAuth(tier); connection != nil { + diagnostic.ProtocolSource = string(tier) + "_oauth" + diagnostic.Channel, diagnostic.KeyID = "oauth", oauthAccountID(connection) + } else { diagnostic.Channel, diagnostic.KeyID = "", "" - if diagnostic.ProtocolSource == "go_subscription" { + if diagnostic.ProtocolSource == "go_oauth" || diagnostic.ProtocolSource == "zen_oauth" { diagnostic.ProtocolSource = "upstream" } } diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 20fb1b4..4faf35e 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -155,7 +155,7 @@ func debugKeyOverrideFrom(ctx context.Context) (DebugKeyOverride, bool) { // replay so the Playground sees the selected key's own answer. func (g *Gateway) doUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs) (*http.Response, models.Route, error) { resp, effectiveRoute, attempts, err := g.doUpstreamTiers(ctx, route, bodies, ids, 0) - if _, selected := debugKeyOverrideFrom(ctx); selected || effectiveRoute.Tier == config.TierGo && g.cfg.GoSubscription != nil { + if _, selected := debugKeyOverrideFrom(ctx); selected || !effectiveRoute.Anonymous && g.tierOAuth(effectiveRoute.Tier) != nil { return resp, effectiveRoute, err } if err != nil || resp == nil || resp.StatusCode != http.StatusBadRequest { @@ -935,11 +935,11 @@ func (g *Gateway) shapeKeyBody(body []byte, route models.Route, tier config.Tier // live traffic before. The attempt is still recorded in telemetry, and any HTTP // response, whatever its status, is returned as is. func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, override DebugKeyOverride, attemptOffset int) (*http.Response, error, int) { - if override.Tier == config.TierGo && g.cfg.GoSubscription != nil { - if override.KeyID != subscriptionAccountID(g.cfg.GoSubscription) { - return nil, errors.New("the selected Go subscription is no longer connected"), 0 + if connection := g.tierOAuth(override.Tier); connection != nil { + if override.KeyID != oauthAccountID(connection) { + return nil, errors.New("the selected Console plan is no longer connected"), 0 } - return g.doGoSubscriptionUpstream(ctx, route, bodies, ids, attemptOffset) + return g.doOAuthUpstream(ctx, route, bodies, ids, attemptOffset) } nodes := g.zenNodes baseURL := g.cfg.Upstream.Zen @@ -1022,8 +1022,8 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, // response (body still open), else the last error, plus the number of // attempts made. func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (response *http.Response, resultErr error, resultAttempts int) { - if route.Tier == config.TierGo && g.cfg.GoSubscription != nil { - return g.doGoSubscriptionUpstream(ctx, route, bodies, ids, attemptOffset) + if g.tierOAuth(route.Tier) != nil { + return g.doOAuthUpstream(ctx, route, bodies, ids, attemptOffset) } var lastResponse *http.Response defer func() { @@ -1305,7 +1305,7 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route, KeyID: keyID, Channel: channel, Anonymous: anonymous, Proxy: proxyName, Status: status, DurationMS: max(duration.Milliseconds(), 0), Success: success, Outcome: outcome, }) - if channel != "subscription" && !isDiagnosticRequest(ctx) && g.availability != nil && g.catalog.IsFreeModel(route.ID) { + if channel != "oauth" && !isDiagnosticRequest(ctx) && g.availability != nil && g.catalog.IsFreeModel(route.ID) { bodySnippet := "" if resp != nil && (resp.StatusCode == 400 || resp.StatusCode == 404 || resp.StatusCode == 410 || resp.StatusCode == 422) { bodySnippet = string(peekResponseBody(resp)) diff --git a/internal/gateway/warp.go b/internal/gateway/warp.go index d9d1d02..8929aee 100644 --- a/internal/gateway/warp.go +++ b/internal/gateway/warp.go @@ -96,11 +96,12 @@ func (g *Gateway) newWarpLease(lease *warp.Lease, useBun bool) (*warpLease, erro if err != nil { return nil, err } + rejectRedirect := func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } return &warpLease{ lease: lease, pool: g.warp, - regular: &http.Client{Transport: transport}, - bun: &http.Client{Transport: bun}, + regular: &http.Client{Transport: transport, CheckRedirect: rejectRedirect}, + bun: &http.Client{Transport: bun, CheckRedirect: rejectRedirect}, useBun: useBun, }, nil } diff --git a/internal/httpx/bun.go b/internal/httpx/bun.go index a9c3855..da9ccec 100644 --- a/internal/httpx/bun.go +++ b/internal/httpx/bun.go @@ -53,8 +53,8 @@ type BunOptions struct { // Idle connections are pooled per host, up to MaxIdleConnsPerHost, until // IdleConnTimeout. A pooled connection the server closes is dropped while it // is idle, and a reused connection the server drops before answering is -// retried once on a fresh one. Unlike http.Transport it does not cap the -// connections per host. +// retried once on a fresh one when the request is safe to replay. Unlike +// http.Transport it does not cap the connections per host. type BunTransport struct { proxy *url.URL dialContext func(context.Context, string, string) (net.Conn, error) @@ -149,13 +149,26 @@ func (t *BunTransport) RoundTrip(req *http.Request) (*http.Response, error) { if err == nil { return resp, nil } - if info.Reused && dropped && !retried && ctx.Err() == nil { + if info.Reused && dropped && !retried && ctx.Err() == nil && bunReplayable(req, body) { continue } return nil, bunContextError(ctx, err) } } +func bunReplayable(req *http.Request, body []byte) bool { + if body != nil && req.GetBody == nil { + return false + } + switch req.Method { + case "", http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace: + return true + } + // A lost response does not prove that the server ignored a POST. Require + // the caller to opt into duplicate suppression before replaying one. + return req.Header.Get("Idempotency-Key") != "" || req.Header.Get("X-Idempotency-Key") != "" +} + // readRequestBody reads and closes the body of req. It returns nil for a // request without a body and a non-nil, possibly empty slice otherwise. func readRequestBody(req *http.Request) ([]byte, error) { @@ -413,6 +426,7 @@ func isBunEncoding(encoding string) bool { // bunDecoder decompresses a response body. The decoder is built on the first // Read, so RoundTrip never waits for a compression header. type bunDecoder struct { + mu sync.Mutex body *bunBody encoding string reader io.Reader @@ -421,11 +435,14 @@ type bunDecoder struct { } func (d *bunDecoder) Read(p []byte) (int, error) { + d.mu.Lock() + defer d.mu.Unlock() if d.err != nil { return 0, d.err } if d.reader == nil { if d.reader, d.release, d.err = newBunDecoder(d.encoding, d.body); d.err != nil { + _ = d.body.Close() return 0, d.err } } @@ -434,6 +451,7 @@ func (d *bunDecoder) Read(p []byte) (int, error) { d.err = err if d.release != nil { d.release() + d.release = nil } if err == io.EOF { // A decoder can stop at the end of its own stream and leave the @@ -446,7 +464,17 @@ func (d *bunDecoder) Read(p []byte) (int, error) { } func (d *bunDecoder) Close() error { - return d.body.Close() + err := d.body.Close() + d.mu.Lock() + defer d.mu.Unlock() + if d.release != nil { + d.release() + d.release = nil + } + if d.err == nil { + d.err = http.ErrBodyReadAfterClose + } + return err } // newBunDecoder returns a reader decoding r for encoding and, when the @@ -464,9 +492,13 @@ func newBunDecoder(encoding string, r io.Reader) (io.Reader, func(), error) { } if header[0]&0x0f == 8 && (uint16(header[0])<<8|uint16(header[1]))%31 == 0 { decoder, err := zlib.NewReader(reader) - return decoder, nil, err + if err != nil { + return nil, nil, err + } + return decoder, func() { _ = decoder.Close() }, nil } - return flate.NewReader(reader), nil, nil + decoder := flate.NewReader(reader) + return decoder, func() { _ = decoder.Close() }, nil case "br": return brotli.NewReader(r), nil, nil case "zstd": @@ -479,7 +511,10 @@ func newBunDecoder(encoding string, r io.Reader) (io.Reader, func(), error) { return decoder, decoder.Close, nil default: decoder, err := gzip.NewReader(r) - return decoder, nil, err + if err != nil { + return nil, nil, err + } + return decoder, func() { _ = decoder.Close() }, nil } } @@ -536,8 +571,24 @@ func bunRequestHead(req *http.Request, body []byte) ([]byte, bool, error) { if method == "" { method = http.MethodGet } + if !validHeaderField(method, "") { + return nil, false, errors.New("bun transport: invalid request method") + } + requestURI := req.URL.RequestURI() + for index := range len(requestURI) { + if requestURI[index] <= ' ' || requestURI[index] == 0x7f { + return nil, false, errors.New("bun transport: invalid request URI") + } + } + host := req.Host + if host == "" { + host = req.URL.Host + } + if host == "" || !validHeaderField("Host", host) || strings.ContainsAny(host, " \t/\\#?@") { + return nil, false, errors.New("bun transport: invalid request host") + } var head strings.Builder - head.WriteString(method + " " + req.URL.RequestURI() + " HTTP/1.1\r\n") + head.WriteString(method + " " + requestURI + " HTTP/1.1\r\n") // fetch computes Content-Length itself when it has a body, so it appears in // the common-header block instead of trailing the request. Header order is // part of what a fingerprint sees, so it belongs where the runtime puts it. @@ -566,10 +617,6 @@ func bunRequestHead(req *http.Request, body []byte) ([]byte, bool, error) { head.WriteString("Accept: */*\r\n") } // fetch takes Host from the parsed URL, which omits a default port. - host := req.Host - if host == "" { - host = req.URL.Host - } if req.URL.Scheme == "https" { host = strings.TrimSuffix(host, ":443") } else { diff --git a/internal/httpx/bun_dial.go b/internal/httpx/bun_dial.go index 871182c..b172f4e 100644 --- a/internal/httpx/bun_dial.go +++ b/internal/httpx/bun_dial.go @@ -134,7 +134,8 @@ func (t *BunTransport) dialProxy(ctx context.Context, addr string) (net.Conn, er if err != nil { return nil, &net.OpError{Op: op, Net: "tcp", Err: err} } - stop := context.AfterFunc(ctx, func() { conn.Close() }) + rawConn := conn + stop := context.AfterFunc(ctx, func() { rawConn.Close() }) _ = conn.SetDeadline(time.Now().Add(bunHandshakeTimeout)) if t.proxy.Scheme == "https" { tlsConn := tls.Client(conn, &tls.Config{ServerName: t.proxy.Hostname()}) @@ -268,7 +269,7 @@ func socks5Connect(conn net.Conn, user *url.Userinfo, addr string) error { if _, err := io.ReadFull(conn, reply); err != nil { return err } - if reply[1] != 0 { + if reply[0] != 1 || reply[1] != 0 { return errors.New("username/password authentication failed") } default: @@ -292,7 +293,7 @@ func socks5Connect(conn net.Conn, user *url.Userinfo, addr string) error { if _, err := io.ReadFull(conn, header); err != nil { return err } - if header[0] != 5 { + if header[0] != 5 || header[2] != 0 { return fmt.Errorf("unexpected protocol version %d", header[0]) } if header[1] != 0 { diff --git a/internal/models/cache.go b/internal/models/cache.go index d49d17a..a5edac4 100644 --- a/internal/models/cache.go +++ b/internal/models/cache.go @@ -19,7 +19,7 @@ import ( // modelCatalogCacheSchemaVersion is the layout version of the catalog cache. A // file with any other version is rejected, so bump it with every layout change. -const modelCatalogCacheSchemaVersion = 3 +const modelCatalogCacheSchemaVersion = 4 // modelCatalogCacheWriteMu serializes cache writes across catalogs: every // runtime built from one config writes the same cache file. @@ -34,6 +34,8 @@ type modelCatalogCache struct { NativeProtocols map[config.Tier]map[string]wire.Protocol `json:"native_protocols"` Unsupported map[config.Tier]map[string]bool `json:"unsupported"` Metadata map[config.Tier]map[string]Metadata `json:"metadata,omitempty"` + OAuthTiers []config.Tier `json:"oauth_tiers,omitempty"` + PendingTiers []config.Tier `json:"pending_tiers,omitempty"` } // LoadCache installs a validated disk snapshot into a catalog. It deliberately @@ -52,12 +54,23 @@ func (c *ModelCatalog) LoadCache(path string) error { c.nativeProtocols = cloneTierProtocols(cache.NativeProtocols) c.unsupported = cloneTierBools(cache.Unsupported) c.modelMeta = cloneModelMeta(cache.Metadata) + c.oauthTiers = make(map[config.Tier]bool, len(cache.OAuthTiers)) + c.pendingTiers = make(map[config.Tier]bool, len(cache.PendingTiers)) + for _, tier := range cache.PendingTiers { + c.pendingTiers[tier] = true + } + for _, tier := range cache.OAuthTiers { + c.oauthTiers[tier] = true + } c.updatedAt = cache.UpdatedAt.UTC() c.cacheSource = "disk" c.stale = true if c.cachePath == "" { c.cachePath = path } + for _, tier := range cache.OAuthTiers { + c.clearOAuthTierLocked(tier) + } c.mu.Unlock() return nil } @@ -77,6 +90,14 @@ func (c *ModelCatalog) SaveCache() error { Unsupported: cloneTierBools(c.unsupported), Metadata: cloneModelMeta(c.modelMeta), } + for _, tier := range []config.Tier{config.TierZen, config.TierGo} { + if c.oauthTiers[tier] { + cache.OAuthTiers = append(cache.OAuthTiers, tier) + } + if c.pendingTiers[tier] { + cache.PendingTiers = append(cache.PendingTiers, tier) + } + } c.mu.RUnlock() if path == "" { return nil @@ -125,12 +146,26 @@ func loadModelCatalogCache(path string) (modelCatalogCache, error) { } cache.Zen = normalizeModelIDs(cache.Zen) cache.Go = normalizeModelIDs(cache.Go) - if len(cache.Zen) == 0 && len(cache.Go) == 0 { + if len(cache.Zen) == 0 && len(cache.Go) == 0 && len(cache.OAuthTiers) == 0 && len(cache.PendingTiers) == 0 { return modelCatalogCache{}, errors.New("model catalog cache is empty") } if err := validateCatalogCapabilities(cache.NativeProtocols, cache.Unsupported); err != nil { return modelCatalogCache{}, err } + seenOAuth := make(map[config.Tier]bool, len(cache.OAuthTiers)) + for _, tier := range cache.OAuthTiers { + if tier != config.TierZen && tier != config.TierGo || seenOAuth[tier] { + return modelCatalogCache{}, errors.New("model catalog cache contains invalid OAuth tier sources") + } + seenOAuth[tier] = true + } + seenPending := make(map[config.Tier]bool, len(cache.PendingTiers)) + for _, tier := range cache.PendingTiers { + if tier != config.TierZen && tier != config.TierGo || seenPending[tier] { + return modelCatalogCache{}, errors.New("model catalog cache contains invalid pending tier sources") + } + seenPending[tier] = true + } cache.NativeProtocols = cloneTierProtocols(cache.NativeProtocols) cache.Unsupported = cloneTierBools(cache.Unsupported) cache.UpdatedAt = cache.UpdatedAt.UTC() diff --git a/internal/models/catalog.go b/internal/models/catalog.go index 07f9ace..144e225 100644 --- a/internal/models/catalog.go +++ b/internal/models/catalog.go @@ -80,6 +80,8 @@ type ModelCatalog struct { stale bool refreshAfter time.Duration freeOnly bool + oauthTiers map[config.Tier]bool + pendingTiers map[config.Tier]bool } // CatalogSnapshot summarizes the catalog for health reporting. Exposed counts @@ -185,14 +187,27 @@ func (c *ModelCatalog) Replace(zen, goModels []string) { // catalog fresh. A nil argument leaves that part of the state unchanged, so a // tier whose listing failed keeps its previous models; native and unsupported // are replaced per tier, metadata as a whole. -func (c *ModelCatalog) ReplaceWithCapabilities(zen, goModels []string, native map[config.Tier]map[string]wire.Protocol, unsupported map[config.Tier]map[string]bool, metadata map[config.Tier]map[string]Metadata) { +func (c *ModelCatalog) ReplaceWithCapabilities(zen, goModels []string, native map[config.Tier]map[string]wire.Protocol, unsupported map[config.Tier]map[string]bool, metadata map[config.Tier]map[string]Metadata, oauthTiers ...config.Tier) { c.mu.Lock() defer c.mu.Unlock() if zen != nil { c.zen = toSet(zen) + delete(c.oauthTiers, config.TierZen) + delete(c.pendingTiers, config.TierZen) } if goModels != nil { c.goModels = toSet(goModels) + delete(c.oauthTiers, config.TierGo) + delete(c.pendingTiers, config.TierGo) + } + for _, tier := range oauthTiers { + if tier != config.TierZen && tier != config.TierGo { + continue + } + if c.oauthTiers == nil { + c.oauthTiers = make(map[config.Tier]bool) + } + c.oauthTiers[tier] = true } if native != nil { for _, tier := range []config.Tier{config.TierZen, config.TierGo} { @@ -216,6 +231,42 @@ func (c *ModelCatalog) ReplaceWithCapabilities(zen, goModels []string, native ma c.stale = false } +// ClearOAuthTier discards account-specific discovery when its authorization +// changes. The tier stays pending until a new authorized catalog replaces it. +func (c *ModelCatalog) ClearOAuthTier(tier config.Tier) { + c.mu.Lock() + defer c.mu.Unlock() + c.clearOAuthTierLocked(tier) +} + +func (c *ModelCatalog) clearOAuthTierLocked(tier config.Tier) { + if !c.oauthTiers[tier] { + return + } + if tier == config.TierZen { + c.zen = map[string]bool{} + } else if tier == config.TierGo { + c.goModels = map[string]bool{} + } + delete(c.nativeProtocols, tier) + delete(c.unsupported, tier) + delete(c.modelMeta, tier) + delete(c.oauthTiers, tier) + if c.pendingTiers == nil { + c.pendingTiers = make(map[config.Tier]bool) + } + c.pendingTiers[tier] = true + c.stale = true +} + +// TierPending reports whether invalidated account discovery still needs a +// refresh; it does not treat a missing model as an authorization decision. +func (c *ModelCatalog) TierPending(tier config.Tier) bool { + c.mu.RLock() + defer c.mu.RUnlock() + return c.pendingTiers[tier] +} + // CopyState copies the discovered state of source (models, capabilities, // metadata and cache freshness) into c, so a runtime rebuilt for a config // change starts with the current catalog. Configuration (protocol overrides, @@ -248,10 +299,20 @@ func (c *ModelCatalog) CopyState(source *ModelCatalog) { updatedAt := source.updatedAt cacheSource := source.cacheSource stale := source.stale + oauthTiers := make(map[config.Tier]bool, len(source.oauthTiers)) + for tier, enabled := range source.oauthTiers { + oauthTiers[tier] = enabled + } + pendingTiers := make(map[config.Tier]bool, len(source.pendingTiers)) + for tier, pending := range source.pendingTiers { + pendingTiers[tier] = pending + } source.mu.RUnlock() c.mu.Lock() c.zen, c.goModels, c.nativeProtocols, c.unsupported, c.updatedAt = zen, goModels, native, unsupported, updatedAt c.modelMeta = meta + c.oauthTiers = oauthTiers + c.pendingTiers = pendingTiers c.cacheSource, c.stale = cacheSource, stale c.mu.Unlock() } diff --git a/internal/goauth/client.go b/internal/oauth/client.go similarity index 90% rename from internal/goauth/client.go rename to internal/oauth/client.go index ff7131d..8b79bf6 100644 --- a/internal/goauth/client.go +++ b/internal/oauth/client.go @@ -1,4 +1,4 @@ -package goauth +package oauth import ( "bytes" @@ -24,6 +24,13 @@ const ( maximumTokenSize = 16 << 10 ) +type Plan string + +const ( + PlanGo Plan = "go" + PlanZen Plan = "zen" +) + type Credential struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` @@ -90,12 +97,16 @@ func (err *OAuthError) Error() string { return "OpenCode sign-in is no longer authorized; sign in again" case "sso_required": return "OpenCode workspace requires a new SSO sign-in" - case "no_go_subscription": - return "OpenCode did not provide a supported Go subscription route" + case "no_go_oauth": + return "OpenCode did not provide a supported Go OAuth route" + case "no_zen_oauth": + return "OpenCode did not provide a supported Zen OAuth pay-as-you-go route" + case "invalid_plan": + return "OpenCode authorization plan is invalid" case "rate_limited": return "OpenCode authorization service is rate limited; try again later" case "invalid_credential": - return "OpenCode subscription credential is invalid" + return "OpenCode OAuth credential is invalid" case "invalid_response": return "OpenCode authorization service returned an invalid response" case "request_timeout": @@ -112,15 +123,17 @@ type Client struct { } func NewClient(client *http.Client) *Client { - transport := http.Client{} + httpClient := http.Client{} if client != nil { - transport = *client + httpClient = *client } - if transport.Timeout <= 0 || transport.Timeout > requestTimeout { - transport.Timeout = requestTimeout + if httpClient.Timeout <= 0 || httpClient.Timeout > requestTimeout { + httpClient.Timeout = requestTimeout } - transport.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } - return &Client{http: &transport} + // Credentials and device codes must never follow a redirect to another + // origin, including redirects supplied by the official service. + httpClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + return &Client{http: &httpClient} } func (credential Credential) Validate() error { @@ -137,6 +150,13 @@ func (credential Credential) Validate() error { } func (connection Connection) Validate() error { + return connection.ValidateForPlan(PlanGo) +} + +func (connection Connection) ValidateForPlan(plan Plan) error { + if !validPlan(plan) { + return &OAuthError{Code: "invalid_plan"} + } if err := connection.Credential.Validate(); err != nil { return err } @@ -144,10 +164,10 @@ func (connection Connection) Validate() error { return &OAuthError{Code: "invalid_credential"} } if len(connection.Routes) == 0 { - return &OAuthError{Code: "no_go_subscription"} + return noRoutesError(plan) } for model, route := range connection.Routes { - base, ok := normalizeBase(route.BaseURL, route.Protocol) + base, ok := normalizeBaseForPlan(route.BaseURL, route.Protocol, plan) if !validOpaque(model, 1024) || !validOpaque(route.ModelID, 1024) || !ok || base != route.BaseURL { return &OAuthError{Code: "invalid_credential"} } @@ -318,11 +338,11 @@ func (client *Client) request(ctx context.Context, method, path string, payload request.Header.Set("x-org-id", credential.OrganizationID) } } - transport := client - if transport == nil || transport.http == nil { - transport = NewClient(nil) + requestClient := client + if requestClient == nil || requestClient.http == nil { + requestClient = NewClient(nil) } - response, err := transport.http.Do(request) + response, err := requestClient.http.Do(request) if err != nil { if ctx.Err() != nil { return nil, ctx.Err() diff --git a/internal/goauth/discovery.go b/internal/oauth/discovery.go similarity index 70% rename from internal/goauth/discovery.go rename to internal/oauth/discovery.go index a5b192d..0de577d 100644 --- a/internal/goauth/discovery.go +++ b/internal/oauth/discovery.go @@ -1,4 +1,4 @@ -package goauth +package oauth import ( "context" @@ -29,6 +29,13 @@ type remoteProvider struct { } func (client *Client) Discover(ctx context.Context, credential Credential) (map[string]Route, error) { + return client.DiscoverForPlan(ctx, credential, PlanGo) +} + +func (client *Client) DiscoverForPlan(ctx context.Context, credential Credential, plan Plan) (map[string]Route, error) { + if !validPlan(plan) { + return nil, &OAuthError{Code: "invalid_plan"} + } if err := credential.Validate(); err != nil { return nil, err } @@ -71,11 +78,13 @@ func (client *Client) Discover(ctx context.Context, credential Credential) (map[ if baseURL == "" { baseURL = provider.Settings.BaseURL } - baseURL, ok = normalizeBase(baseURL, wireProtocol) + baseURL, ok = normalizeBaseForPlan(baseURL, wireProtocol, plan) if !ok { continue } route := Route{ModelID: modelID, Protocol: wireProtocol, BaseURL: baseURL} + // Map iteration order is arbitrary. Drop conflicting aliases instead + // of letting it decide which provider receives a billed request. if existing, exists := routes[name]; exists && existing != route { delete(routes, name) ambiguous[name] = true @@ -85,7 +94,7 @@ func (client *Client) Discover(ctx context.Context, credential Credential) (map[ } } if len(routes) == 0 { - return nil, &OAuthError{Code: "no_go_subscription"} + return nil, noRoutesError(plan) } return routes, nil } @@ -109,16 +118,25 @@ func packageProtocol(packageName string) (protocol.Protocol, bool) { } } -func normalizeBase(raw string, wireProtocol protocol.Protocol) (string, bool) { - if wireProtocol != protocol.Chat && wireProtocol != protocol.Responses && wireProtocol != protocol.Anthropic { +func normalizeBaseForPlan(raw string, wireProtocol protocol.Protocol, plan Plan) (string, bool) { + if !validPlan(plan) || wireProtocol != protocol.Chat && wireProtocol != protocol.Responses && wireProtocol != protocol.Anthropic { return "", false } + // Only official, plan-specific inference roots may receive OAuth tokens. + // Reject encoded paths and suffixes before canonicalizing route URLs. parsed, err := url.Parse(raw) if err != nil || !officialURL(parsed) || parsed.RawQuery != "" || parsed.ForceQuery || parsed.Fragment != "" || parsed.RawPath != "" { return "", false } path := strings.TrimRight(parsed.Path, "/") - if path == "/inference/go" { + root := "/inference/go" + if plan == PlanZen { + if path == "/zen" || path == "/zen/v1" { + return "https://opencode.ai/zen", true + } + root = "/inference" + } + if path == root { if wireProtocol == protocol.Anthropic { path += "/anthropic" } else { @@ -126,17 +144,28 @@ func normalizeBase(raw string, wireProtocol protocol.Protocol) (string, bool) { } } switch path { - case "/inference/go/openai", "/inference/go/openai/v1": + case root + "/openai", root + "/openai/v1": if wireProtocol == protocol.Anthropic { return "", false } - return "https://opencode.ai/inference/go/openai", true - case "/inference/go/anthropic", "/inference/go/anthropic/v1": + return "https://opencode.ai" + root + "/openai", true + case root + "/anthropic", root + "/anthropic/v1": if wireProtocol != protocol.Anthropic { return "", false } - return "https://opencode.ai/inference/go/anthropic", true + return "https://opencode.ai" + root + "/anthropic", true default: return "", false } } + +func validPlan(plan Plan) bool { + return plan == PlanGo || plan == PlanZen +} + +func noRoutesError(plan Plan) error { + if plan == PlanZen { + return &OAuthError{Code: "no_zen_oauth"} + } + return &OAuthError{Code: "no_go_oauth"} +} diff --git a/internal/protocol/collapse.go b/internal/protocol/collapse.go index 529296d..b28029e 100644 --- a/internal/protocol/collapse.go +++ b/internal/protocol/collapse.go @@ -2,7 +2,6 @@ package protocol import ( "encoding/json" - "fmt" "io" "time" ) @@ -43,7 +42,7 @@ func CollapseStream(reader io.Reader, protocol Protocol, model string) ([]byte, terminated = true return errStreamNormalTermination case "error": - streamErr = fmt.Errorf("%s", firstNonEmpty(event.Error, "upstream stream failed")) + streamErr = &StreamFailure{Message: event.Error, Type: event.ErrorType} return errStreamUpstreamFailure default: acc.apply(event) @@ -149,13 +148,3 @@ func (acc *collapseAccumulator) toolBlock(key, id, name string) *bridgeBlock { acc.tools[key] = len(acc.response.Tools) - 1 return &acc.response.Tools[len(acc.response.Tools)-1] } - -// firstNonEmpty returns the first non-empty string, or "". -func firstNonEmpty(values ...string) string { - for _, value := range values { - if value != "" { - return value - } - } - return "" -} diff --git a/internal/protocol/response.go b/internal/protocol/response.go index d9203fc..1259c84 100644 --- a/internal/protocol/response.go +++ b/internal/protocol/response.go @@ -29,7 +29,7 @@ func ConvertResponse(from, to Protocol, body []byte) ([]byte, error) { return nil, err } if response.Error != "" || response.Stop == "error" { - return nil, fmt.Errorf("upstream response failed: %s", jsonutil.FirstString(response.Error, "upstream response failed")) + return nil, &StreamFailure{Message: response.Error, Type: "upstream_error"} } return json.Marshal(encodeBridgeResponse(to, response)) } diff --git a/internal/protocol/stream.go b/internal/protocol/stream.go index 5cb6bf0..48d25e7 100644 --- a/internal/protocol/stream.go +++ b/internal/protocol/stream.go @@ -26,6 +26,10 @@ var errStreamNormalTermination = errors.New("upstream stream terminated normally // errSSEUnexpectedEOF reports a stream that ended without a terminal event. var errSSEUnexpectedEOF = errors.New("unexpected end of SSE stream") +const maxSSEFrameBytes = 16 << 20 + +var errSSEFrameTooLarge = errors.New("upstream SSE event exceeds 16 MiB") + // streamTermination records how a transcoded stream ended, so the code after // readSSE can tell a normal terminal event from an upstream error. type streamTermination uint8 @@ -91,7 +95,7 @@ func TranscodeStream(ctx context.Context, w http.ResponseWriter, reader io.Reade events, err := parser.Parse(eventName, data) if err != nil { termination = streamErrorTermination - if emitErr := emitter.Emit(bridgeStreamEvent{Kind: "error", Error: err.Error(), ErrorType: "upstream_error"}); emitErr != nil { + if emitErr := emitter.Emit(bridgeStreamEvent{Kind: "error", Error: "upstream SSE event could not be decoded", ErrorType: "upstream_error"}); emitErr != nil { return emitErr } return errStreamUpstreamFailure @@ -102,6 +106,8 @@ func TranscodeStream(ctx context.Context, w http.ResponseWriter, reader io.Reade termination = streamNormalTermination case "error": termination = streamErrorTermination + event.Error = "upstream stream failed" + event.ErrorType = "upstream_error" } if err := emitter.Emit(event); err != nil { return err @@ -147,7 +153,7 @@ func TranscodeStream(ctx context.Context, w http.ResponseWriter, reader io.Reade func emitUnexpectedStreamError(emitter *bridgeStreamEncoder, cause error) error { message := "upstream SSE stream ended before a terminal event" if cause != nil && !errors.Is(cause, errSSEUnexpectedEOF) { - message = fmt.Sprintf("upstream SSE stream failed: %v", cause) + message = "upstream SSE stream failed" } err := emitter.Emit(bridgeStreamEvent{Kind: "error", Error: message, ErrorType: "upstream_error"}) if errors.Is(err, errStreamUpstreamFailure) { @@ -165,47 +171,35 @@ func ClientCanceled(ctx context.Context, streamErr error) bool { return ctx != nil && ctx.Err() != nil } -// sseFlushWriter preserves an upstream SSE byte stream while making each -// successful write visible to the client immediately. io.Copy is free to -// choose large writes, so flushing in Write is the only reliable place to -// keep same-protocol streams live. -type sseFlushWriter struct { - writer io.Writer - flusher http.Flusher -} - -func (writer *sseFlushWriter) Write(data []byte) (int, error) { - n, err := writer.writer.Write(data) - if n > 0 { - writer.flusher.Flush() - } - return n, err -} - -// ForwardStream relays a same-protocol upstream stream to the client byte for -// byte, flushing each write, while a usage tracker reads the same bytes -// through a TeeReader. It returns the tracked usage and whether the upstream -// reported any, plus an error: the copy error, if any, for a normal -// termination that parsed cleanly; otherwise errStreamUpstreamFailure when an -// upstream error event was relayed, the copy error, or the parse error (or -// errSSEUnexpectedEOF) after an error event was emitted for a stream that -// ended early. A canceled client gets no synthetic error event. +// ForwardStream relays complete, valid same-protocol SSE frames unchanged and +// flushes each one while tracking usage. Error frames are replaced with a +// generic failure because upstream errors may echo credentials. A malformed, +// oversized or unterminated frame is never written downstream. Before the +// first frame a failure is a JSON 502; later failures are SSE error events. +// A canceled client gets no synthetic error event. func ForwardStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, protocol Protocol, model string) (Usage, bool, error) { flusher, ok := w.(http.Flusher) if !ok { return Usage{}, false, fmt.Errorf("response writer does not support streaming") } observer := streamUsageObserver(protocol) - _, copyErr := io.Copy(&sseFlushWriter{writer: w, flusher: flusher}, io.TeeReader(reader, observer)) - usage := observer.Finish() - if observer.ErrorTermination() { - if copyErr != nil { - return usage, observer.Reported(), copyErr + committed := false + observer.forward = func(frame []byte) error { + committed = true + written, err := w.Write(frame) + if err == nil && written != len(frame) { + err = io.ErrShortWrite } - return usage, observer.Reported(), errStreamUpstreamFailure + if err != nil { + return &ClientWriteError{Err: err} + } + flusher.Flush() + return nil } - if observer.NormalTermination() && observer.ParseError() == nil { - return usage, observer.Reported(), copyErr + _, copyErr := io.Copy(observer, reader) + usage := observer.Finish() + if errors.Is(copyErr, errStreamNormalTermination) { + return usage, observer.Reported(), nil } if ClientCanceled(ctx, copyErr) { if copyErr == nil { @@ -213,6 +207,10 @@ func ForwardStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, } return usage, observer.Reported(), copyErr } + var writeErr *ClientWriteError + if errors.As(copyErr, &writeErr) { + return usage, observer.Reported(), copyErr + } cause := observer.ParseError() if copyErr != nil { cause = copyErr @@ -220,6 +218,11 @@ func ForwardStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, if cause == nil { cause = errSSEUnexpectedEOF } + if !committed { + w.Header().Del("X-Accel-Buffering") + WriteError(w, protocol, http.StatusBadGateway, "upstream SSE stream failed", "upstream_error", "") + return usage, observer.Reported(), cause + } emitter := bridgeStreamEmitter(w, flusher, protocol, model) if err := emitUnexpectedStreamError(emitter, cause); err != nil { return usage, observer.Reported(), err @@ -261,11 +264,21 @@ func (reader *renameStreamReader) Read(data []byte) (int, error) { if reader.err != nil { return 0, reader.err } - // ReadString either returns a non-empty chunk with a nil error or - // returns the trailing chunk together with EOF, so one iteration - // always either fills pending or reports the error below; the loop - // condition only guards the entry. - line, err := reader.buffer.ReadString('\n') + var lineBytes []byte + var err error + for { + var part []byte + part, err = reader.buffer.ReadSlice('\n') + if len(lineBytes)+len(part) > maxSSEFrameBytes { + reader.err = errSSEFrameTooLarge + return 0, reader.err + } + lineBytes = append(lineBytes, part...) + if !errors.Is(err, bufio.ErrBufferFull) { + break + } + } + line := string(lineBytes) if len(line) > 0 { reader.pending = reader.rewriteLine(line) } @@ -398,7 +411,9 @@ func (renamer *streamToolRenamer) rewriteChatFrame(raw string) []byte { if function == nil { continue } - key := fmt.Sprint(jsonutil.FirstAny(call["index"], jsonutil.StringAt(call, "id"), callIndex)) + // Tool indices restart at zero in each choice. Keeping the choice + // in the key prevents one completion from consuming another's name. + key := fmt.Sprint(choiceIndex) + "\x00" + fmt.Sprint(jsonutil.FirstAny(call["index"], jsonutil.StringAt(call, "id"), callIndex)) state := renamer.toolState(key) state.callIndex = jsonutil.FirstAny(call["index"], callIndex) state.choiceIndex = choiceIndex @@ -632,6 +647,7 @@ func (renamer *streamToolRenamer) toolState(key string) *streamToolRenameState { // modifies the bytes it is given. type streamUsageTracker struct { parser *bridgeStreamParser + forward func([]byte) error buffer []byte usage Usage reported bool @@ -649,18 +665,51 @@ func streamUsageObserver(protocol Protocol) *streamUsageTracker { }} } -// Write buffers the relayed bytes and consumes every complete SSE frame they -// contain, keeping the incomplete tail for the next call. It never fails. +// Write validates each complete frame before passing its original bytes to +// forward. The bounded tail is retained until a delimiter arrives; errors and +// the terminal event stop copying before any later bytes can be forwarded. func (observer *streamUsageTracker) Write(data []byte) (int, error) { - observer.buffer = append(observer.buffer, data...) - for { - index, width := nextSSEBoundary(observer.buffer) - if index < 0 { - break + if observer.parseErr != nil { + return 0, observer.parseErr + } + remaining := data + for len(remaining) > 0 { + count := min(len(remaining), maxSSEFrameBytes+1-len(observer.buffer)) + observer.buffer = append(observer.buffer, remaining[:count]...) + remaining = remaining[count:] + for { + index, width := nextSSEBoundary(observer.buffer) + if index < 0 { + break + } + if index+width > maxSSEFrameBytes { + observer.parseErr = errSSEFrameTooLarge + break + } + observer.consume(observer.buffer[:index+width]) + if observer.parseErr != nil { + return len(data) - len(remaining), observer.parseErr + } + if observer.error { + return len(data) - len(remaining), errStreamUpstreamFailure + } + if observer.forward != nil { + if err := observer.forward(observer.buffer[:index+width]); err != nil { + return len(data) - len(remaining), err + } + } + observer.buffer = observer.buffer[index+width:] + if observer.normal { + return len(data) - len(remaining), errStreamNormalTermination + } + } + if len(observer.buffer) > maxSSEFrameBytes { + observer.parseErr = errSSEFrameTooLarge + } + if observer.parseErr != nil { + observer.buffer = nil + return len(data) - len(remaining), observer.parseErr } - frame := append([]byte(nil), observer.buffer[:index+width]...) - observer.buffer = observer.buffer[index+width:] - observer.consume(frame) } return len(data), nil } @@ -675,17 +724,12 @@ func (observer *streamUsageTracker) Finish() Usage { func (observer *streamUsageTracker) Reported() bool { return observer.reported } -func (observer *streamUsageTracker) NormalTermination() bool { return observer.normal } - -func (observer *streamUsageTracker) ErrorTermination() bool { return observer.error } - func (observer *streamUsageTracker) ParseError() error { return observer.parseErr } -// consume parses one complete SSE frame and records its terminal events and -// usage. A parse error is remembered but not propagated, because the relay -// must keep copying bytes. +// consume parses one complete SSE frame and records its terminal events, +// usage and parse error before Write decides whether the frame can be relayed. func (observer *streamUsageTracker) consume(frame []byte) { - _ = readSSE(strings.NewReader(string(frame)), func(eventName, data string) error { + err := readSSE(bytes.NewReader(frame), func(eventName, data string) error { events, err := observer.parser.Parse(eventName, data) if err != nil { if observer.parseErr == nil { @@ -707,6 +751,9 @@ func (observer *streamUsageTracker) consume(frame []byte) { } return nil }) + if err != nil && observer.parseErr == nil { + observer.parseErr = err + } } // nextSSEBoundary finds the end of the first complete SSE frame in data: it @@ -736,9 +783,10 @@ func nextSSEBoundary(data []byte) (int, int) { // errors, and errors returned by handler, end the read. func readSSE(reader io.Reader, handler func(eventName, data string) error) error { scanner := bufio.NewScanner(reader) - scanner.Buffer(make([]byte, 64<<10), 16<<20) + scanner.Buffer(make([]byte, 64<<10), maxSSEFrameBytes) var eventName string var dataLines []string + frameBytes := 0 flush := func() error { if len(dataLines) == 0 { eventName = "" @@ -751,10 +799,15 @@ func readSSE(reader io.Reader, handler func(eventName, data string) error) error } for scanner.Scan() { line := strings.TrimSuffix(scanner.Text(), "\r") + frameBytes += len(line) + 1 + if frameBytes > maxSSEFrameBytes { + return errSSEFrameTooLarge + } if line == "" { if err := flush(); err != nil { return err } + frameBytes = 0 continue } if strings.HasPrefix(line, ":") { diff --git a/internal/protocol/tools.go b/internal/protocol/tools.go index 99e2045..28f0407 100644 --- a/internal/protocol/tools.go +++ b/internal/protocol/tools.go @@ -121,6 +121,18 @@ func (r *ToolRenames) Add(client, wire string) { if _, taken := r.toClient[wire]; taken { return } + if r.toWire == nil { + r.toWire = map[string]string{} + } + if r.toClient == nil { + r.toClient = map[string]string{} + } + if r.byCase == nil { + r.byCase = map[string]string{} + } + if r.byShape == nil { + r.byShape = map[string]string{} + } r.toWire[client] = wire r.toClient[wire] = client r.bindFolded(r.byCase, strings.ToLower(client), client) diff --git a/internal/rotation/state.go b/internal/rotation/state.go index 142805f..86ed479 100644 --- a/internal/rotation/state.go +++ b/internal/rotation/state.go @@ -6,13 +6,14 @@ package rotation import ( "encoding/json" "fmt" - "opencode2api/internal/config" "os" "path/filepath" "slices" "sort" "sync" "time" + + "opencode2api/internal/config" ) // Attempt is one upstream attempt of a rotation request, kept for the WebUI. @@ -85,13 +86,13 @@ type Manager struct { func New(path string, cfg config.RotationConfig) (*Manager, error) { m := &Manager{path: path} if path != "" { - b, e := os.ReadFile(path) - if e == nil { - if e = json.Unmarshal(b, &m.state); e != nil { - return nil, fmt.Errorf("invalid rotation state: %w", e) + data, err := os.ReadFile(path) + if err == nil { + if err := json.Unmarshal(data, &m.state); err != nil { + return nil, fmt.Errorf("invalid rotation state: %w", err) } - } else if !os.IsNotExist(e) { - return nil, e + } else if !os.IsNotExist(err) { + return nil, err } } if len(m.state.Groups) != 0 && (len(m.state.Groups) != 2 || m.state.Groups[0] == nil || m.state.Groups[1] == nil || m.state.Groups[0].ID != "sota" || m.state.Groups[1].ID != "sweet") { @@ -214,8 +215,8 @@ func (m *Manager) Snapshot() Snapshot { return s } -// group returns the group with id, or nil. The caller holds m.mu. -func (m *Manager) group(id string) *Group { +// groupLocked returns the group with id, or nil. The caller holds m.mu. +func (m *Manager) groupLocked(id string) *Group { for _, g := range m.state.Groups { if g.ID == id { return g @@ -224,8 +225,8 @@ func (m *Manager) group(id string) *Group { return nil } -// usable reports whether model is available in g and not paused. -func usable(g *Group, model string) bool { +// modelUsable reports whether model is available in g and not paused. +func modelUsable(g *Group, model string) bool { return g.Available[model] && !time.Now().Before(g.Paused[model]) } @@ -237,18 +238,18 @@ func usable(g *Group, model string) bool { func (m *Manager) Select(id string, visited map[string]bool) (Token, bool) { m.mu.Lock() defer m.mu.Unlock() - g := m.group(id) + g := m.groupLocked(id) if g == nil || len(g.Order) == 0 { return Token{}, false } start := max(slices.Index(g.Order, g.Current), 0) for n := 0; n < len(g.Order); n++ { model := g.Order[(start+n)%len(g.Order)] - if visited[model] || !usable(g, model) { + if visited[model] || !modelUsable(g, model) { continue } // A request-local skip must not change a newer, healthy global selection. - if !usable(g, g.Current) { + if !modelUsable(g, g.Current) { m.switchLocked(g, model, "当前模型暂停或已下架") m.saveLocked() } @@ -279,7 +280,7 @@ func (m *Manager) switchLocked(g *Group, to, reason string) { func (m *Manager) Fail(t Token, pause time.Duration, reason string) { m.mu.Lock() defer m.mu.Unlock() - g := m.group(t.Group) + g := m.groupLocked(t.Group) if g == nil { return } @@ -292,7 +293,7 @@ func (m *Manager) Fail(t Token, pause time.Duration, reason string) { next := t.Model for n := 1; n < len(g.Order); n++ { v := g.Order[(start+n)%len(g.Order)] - if usable(g, v) { + if modelUsable(g, v) { next = v break } @@ -308,7 +309,7 @@ func (m *Manager) Fail(t Token, pause time.Duration, reason string) { func (m *Manager) Manual(id, model string) error { m.mu.Lock() defer m.mu.Unlock() - g := m.group(id) + g := m.groupLocked(id) if g == nil || !slices.Contains(g.Order, model) || !g.Available[model] { return fmt.Errorf("请选择该组当前可用的 Go 模型") } diff --git a/internal/telemetry/http.go b/internal/telemetry/http.go index 195285b..a95eb03 100644 --- a/internal/telemetry/http.go +++ b/internal/telemetry/http.go @@ -103,6 +103,9 @@ func (w *statusWriter) Write(data []byte) (int, error) { } func (w *statusWriter) Flush() { + if w.status == 0 { + w.WriteHeader(http.StatusOK) + } _ = http.NewResponseController(w.ResponseWriter).Flush() } diff --git a/internal/telemetry/logging.go b/internal/telemetry/logging.go index 1029be6..8073370 100644 --- a/internal/telemetry/logging.go +++ b/internal/telemetry/logging.go @@ -1,11 +1,13 @@ package telemetry import ( + "bytes" "context" - "fmt" + "encoding/json" "io" "log/slog" "os" + "reflect" "strings" "sync" "time" @@ -146,10 +148,17 @@ type hubHandler struct { base slog.Handler hub *LogBroker redactor *config.Redactor - attrs []slog.Attr + attrs []scopedLogAttr groups []string } +// scopedLogAttr keeps the group active when WithAttrs was called; later +// WithGroup calls must not move previously bound attributes into that group. +type scopedLogAttr struct { + attr slog.Attr + groups []string +} + // StructuredLogger returns a logger that writes JSON to stdout and mirrors // every record into hub. Both outputs pass through redactor, and attributes // whose keys mention a password, authorization, cookie or secret are masked. @@ -159,53 +168,135 @@ func StructuredLogger(level *slog.LevelVar, hub *LogBroker, redactor *config.Red // structuredLogger is StructuredLogger with an explicit JSON output. func structuredLogger(output io.Writer, level *slog.LevelVar, hub *LogBroker, redactor *config.Redactor) *slog.Logger { - base := slog.NewJSONHandler(output, &slog.HandlerOptions{Level: level, ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr { - return sanitizeLogAttr(redactor, attr) - }}) + base := slog.NewJSONHandler(output, &slog.HandlerOptions{Level: level}) return slog.New(&hubHandler{base: base, hub: hub, redactor: redactor}) } -// sanitizeLogAttr prepares an attribute for the JSON output: a sensitive key -// masks the value, and string and error values pass through redactor. +// sanitizeLogAttr applies the same policy to scalars, groups and structured +// values. Redacting only strings leaves secrets inside slog.Any untouched. func sanitizeLogAttr(redactor *config.Redactor, attr slog.Attr) slog.Attr { attr.Value = attr.Value.Resolve() - lower := strings.ToLower(attr.Key) - if strings.Contains(lower, "password") || strings.Contains(lower, "authorization") || strings.Contains(lower, "cookie") || strings.Contains(lower, "secret") { - return slog.String(attr.Key, "***") + if sensitiveLogKey(attr.Key) { + return slog.String(redactor.String(attr.Key), "***") } + attr.Key = redactor.String(attr.Key) switch attr.Value.Kind() { case slog.KindString: attr.Value = slog.StringValue(redactor.String(attr.Value.String())) - case slog.KindAny: - if err, ok := attr.Value.Any().(error); ok { - attr.Value = slog.StringValue(redactor.String(err.Error())) + case slog.KindGroup: + children := attr.Value.Group() + sanitized := make([]slog.Attr, 0, len(children)) + for _, child := range children { + sanitized = append(sanitized, sanitizeLogAttr(redactor, child)) } + attr.Value = slog.GroupValue(sanitized...) + case slog.KindAny: + value := attr.Value.Any() + if value == nil { + break + } + reflected := reflect.ValueOf(value) + if reflected.Kind() == reflect.Pointer && reflected.IsNil() { + attr.Value = slog.AnyValue(nil) + break + } + if err, ok := value.(error); ok { + attr.Value = slog.StringValue(redactor.String(err.Error())) + break + } + encoded, err := json.Marshal(value) + if err != nil { + attr.Value = slog.StringValue("") + break + } + var decoded any + decoder := json.NewDecoder(bytes.NewReader(encoded)) + decoder.UseNumber() + if err := decoder.Decode(&decoded); err != nil { + attr.Value = slog.StringValue("") + break + } + attr.Value = slog.AnyValue(sanitizeLogValue(redactor, decoded)) } return attr } +func sensitiveLogKey(key string) bool { + key = strings.Map(func(character rune) rune { + if character == '_' || character == '-' || character == '.' { + return -1 + } + return character + }, strings.ToLower(key)) + for _, marker := range []string{"password", "authorization", "cookie", "secret", "credential", "apikey", "privatekey", "accesstoken", "refreshtoken", "authtoken", "sessiontoken", "idtoken"} { + if strings.Contains(key, marker) { + return true + } + } + return key == "token" || key == "bearer" || key == "jwt" +} + +func sanitizeLogValue(redactor *config.Redactor, value any) any { + switch current := value.(type) { + case string: + return redactor.String(current) + case map[string]any: + sanitized := make(map[string]any, len(current)) + for key, child := range current { + if sensitiveLogKey(key) { + sanitized[redactor.String(key)] = "***" + } else { + sanitized[redactor.String(key)] = sanitizeLogValue(redactor, child) + } + } + return sanitized + case []any: + for index, child := range current { + current[index] = sanitizeLogValue(redactor, child) + } + } + return value +} + func (h *hubHandler) Enabled(ctx context.Context, level slog.Level) bool { return h.base.Enabled(ctx, level) } func (h *hubHandler) Handle(ctx context.Context, record slog.Record) error { - if err := h.base.Handle(ctx, record); err != nil { - return err - } + // Sanitize bound attributes at emission time. JSONHandler.WithAttrs would + // cache their old masking policy across configuration and token refreshes. + output := slog.NewRecord(record.Time, record.Level, h.redactor.String(record.Message), record.PC) + handler := h.base + groupDepth := 0 fields := make(map[string]any, record.NumAttrs()+len(h.attrs)) for _, attr := range h.attrs { - h.addAttr(fields, attr) + for groupDepth < len(attr.groups) { + handler = handler.WithGroup(h.redactor.String(attr.groups[groupDepth])) + groupDepth++ + } + sanitized := h.scopedAttr(attr.attr, attr.groups) + handler = handler.WithAttrs([]slog.Attr{sanitized}) + h.addAttr(fields, sanitized, h.redactedGroups(attr.groups)) + } + for groupDepth < len(h.groups) { + handler = handler.WithGroup(h.redactor.String(h.groups[groupDepth])) + groupDepth++ } record.Attrs(func(attr slog.Attr) bool { - h.addAttr(fields, attr) + sanitized := h.scopedAttr(attr, h.groups) + output.AddAttrs(sanitized) + h.addAttr(fields, sanitized, h.redactedGroups(h.groups)) return true }) + if err := handler.Handle(ctx, output); err != nil { + return err + } component, _ := fields["component"].(string) delete(fields, "component") h.hub.Publish(LogEvent{ Time: record.Time.UTC(), Level: strings.ToLower(record.Level.String()), - Message: h.redactor.String(record.Message), + Message: output.Message, Component: component, Fields: fields, }) @@ -214,35 +305,64 @@ func (h *hubHandler) Handle(ctx context.Context, record slog.Record) error { func (h *hubHandler) WithAttrs(attrs []slog.Attr) slog.Handler { clone := *h - clone.base = h.base.WithAttrs(attrs) - clone.attrs = append(append([]slog.Attr(nil), h.attrs...), attrs...) + clone.attrs = append([]scopedLogAttr(nil), h.attrs...) + for _, attr := range attrs { + clone.attrs = append(clone.attrs, scopedLogAttr{attr: attr, groups: append([]string(nil), h.groups...)}) + } return &clone } func (h *hubHandler) WithGroup(name string) slog.Handler { + if name == "" { + return h + } clone := *h - clone.base = h.base.WithGroup(name) clone.groups = append(append([]string(nil), h.groups...), name) return &clone } -// addAttr stores attr in fields under its dotted group path. A sensitive key -// masks the value; strings and values of non-scalar kinds are redacted as text. -func (h *hubHandler) addAttr(fields map[string]any, attr slog.Attr) { - attr.Value = attr.Value.Resolve() - key := attr.Key - if len(h.groups) > 0 { - key = strings.Join(append(append([]string(nil), h.groups...), key), ".") +func (h *hubHandler) scopedAttr(attr slog.Attr, groups []string) slog.Attr { + if attr.Equal(slog.Attr{}) { + return attr } - lower := strings.ToLower(key) - if strings.Contains(lower, "password") || strings.Contains(lower, "authorization") || strings.Contains(lower, "cookie") || strings.Contains(lower, "secret") { - fields[key] = "***" + for _, group := range groups { + if sensitiveLogKey(group) { + return slog.String(h.redactor.String(attr.Key), "***") + } + } + return sanitizeLogAttr(h.redactor, attr) +} + +func (h *hubHandler) redactedGroups(groups []string) []string { + result := make([]string, len(groups)) + for index, group := range groups { + result[index] = h.redactor.String(group) + } + return result +} + +// addAttr stores attr in fields under its dotted group path. A sensitive key +// masks the value. Groups are traversed so both outputs scrub nested secrets. +func (h *hubHandler) addAttr(fields map[string]any, attr slog.Attr, groups []string) { + if attr.Equal(slog.Attr{}) { return } + key := attr.Key + if len(groups) > 0 { + key = strings.Join(append(append([]string(nil), groups...), key), ".") + } var value any switch attr.Value.Kind() { + case slog.KindGroup: + if attr.Key != "" { + groups = append(append([]string(nil), groups...), attr.Key) + } + for _, child := range attr.Value.Group() { + h.addAttr(fields, child, groups) + } + return case slog.KindString: - value = h.redactor.String(attr.Value.String()) + value = attr.Value.String() case slog.KindInt64: value = attr.Value.Int64() case slog.KindUint64: @@ -256,7 +376,7 @@ func (h *hubHandler) addAttr(fields map[string]any, attr slog.Attr) { case slog.KindTime: value = attr.Value.Time().UTC() default: - value = h.redactor.String(fmt.Sprint(attr.Value.Any())) + value = attr.Value.Any() } fields[key] = value } diff --git a/internal/telemetry/metrics.go b/internal/telemetry/metrics.go index 2916ab8..c3df130 100644 --- a/internal/telemetry/metrics.go +++ b/internal/telemetry/metrics.go @@ -320,6 +320,7 @@ var latencyBounds = [...]uint64{50, 100, 250, 500, 1000, 2500, 5000, 10000, 3000 // request was routed to a tier, and a request that carries a request ID and a // model joins the recent requests. func (m *Metrics) Record(endpoint string, status int, duration time.Duration, meta *RequestMeta) { + endpoint = metricEndpoint(endpoint) success := requestSucceeded(status, meta) m.total.Add(1) if success { @@ -399,6 +400,17 @@ func (m *Metrics) Record(endpoint string, status int, duration time.Duration, me m.mu.Unlock() } +// metricEndpoint bounds label cardinality before authentication or routing. +// Arbitrary 404 paths must not allocate a new counter on every request. +func metricEndpoint(path string) string { + switch path { + case "/healthz", "/v1/models", "/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone": + return path + default: + return "other" + } +} + // requestSucceeded reports whether a request counts as a success: a 2xx or 3xx // status and no terminal failure in meta.Outcome. A stream can fail after HTTP // headers have been sent. Preserve its HTTP status while using the terminal diff --git a/internal/warp/exit.go b/internal/warp/exit.go index 4c8e5f9..716bd04 100644 --- a/internal/warp/exit.go +++ b/internal/warp/exit.go @@ -73,14 +73,9 @@ type exit struct { closeOnce sync.Once } -func newExit(ctx context.Context, reg registration) (*exit, error) { - return newExitWithStack(ctx, reg, DefaultStack, netip.Addr{}) -} - // newExitWithStack builds one userspace tunnel for reg. A valid source pins -// the outer WireGuard socket to that address and restricts the peer endpoints -// to IPv6, so the public egress is derived from the rotating source rather than -// from whatever address the host happens to share. +// the outer IPv6 socket and tries IPv6 endpoints first. IPv4 endpoints remain +// available as a fallback when the host cannot reach Cloudflare over IPv6. func newExitWithStack(ctx context.Context, reg registration, stack Stack, source netip.Addr) (*exit, error) { normalized, err := ParseStack(string(stack)) if err != nil { diff --git a/internal/warp/pool.go b/internal/warp/pool.go index f15e98a..d617701 100644 --- a/internal/warp/pool.go +++ b/internal/warp/pool.go @@ -496,7 +496,7 @@ func (p *Pool) replace(old *exit, reason string) { return } if p.logger != nil { - p.logger.Infof("OpenCode WARP egress %s replaced by %s at %s (%s), active=%d", old.id, replacement.id, replacement.egress, reason, len(p.active)) + p.logger.Infof("OpenCode WARP egress %s replaced by %s at %s (%s)", old.id, replacement.id, replacement.egress, reason) } old.retire() p.startRefill() @@ -618,10 +618,9 @@ func (p *Pool) released() { } closed := p.closed wantRefill := !closed && len(p.active) < p.desiredLocked() - started := p.scaling - if !closed && !started && len(p.active) > p.desiredLocked() { + scheduleScaleDown := !closed && !p.scaling && len(p.active) > p.desiredLocked() + if scheduleScaleDown { p.scaling = true - started = true } p.mu.Unlock() if closed { @@ -630,7 +629,7 @@ func (p *Pool) released() { if wantRefill { p.startRefill() } - if started { + if scheduleScaleDown { p.after(scaleDownDelay, p.scaleDown) } } diff --git a/internal/warp/registrar.go b/internal/warp/registrar.go index 1dcfe0f..3db0b5e 100644 --- a/internal/warp/registrar.go +++ b/internal/warp/registrar.go @@ -93,7 +93,8 @@ func newRegistrar() *registrar { return ®istrar{ base: defaultAPIBase, client: &http.Client{ - Timeout: 30 * time.Second, + Timeout: 30 * time.Second, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, Transport: &http.Transport{ Proxy: nil, ForceAttemptHTTP2: false, @@ -293,7 +294,6 @@ func (r *registrar) doJSON(ctx context.Context, method, path string, body []byte continue } if resp.StatusCode < 200 || resp.StatusCode >= 300 { - bodyText := strings.TrimSpace(string(data)) if resp.StatusCode == http.StatusTooManyRequests { // Cloudflare's own limit becomes the pacing. Record it and fail // fast: sleeping here would hold the pool's create mutex and @@ -306,9 +306,11 @@ func (r *registrar) doJSON(ctx context.Context, method, path string, body []byte pause = maxRateLimitPause } r.pause(pause) - return ®istrationPausedError{retryAfter: pause, reason: bodyText} + return ®istrationPausedError{retryAfter: pause, reason: "Cloudflare rate limit"} } - lastErr = fmt.Errorf("Cloudflare API HTTP %d: %s", resp.StatusCode, bodyText) + // Registration replies can echo device credentials. Retain the + // status for diagnostics without putting those replies into logs. + lastErr = fmt.Errorf("Cloudflare API HTTP %d", resp.StatusCode) if resp.StatusCode < 500 { return lastErr } diff --git a/webui/index.html b/webui/index.html index 1b81d77..0cf6b94 100644 --- a/webui/index.html +++ b/webui/index.html @@ -13,16 +13,7 @@ - + @@ -650,18 +641,35 @@
-

Go 订阅登录

-

通过 OpenCode 官方页面授权,无需复制凭证。手动 Go Key 仍保留,订阅连接期间不作备用通道,断开后恢复原有路由。

+

Go OAuth 登录

+

通过 OpenCode 官方页面完成 Go OAuth 授权,无需复制凭证。手动 Go Key 仍保留,Go OAuth 连接期间不作备用通道,断开后恢复原有路由。

- +
-
+
- - - + + +
-

只接入已确认的 Go 订阅路由,不自动改用余额通道。OAuth 订阅额度查询不可用时显示未知,不推算剩余额度。

+

只接入已确认的 Go 订阅路由,不自动改用余额通道。Go 订阅额度查询不可用时显示未知,不推算剩余额度。

+
+
+
+
+

Zen / Console PAYG OAuth

+

独立授权 Zen 按量付费通道;保留手动 Zen Key 和 Go OAuth 连接。Go OAuth 登录不会启用此通道。

+
+ +
+

启用后走 Zen OAuth 的请求按 PAYG 消耗 credits,不使用 Go 订阅额度;不会自动将 Go 失败转入本通道,模型仍依配置 prefer 选路。

+
+
+ + + +
+

本页 Go 额度不代表 Zen credits 余额;不推算 PAYG 余额或可用次数,请在官方 Console 查看计费信息。断开仅移除本地登录,不撤销官方会话。

diff --git a/webui/js/api.js b/webui/js/api.js index b1ae577..201bdc9 100644 --- a/webui/js/api.js +++ b/webui/js/api.js @@ -3,14 +3,17 @@ import * as store from "./store.js"; import { t } from "./i18n.js"; let csrf = ""; +let sessionVersion = 0; let onUnauthorized = null; export function setCsrf(value) { csrf = value || ""; + sessionVersion++; } export function clearCsrf() { csrf = ""; + sessionVersion++; } export function hasSession() { @@ -22,13 +25,18 @@ export function setUnauthorizedHandler(handler) { } export async function api(path, options = {}) { + const requestVersion = sessionVersion; const headers = { ...(options.headers || {}), Accept: "application/json" }; if (options.body) headers["Content-Type"] = "application/json"; if (csrf && !["GET", "HEAD"].includes((options.method || "GET").toUpperCase())) headers["X-CSRF-Token"] = csrf; const response = await fetch(path, { ...options, headers }); + const data = response.status === 204 ? null : await response.json().catch(() => ({})); + // A response from a previous login must not reveal data or invalidate the + // new session after the operator logs out and signs in again. + if (requestVersion !== sessionVersion) + throw new DOMException("The management session changed", "AbortError"); if (response.status === 204) return null; - const data = await response.json().catch(() => ({})); if (!response.ok) { // The login endpoint answers 401 for bad credentials: surface its message // instead of treating the attempt as an expired session. diff --git a/webui/js/go-auth.js b/webui/js/go-auth.js deleted file mode 100644 index 0420066..0000000 --- a/webui/js/go-auth.js +++ /dev/null @@ -1,290 +0,0 @@ -import { api, hasSession } from "./api.js"; -import * as store from "./store.js"; -import { t, onChange } from "./i18n.js"; -import { $, confirmDialog, el, localTime } from "./ui.js"; - -let state = null; -let timer = null; -let active = false; -let busy = false; -let generation = 0; -let controller = null; -let failure = ""; -let connectionChanged = null; -let synchronizationPending = false; - -function stopPolling() { - clearTimeout(timer); - timer = null; -} - -function verificationURL(value) { - try { - const parsed = new URL(value, "https://opencode.ai/console/"); - if ( - parsed.protocol !== "https:" || - parsed.host !== "opencode.ai" || - parsed.username || - parsed.password - ) - return null; - return parsed.href; - } catch { - return null; - } -} - -function pendingExpired() { - const expires = Date.parse(state?.pending?.expires_at); - return Number.isFinite(expires) && expires <= Date.now(); -} - -function connectionID(value) { - return value?.connected - ? JSON.stringify([ - value.account?.email, - value.account?.organization, - value.account?.models, - !!value.account?.needs_login, - ]) - : ""; -} - -function current(operation) { - return operation === generation && hasSession(); -} - -async function synchronize(operation) { - const [config, debug] = await Promise.all([api("/api/config"), api("/api/debug/models")]); - if (!current(operation)) return; - store.set("config", config); - if (debug.last_inference) store.set("lastPlayground", debug.last_inference); - store.set("debug", debug); - await connectionChanged?.(); - if (current(operation)) synchronizationPending = false; -} - -function schedulePoll() { - stopPolling(); - const pending = state?.pending; - if ( - !active || - document.hidden || - busy || - failure || - !hasSession() || - !pending || - pendingExpired() || - pending.status === "failed" || - pending.status === "choosing_org" - ) - return; - const seconds = Number(pending.retry_after_seconds ?? pending.interval_seconds ?? 5); - const wait = Number.isFinite(seconds) ? Math.max(1, Math.min(seconds, 86400)) : 5; - timer = setTimeout(() => { - if (pendingExpired() || state?.pending?.status === "starting") refresh(); - else poll(); - }, wait * 1000); -} - -async function request(path, options = {}, action = "refresh") { - if (busy || !hasSession()) return; - stopPolling(); - const operation = generation; - const previous = connectionID(state); - busy = true; - failure = ""; - controller = new AbortController(); - render(); - try { - const next = await api(path, { ...options, signal: controller.signal }); - if (!current(operation)) return; - state = next; - render(); - if ( - action === "disconnect" || - previous !== connectionID(next) || - (action === "poll" && next.connected && !next.pending) - ) - synchronizationPending = true; - if (synchronizationPending) await synchronize(operation); - } catch (error) { - if (current(operation) && error.name !== "AbortError") failure = error.message; - } finally { - if (current(operation)) { - busy = false; - controller = null; - render(); - schedulePoll(); - } - } -} - -function poll(organizationID) { - if (!state?.pending?.id) return; - const body = { id: state.pending.id }; - if (organizationID) body.organization_id = organizationID; - return request("/api/go/auth/poll", { method: "POST", body: JSON.stringify(body) }, "poll"); -} - -async function disconnect() { - const operation = generation; - const confirmed = await confirmDialog({ - title: t("断开 Go 订阅登录", "goAuth.disconnect"), - message: t( - "仅移除网关保存的订阅登录,不删除手动 Go Key,也不会撤销 OpenCode 官方会话。是否继续?", - "goAuth.disconnectConfirm", - ), - confirmLabel: t("断开连接", "goAuth.disconnectAction"), - danger: true, - }); - if (!confirmed || !current(operation)) return; - await request("/api/go/connection", { method: "DELETE", body: "{}" }, "disconnect"); -} - -function render() { - const pending = state?.pending; - const expired = pendingExpired(); - const selected = $("#go-auth-organization")?.value; - const host = $("#go-auth-content"); - host.replaceChildren(); - $("#go-auth-start").textContent = state?.connected - ? t("重新登录 Go 订阅", "goAuth.reconnect") - : t("浏览器登录 Go 订阅", "goAuth.start"); - $("#go-auth-start").disabled = busy || !!(pending && pending.status !== "failed" && !expired); - $("#go-auth-refresh").disabled = busy; - $("#go-auth-cancel").classList.toggle("hidden", !pending); - $("#go-auth-cancel").disabled = busy; - $("#go-auth-disconnect").classList.toggle("hidden", !state?.connected); - $("#go-auth-disconnect").disabled = busy; - if (state?.connected) { - const account = state.account || {}; - host.append( - el("p", { - class: account.needs_login ? "warn" : "ok", - text: account.needs_login - ? t("Go 订阅登录已失效,请重新登录。手动 Go Key 不会作为备用通道。", "goAuth.needsLogin") - : t("Go 订阅已连接,登录凭证仅保存在网关服务端。", "goAuth.connected"), - }), - ); - if (account.error) host.append(el("p", { class: "warn", text: account.error })); - if (account.email) host.append(el("p", { class: "mono", text: account.email })); - if (account.organization) - host.append(el("p", { text: t("组织:{0}", "goAuth.organizationValue", account.organization) })); - if (account.models != null) - host.append(el("p", { text: t("已获取 {0} 个订阅模型。", "goAuth.models", account.models) })); - if (account.expires_at && !account.needs_login) - host.append( - el("p", { - class: "section-caption", - text: t("访问凭证到期:{0};网关按需自动刷新。", "goAuth.expires", localTime(account.expires_at)), - }), - ); - } else if (!pending) { - host.append(el("p", { - class: "section-caption", - text: t("尚未连接 Go 订阅。手动配置的 Go Key 不受此登录影响。", "goAuth.disconnected"), - })); - } - if (pending) { - if (expired) { - host.append(el("p", { class: "warn", text: t("本次登录已过期,请重新开始。", "goAuth.expired") })); - } else if (pending.status === "failed") { - host.append(el("p", { - class: "warn", - text: pending.error || t("订阅登录未完成,请重新开始。", "goAuth.failed"), - })); - } else if (pending.status === "choosing_org") { - const select = el("select", { id: "go-auth-organization" }); - select.append(el("option", { value: "", text: t("请选择订阅所在组织", "goAuth.chooseOrganization") })); - for (const organization of pending.organizations || []) - select.append(el("option", { value: organization.id, text: organization.name || organization.id })); - if ([...select.options].some((option) => option.value === selected)) select.value = selected; - const confirm = el("button", { - type: "button", - class: "btn btn-sm btn-primary", - text: t("连接所选组织", "goAuth.confirmOrganization"), - disabled: busy || !select.value, - }); - select.disabled = busy; - select.addEventListener("change", () => (confirm.disabled = !select.value)); - confirm.addEventListener("click", () => poll(select.value)); - host.append(el("div", { class: "field" }, [ - el("label", { for: "go-auth-organization", text: t("订阅所在组织", "goAuth.organization") }), - select, - ]), confirm); - } else if (pending.status === "starting") { - host.append(el("p", { text: t("正在申请官方登录验证码…", "goAuth.starting") })); - } else { - host.append(el("p", { text: t("打开官方页面完成登录,并确认这是您发起的授权。", "goAuth.instructions") })); - if (pending.user_code) - host.append(el("p", {}, [ - el("span", { text: t("验证码:", "goAuth.userCode") }), - el("code", { class: "mono", text: pending.user_code }), - ])); - const url = pending.verification_url && verificationURL(pending.verification_url); - if (url) - host.append(el("a", { - class: "btn btn-sm btn-primary", - href: url, - target: "_blank", - rel: "noopener noreferrer", - text: t("打开 OpenCode 官方登录页", "goAuth.openVerification"), - })); - else - host.append(el("p", { class: "warn", text: t("官方验证链接无效,请取消后重试。", "goAuth.invalidURL") })); - if (pending.expires_at) - host.append(el("p", { - class: "section-caption", - text: t("验证码有效至 {0};授权后将自动检查结果。", "goAuth.pendingExpires", localTime(pending.expires_at)), - })); - } - } - if (failure) - host.append(el("p", { class: "warn", role: "alert", text: t("操作失败:{0}", "goAuth.error", failure) })); -} - -export function init(onConnectionChanged) { - connectionChanged = onConnectionChanged; - $("#go-auth-start").addEventListener("click", () => - request("/api/go/auth/start", { method: "POST", body: "{}" }, "start"), - ); - $("#go-auth-refresh").addEventListener("click", refresh); - $("#go-auth-cancel").addEventListener("click", () => - request("/api/go/auth", { method: "DELETE", body: "{}" }, "cancel"), - ); - $("#go-auth-disconnect").addEventListener("click", disconnect); - document.addEventListener("visibilitychange", () => { - if (document.hidden) stopPolling(); - else if (active) refresh(); - }); - onChange(render); - render(); -} - -export function refresh() { - return request("/api/go/auth"); -} - -export function show() { - active = true; - if (!document.hidden) refresh(); -} - -export function hide() { - active = false; - stopPolling(); -} - -export function reset() { - generation++; - active = false; - stopPolling(); - controller?.abort(); - controller = null; - state = null; - busy = false; - failure = ""; - synchronizationPending = false; - render(); -} diff --git a/webui/js/i18n.js b/webui/js/i18n.js index f703767..8c33eff 100644 --- a/webui/js/i18n.js +++ b/webui/js/i18n.js @@ -551,34 +551,53 @@ const DICTIONARY = { "diag.noAttempts": "No upstream attempts", "diag.noMatch": "No matching models", - "goAuth.title": "Go subscription sign-in", - "goAuth.caption": "Authorize on the official OpenCode page without copying credentials. Manual Go keys are kept but are not fallback routes while the subscription is connected; their previous routing resumes after disconnecting.", - "goAuth.refresh": "Refresh sign-in status", - "goAuth.start": "Sign in to Go in your browser", - "goAuth.reconnect": "Sign in to Go again", - "goAuth.cancel": "Cancel this sign-in", - "goAuth.disconnect": "Disconnect Go subscription", - "goAuth.disconnectAction": "Disconnect", - "goAuth.disconnectConfirm": "This only removes the subscription sign-in saved by the gateway. Manual Go keys are kept and the official OpenCode session is not revoked. Continue?", - "goAuth.notice": "Only confirmed Go subscription routes are used; there is no automatic switch to pay-as-you-go. Unavailable OAuth subscription quota stays unknown instead of being estimated.", - "goAuth.connected": "Go subscription connected. Sign-in credentials stay on the gateway server.", - "goAuth.needsLogin": "Your Go subscription sign-in has expired. Sign in again. Manual Go keys will not be used as fallback routes.", - "goAuth.disconnected": "No Go subscription is connected. Manually configured Go keys are not affected.", - "goAuth.organizationValue": "Organization: {0}", - "goAuth.models": "Loaded {0} subscription models.", - "goAuth.expires": "Access credential expires at {0}; the gateway refreshes it when needed.", - "goAuth.expired": "This sign-in has expired. Start again.", - "goAuth.failed": "Subscription sign-in did not finish. Start again.", - "goAuth.organization": "Subscription organization", - "goAuth.chooseOrganization": "Select the organization with your subscription", - "goAuth.confirmOrganization": "Connect selected organization", - "goAuth.starting": "Requesting an official sign-in code…", - "goAuth.instructions": "Open the official page to sign in, and confirm that you initiated this authorization.", - "goAuth.userCode": "Verification code: ", - "goAuth.openVerification": "Open official OpenCode sign-in", - "goAuth.invalidURL": "The official verification link is invalid. Cancel and try again.", - "goAuth.pendingExpires": "Code valid until {0}; authorization will be checked automatically.", - "goAuth.error": "Operation failed: {0}", + "goOAuth.title": "Go OAuth sign-in", + "goOAuth.caption": "Authorize Go OAuth on the official OpenCode page without copying credentials. Manual Go keys are kept but are not fallback routes while Go OAuth is connected; their previous routing resumes after disconnecting.", + "oauth.refresh": "Refresh sign-in status", + "goOAuth.start": "Sign in with Go OAuth in your browser", + "goOAuth.reconnect": "Sign in with Go OAuth again", + "oauth.cancel": "Cancel this sign-in", + "goOAuth.disconnect": "Disconnect Go OAuth", + "oauth.disconnectAction": "Disconnect", + "goOAuth.disconnectConfirm": "This only removes the Go OAuth sign-in saved by the gateway. Manual Go keys are kept and the official OpenCode session is not revoked. Continue?", + "goOAuth.notice": "Only confirmed Go subscription routes are used; there is no automatic switch to pay-as-you-go. Unavailable Go subscription quota stays unknown instead of being estimated.", + "goOAuth.connected": "Go OAuth connected. Sign-in credentials stay on the gateway server.", + "goOAuth.needsLogin": "Your Go OAuth sign-in has expired. Sign in again. Manual Go keys will not be used as fallback routes.", + "goOAuth.disconnected": "Go OAuth is not connected. Manually configured Go keys are not affected.", + "oauth.organizationValue": "Organization: {0}", + "goOAuth.models": "Loaded {0} Go subscription models.", + "oauth.expires": "Access credential expires at {0}; the gateway refreshes it when needed.", + "oauth.expired": "This sign-in has expired. Start again.", + "goOAuth.failed": "Go OAuth sign-in did not finish. Start again.", + "goOAuth.organization": "Go OAuth authorization organization", + "goOAuth.chooseOrganization": "Select the organization for Go OAuth authorization", + "oauth.confirmOrganization": "Connect selected organization", + "oauth.starting": "Requesting an official sign-in code…", + "oauth.instructions": "Open the official page to sign in, and confirm that you initiated this authorization.", + "oauth.userCode": "Verification code: ", + "oauth.openVerification": "Open official OpenCode sign-in", + "oauth.invalidURL": "The official verification link is invalid. Cancel and try again.", + "oauth.pendingExpires": "Code valid until {0}; authorization will be checked automatically.", + "oauth.error": "Operation failed: {0}", + + "zenOAuth.title": "Zen / Console PAYG OAuth", + "zenOAuth.caption": "Authorize the Zen pay-as-you-go channel separately. Manual Zen keys and the Go OAuth connection are kept. Signing in with Go OAuth does not enable this channel.", + "zenOAuth.notice": "Requests routed through Zen OAuth consume credits at PAYG rates, not Go subscription quota. Failed Go requests are not automatically moved to this channel; model routing still follows the configured prefer setting.", + "zenOAuth.balanceNotice": "The Go quota on this page is not your Zen credits balance. PAYG balance and request counts are not estimated; check billing in the official Console. Disconnecting only removes local sign-in and does not revoke the official session.", + "zenOAuth.start": "Sign in to Zen / Console PAYG in your browser", + "zenOAuth.reconnect": "Sign in to Zen / Console PAYG again", + "zenOAuth.disconnect": "Disconnect Zen / Console PAYG", + "zenOAuth.disconnectConfirm": "This only removes the Zen PAYG sign-in saved by the gateway. Manual Zen and Go keys and the Go OAuth connection are kept; the official OpenCode session is not revoked. Continue?", + "zenOAuth.connected": "Zen / Console PAYG is connected. Requests through this channel are charged against credits; sign-in credentials stay on the server.", + "zenOAuth.needsLogin": "Your Zen / Console PAYG sign-in has expired. Sign in again. Manual keys and the Go OAuth connection are kept.", + "zenOAuth.disconnected": "Zen / Console PAYG is not connected. This sign-in is managed separately from Go OAuth and manual keys.", + "zenOAuth.models": "Loaded {0} Zen PAYG models; the model count does not indicate remaining credits.", + "zenOAuth.failed": "Zen PAYG sign-in did not finish. Start again.", + "zenOAuth.chooseOrganization": "Select the organization paying for PAYG usage", + "zenOAuth.organization": "PAYG billing organization", + "zenOAuth.confirmTitle": "Confirm the Zen PAYG billing channel", + "zenOAuth.confirmPayg": "Requests routed through Zen OAuth consume credits at PAYG rates, not Go subscription quota. Failed Go requests are not automatically moved to this channel; model routing still follows the configured prefer setting. Confirm and continue to official authorization?", + "zenOAuth.confirmAction": "Accept PAYG billing and continue", "quotas.noKey": "No Go Key configured", "quotas.addKeyFirst": "Add an OpenCode Go Key in the Configuration center first.", diff --git a/webui/js/main.js b/webui/js/main.js index d2d3309..f13c8ca 100644 --- a/webui/js/main.js +++ b/webui/js/main.js @@ -3,7 +3,7 @@ import { api, setCsrf, clearCsrf, setUnauthorizedHandler } from "./api.js"; import { refreshMonitor, loadConfig, loadDebugModels } from "./data.js"; import * as i18n from "./i18n.js"; import * as store from "./store.js"; -import { $, $$, toast } from "./ui.js"; +import { $, $$, closeDialogs, toast } from "./ui.js"; import * as logstream from "./logstream.js"; import { init as initTheme } from "./theme.js"; @@ -53,6 +53,9 @@ function openPage(id) { function showLogin() { clearCsrf(); + store.clear(); + closeDialogs(); + $$("input[type='password']").forEach((input) => (input.value = "")); current?.hide?.(); current = null; $("#app").classList.add("hidden"); diff --git a/webui/js/oauth.js b/webui/js/oauth.js new file mode 100644 index 0000000..32d50cf --- /dev/null +++ b/webui/js/oauth.js @@ -0,0 +1,366 @@ +import { api, hasSession } from "./api.js"; +import * as store from "./store.js"; +import { t, onChange } from "./i18n.js"; +import { $, confirmDialog, el, localTime } from "./ui.js"; + +let connectionChanged = null; +let synchronizationVersion = 0; + +const plans = [ + { + id: "go", + copy: { + start: "浏览器登录 Go OAuth", + reconnect: "重新登录 Go OAuth", + disconnect: "断开 Go OAuth 登录", + disconnectConfirm: "仅移除网关保存的 Go OAuth 登录,不删除手动 Go Key,也不会撤销 OpenCode 官方会话。是否继续?", + connected: "Go OAuth 已连接,登录凭证仅保存在网关服务端。", + needsLogin: "Go OAuth 登录已失效,请重新登录。手动 Go Key 不会作为备用通道。", + disconnected: "尚未连接 Go OAuth。手动配置的 Go Key 不受此登录影响。", + models: "已获取 {0} 个 Go 订阅模型。", + failed: "Go OAuth 登录未完成,请重新开始。", + chooseOrganization: "请选择 Go OAuth 授权组织", + organization: "Go OAuth 授权组织", + }, + }, + { + id: "zen", + copy: { + start: "浏览器登录 Zen / Console PAYG", + reconnect: "重新登录 Zen / Console PAYG", + disconnect: "断开 Zen / Console PAYG 登录", + disconnectConfirm: "仅移除网关保存的 Zen PAYG 登录,保留手动 Zen Key、Go Key 和 Go OAuth 连接,不撤销 OpenCode 官方会话。是否继续?", + connected: "Zen / Console PAYG 已连接;经此通道的请求按 credits 计费,登录凭证仅保存在服务端。", + needsLogin: "Zen / Console PAYG 登录已失效,请重新登录。手动 Key 与 Go OAuth 连接仍保留。", + disconnected: "尚未连接 Zen / Console PAYG。此登录与 Go OAuth 及手动 Key 分开管理。", + models: "已获取 {0} 个 Zen PAYG 模型;模型数量不代表剩余 credits。", + failed: "Zen PAYG 登录未完成,请重新开始。", + chooseOrganization: "请选择承担 PAYG 费用的组织", + organization: "PAYG 计费组织", + }, + }, +].map(createOAuthPanel); + +function verificationURL(value) { + try { + const parsed = new URL(value, "https://opencode.ai/console/"); + if ( + parsed.protocol !== "https:" || + parsed.host !== "opencode.ai" || + parsed.username || + parsed.password + ) + return null; + return parsed.href; + } catch { + return null; + } +} + +function connectionID(value) { + return value?.connected + ? JSON.stringify([ + value.account?.email, + value.account?.organization, + value.account?.models, + !!value.account?.needs_login, + ]) + : ""; +} + +function createOAuthPanel(plan) { + let state = null; + let timer = null; + let active = false; + let busy = false; + let confirming = false; + let generation = 0; + let controller = null; + let failure = ""; + let synchronizationPending = false; + const node = (name) => $(`#${plan.id}-oauth-${name}`); + const message = (name, ...values) => t(plan.copy[name], `${plan.id}OAuth.${name}`, ...values); + const oauthPath = `/api/${plan.id}/auth`; + + function stopPolling() { + clearTimeout(timer); + timer = null; + } + + function pendingExpired() { + const expires = Date.parse(state?.pending?.expires_at); + return Number.isFinite(expires) && expires <= Date.now(); + } + + function current(operation) { + return operation === generation && hasSession(); + } + + async function synchronize(operation, signal) { + const version = ++synchronizationVersion; + const [config, debug] = await Promise.all([ + api("/api/config", { signal }), api("/api/debug/models", { signal }), + ]); + if (!current(operation) || version !== synchronizationVersion) return; + store.set("config", config); + if (debug.last_inference) store.set("lastPlayground", debug.last_inference); + store.set("debug", debug); + await connectionChanged?.(); + if (current(operation) && version === synchronizationVersion) synchronizationPending = false; + } + + function schedulePoll() { + stopPolling(); + const pending = state?.pending; + if ( + !active || + document.hidden || + busy || + confirming || + failure || + !hasSession() || + !pending || + pendingExpired() || + pending.status === "failed" || + pending.status === "choosing_org" + ) + return; + const seconds = Number(pending.retry_after_seconds ?? pending.interval_seconds ?? 5); + const wait = Number.isFinite(seconds) ? Math.max(1, Math.min(seconds, 86400)) : 5; + timer = setTimeout(() => { + if (pendingExpired() || state?.pending?.status === "starting") refresh(); + else poll(); + }, wait * 1000); + } + + async function request(path, options = {}, action = "refresh") { + if (busy || confirming || !hasSession()) return; + stopPolling(); + const operation = generation; + const previous = connectionID(state); + busy = true; + failure = ""; + controller = new AbortController(); + const signal = controller.signal; + render(); + try { + const next = await api(path, { ...options, signal }); + if (!current(operation)) return; + state = next; + render(); + if ( + action === "disconnect" || + previous !== connectionID(next) || + (action === "poll" && next.connected && !next.pending) + ) + synchronizationPending = true; + if (synchronizationPending) await synchronize(operation, signal); + } catch (error) { + if (current(operation) && error.name !== "AbortError") failure = error.message; + } finally { + if (current(operation)) { + busy = false; + controller = null; + render(); + schedulePoll(); + } + } + } + + function poll(organizationID) { + if (!state?.pending?.id) return; + const body = { id: state.pending.id }; + if (organizationID) body.organization_id = organizationID; + return request(`${oauthPath}/poll`, { method: "POST", body: JSON.stringify(body) }, "poll"); + } + + async function confirm(options) { + if (busy || confirming || !hasSession()) return false; + const operation = generation; + confirming = true; + stopPolling(); + render(); + try { + return (await confirmDialog(options)) && current(operation); + } finally { + if (operation === generation) { + confirming = false; + render(); + schedulePoll(); + } + } + } + + async function start() { + const operation = generation; + if (plan.id === "zen") { + const accepted = await confirm({ + title: t("确认启用 Zen PAYG 计费通道", "zenOAuth.confirmTitle"), + message: t( + "启用后走 Zen OAuth 的请求按 PAYG 消耗 credits,不使用 Go 订阅额度;不会自动将 Go 失败转入本通道,模型仍依配置 prefer 选路。是否确认并继续官方授权?", + "zenOAuth.confirmPayg", + ), + confirmLabel: t("确认 PAYG 计费并继续", "zenOAuth.confirmAction"), + }); + if (!accepted || !current(operation)) return; + } + return request(`${oauthPath}/start`, { + method: "POST", body: JSON.stringify(plan.id === "zen" ? { acknowledge_payg: true } : {}), + }, "start"); + } + + async function disconnect() { + const operation = generation; + const accepted = await confirm({ + title: message("disconnect"), message: message("disconnectConfirm"), + confirmLabel: t("断开连接", "oauth.disconnectAction"), danger: true, + }); + if (!accepted || !current(operation)) return; + return request(`/api/${plan.id}/connection`, { method: "DELETE", body: "{}" }, "disconnect"); + } + + function render() { + const pending = state?.pending; + const expired = pendingExpired(); + const selected = node("organization")?.value; + const host = node("content"); + const working = busy || confirming; + host.replaceChildren(); + node("start").textContent = message(state?.connected ? "reconnect" : "start"); + node("start").disabled = working || !!(pending && pending.status !== "failed" && !expired); + node("refresh").disabled = working; + node("cancel").classList.toggle("hidden", !pending); + node("cancel").disabled = working; + node("disconnect").classList.toggle("hidden", !state?.connected); + node("disconnect").disabled = working; + if (state?.connected) { + const account = state.account || {}; + host.append(el("p", { + class: account.needs_login ? "warn" : "ok", + text: message(account.needs_login ? "needsLogin" : "connected"), + })); + if (account.error) host.append(el("p", { class: "warn", text: account.error })); + if (account.email) host.append(el("p", { class: "mono", text: account.email })); + if (account.organization) + host.append(el("p", { text: t("组织:{0}", "oauth.organizationValue", account.organization) })); + if (account.models != null) host.append(el("p", { text: message("models", account.models) })); + if (account.expires_at && !account.needs_login) + host.append(el("p", { + class: "section-caption", + text: t("访问凭证到期:{0};网关按需自动刷新。", "oauth.expires", localTime(account.expires_at)), + })); + } else if (!pending) { + host.append(el("p", { class: "section-caption", text: message("disconnected") })); + } + if (pending) { + if (expired) { + host.append(el("p", { class: "warn", text: t("本次登录已过期,请重新开始。", "oauth.expired") })); + } else if (pending.status === "failed") { + host.append(el("p", { class: "warn", text: pending.error || message("failed") })); + } else if (pending.status === "choosing_org") { + const select = el("select", { id: `${plan.id}-oauth-organization` }); + select.append(el("option", { value: "", text: message("chooseOrganization") })); + for (const organization of pending.organizations || []) + select.append(el("option", { value: organization.id, text: organization.name || organization.id })); + if ([...select.options].some((option) => option.value === selected)) select.value = selected; + const choose = el("button", { + type: "button", class: "btn btn-sm btn-primary", + text: t("连接所选组织", "oauth.confirmOrganization"), disabled: working || !select.value, + }); + select.disabled = working; + select.addEventListener("change", () => (choose.disabled = working || !select.value)); + choose.addEventListener("click", () => poll(select.value)); + host.append(el("div", { class: "field" }, [ + el("label", { for: `${plan.id}-oauth-organization`, text: message("organization") }), select, + ]), choose); + } else if (pending.status === "starting") { + host.append(el("p", { text: t("正在申请官方登录验证码…", "oauth.starting") })); + } else { + host.append(el("p", { text: t("打开官方页面完成登录,并确认这是您发起的授权。", "oauth.instructions") })); + if (pending.user_code) + host.append(el("p", {}, [ + el("span", { text: t("验证码:", "oauth.userCode") }), + el("code", { class: "mono", text: pending.user_code }), + ])); + const url = pending.verification_url && verificationURL(pending.verification_url); + if (url) + host.append(el("a", { + class: "btn btn-sm btn-primary", href: url, target: "_blank", rel: "noopener noreferrer", + text: t("打开 OpenCode 官方登录页", "oauth.openVerification"), + })); + else + host.append(el("p", { class: "warn", text: t("官方验证链接无效,请取消后重试。", "oauth.invalidURL") })); + if (pending.expires_at) + host.append(el("p", { + class: "section-caption", + text: t("验证码有效至 {0};授权后将自动检查结果。", "oauth.pendingExpires", localTime(pending.expires_at)), + })); + } + } + if (failure) + host.append(el("p", { class: "warn", role: "alert", text: t("操作失败:{0}", "oauth.error", failure) })); + } + + function refresh() { + return request(oauthPath); + } + + return { + init() { + node("start").addEventListener("click", start); + node("refresh").addEventListener("click", refresh); + node("cancel").addEventListener("click", () => request(oauthPath, { method: "DELETE", body: "{}" }, "cancel")); + node("disconnect").addEventListener("click", disconnect); + document.addEventListener("visibilitychange", () => { + if (document.hidden) stopPolling(); + else if (active) refresh(); + }); + onChange(render); + render(); + }, + refresh, + show() { + active = true; + if (!document.hidden) return refresh(); + }, + hide() { + active = false; + stopPolling(); + }, + reset() { + generation++; + active = false; + stopPolling(); + controller?.abort(); + controller = null; + state = null; + busy = false; + confirming = false; + failure = ""; + synchronizationPending = false; + render(); + }, + }; +} + +export function init(onConnectionChanged) { + connectionChanged = onConnectionChanged; + for (const plan of plans) plan.init(); +} + +export function refresh() { + return Promise.all(plans.map((plan) => plan.refresh())); +} + +export function show() { + return Promise.all(plans.map((plan) => plan.show())); +} + +export function hide() { + for (const plan of plans) plan.hide(); +} + +export function reset() { + synchronizationVersion++; + for (const plan of plans) plan.reset(); +} diff --git a/webui/js/pages/config.js b/webui/js/pages/config.js index 49b3929..b65bc01 100644 --- a/webui/js/pages/config.js +++ b/webui/js/pages/config.js @@ -5,23 +5,29 @@ import { t, onChange } from "../i18n.js"; import { $, $$, bindTabs, el, openDialog, toast } from "../ui.js"; import { fillProxies, initProxies, lockProxies, proxyInputs, resetProxies, stopChecks } from "./proxies.js"; -// A long proxy list is rendered collapsed: the first CHIP_RENDER_LIMIT chips +// A long key list is rendered collapsed: the first CHIP_RENDER_LIMIT chips // plus a toggle. A single flex-wrap row with thousands of chips is what froze // the config page on large pools. const CHIP_RENDER_LIMIT = 100; const expandedChips = new Set(); +const removedChips = new Map(); let mutation = null; +let revealOperation = null; function renderChips(name) { const host = $(`#${name}-chips`); host.replaceChildren(); - const items = store.get("config")?.[name] || []; + const items = (store.get("config")?.[name] || []).filter((item) => !removedChips.get(name)?.has(item.id)); const expanded = expandedChips.has(name); const visible = expanded ? items : items.slice(0, CHIP_RENDER_LIMIT); visible.forEach((item) => { const remove = el("button", { type: "button", title: t("移除", "common.remove"), text: "×" }); const chip = el("span", { class: "chip", dataset: { id: item.id } }); - remove.addEventListener("click", () => chip.remove()); + remove.addEventListener("click", () => { + if (!removedChips.has(name)) removedChips.set(name, new Set()); + removedChips.get(name).add(item.id); + renderChips(name); + }); chip.append(el("span", { text: item.display }), remove); host.append(chip); }); @@ -63,9 +69,11 @@ function renderRestartNotice(value) { function secretInputs(name) { if (name === "proxies") return proxyInputs(); - const kept = [...$(`#${name}-chips`).children] - .filter((node) => node.dataset.id !== undefined) - .map((node) => ({ id: node.dataset.id })); + // Collapsed chips are only a view; keys outside the rendered page must + // survive saving, expanding, and collapsing the list. + const kept = (store.get("config")?.[name] || []) + .filter((item) => !removedChips.get(name)?.has(item.id)) + .map((item) => ({ id: item.id })); const added = $(`#${name}-new`) .value.split(/\r?\n/) .map((value) => value.trim()) @@ -159,6 +167,7 @@ async function save(event) { upstream: { ...current.upstream, zen: $("#c-up-zen").value, go: $("#c-up-go").value }, retry: { max_attempts: numberValue("#c-attempts"), timeout_seconds: numberValue("#c-timeout") }, models: { + ...current.models, refresh_seconds: numberValue("#c-refresh"), protocols: JSON.parse($("#c-protocols").value || "{}"), free_only: $("#c-free-only").checked, @@ -169,6 +178,7 @@ async function save(event) { effort_by_model: JSON.parse($("#c-reasoning-by-model").value || "{}"), }, performance: { + ...current.performance, max_idle_conns: numberValue("#c-idle"), max_idle_conns_per_host: numberValue("#c-idle-host"), max_conns_per_host: numberValue("#c-max-host"), @@ -195,6 +205,7 @@ async function save(event) { }); if (!currentMutation(operation)) return; fillProxies(result.config.proxies || [], true); + removedChips.clear(); store.set("config", result.config); ["server_keys", "zen_keys", "go_keys"].forEach( (name) => ($(`#${name}-new`).value = ""), @@ -233,6 +244,7 @@ async function reload() { const value = await api("/api/config", { signal: operation.controller.signal }); if (!currentMutation(operation)) return; fillProxies(value.proxies || [], true); + removedChips.clear(); store.set("config", value); await refreshDebug(operation); if (!currentMutation(operation)) return; @@ -252,13 +264,20 @@ async function reload() { } function reveal() { + if (revealOperation || !hasSession()) return; + const operation = { controller: new AbortController(), busy: false }; + revealOperation = operation; const input = el("input", { type: "password", autocomplete: "current-password" }); const submit = async (close) => { + if (revealOperation !== operation || operation.busy || !hasSession()) return; + operation.busy = true; try { const values = await api("/api/config/reveal", { method: "POST", body: JSON.stringify({ password: input.value }), + signal: operation.controller.signal, }); + if (revealOperation !== operation || !hasSession()) return; close(); openDialog({ title: t("敏感配置", "modal.title"), @@ -267,7 +286,9 @@ function reveal() { actions: [{ label: t("关闭", "modal.close") }], }); } catch (error) { - toast(error.message, true); + if (revealOperation === operation && error.name !== "AbortError") toast(error.message, true); + } finally { + operation.busy = false; } }; const dialog = openDialog({ @@ -276,6 +297,11 @@ function reveal() { el("label", { text: t("请再次输入管理密码", "config.revealPrompt") }), input, ]), + onClose: () => { + input.value = ""; + operation.controller.abort(); + if (revealOperation === operation) revealOperation = null; + }, actions: [ { label: t("取消", "common.cancel") }, { label: t("查看", "common.view"), kind: "btn-primary", onClick: submit }, @@ -297,6 +323,11 @@ export default { reset() { mutation?.controller.abort(); mutation = null; + revealOperation?.controller.abort(); + revealOperation = null; + removedChips.clear(); + expandedChips.clear(); + ["server_keys", "zen_keys", "go_keys"].forEach((name) => ($(`#${name}-new`).value = "")); lockConfig(false); resetProxies(); }, diff --git a/webui/js/pages/model-quotas.js b/webui/js/pages/model-quotas.js index bb321c5..2d7e71f 100644 --- a/webui/js/pages/model-quotas.js +++ b/webui/js/pages/model-quotas.js @@ -1,7 +1,7 @@ // Page: 模型与额度 — Go quota windows and free model availability. import { api, hasSession } from "../api.js"; import { loadDebugModels } from "../data.js"; -import * as goAuth from "../go-auth.js"; +import * as oauth from "../oauth.js"; import { t, onChange } from "../i18n.js"; import { $, bindTabs, copyText, el, emptyRow, localTime, toast } from "../ui.js"; @@ -267,15 +267,15 @@ export default { title: "模型与额度", sub: "共享套餐额度与免费模型探测状态。", init() { - goAuth.init(load); + oauth.init(load); bindTabs($("#page-model-quotas"), (id) => { activeTab = id; if (id === "quota") { - goAuth.show(); + oauth.show(); load(); startPolling(); } else { - goAuth.hide(); + oauth.hide(); stopPolling(); loadAvailability(); } @@ -296,7 +296,7 @@ export default { }, show() { if (activeTab === "quota") { - goAuth.show(); + oauth.show(); load(); startPolling(); } else { @@ -304,12 +304,12 @@ export default { } }, hide() { - goAuth.hide(); + oauth.hide(); stopPolling(); }, refresh() { if (activeTab === "quota") { - goAuth.refresh(); + oauth.refresh(); load(); } else loadAvailability(); }, @@ -318,7 +318,7 @@ export default { data = null; loading = false; stopPolling(); - goAuth.reset(); + oauth.reset(); $("#quota-account").replaceChildren(); $("#quota-cards").replaceChildren(); $("#quota-models").replaceChildren(); diff --git a/webui/js/store.js b/webui/js/store.js index 8ef1a84..422d94e 100644 --- a/webui/js/store.js +++ b/webui/js/store.js @@ -13,6 +13,10 @@ export function get(key) { return state[key]; } +export function clear() { + for (const key of Object.keys(state)) state[key] = null; +} + export function set(key, value) { state[key] = value; const subscribers = listeners.get(key); diff --git a/webui/js/theme-init.js b/webui/js/theme-init.js new file mode 100644 index 0000000..defa600 --- /dev/null +++ b/webui/js/theme-init.js @@ -0,0 +1,11 @@ +// Apply the theme before first paint while honoring the script-src policy. +// The theme module owns changes after the console starts. +(() => { + try { + const mode = localStorage.getItem("opencode2api.ui.theme") || "auto"; + const dark = + mode === "dark" || + (mode === "auto" && matchMedia("(prefers-color-scheme: dark)").matches); + document.documentElement.setAttribute("data-theme", dark ? "dark" : "light"); + } catch (_) {} +})(); diff --git a/webui/js/theme.js b/webui/js/theme.js index 479cfe1..ee151ff 100644 --- a/webui/js/theme.js +++ b/webui/js/theme.js @@ -1,5 +1,5 @@ -// Theme handling: an auto/light/dark cycle persisted per browser. The inline -// head script applies the stored choice before first paint; this module owns +// Theme handling: an auto/light/dark cycle persisted per browser. The +// theme-init script applies the stored choice before first paint; this module owns // the topbar toggle and keeps "auto" tracking the system preference. import { t, onChange } from "./i18n.js"; diff --git a/webui/js/ui.js b/webui/js/ui.js index e4c39b8..72cd5d8 100644 --- a/webui/js/ui.js +++ b/webui/js/ui.js @@ -71,6 +71,8 @@ export function renderFacts(host, entries) { } } +const openDialogs = new Set(); + // Generic dialog host; onClose fires on every close path so promise-based // dialogs settle exactly once. export function openDialog({ title, body = null, size = "", actions = [], onClose }) { @@ -89,11 +91,13 @@ export function openDialog({ title, body = null, size = "", actions = [], onClos const close = () => { if (closed) return; closed = true; + openDialogs.delete(close); overlay.remove(); document.removeEventListener("keydown", onKey, true); if (previous instanceof HTMLElement && previous.isConnected) previous.focus(); onClose?.(); }; + openDialogs.add(close); const onKey = (event) => { if (event.key === "Escape") { event.stopPropagation(); @@ -125,6 +129,10 @@ export function openDialog({ title, body = null, size = "", actions = [], onClos return { close, dialog }; } +export function closeDialogs() { + for (const close of [...openDialogs]) close(); +} + export function confirmDialog({ title, message = "",