opencode-auth-load-balancer 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,7 +8,7 @@ Selection is **not** round-robin. It is weighted primarily by **weekly** usage,
8
8
 
9
9
  ## Features
10
10
 
11
- - **Account pool** — register many Claude / Codex / Kimi Code accounts (Claude also by a long-lived `claude setup-token` token, which a Claude OAuth login now mints itself; Kimi also by API key); the plugin manages and rotates them.
11
+ - **Account pool** — register many Claude / Codex / Kimi Code accounts (Claude also by a long-lived `claude setup-token` token; Kimi also by API key); the plugin manages and rotates them.
12
12
  - **Weekly-usage-weighted scheduling** — `urgency = weeklyRemaining / daysUntilWeeklyReset`. A sooner reset (e.g. 3 days) outranks a later one (7 days) at equal headroom; perishable quota is drained progressively, never crammed into the final hour.
13
13
  - **Automatic rotation** — on `429`/auth errors an account is cooled down and the next-best is tried; `retry-after` is honored.
14
14
  - **Model-tier fallback ladder (Fable, Opus, …)** — Claude Max accounts have *separate* weekly caps per premium model tier. When one is exhausted (a 429 whose `representative-claim` names a tier window, e.g. `seven_day_fable` / `seven_day_opus`), the balancer records a **per-tier** cooldown instead of cooling the whole account down (which used to cascade every account into a false "cooldown" and block *every* model on it). Requests for that tier then **steer to an account with tier headroom** — keeping the model you asked for — and only when the *whole pool* is tier-limited does the request descend **one rung down the fallback ladder**: the next model family in `fable → opus → sonnet → haiku` (order configurable via `OPENCODE_AUTH_LB_ANTHROPIC_FAMILY_ORDER`), picking the **highest-versioned model your provider config actually has** (a capped `claude-fable-5` prefers `claude-opus-4-9` over `claude-opus-4-8`). If that tier is capped too, it descends again (`fable → opus → sonnet`), each step toasted, preferably on the session's pinned account (keeping its prompt cache). Pin a fixed target or disable entirely via `OPENCODE_AUTH_LB_ANTHROPIC_OPUS_FALLBACK_MODEL`.
@@ -18,7 +18,7 @@ Selection is **not** round-robin. It is weighted primarily by **weekly** usage,
18
18
  - **Proactive migration** — leaves an account at a configurable soft threshold (~95%) instead of waiting for a hard 100% wall (which can break in-flight subagents).
19
19
  - **Single-use refresh-token safety** — per-account singleflight refresh; rotated tokens are persisted immediately.
20
20
  - **Visibility** — toasts for account switches, model fallback, pending/recovery, and restart restoration; an on-demand `auth_lb_status` tool; and a `bun run status` CLI dashboard.
21
- - **Gist sync of static credentials** — machines share their Claude tokens and Kimi API keys, encrypted, through a secret GitHub gist, both ways: every machine that follows the link downloads, and one with a GitHub token also uploads its own. See [Sync static credentials between machines](#sync-static-credentials-between-machines-github-gist).
21
+ - **Gist sync of credentials and OAuth logins** — machines share their Claude tokens, Kimi API keys and (unless switched off) their Claude / Codex / Kimi OAuth logins, encrypted, through a secret GitHub gist, both ways: every machine that follows the link downloads, and one with a GitHub token also uploads its own. See [Sync credentials and OAuth logins between machines](#sync-credentials-and-oauth-logins-between-machines-github-gist).
22
22
 
23
23
  ---
24
24
 
@@ -136,7 +136,7 @@ Durable turn references live beside the pool as `auth-load-balancer-pending.json
136
136
 
137
137
  A third file, `auth-load-balancer-cc-version.json`, caches the discovered Claude Code version (`{"version","fetchedAt"}` — see [Claude Code version](#claude-code-version)). It holds no account data and is safe to delete; it is rebuilt on the next start.
138
138
 
139
- [Gist sync](#sync-static-credentials-between-machines-github-gist) adds four more, none of them part of the pool: `auth-load-balancer-sync.json` (gist id, the **encryption key**, and which rows were imported — treat it like the pool file), `auth-load-balancer-sync-origin.json` (this machine's random id in the gist; not secret), `auth-load-balancer-sync-status.json` (the latest outcome, for the TUI; no secrets) and `auth-load-balancer-sync-intent.json` (a one-shot request from the TUI, deleted the moment the plugin reads it).
139
+ [Gist sync](#sync-credentials-and-oauth-logins-between-machines-github-gist) adds four more, none of them part of the pool: `auth-load-balancer-sync.json` (gist id, the **encryption key**, which rows were imported, and which login rows this machine holds or deleted — treat it like the pool file), `auth-load-balancer-sync-origin.json` (this machine's random id in the gist; not secret), `auth-load-balancer-sync-status.json` (the latest outcome, for the TUI; no secrets) and `auth-load-balancer-sync-intent.json` (a one-shot request from the TUI, deleted the moment the plugin reads it).
140
140
 
141
141
  > **OpenAI/Codex note:** the OpenAI path assumes opencode is configured to use the **Responses API** (the standard ChatGPT/Codex setup); `/responses` requests are routed to the Codex backend.
142
142
 
@@ -147,7 +147,7 @@ An OAuth login lives on a refresh token that rotates on every refresh, and once
147
147
  - **setup-token → inference.** Every request is sent with it; the OAuth login is never refreshed on the request path.
148
148
  - **OAuth login → usage.** It polls Anthropic's usage endpoint, which a setup-token cannot use (it is scoped to inference only, and the endpoint answers it `403 OAuth token does not meet scope requirement user:profile`).
149
149
 
150
- **An OAuth login brings its own.** Once an OAuth login (**"Claude Pro/Max (add account to load balancer)"**) lands, the plugin mints the account its token, with no Claude Code and no second approval, and the row is tagged `token+oauth` right away (see **Minted tokens** below). To paste one instead:
150
+ **An OAuth login does not bring one.** Anthropic only issues the year-long token through its own `setup-token` approval; a refresh grant cannot mint it (see **Minting is off** below). To add one:
151
151
 
152
152
  1. Run `claude setup-token` and approve it in the browser; it prints a token (`sk-ant-oat01-…`).
153
153
  2. `opencode auth login` → **Anthropic** → **"Claude Pro/Max setup-token (add account to load balancer)"**, and paste the token at the prompt. The CLI labels it "authorization code", but paste the token; line breaks from a wrapped terminal are ignored.
@@ -160,14 +160,18 @@ An OAuth login lives on a refresh token that rotates on every refresh, and once
160
160
  | What happened | Result |
161
161
  |---|---|
162
162
  | The OAuth login is revoked or expires | The row keeps serving inference on its token and is marked **`oauth re-login`** — in the dashboard state, in the TUI sidebar (with a **Re-login OAuth** menu item), and in the bottom bar — until an OAuth login is paired again. Meanwhile usage falls back to the response headers and, while the account sits idle, Claude Code's own quota check: a one-token `claude-haiku-4-5` request, sent at most once per 5 minutes per account. |
163
- | The token is revoked or expires (after a year) | The token is dropped, the same request is retried on the OAuth login, and the row is marked **`token re-login`** until a token is added again — with minting on, by the next request, which mints a new one in the background. |
163
+ | The token is revoked or expires (after a year) | The token is dropped, the same request is retried on the OAuth login, and the row is marked **`token re-login`** until a token is added again. |
164
164
  | Both are gone, or a token-only row's token answers `401` | The row switches to `re-login`; the TUI's re-login asks for a new token on a token-only row. |
165
165
 
166
166
  **OAuth logins expire on their own.** Anthropic gives an OAuth login a fixed lifetime that refreshes do not extend: `refresh_token_expires_in` when the token endpoint states it, otherwise the 30 days Claude Code itself assumes. In its last 3 days a row shows **`oauth expires Nd`**, mirroring Claude Code's own "Your login expires in N days" notice. Re-login OAuth then, or pair a setup-token so the expiry only costs usage measurement.
167
167
 
168
- **Minted tokens.** The plugin asks for the token with the refresh grant Claude Code's own `claude auth login` uses to mint its one-year token: the OAuth login's refresh token, with `scope=user:inference` and `expires_in=31536000`, the scope and lifetime `claude setup-token` asks for. Rows already in the pool are minted theirs when opencode starts, and a row whose token was dropped gets a new one on its next request. A minted token is renewed in its last 30 days while its OAuth login works; a pasted token's lifetime is unknown, so it is replaced only once it is dropped. The grant spends the refresh token like any refresh, under the same lock, and the row keeps the rotated one. A refused grant changes nothing (a dead login is left for the regular refresh to find) and is retried at most every 6 hours per opencode process, and a token granted less than 60 days is not pooled. Set `OPENCODE_AUTH_LB_ANTHROPIC_AUTO_TOKEN=0` to turn minting off.
168
+ **Minting is off.** Earlier versions asked for the token with a refresh grant (the OAuth login's refresh token, `scope=user:inference`, `expires_in=31536000`) at start-up and every 6 hours. Measured against Anthropic's token endpoint, that grant does not work and does harm:
169
169
 
170
- > Not yet verified against a live account: whether a minted token keeps working once the OAuth login it came from is revoked or expires. A pasted `claude setup-token` comes from its own approval, independent of any OAuth login. If a minted token dies with its login, the row goes to `re-login` as in the table above, and pasting a `claude setup-token` still gives it an independent token.
170
+ - The server ignores `expires_in` and answers with an 8-hour token, which is too short to pool (a token must live 60 days or more), so no row ever received one.
171
+ - The grant still rotates the refresh token, and the one it returns is narrowed to `user:inference` for good. The usage endpoint then answers that login `403 … user:profile`, and asking for the full scope again is refused with `400 invalid_scope`.
172
+ - Only a fresh OAuth login restores a narrowed row. Until then it keeps serving inference but loses usage polling.
173
+
174
+ `OPENCODE_AUTH_LB_ANTHROPIC_AUTO_TOKEN=1` turns the old behaviour back on; do not, unless you are testing the endpoint. The year-long token comes from a pasted `claude setup-token`, which is its own approval and independent of any OAuth login.
171
175
 
172
176
  ### Kimi Code
173
177
 
@@ -182,9 +186,12 @@ Every login is checked against the account behind it (`GET /me`), so one subscri
182
186
 
183
187
  The sign-in identifies itself to Kimi's OAuth host the way Kimi's own clients do, with `X-Msh-*` headers: platform `opencode_auth_load_balancer`, this machine's host name and OS, and a device id hashed from the host name and home directory.
184
188
 
185
- ### Sync static credentials between machines (GitHub gist)
189
+ ### Sync credentials and OAuth logins between machines (GitHub gist)
190
+
191
+ Logging in on every machine is tedious, and for Claude every OAuth login is an approval in the browser. Machines can share two kinds of credential through one secret GitHub gist, **both ways**:
186
192
 
187
- Logging in on every machine is tedious, and for Claude every OAuth login is an approval in the browser. Machines can share their *static* credentials — the long-lived Claude tokens (pasted, or minted by this plugin) and Kimi API keys — through one secret GitHub gist, **both ways**: a token minted on any machine reaches the others, and a token removed on the machine that owns it leaves them.
193
+ - **Static credentials** — the long-lived Claude tokens (pasted `claude setup-token` tokens) and Kimi API keys. A token added on any machine reaches the others, and a token removed on the machine that owns it leaves them.
194
+ - **OAuth logins** — the access + refresh token pair of a Claude, Codex or Kimi sign-in. On by default; switch it off with `OPENCODE_AUTH_LB_SYNC_LOGINS=0` (see [OAuth logins](#oauth-logins-in-the-gist) for what that means and what it risks).
188
195
 
189
196
  **Members.** A machine joins a gist by creating it (**Create a new secret gist…**) or by following its link (**Follow a gist link**). Every member **always downloads and applies** the gist (at start, every 15 minutes, and on **Sync now**). A member also **uploads its own credentials** when it can: when a GitHub token is discoverable (`GITHUB_TOKEN`, `GH_TOKEN`, or a logged-in [GitHub CLI](https://cli.github.com), whose `gh auth token` is run) *and* that GitHub account may write the gist. A machine with only the link — no GitHub account, no login — downloads and never writes. The sidebar says which it is: `syncing (upload + download)`, `syncing (download only: no GitHub login)`, `syncing (download only: this GitHub account cannot update the gist)`.
190
197
 
@@ -192,17 +199,18 @@ Logging in on every machine is tedious, and for Claude every OAuth login is an a
192
199
 
193
200
  | Syncs | Never syncs |
194
201
  |---|---|
195
- | Claude `inferenceToken` (and its `inferenceExpires`) | OAuth access and refresh tokens — Claude, Codex, Kimi sign-in |
196
- | Kimi Code API keys (a row with the static-credential expiry and no refresh token — never an OAuth sign-in, even one that left no refresh token) | `refreshExpires`, usage windows, cooldowns, sessions, `tokenGen`, pending turns |
202
+ | Claude `inferenceToken` (and its `inferenceExpires`) | Usage windows, cooldowns, sessions, `tokenGen`, pending turns, local row ids |
203
+ | Kimi Code API keys (a row with the static-credential expiry and no refresh token — never an OAuth sign-in, even one that left no refresh token) | A login whose refresh was refused (`oauth re-login`), a disabled row, a row without a refresh token or without a known account id |
204
+ | OAuth logins — Claude, Codex, Kimi sign-in: access token, refresh token, their expiries, the account and organization ids, and the login's version (unless `OPENCODE_AUTH_LB_SYNC_LOGINS` is off) | The share link and key; a Kimi API key or setup-token row is a static credential, not a login |
197
205
  | Each row's label and provider, so it can be registered | |
198
206
 
199
- OAuth refresh tokens are single-use and rotate on every refresh; two machines sharing one would race, and the loser kills the token family for both. So every machine keeps its **own** OAuth logins, and only the credentials that cannot rotate are shared.
207
+ OAuth refresh tokens are single-use and rotate on every refresh, so a shared login is only as good as its **newest** pair: see [OAuth logins](#oauth-logins-in-the-gist) for how the machines agree on which pair that is, and for the risk of sharing one.
200
208
 
201
209
  **Who owns what (origins).** Every machine has a random **origin** (128 bits, kept in `auth-load-balancer-sync-origin.json`; not secret, not derived from the host name; it survives *Stop syncing*, so rejoining lists as the same machine). An entry in the gist is identified by *(origin, row id)* and is added, changed and removed **only by the machine with that origin**: a machine never deletes another machine's entry. A row's static credential counts as this machine's **own** — and is uploaded — unless sync itself put it there (it is then *imported*, and travels from the machine that has it, never back). If another machine with a smaller origin already lists the same secret, this one does not list a second copy; if that machine later removes it while this one still holds it, this one takes over listing it.
202
210
 
203
211
  **What each machine does with the others' entries.** A token is verified with the same probe as a pasted `claude setup-token`, then registered on this machine's own OAuth row for that organization if it has one (the usual pairing rules, described above), else as a token-only row. A Kimi key becomes a key row; if this machine is already signed in to that Kimi account by OAuth, that sign-in is left alone. **An account that already has a working token on this machine is never given a second one, and its token is never replaced**: two machines that each minted a token for the same account keep *both* (each uses its own), and an incoming token for it is skipped as redundant. The skip is remembered together with the row that was in the way, so the entry is not probed again every sync; the moment that row loses its token or goes (for example the token it shared was removed on its owner), the skipped entry is imported in the same sync. A machine with no row for the account at all gets exactly one token for it, whichever entry comes first. (This relies on the organization the probe reports: a Team/Enterprise organization with several seats, or a probe that reports none, cannot be matched to one account, and then the token gets a row of its own.)
204
212
 
205
- **One cycle.** Each sync cycle (download, then upload) is in this order: (1) read the **current** gist — with the GitHub token when there is one, which avoids the 60/hour anonymous limit; the token goes only to `api.github.com`; (2) **apply** that snapshot locally; (3) only if this machine may write: list *every other origin's entries untouched* plus this machine's own current entries; (4) PATCH **only if that list differs from what the gist holds**. A machine therefore never uploads on top of a snapshot it has not merged, and an idle machine writes nothing. A write is made a few seconds after this machine's own static credentials change (a token minted, a key added, a row removed), or on **Upload now**. Each write is stamped later than the snapshot it was based on and than this machine's last write, so a machine whose clock runs behind never produces a snapshot the others refuse as "older"; a snapshot older than one a machine already applied is still refused (a gist owner restoring an old ciphertext cannot roll anyone back) — but a member that can write repairs such a gist by writing a newer one over it, and a link-only machine waits for that.
213
+ **One cycle.** Each sync cycle (download, then upload) is in this order: (1) read the **current** gist — with the GitHub token when there is one, which avoids the 60/hour anonymous limit; the token goes only to `api.github.com`; (2) **apply** that snapshot locally; (3) only if this machine may write: list *every other origin's entries untouched* plus this machine's own current entries, and per OAuth login the newer of the gist's copy and this machine's (a login only the gist has is carried over); (4) PATCH **only if those lists differ from what the gist holds**. A machine therefore never uploads on top of a snapshot it has not merged, and an idle machine writes nothing. A write is made a few seconds after this machine's own static credentials or shared OAuth logins change (a token minted, a key added, a row removed, a login made or refreshed), or on **Upload now**. Each write is stamped later than the snapshot it was based on and than this machine's last write, so a machine whose clock runs behind never produces a snapshot the others refuse as "older"; a snapshot older than one a machine already applied is still refused (a gist owner restoring an old ciphertext cannot roll anyone back) — but a member that can write repairs such a gist by writing a newer one over it, and a link-only machine waits for that.
206
214
 
207
215
  **When a machine cannot write.** There is no extra permission check: the PATCH is attempted, and a `403`/`404` answer means *this GitHub account cannot update the gist* (only the gist's owner account can). The machine then says so once, stops trying for an hour (the back-off is kept in the sync state; **Upload now** tries anyway), and goes on downloading. No GitHub token at all is a quiet download-only state — no message every cycle, only the sidebar line. If the gist holds entries this version cannot read (a newer plugin added a provider), the machine **does not write** — it would silently drop them — and says once: *update this plugin to upload*.
208
216
 
@@ -212,25 +220,36 @@ OAuth refresh tokens are single-use and rotate on every refresh; two machines sh
212
220
 
213
221
  **Encryption.** The payload is encrypted with AES-256-GCM (`node:crypto`) under a random 32-byte key, a fresh random nonce on every upload, and the format version authenticated. The key lives only in the link's fragment — `https://gist.github.com/<user>/<id>#<key>` — and a URL fragment is never sent to a server, so GitHub holds ciphertext only. (That also keeps GitHub's secret scanning, and Anthropic's scanning partnership, from seeing a plaintext `sk-ant-…` token and revoking it.) The gist is created **secret** (unlisted, not private: anyone with the URL can read the ciphertext, which is why the key matters). The key is shared by everyone who follows the link, and every member of the gist can read every entry.
214
222
 
215
- > **The link is the secret, and deleting the gist does not take it back.** Anyone who has the whole link, `#key` included, can read these credentials, and anyone who has already read them keeps what they read: deleting the gist or uploading to a new one (new key, new link) only stops *later* reads. If a link may have leaked, treat every credential in it as exposed. Replace the Kimi API keys in Kimi's console (the old ones then stop working). For Claude tokens, this plugin has no way to revoke a setup-token or a minted token and cannot verify that one was revoked elsewhere: check your Anthropic account for what is available, and until you have, assume the token still works. Then delete the gist and create a new one so the next snapshot is not readable with the old link.
223
+ > **The link is the secret, and deleting the gist does not take it back.** Anyone who has the whole link, `#key` included, can read these credentials, and anyone who has already read them keeps what they read: deleting the gist or uploading to a new one (new key, new link) only stops *later* reads. If a link may have leaked, treat every credential in it as exposed. Replace the Kimi API keys in Kimi's console (the old ones then stop working). A shared OAuth login is a live session of your account: its leaked pair works until the next refresh replaces it or the provider revokes it, so log in again on every machine (and sign out of the leaked session at the provider where it offers that) once the gist is gone. For Claude tokens, this plugin has no way to revoke a setup-token or a minted token and cannot verify that one was revoked elsewhere: check your Anthropic account for what is available, and until you have, assume the token still works. Then delete the gist and create a new one so the next snapshot is not readable with the old link.
216
224
 
217
225
  **Set up.**
218
226
 
219
- 1. On the machine that has the credentials and a GitHub token: click **Gist sync** at the bottom of the account list in the sidebar → **Create a new secret gist from this pool's static credentials**. The share link is shown in a dialog, once, because you asked for it; **Show the share link** brings it back on this machine only (the machine that created the gist is the only one that has it to show).
227
+ 1. On the machine that has the credentials and a GitHub token: click **Gist sync** at the bottom of the account list in the sidebar → **Create a new secret gist from this pool's credentials** (the new gist holds this pool's static credentials and, unless that is switched off, its shareable OAuth logins). The share link is shown in a dialog, once, because you asked for it; **Show the share link** brings it back on this machine only (the machine that created the gist is the only one that has it to show).
220
228
  2. On every other machine: **Gist sync** → **Follow a gist link**, and paste the link. That is all; with a GitHub token on that machine it uploads its own credentials too, without one it only downloads.
221
229
 
222
230
  **Leaving.**
223
231
 
224
232
  - An entry that **disappears** from the gist is removed locally **only if it was imported from that gist**. A paired row keeps its own OAuth login and loses just the imported token; a row that existed only for that credential goes. Rows you created yourself are never deleted, and a credential you already held locally is left as yours.
225
- - If you deleted or re-pointed an imported row yourself, the next sync does not undo it until the gist's token itself changes.
233
+ - If you deleted or re-pointed an imported row yourself, the next sync does not undo it until the gist's token itself changes. A deleted OAuth login row stays deleted until you log in to that account again (see [OAuth logins](#oauth-logins-in-the-gist)).
226
234
  - An unreachable, deleted, rotated (new key), tampered, or other-version gist **leaves the pool exactly as it was** and shows one short line in the sidebar. Nothing falls back to plaintext. A gist written by the previous (one-way, version 1) format is reported as written by another version; create a new one.
227
235
  - **Stop syncing** forgets the link (and the key) on this machine and nothing else: accounts already imported stay in the pool as ordinary rows, **which this machine will then list as its own if it rejoins** (the origin is kept, so rejoining the same gist does not duplicate entries, but the formerly imported credentials now travel from here).
228
236
 
229
- **Limits.** An unauthenticated download counts against GitHub's 60 requests/hour/IP limit; a poll every 15 minutes uses 4 an hour, and `ETag`/`If-None-Match` makes an unchanged gist a cheap `304` (a machine with a GitHub token reads authenticated, which is not limited that way). On a rate limit (`403`/`429`) the plugin waits as long as GitHub says (at least a minute, at most an hour) instead of retrying; a deleted gist (`404`) is reported and left for the next poll. When the next cycle is due, and any back-off, is kept in the sync-state file, so several opencode windows (and restarts) on one machine share one schedule and one lock: only one of them fetches, and any one of them serves the TUI's request. A response larger than 1 MiB is refused unread. The gist holds at most 64 entries in total. Set `OPENCODE_AUTH_LB_SYNC=0` to turn sync off entirely.
237
+ **Limits.** An unauthenticated download counts against GitHub's 60 requests/hour/IP limit; a poll every 15 minutes uses 4 an hour, and `ETag`/`If-None-Match` makes an unchanged gist a cheap `304` (a machine with a GitHub token reads authenticated, which is not limited that way). On a rate limit (`403`/`429`) the plugin waits as long as GitHub says (at least a minute, at most an hour) instead of retrying; a deleted gist (`404`) is reported and left for the next poll. When the next cycle is due, and any back-off, is kept in the sync-state file, so several opencode windows (and restarts) on one machine share one schedule and one lock: only one of them fetches, and any one of them serves the TUI's request. A response larger than 1 MiB is refused unread. The gist holds at most 64 entries and 64 OAuth logins, and its encrypted file at most 256 KiB. Set `OPENCODE_AUTH_LB_SYNC=0` to turn sync off entirely, or `OPENCODE_AUTH_LB_SYNC_LOGINS=0` to leave OAuth logins out of it.
230
238
 
231
239
  **Deliberately not an agent tool.** The link embeds the key, so a tool the model could call would put it in the chat history and in every model request. Sync is driven from the TUI sidebar only, the link is never logged, toasted, or written to the pool or pending files (the sync-state file holds it, owner-only where the OS supports modes), and the one-shot request file that carries a pasted link from the TUI to the plugin is deleted as soon as it is read. Until it is read that file holds the link, key included: the TUI withdraws a request nobody answered within 25 seconds, a request older than 10 minutes (or stamped more than a minute ahead) is ignored and deleted, and a server that is busy with another window's run leaves it on disk rather than losing it. On Windows the file mode `0600` gives no ACL guarantee; its protection is the data directory's inherited ACL (the same as the pool file's), so keep that directory private.
232
240
 
233
- > Not verified against a live GitHub account or a real second machine: the suite and the bundle run against an in-memory (and, for the end-to-end script, file-backed) fake of the gist API. Also unverified, as in [Minted tokens](#claude-long-lived-token-claude-setup-token): whether a minted Claude token keeps working once the OAuth login it came from is revoked — a machine that gets such a token inherits that uncertainty. The TUI rendering of the new sidebar lines and menu has been type-checked and unit-tested, not rendered in a live opencode.
241
+ #### OAuth logins in the gist
242
+
243
+ - **What is shared.** Each OAuth login that has a refresh token and a known account id, and that still works (not disabled, not marked `oauth re-login`): provider, label, access token, refresh token, their expiries, the account and organization ids, and the login's version. A login is identified by `<provider>:<account id>`, so the rows of one account on different machines are one login. Usage, cooldowns, sessions, `tokenGen`, the setup-token and local row ids are not shared.
244
+ - **Consent switch.** On by default. `OPENCODE_AUTH_LB_SYNC_LOGINS=0` (or `false` / `no` / `off`) makes this machine neither upload nor import logins. A machine with the switch off still writes the gist when its static credentials change, and then carries the logins already in the gist over unchanged: it never drops another machine's logins.
245
+ - **The newest login wins.** Every login has a revision (1 when the login is made; plus one for each re-login, refresh and token rotation) and the time of that change. Machines order the copies by *(revision, time, a fingerprint of the refresh token)*, the same order everywhere, so all of them pick the same winner. A newer copy from the gist replaces the tokens of the row that holds the same login; the row keeps its label, usage, cooldowns, sessions and setup-token, a manual disable stays, and an automatic `re-login` disable (and the `oauth re-login` mark) is lifted. A row that had fallen back to its setup-token is an OAuth row again. With no such row the login is added like a local one would be (so it pairs onto a token-only row of the same organization), under a label that is unique in the pool. A copy that is not newer is ignored, and a local copy that is newer is uploaded.
246
+ - **Any machine may refresh.** There is no owner of a login. A machine that refreshes it publishes the new pair right after the refresh commits (about a second, outside the refresh lock; if that upload fails, the regular schedule publishes it within a few seconds to minutes), and a login made on a machine that follows a gist is uploaded as soon as it lands, bounded to about 20 seconds so a slow GitHub never holds the login back. Pasting a share link both downloads the gist and uploads this machine's own logins in that same step. The other machines adopt the new pair on their next cycle (within 15 minutes, or at once with **Sync now**).
247
+ - **The risk.** A refresh token is single-use. If two machines refresh the same login at about the same moment, each spends the token the other is about to spend, and the provider may revoke the login for both: both then show `oauth re-login` (or `re-login`) and the account has to be logged in again. Nothing locks a login across machines.
248
+ - **What is mitigated, and what is not.** (1) A refresh is published right after it commits, so the other machines can see it within about a second. (2) A machine that is about to refresh a shared login first reads the gist (inside the account's refresh lock, so only one process per machine does it) and, if the gist holds a newer copy, uses that copy instead and sends **no** request to the provider when it is still valid. (3) If the provider refuses a refresh token and the gist already holds a newer copy, the machine adopts that copy and does not mark the login lost; without one it behaves as before. A failed or unreachable gist read changes nothing: the refresh goes ahead. **Not closed:** the collision window shrinks to the time between one machine's request to the provider and its publish (plus the other machine's read of the gist), but two machines refreshing inside that window can still log each other out, and the provider may revoke the whole login. There is no lease or election between machines. If you cannot accept that, set `OPENCODE_AUTH_LB_SYNC_LOGINS=0` (no logins are uploaded, imported or pulled).
249
+ - **Deleting.** A row you delete stays deleted: sync records which logins this machine holds, and a login whose row you removed is not imported again until you log in to that account again (that fresh login then outranks the copy in the gist). Removal is not propagated: the gist and the other machines keep the login, and **Stop syncing** leaves the imported rows in the pool as ordinary rows.
250
+ - **Compatibility.** A gist that carries logins is payload version 3. A plugin that only knows version 2 refuses it as written by a newer version: it neither reads nor writes the gist until updated, so update every machine that follows the gist. Version 2 gists are still read, and the first write by this version upgrades them. The gist holds at most 64 logins, and a login this version cannot read stops this machine from uploading, as for unreadable entries.
251
+
252
+ > Not verified against a live GitHub account or a real second machine: the suite and the bundle run against an in-memory (and, for the end-to-end script, file-backed) fake of the gist API. The TUI rendering of the new sidebar lines and menu has been type-checked and unit-tested, not rendered in a live opencode.
234
253
 
235
254
  ---
236
255
 
@@ -326,9 +345,10 @@ All knobs are environment variables with sane defaults.
326
345
  | `OPENCODE_AUTH_LB_MAX_WAIT_MS` | `305000` | Bounded wait for requests that do **not** carry both an opencode session id and user-message id (provider-internal or external fetches). Session-bound user turns use durable pending instead and wait until provider quota recovers or the user cancels. Auth (`401`/`403`), disabled/re-login accounts, and network failures are never converted into quota waits. `0` makes anonymous requests fail fast. |
327
346
  | `OPENCODE_AUTH_LB_ANTHROPIC_OPUS_FALLBACK_MODEL` | *(unset — ladder mode)* | Claude Max accounts have **separate weekly caps per premium model tier** (Fable, Opus, …). When one is exhausted, that tier's requests 429 (`anthropic-ratelimit-unified-representative-claim: seven_day_fable` / `seven_day_opus` / …) even though the account's aggregate 5h/7d windows still have headroom and every other model works. Instead of cooling the **whole account** down (which cascaded every account into "cooldown"), the balancer records a **per-tier** cooldown: requests for that tier steer to accounts with tier headroom, and once the whole pool is tier-limited they descend the **fallback ladder** (next family down, best version in your provider's model list; toasted, never silent). **Unset** = ladder mode (recommended). Set to a **model id** to pin a fixed downgrade target (bypassing the ladder). Set to an **empty string** to disable (revert to the account-wide cooldown). The env name keeps `OPUS` for compatibility but applies to **every** tier. |
328
347
  | `OPENCODE_AUTH_LB_ANTHROPIC_FAMILY_ORDER` | `fable,opus,sonnet,haiku` | The fallback ladder's model families, **best first**. A tier-capped request downgrades to the highest-versioned configured model of the next family below the capped one (e.g. capped `fable` → newest `opus`; capped `opus` → newest `sonnet`). A family not in the list (a future top tier) is treated as above the first entry — so when Anthropic ships a new premium tier, a config tweak (or nothing at all, if it slots on top) keeps the ladder correct without a code change. |
329
- | `OPENCODE_AUTH_LB_ANTHROPIC_AUTO_TOKEN` | `true` | Mint each Claude OAuth login a long-lived inference token (what `claude setup-token` prints) and renew it in its last 30 days — see [Claude long-lived token](#claude-long-lived-token-claude-setup-token). `0` / `false` / `no` / `off` turns minting off; tokens already minted stay. |
348
+ | `OPENCODE_AUTH_LB_ANTHROPIC_AUTO_TOKEN` | `false` | Try to mint each Claude OAuth login a long-lived inference token with a refresh grant. Off, because Anthropic answers that grant with an 8-hour token and narrows the login's refresh token to `user:inference` — see [Minting is off](#claude-long-lived-token-claude-setup-token). `1` / `true` / `yes` / `on` turns it on. |
330
349
  | `OPENCODE_AUTH_LB_ANTHROPIC_CLAUDE_CODE_VERSION` | *(unset — auto)* | Pin the Claude Code version the plugin claims to be, bypassing both the npm lookup and the built-in floor. Anthropic **gates new models on this version** — asking for a model newer than the version you report is rejected with `claude_code_version_too_old` — so by default the plugin resolves it automatically, and relearns it from a rejection when the gate moves before npm does (see [Claude Code version](#claude-code-version)). A pin also disables that reactive recovery, since the retry would send the version you pinned. Set this only to pin **forward** (a version npm hasn't tagged `latest` yet) or **back** (to reproduce a failure, or if a future release changes the request fingerprint and the newest version starts failing). Must be a plain `x.y.z`; anything else is ignored. |
331
- | `OPENCODE_AUTH_LB_SYNC` | `true` | The [gist sync](#sync-static-credentials-between-machines-github-gist) schedule (a cycle every 15 minutes, one after this machine's own credentials change, serve the TUI's requests). `0` / `false` / `no` / `off` turns it off. |
350
+ | `OPENCODE_AUTH_LB_SYNC` | `true` | The [gist sync](#sync-credentials-and-oauth-logins-between-machines-github-gist) schedule (a cycle every 15 minutes, one after this machine's own credentials change, serve the TUI's requests). `0` / `false` / `no` / `off` turns it off. |
351
+ | `OPENCODE_AUTH_LB_SYNC_LOGINS` | `true` | Whether gist sync also shares [OAuth logins](#oauth-logins-in-the-gist). `0` / `false` / `no` / `off`: this machine neither uploads nor imports logins, and carries the gist's logins over unchanged when it writes. Two machines refreshing one shared login at once can revoke it for both. |
332
352
  | `GITHUB_TOKEN`, `GH_TOKEN` | — | A GitHub token with the `gist` scope (checked in this order, then `gh auth token`). It is what lets a member **upload** its own credentials (and read without the anonymous rate limit); a machine without one still downloads. Sent only to `api.github.com`. |
333
353
  | `OPENCODE_AUTH_LB_DIR` | — | Override the pool-file directory (handy for tests). |
334
354
  | `OPENCODE_AUTH_LB_DEBUG` | — | `1`/`true` logs each selection to stderr. |
@@ -411,7 +431,7 @@ src/
411
431
  accounts.ts # append / bootstrap accounts into the pool
412
432
  pairing.ts # which row a login lands on (setup-token ↔ OAuth pairing)
413
433
  login-health.ts # login tags, re-login / expiry warnings, why a login was lost
414
- token-mint.ts # long-lived Claude tokens minted from OAuth logins, renewed before they lapse
434
+ token-mint.ts # opt-in refresh-grant minting of Claude inference tokens (off by default; see "Minting is off")
415
435
  session.ts # derive a stable session key (affinity)
416
436
  types.ts # provider-agnostic data model (accounts, usage windows, pool file)
417
437
  usage-merge.ts # fixed weekly-anchor preservation / roll-forward
@@ -420,7 +440,8 @@ src/
420
440
  notify.ts # toast on account switch
421
441
  usage-refresh.ts # cold-start usage seeding via the usage endpoint
422
442
  prime.ts # point the in-use marker at the top-ranked account at startup
423
- sync/ # gist sync: crypto, gist client, payload (v2, origins), own/imported split, merge plan, one read-apply-write cycle, state, schedule
443
+ login-rev.ts # the shared version (loginRev / loginAt) of a row's OAuth login
444
+ sync/ # gist sync: crypto, gist client, payload (v3: entries with origins + OAuth logins), own/imported split, merge plan, login export/import, one read-apply-write cycle, state, schedule
424
445
  pending/ # recovery classifier, reference store, per-turn lease, restart coordinator
425
446
  scheduler/ # config, score-core (shared scorer), select
426
447
  pool/ # data-dir resolution + atomic, serialized pool store
@@ -464,7 +485,7 @@ The account pool and durable pending references are separate JSON files (opencod
464
485
  - **Kimi Code** sign-ins must be approved within 15 minutes, or the login fails and has to be started again. A key imported from opencode's store at startup is keyed by the key itself — the import makes no network call to learn its account — so log that subscription in again before adding it a second way, or it can count twice.
465
486
  - **Plugin reloads require restart**: opencode loads server plugins once at process startup. After installing a new build, restart the running opencode process once; durable turns are restored on that next start and are never sent while opencode is closed.
466
487
  - **Cross-process refresh**: per-process singleflight protects token rotation within one opencode instance. Running two opencode instances at once could still race the single-use refresh token.
467
- - **Gist sync** shares only static credentials, so a machine with no OAuth login for an account serves it on the shared token alone: its usage comes from response headers and the idle quota check, not the usage endpoint (see the setup-token section). The TUI asks the plugin to sync through a small request file beside the pool and shows the plugin's answer from a status file, because the TUI cannot import the plugin; if no opencode server is running, a request waits until one starts and is dropped after 10 minutes. A machine without a GitHub token reads the gist through the unauthenticated API, so an IP behind a busy shared NAT can hit GitHub's 60/hour limit. Gist writes have no compare-and-swap: two machines writing at once can lose one update until the next cycle re-asserts it (see the sync section).
488
+ - **Gist sync** shares static credentials and, unless switched off, OAuth logins. A machine that gets only a shared token (a login-sharing switch off somewhere, or a login whose refresh was refused) serves the account on that token alone: its usage comes from response headers and the idle quota check, not the usage endpoint (see the setup-token section). Two machines refreshing one shared login at the same moment can revoke it for both (see [OAuth logins](#oauth-logins-in-the-gist)). The TUI asks the plugin to sync through a small request file beside the pool and shows the plugin's answer from a status file, because the TUI cannot import the plugin; if no opencode server is running, a request waits until one starts and is dropped after 10 minutes. A machine without a GitHub token reads the gist through the unauthenticated API, so an IP behind a busy shared NAT can hit GitHub's 60/hour limit. Gist writes have no compare-and-swap: two machines writing at once can lose one update until the next cycle re-asserts it (see the sync section).
468
489
  - **TUI pool writes**: the TUI sidebar's Rename / Delete actions write the pool file atomically (temp + rename) but WITHOUT the cross-process file lock the server uses around its own read-modify-write — so a server usage / cooldown / session / `tokenGen` update committed between the TUI's `readFileSync` and `renameSync` can be silently overwritten. Impact is bounded: the next request re-records usage from response headers, so the window is one cycle of staleness on the affected account; correctness recovers on its own.
469
490
  - Live OAuth/login and real-account end-to-end behavior should be smoke-tested in your environment; the test suite mocks the network.
470
491