mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 16:04:01 +00:00
refactor: harden gateway and document Go/Zen OAuth
Preserve Go and Zen OAuth routing while fixing authentication, secret redaction, streaming, transport, and configuration issues. Refresh README and management guides in four languages while preserving sponsors, LinuxDo acknowledgements, and Linux/Docker quick start instructions.
This commit is contained in:
1 parent
0d05fe9393
commit
e2b2a7c281
62 files changed
+4390
-3609
No files matched your search
@@ -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.<impronta-upstream-Zen>.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.
|
||||
@@ -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.<Zen-upstream-fingerprint>.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.
|
||||
@@ -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.<dấu vân tay thượng nguồn Zen>.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.
|
||||
+225
-105
@@ -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.<Zen上游指纹>.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 用户注意保存卷中的实际文件。不要把凭证、日志、运行状态或本地验证产物加入源码。
|
||||
Reference in new issue
Block a user