@yugimob/pi-opencode-go-rotation 1.7.0 → 1.7.2

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
@@ -1,6 +1,6 @@
1
1
  # pi-opencode-go-rotation
2
2
 
3
- Rotate between multiple OpenCode Go API keys. The extension checks OpenCode Go usage when a 429 response arrives, rotates around quota-blocked and cooling-down keys, and recovers silent stalls detected by the watchdog.
3
+ Rotate between multiple OpenCode Go API keys. The extension checks OpenCode Go usage when a 429 response arrives, rotates around quota-blocked keys, and aborts silent stalls detected by the watchdog. Automatic rotation is policy-gated and defaults to `quota-only`: it switches keys only when usage proves an exhausted window or a quota error carries a parseable reset.
4
4
 
5
5
  Fork of [lnilluv/pi-opencode-go-rotation](https://github.com/lnilluv/pi-opencode-go-rotation). This fork adds a live footer status line for the active key's OpenCode Go usage.
6
6
 
@@ -22,6 +22,8 @@ Add your API keys:
22
22
 
23
23
  The first key added becomes active immediately.
24
24
 
25
+ If `OPENCODE_API_KEY` is set in the environment and no keys are configured, the extension recognizes it as an unmanaged `env` key: it reports that key's usage and keeps the footer working, but never writes it to the config file. Pi already uses that variable for its own requests, so nothing changes about how the model is called. `/opencode add` stores a managed copy that participates in rotation.
26
+
25
27
  The extension never imports keys from `auth.json` automatically. When no keys are configured, `/opencode` offers to import the auth.json key once; declining is remembered and it is not asked again.
26
28
 
27
29
  ## Interactive key manager
@@ -33,24 +35,34 @@ In interactive mode, `/opencode` (or `/opencode config`) opens the key manager o
33
35
  - Remove a key
34
36
  - Add a key without remembering the command syntax
35
37
  - Check a key's usage after the window closes
36
- - Change the cooldown duration and the watchdog settings
38
+ - Change the cooldown duration, the rotation policy, candidate verification, and the watchdog settings
37
39
  - Clear every cooldown and quota block
38
40
 
39
41
  Changes are saved as soon as they are confirmed. Outside interactive mode the command prints the text status instead.
40
42
 
41
43
  ## How it works
42
44
 
43
- The extension sets the active key as a runtime override, which takes priority over `OPENCODE_API_KEY` environment variables and `auth.json` credentials.
45
+ The extension sets the active key as a runtime override, which takes priority over `OPENCODE_API_KEY` environment variables and `auth.json` credentials. When no keys are configured, the environment key is only observed (as `env`) and never overridden or persisted.
46
+
47
+ Automatic rotation is governed by `rotationPolicy`:
48
+
49
+ | Policy | Rotates when |
50
+ |--------|--------------|
51
+ | `off` | Never automatically. Usage checks still report and manual `/opencode next` and `/opencode use <n>` still switch. |
52
+ | `quota-only` (default) | OpenCode Go usage confirms an exhausted window, or a fixed-window quota error carries a parseable reset. |
53
+ | `full` | Also on transient rate limits and on watchdog stalls. |
54
+
55
+ Candidate verification is a separate switch (`verifyCandidates`, default `false`). When enabled, each candidate key's usage is checked before switching to it; when disabled, the next key is chosen from configuration state without sending its key to the usage endpoint. The active key is still checked when it reports a 429 or a quota error, and `/opencode usage` still works on demand.
44
56
 
45
57
  The extension has three recovery paths:
46
58
 
47
- 1. **Usage-verified Go quota exhaustion**: when OpenCode Go returns HTTP 429, the extension sends the active key only to `https://opencode.ai/zen/go/v1/usage`. If a usage window is `rate-limited`, the failed key is blocked until the latest reported reset and the next non-quota-blocked key is activated. Rotation prefers keys outside transient cooldown, but can clear a cooldown rather than keep using an exhausted key. Repeated failures try each configured key once. When every key is quota-blocked, rotation stops and reports the earliest reset instead of cycling.
48
- 2. **Transient limit errors**: when the usage endpoint is unavailable, does not report a rate-limited window, or does not finish within 10 seconds, the extension preserves the existing transient 429 behavior. It aborts a timed-out usage request, marks the current key as on cooldown, switches to the next key that is not quota-blocked, and applies it via `setRuntimeApiKey`.
49
- 3. **Silent stalls**: when an `opencode-go` provider request has no response or stream activity for the watchdog window, the extension rotates to an eligible key, aborts the hung turn, and rewrites the abort as a retryable timeout error.
59
+ 1. **Usage-verified Go quota exhaustion**: when OpenCode Go returns HTTP 429, the extension sends the active key only to `https://opencode.ai/zen/go/v1/usage`. A key with a `rate-limited` window or a window at 100% is blocked until the latest reported reset, and the next candidate is activated. With `verifyCandidates` enabled, candidate keys are checked the same way before they are selected, so an exhausted key is blocked and skipped instead of being tried. Rotation prefers keys outside transient cooldown, but can clear a cooldown rather than keep using an exhausted key. When every key is quota-blocked, rotation stops and reports the earliest reset instead of cycling.
60
+ 2. **Transient limit errors** (`full` only): when the usage endpoint is unavailable, does not report an exhausted window, or does not finish within 10 seconds, the extension aborts a timed-out usage request, marks the current key as on cooldown, and switches to the next key that is not quota-blocked. Under `quota-only` and `off` the key stays active and the extension reports the limit instead of rotating.
61
+ 3. **Silent stalls**: when an `opencode-go` provider request has no response or stream activity for the watchdog window, the extension aborts the hung turn and rewrites the abort as a retryable timeout error. It rotates only under `full`; otherwise pi retries the same key.
50
62
 
51
- This is still reactive: it does not poll usage or check limits before normal requests.
63
+ Checks happen at decision points only: a candidate is verified when `verifyCandidates` is enabled and it is about to be selected, and a key with a recorded block is left alone until its stored reset passes. Normal requests are not pre-checked. With the interactive footer active, the periodic footer refresh also re-checks the active key and, unless `rotationPolicy` is `off`, records a block if a window is full, so the next request can rotate before it fails.
52
64
 
53
- Fixed-window Go plan quota errors reported at message end follow the same rotation path. A parseable reset timestamp is authoritative; otherwise the configured cooldown duration is used as the block duration. A response-hook rotation is deduplicated so the matching message-end error cannot rotate twice.
65
+ Fixed-window Go plan quota errors reported at message end follow the same policy: a parseable reset timestamp is authoritative; without one, `quota-only` and `off` record the cooldown-length block without rotating, and `full` rotates. A response-hook rotation is deduplicated so the matching message-end error cannot rotate twice.
54
66
 
55
67
  Pi's built-in auto-retry picks up the new key on the next request.
56
68
 
@@ -67,14 +79,14 @@ personal: wk 40% · mo 55% | ↻ Nov 12
67
79
  ```
68
80
  The rolling 5-hour window is omitted from the footer.
69
81
 
70
- It refreshes on session start, model changes, turns, key rotations, manual key commands, and every 5 minutes. The active key's name leads the line, and switching to another provider clears it.
82
+ It refreshes on session start, model changes, turns, key rotations, manual key commands, and every 5 minutes. Under `quota-only` and `full`, a window at 100% or rate-limited blocks the active key until the window's reset and the next request moves to another key; under `off` the footer reports the window without changing keys. The active key's name leads the line, and switching to another provider clears it.
71
83
 
72
84
  ## Commands
73
85
 
74
86
  | Command | Description |
75
87
  |---------|-------------|
76
88
  | `/opencode` or `/opencode config` | Open the interactive key manager |
77
- | `/opencode status` | Show all keys, active key marker, cooldown and quota-blocked status |
89
+ | `/opencode status` | Show all keys, active key marker, cooldown and quota-blocked status, or the `env` key when only `OPENCODE_API_KEY` is set |
78
90
  | `/opencode usage` or `/opencode quota` | Fetch OpenCode Go usage for the active key without showing key material |
79
91
  | `/opencode use <n>` | Switch to key number `n` (1-based) and clear its cooldown and quota block |
80
92
  | `/opencode next` | Advance to the next configured key and clear its cooldown and quota block before activating it |
@@ -82,6 +94,8 @@ It refreshes on session start, model changes, turns, key rotations, manual key c
82
94
  | `/opencode rm <n>` | Remove key number `n` |
83
95
  | `/opencode reset` | Clear all cooldowns and quota blocks |
84
96
  | `/opencode cooldown <min>` | Set or view cooldown duration in minutes |
97
+ | `/opencode policy [off\|quota-only\|full]` | Set or view the automatic rotation policy |
98
+ | `/opencode verify <on\|off>` | Enable or disable candidate usage verification before switching |
85
99
  | `/opencode events` | Show recent watchdog timeout history (last 10) |
86
100
  | `/opencode watchdog [status\|on\|off\|<seconds>]` | Configure silent-stall detection |
87
101
 
@@ -99,6 +113,8 @@ Keys are stored in `~/.pi/agent/opencode-keys.json` with file permissions `0600`
99
113
  "cooldownMinutes": 60,
100
114
  "watchdogEnabled": true,
101
115
  "watchdogIdleMs": 90000,
116
+ "rotationPolicy": "quota-only",
117
+ "verifyCandidates": false,
102
118
  "cooldowns": {},
103
119
  "quotaBlockedUntil": {},
104
120
  "authImportDeclined": false
@@ -122,12 +138,15 @@ Set `maxRetries` to at least the number of keys so all keys get a chance before
122
138
 
123
139
  ## Limitations
124
140
 
125
- - The watchdog is scoped to the `opencode-go` provider only. Other providers are not aborted or rotated.
126
- - A legitimate long-running request with no stream activity can be treated as stalled; tune with `/opencode watchdog <seconds>` or disable with `/opencode watchdog off`.
127
- - When all non-quota-blocked keys are transiently cooling down, the extension may clear the next eligible key's cooldown. It never automatically clears or force-selects a quota-blocked key.
128
- - When all keys are quota-blocked, automatic rotation stops on the current runtime key until a block expires or a manual command clears one.
141
+ - The watchdog is scoped to the `opencode-go` provider only. Other providers are not aborted, and the watchdog rotates only under `rotationPolicy` `full`.
142
+ - A legitimate long-running request with no stream activity can be treated as stalled and aborted; tune with `/opencode watchdog <seconds>` or disable with `/opencode watchdog off`.
143
+ - Under `quota-only`, a bare 429, an HTTP 401, an unconfirmed usage result, and a watchdog stall never switch keys; the extension reports them and leaves the active key in place. `full` restores the earlier behavior.
144
+ - When all non-quota-blocked keys are transiently cooling down (`full` only), the extension may clear the next eligible key's cooldown. It never automatically clears or force-selects a quota-blocked key.
145
+ - When all keys are quota-blocked, automatic rotation stops on the current runtime key; each key becomes eligible again automatically when its stored reset deadline passes, or immediately after `/opencode reset`.
146
+ - Recorded blocks are never re-probed before their stored reset, so there is no plan-top-up recovery; use `/opencode reset` or `/opencode use <n>` to clear a block early.
129
147
  - Go plan usage limits are tied to the subscription workspace; multiple keys from one workspace should not be assumed to provide independent quota. See the [OpenCode Go documentation](https://opencode.ai/docs/go/).
130
148
  - Keys added via `/opencode add` are stored in plaintext. The config file is created and maintained with `0600` permissions.
149
+ - An `OPENCODE_API_KEY` environment key is never stored, so it cannot rotate and is not remembered across sessions; `/opencode add` creates a managed copy. A stored `auth.json` credential takes precedence over the environment variable, and the extension follows the credential pi resolves.
131
150
 
132
151
  ## License
133
152
 
@@ -1,6 +1,7 @@
1
1
  export declare const CONFIG_PATH_ENV = "PI_OPENCODE_ROTATION_CONFIG";
2
2
  export declare const DEFAULT_COOLDOWN_MINUTES = 60;
3
3
  export declare const DEFAULT_WATCHDOG_IDLE_MS = 90000;
4
+ export type RotationPolicy = "off" | "quota-only" | "full";
4
5
  export interface KeyEntry {
5
6
  name: string;
6
7
  key: string;
@@ -11,7 +12,8 @@ export interface Config {
11
12
  cooldownMinutes: number;
12
13
  watchdogEnabled: boolean;
13
14
  watchdogIdleMs: number;
14
- /** Key index → epoch ms when cooldown started */
15
+ rotationPolicy: RotationPolicy;
16
+ verifyCandidates: boolean;
15
17
  cooldowns: Record<number, number>;
16
18
  quotaBlockedUntil: Record<number, number>;
17
19
  authImportDeclined: boolean;
@@ -5,6 +5,8 @@ import { randomUUID } from "node:crypto";
5
5
  export const CONFIG_PATH_ENV = "PI_OPENCODE_ROTATION_CONFIG";
6
6
  export const DEFAULT_COOLDOWN_MINUTES = 60;
7
7
  export const DEFAULT_WATCHDOG_IDLE_MS = 90_000;
8
+ const DEFAULT_ROTATION_POLICY = "quota-only";
9
+ const DEFAULT_VERIFY_CANDIDATES = false;
8
10
  const CONFIG_FILE_MODE = 0o600;
9
11
  const LOCK_TIMEOUT_MS = 10_000;
10
12
  const LOCK_STALE_MS = 30_000;
@@ -24,6 +26,8 @@ export function createEmptyConfig() {
24
26
  cooldownMinutes: DEFAULT_COOLDOWN_MINUTES,
25
27
  watchdogEnabled: true,
26
28
  watchdogIdleMs: DEFAULT_WATCHDOG_IDLE_MS,
29
+ rotationPolicy: DEFAULT_ROTATION_POLICY,
30
+ verifyCandidates: DEFAULT_VERIFY_CANDIDATES,
27
31
  cooldowns: {},
28
32
  quotaBlockedUntil: {},
29
33
  authImportDeclined: false,
@@ -78,6 +82,14 @@ function parseConfig(value, path) {
78
82
  if (typeof watchdogIdleMs !== "number" || !Number.isFinite(watchdogIdleMs) || watchdogIdleMs < 1) {
79
83
  throw new ConfigLoadError(path, "watchdogIdleMs is invalid");
80
84
  }
85
+ const rotationPolicyValue = value.rotationPolicy;
86
+ const rotationPolicy = rotationPolicyValue === undefined ? DEFAULT_ROTATION_POLICY : rotationPolicyValue;
87
+ if (rotationPolicy !== "off" && rotationPolicy !== "quota-only" && rotationPolicy !== "full") {
88
+ throw new ConfigLoadError(path, "rotationPolicy is invalid");
89
+ }
90
+ const verifyCandidates = value.verifyCandidates ?? DEFAULT_VERIFY_CANDIDATES;
91
+ if (typeof verifyCandidates !== "boolean")
92
+ throw new ConfigLoadError(path, "verifyCandidates is invalid");
81
93
  const authImportDeclined = value.authImportDeclined ?? false;
82
94
  if (typeof authImportDeclined !== "boolean")
83
95
  throw new ConfigLoadError(path, "authImportDeclined is invalid");
@@ -87,6 +99,8 @@ function parseConfig(value, path) {
87
99
  cooldownMinutes,
88
100
  watchdogEnabled,
89
101
  watchdogIdleMs,
102
+ rotationPolicy,
103
+ verifyCandidates,
90
104
  authImportDeclined,
91
105
  cooldowns: parseNumberRecord(value.cooldowns, "cooldowns", path),
92
106
  quotaBlockedUntil: parseNumberRecord(value.quotaBlockedUntil, "quotaBlockedUntil", path),
@@ -127,9 +141,7 @@ function acquireLock(path) {
127
141
  continue;
128
142
  }
129
143
  }
130
- catch {
131
- // The other process may have released the lock between stat and removal.
132
- }
144
+ catch { }
133
145
  if (Date.now() - startedAt >= LOCK_TIMEOUT_MS) {
134
146
  throw new Error(`Timed out waiting for OpenCode rotation config lock: ${lockPath}`);
135
147
  }
package/dist/config-ui.js CHANGED
@@ -454,7 +454,21 @@ export async function openOpencodeConfig(ctx) {
454
454
  label: "Watchdog",
455
455
  currentValue: current.watchdogEnabled ? "on" : "off",
456
456
  values: ["on", "off"],
457
- description: "Abort and rotate an opencode-go request that stalls with no response or stream activity.",
457
+ description: "Abort an opencode-go request that stalls with no response or stream activity and retry it.",
458
+ });
459
+ items.push({
460
+ id: "rotationPolicy",
461
+ label: "Rotation policy",
462
+ currentValue: current.rotationPolicy,
463
+ values: ["off", "quota-only", "full"],
464
+ description: "off never rotates automatically. quota-only rotates on a confirmed exhausted window or a parsed reset. full also rotates on transient limits and stalls.",
465
+ });
466
+ items.push({
467
+ id: "verifyCandidates",
468
+ label: "Verify candidates",
469
+ currentValue: current.verifyCandidates ? "on" : "off",
470
+ values: ["on", "off"],
471
+ description: "Check a candidate key's usage before switching to it.",
458
472
  });
459
473
  items.push({
460
474
  id: "watchdogIdle",
@@ -513,20 +527,37 @@ export async function openOpencodeConfig(ctx) {
513
527
  container.clear();
514
528
  container.addChild(rule(tui, theme));
515
529
  container.addChild(new tui.Text(theme.fg("accent", theme.bold("OpenCode Go keys")), 1, 0));
516
- container.addChild(new tui.Text(theme.fg("dim", "Keys, cooldowns, quota blocks, and the stall watchdog. Esc closes."), 1, 0));
530
+ container.addChild(new tui.Text(theme.fg("dim", "Keys, rotation policy, cooldowns, quota blocks, and the stall watchdog. Esc closes."), 1, 0));
517
531
  container.addChild(list);
518
532
  container.addChild(status);
519
533
  container.addChild(rule(tui, theme));
520
534
  interactive.requestRender();
521
535
  };
522
536
  const onChange = (id, value) => {
523
- if (id !== "watchdog")
537
+ if (id === "watchdog") {
538
+ const enabled = value === "on";
539
+ if (persist((fresh) => {
540
+ fresh.watchdogEnabled = enabled;
541
+ }) === undefined)
542
+ rebuild("watchdog");
543
+ return;
544
+ }
545
+ if (id === "rotationPolicy") {
546
+ if (value !== "off" && value !== "quota-only" && value !== "full")
547
+ return;
548
+ const policy = value;
549
+ if (persist((fresh) => {
550
+ fresh.rotationPolicy = policy;
551
+ }) === undefined)
552
+ rebuild("rotationPolicy");
524
553
  return;
525
- const enabled = value === "on";
526
- if (persist((fresh) => {
527
- fresh.watchdogEnabled = enabled;
528
- }) === undefined) {
529
- rebuild("watchdog");
554
+ }
555
+ if (id === "verifyCandidates") {
556
+ const enabled = value === "on";
557
+ if (persist((fresh) => {
558
+ fresh.verifyCandidates = enabled;
559
+ }) === undefined)
560
+ rebuild("verifyCandidates");
530
561
  }
531
562
  };
532
563
  rebuild();
package/dist/index.js CHANGED
@@ -3,6 +3,8 @@ import { openOpencodeConfig, removeKey } from "./config-ui.js";
3
3
  import { formatDuration, formatResetIn } from "./format-time.js";
4
4
  export { formatResetIn };
5
5
  const PROVIDER = "opencode-go";
6
+ const OPENCODE_KEY_ENV = "OPENCODE_API_KEY";
7
+ const AMBIENT_KEY_NAME = "env";
6
8
  const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
7
9
  const OPENCODE_GO_USAGE_TIMEOUT_MS = 10_000;
8
10
  const FIXED_WINDOW_QUOTA_RE = /\b(?:5[- ]hour|weekly|monthly)\b[\s\S]*\b(?:usage\s+)?(?:quota|limit)\b|\b(?:usage|plan)\s+allocated\s+quota\s+exceeded\b|\b(?:quota|limit)\b[\s\S]*\b(?:will\s+reset|resets?\s+at|fixed[- ]window)\b/i;
@@ -132,60 +134,73 @@ function getQuotaBlockedUntil(config, keyIndex, now) {
132
134
  ? blockedUntil
133
135
  : undefined;
134
136
  }
135
- /** Keys held by a live recorded block, optionally ignoring the key that just failed. */
136
- function getQuotaBlockedTargets(config, now, skipKeyIndex) {
137
- const targets = [];
138
- for (let keyIndex = 0; keyIndex < config.keys.length; keyIndex++) {
139
- if (keyIndex === skipKeyIndex)
140
- continue;
141
- if (getQuotaBlockedUntil(config, keyIndex, now) === undefined)
142
- continue;
143
- const target = getUsageTargetForKeyIndex(config, keyIndex);
144
- if (target)
145
- targets.push(target);
146
- }
147
- return targets;
137
+ function allowsQuotaRotation(config) {
138
+ return config.rotationPolicy !== "off";
139
+ }
140
+ function allowsTransientRotation(config) {
141
+ return config.rotationPolicy === "full";
142
+ }
143
+ function allowsWatchdogRotation(config) {
144
+ return config.rotationPolicy === "full";
148
145
  }
149
146
  function pickAvailableKeyIndex(config, now = Date.now()) {
147
+ if (config.keys.length === 0)
148
+ return undefined;
149
+ if (!allowsQuotaRotation(config))
150
+ return config.activeKeyIndex;
150
151
  const cdMs = getCooldownMs(config);
151
152
  for (let i = 0; i < config.keys.length; i++) {
152
153
  const idx = (config.activeKeyIndex + i) % config.keys.length;
153
154
  if (getQuotaBlockedUntil(config, idx, now) !== undefined)
154
155
  continue;
156
+ if (!allowsTransientRotation(config))
157
+ return idx;
155
158
  const cooldownStart = config.cooldowns[idx];
156
159
  if (cooldownStart === undefined || now - cooldownStart >= cdMs)
157
160
  return idx;
158
161
  }
159
162
  return undefined;
160
163
  }
164
+ function listRotationCandidates(config, startIndex, currentTime) {
165
+ const preferred = [];
166
+ const cooling = [];
167
+ const cooldownMs = getCooldownMs(config);
168
+ for (let offset = 1; offset < config.keys.length; offset++) {
169
+ const keyIndex = (startIndex + offset) % config.keys.length;
170
+ if (getQuotaBlockedUntil(config, keyIndex, currentTime) !== undefined)
171
+ continue;
172
+ const cooldownStart = config.cooldowns[keyIndex];
173
+ if (cooldownStart === undefined || currentTime - cooldownStart >= cooldownMs)
174
+ preferred.push(keyIndex);
175
+ else
176
+ cooling.push(keyIndex);
177
+ }
178
+ return [...preferred, ...cooling];
179
+ }
180
+ function applyRotationMode(mode, config, keyIndex, currentTime) {
181
+ if (mode.kind === "quota") {
182
+ if (mode.authoritative)
183
+ config.quotaBlockedUntil[keyIndex] = mode.blockedUntil;
184
+ else
185
+ setQuotaBlock(config, keyIndex, mode.blockedUntil, currentTime);
186
+ return;
187
+ }
188
+ config.cooldowns[keyIndex] = currentTime;
189
+ }
161
190
  function rotateToNextKey(config, options = {}) {
162
191
  if (config.keys.length === 0)
163
192
  return undefined;
164
193
  const now = options.now ?? Date.now();
165
194
  config.cooldowns[config.activeKeyIndex] = now;
166
- const next = pickAvailableKeyIndex(config, now);
167
- if (next !== undefined) {
168
- config.activeKeyIndex = next;
169
- return next;
170
- }
171
- for (let offset = 1; offset <= config.keys.length; offset++) {
172
- const candidate = (config.activeKeyIndex + offset) % config.keys.length;
173
- if (getQuotaBlockedUntil(config, candidate, now) !== undefined)
174
- continue;
175
- config.activeKeyIndex = candidate;
176
- delete config.cooldowns[candidate];
177
- return candidate;
178
- }
179
- return undefined;
195
+ const next = listRotationCandidates(config, config.activeKeyIndex, now)[0];
196
+ if (next === undefined)
197
+ return undefined;
198
+ config.activeKeyIndex = next;
199
+ delete config.cooldowns[next];
200
+ return next;
180
201
  }
181
- // Key equality detects credential changes, but persisted history has no issuer
182
- // provenance (including after reload). Never replay signed reasoning on this
183
- // rotating route, even before this process observes its first rotation.
184
202
  const droppedReasoningDetail = Symbol("dropped-caller-bound-reasoning");
185
203
  function projectReasoningDetails(details) {
186
- // map/filter, never flatMap: entries that are not plain reasoning detail
187
- // objects (nested arrays, numbers, booleans, ...) must pass through as the
188
- // same element in the same position, with their original shape intact.
189
204
  return details
190
205
  .map((detail) => {
191
206
  if (!isRecord(detail))
@@ -197,12 +212,6 @@ function projectReasoningDetails(details) {
197
212
  })
198
213
  .filter((detail) => detail !== droppedReasoningDetail);
199
214
  }
200
- /**
201
- * Anthropic serializes signed thinking as `thinking` blocks and opaque redacted
202
- * reasoning as `redacted_thinking`. Emit the SDK's own unsigned shape instead: a
203
- * plain text block. Drop entries emptied by that projection, and report an
204
- * assistant message for omission only when the projection emptied it.
205
- */
206
215
  function projectAssistantContent(content) {
207
216
  let projected = false;
208
217
  const result = [];
@@ -250,9 +259,6 @@ function sanitizeReasoningPayload(payload) {
250
259
  if (Array.isArray(message.reasoning_details)) {
251
260
  const { reasoning_details: _details, ...visible } = projected;
252
261
  const reasoning_details = projectReasoningDetails(message.reasoning_details);
253
- // Strip the key entirely when nothing remains to send: an empty array is an
254
- // unvalidated request shape, and this sanitiser exists to emit only shapes the
255
- // provider accepts. Non-detail entries above keep identity/position/shape.
256
262
  projected = reasoning_details.length === 0 ? visible : { ...visible, reasoning_details };
257
263
  }
258
264
  messages.push(projected);
@@ -275,7 +281,6 @@ function getRuntimeKeyStore(modelRegistry) {
275
281
  function ignoreAsyncRefresh(result) {
276
282
  void result?.catch(() => { });
277
283
  }
278
- /** Set the active key as runtime override (highest priority in auth chain). */
279
284
  function applyActiveKey(config, modelRegistry, now = Date.now()) {
280
285
  const idx = pickAvailableKeyIndex(config, now);
281
286
  if (idx === undefined)
@@ -312,11 +317,6 @@ function captureSelectionSnapshot(config, currentTime, keyIndex) {
312
317
  cooldownStart: config.cooldowns[target.keyIndex],
313
318
  };
314
319
  }
315
- /**
316
- * A deferred decision owns one credential, selection, block and cooldown. Every later
317
- * mutation re-checks that exact snapshot under the lock, so an operation that started
318
- * before an external update can never write to the replacement state.
319
- */
320
320
  function matchesSelectionSnapshot(config, snapshot, currentTime) {
321
321
  const entry = config.keys[snapshot.keyIndex];
322
322
  if (entry === undefined)
@@ -470,24 +470,22 @@ function matchesUsageTarget(config, target) {
470
470
  && (entry.name || `key-${target.keyIndex + 1}`) === target.keyName
471
471
  && entry.key === target.bearerToken;
472
472
  }
473
- function hasRateLimitedUsageWindow(result) {
474
- return result.ok && result.usage.windows.some((window) => window.status === "rate-limited");
473
+ function usageWindowExhausted(window) {
474
+ if (window.status === "rate-limited")
475
+ return true;
476
+ if (window.usagePercent !== undefined && window.usagePercent >= 100)
477
+ return true;
478
+ if (window.used !== undefined && window.limit !== undefined && window.limit > 0 && window.used >= window.limit)
479
+ return true;
480
+ return window.remaining !== undefined && window.remaining <= 0;
475
481
  }
476
- /**
477
- * A recorded block can go stale: the plan was topped up, or the window reset before the
478
- * deadline we stored. Only a clean reading releases it -- a failed or unrecognised usage
479
- * response is not evidence of headroom. A response with no windows, or with any window
480
- * that is not positively active, stays conservative and keeps the recorded block.
481
- */
482
- function hasConfirmedHeadroom(result) {
483
- return result.ok
484
- && result.usage.windows.length > 0
485
- && result.usage.windows.every((window) => window.status === "active");
482
+ function hasExhaustedWindow(result) {
483
+ return result.ok && result.usage.windows.some(usageWindowExhausted);
486
484
  }
487
- function getRateLimitedUntil(usage, now, fallbackMs) {
485
+ function getExhaustedUntil(usage, now, fallbackMs) {
488
486
  let blockedUntil = now;
489
487
  for (const window of usage.windows) {
490
- if (window.status !== "rate-limited")
488
+ if (!usageWindowExhausted(window))
491
489
  continue;
492
490
  const resetTimes = [];
493
491
  if (window.resetInSec !== undefined) {
@@ -522,28 +520,6 @@ function getEarliestQuotaReset(config, now) {
522
520
  function setQuotaBlock(config, keyIndex, blockedUntil, now) {
523
521
  config.quotaBlockedUntil[keyIndex] = Math.max(getQuotaBlockedUntil(config, keyIndex, now) ?? 0, blockedUntil);
524
522
  }
525
- function blockQuotaAndSelectNext(config, keyIndex, blockedUntil, now, isAuthoritative = false) {
526
- if (isAuthoritative) {
527
- config.quotaBlockedUntil[keyIndex] = blockedUntil;
528
- }
529
- else {
530
- setQuotaBlock(config, keyIndex, blockedUntil, now);
531
- }
532
- let next = pickAvailableKeyIndex(config, now);
533
- if (next === undefined) {
534
- for (let offset = 1; offset <= config.keys.length; offset++) {
535
- const candidate = (keyIndex + offset) % config.keys.length;
536
- if (getQuotaBlockedUntil(config, candidate, now) !== undefined)
537
- continue;
538
- next = candidate;
539
- delete config.cooldowns[candidate];
540
- break;
541
- }
542
- }
543
- if (next !== undefined)
544
- config.activeKeyIndex = next;
545
- return next;
546
- }
547
523
  function formatUsageAmount(value) {
548
524
  return value === undefined ? undefined : value.toLocaleString("en-US");
549
525
  }
@@ -637,10 +613,14 @@ function usageWindowPercent(window) {
637
613
  return (window.used / window.limit) * 100;
638
614
  return undefined;
639
615
  }
640
- function formatStatus(config, now = Date.now()) {
616
+ function formatStatus(config, now = Date.now(), ambientKeyApplied = false) {
641
617
  const watchdogStatus = `Watchdog: ${config.watchdogEnabled ? "on" : "off"} (${Math.ceil(getWatchdogIdleMs(config) / 1000)}s idle)`;
618
+ const policyStatus = `Rotation: ${config.rotationPolicy} (candidate verification ${config.verifyCandidates ? "on" : "off"})`;
642
619
  if (config.keys.length === 0) {
643
- return `No keys configured. Use /opencode add <name> <key>.\n${watchdogStatus}`;
620
+ const keyStatus = ambientKeyApplied
621
+ ? `Using ${AMBIENT_KEY_NAME} key from ${OPENCODE_KEY_ENV}.`
622
+ : "No keys configured. Use /opencode add <name> <key>.";
623
+ return `${keyStatus}\n${policyStatus}\n${watchdogStatus}`;
644
624
  }
645
625
  const cdMs = getCooldownMs(config);
646
626
  return `${config.keys.map((key, i) => {
@@ -657,7 +637,7 @@ function formatStatus(config, now = Date.now()) {
657
637
  tag = ` [cooldown ${Math.ceil(remaining / 60_000)}m]`;
658
638
  }
659
639
  return `${marker} ${i + 1}. ${key.name}${tag}`;
660
- }).join("\n")}\n${watchdogStatus}`;
640
+ }).join("\n")}\n${policyStatus}\n${watchdogStatus}`;
661
641
  }
662
642
  function formatTimeoutInfo(info) {
663
643
  const status = info.lastStatus === undefined ? "" : `, last HTTP ${info.lastStatus}`;
@@ -678,9 +658,6 @@ function formatWatchdogEvents(events, now = Date.now()) {
678
658
  })
679
659
  .join("\n");
680
660
  }
681
- // ---------------------------------------------------------------------------
682
- // Extension
683
- // ---------------------------------------------------------------------------
684
661
  export function createOpencodeGoRotationExtension(options = {}) {
685
662
  return function opencodeGoRotationExtension(pi) {
686
663
  let config = createEmptyConfig();
@@ -699,6 +676,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
699
676
  let usageStatusKeyIndex;
700
677
  let usageStatusFetchedAt = 0;
701
678
  let usageStatusInFlight;
679
+ let ambientKey;
702
680
  const statusTimerApi = options.timers ?? {
703
681
  setTimeout: (callback, ms) => globalThis.setTimeout(callback, ms),
704
682
  clearTimeout: (timer) => globalThis.clearTimeout(timer),
@@ -723,6 +701,21 @@ export function createOpencodeGoRotationExtension(options = {}) {
723
701
  return false;
724
702
  }
725
703
  }
704
+ async function resolveEnvKey(ctx) {
705
+ const envKey = process.env[OPENCODE_KEY_ENV]?.trim();
706
+ if (!envKey)
707
+ return undefined;
708
+ const resolved = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
709
+ return resolved === undefined || resolved === envKey ? envKey : undefined;
710
+ }
711
+ function getAmbientUsageTarget() {
712
+ return ambientKey
713
+ ? { keyIndex: -1, keyName: AMBIENT_KEY_NAME, bearerToken: ambientKey }
714
+ : undefined;
715
+ }
716
+ function getStatusUsageTarget(current) {
717
+ return getActiveUsageTarget(current) ?? getAmbientUsageTarget();
718
+ }
726
719
  function mutateSharedConfig(mutator) {
727
720
  try {
728
721
  const updated = updateConfig(mutator);
@@ -809,7 +802,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
809
802
  return;
810
803
  if (!refreshConfig())
811
804
  return;
812
- const target = getActiveUsageTarget(config);
805
+ const target = getStatusUsageTarget(config);
813
806
  if (!target) {
814
807
  setUsageStatus("opencode-go: no keys configured");
815
808
  return;
@@ -822,15 +815,25 @@ export function createOpencodeGoRotationExtension(options = {}) {
822
815
  return;
823
816
  const request = (async () => {
824
817
  const usage = await fetchOpenCodeGoUsage(target, fetchApi, options.timers);
818
+ const receivedAt = now();
825
819
  usageStatusKeyIndex = target.keyIndex;
826
- usageStatusFetchedAt = now();
820
+ usageStatusFetchedAt = receivedAt;
827
821
  if (usageStatusCtx !== ctx)
828
822
  return;
829
- if (!refreshConfig() || getActiveUsageTarget(config)?.keyIndex !== target.keyIndex)
823
+ if (!refreshConfig() || getStatusUsageTarget(config)?.bearerToken !== target.bearerToken)
830
824
  return;
825
+ if (target.keyIndex >= 0 && allowsQuotaRotation(config) && usage.ok && hasExhaustedWindow(usage) && getQuotaBlockedUntil(config, target.keyIndex, receivedAt) === undefined) {
826
+ mutateSharedConfig((freshConfig) => {
827
+ if (!matchesUsageTarget(freshConfig, target))
828
+ return;
829
+ if (getQuotaBlockedUntil(freshConfig, target.keyIndex, receivedAt) !== undefined)
830
+ return;
831
+ setQuotaBlock(freshConfig, target.keyIndex, getExhaustedUntil(usage.usage, receivedAt, getCooldownMs(freshConfig)), receivedAt);
832
+ });
833
+ }
831
834
  setUsageStatus(usage.ok
832
- ? formatFooterUsage(usage.usage.windows, { keyName: target.keyName, nowMs: currentTime })
833
- : formatFooterUsage([], { keyName: target.keyName, nowMs: currentTime, error: usage.message }));
835
+ ? formatFooterUsage(usage.usage.windows, { keyName: target.keyName, nowMs: receivedAt })
836
+ : formatFooterUsage([], { keyName: target.keyName, nowMs: receivedAt, error: usage.message }));
834
837
  })();
835
838
  usageStatusInFlight = request;
836
839
  try {
@@ -885,134 +888,75 @@ export function createOpencodeGoRotationExtension(options = {}) {
885
888
  function currentRotationOperation(currentTime) {
886
889
  return captureRotationOperation(config, currentTime, config.activeKeyIndex, usageDecisionEpoch);
887
890
  }
888
- /** Post-await effects are allowed only while the completed decision still owns the state. */
889
891
  function isCompletionCurrent(outcome) {
890
892
  return (outcome.kind === "rotated" || outcome.kind === "none")
891
893
  && refreshConfig()
892
894
  && isRotationOperationCurrent(outcome.completion, config, usageDecisionEpoch);
893
895
  }
894
- /**
895
- * A benched key can become usable again after we recorded its block. Probe the blocked
896
- * keys without mutating anything; only a positive reading is collected as candidate
897
- * headroom. The probes are data-only, so a stale result can never be applied without the
898
- * guarded commit re-checking the credential, block and cooldown it was sampled from.
899
- */
900
- async function probeRecoveredHeadroom(currentTime, skipKeyIndex) {
901
- if (!refreshConfig())
902
- return [];
903
- const candidates = getQuotaBlockedTargets(config, currentTime, skipKeyIndex)
904
- .map((target) => captureSelectionSnapshot(config, currentTime, target.keyIndex))
905
- .filter((snapshot) => snapshot !== undefined);
906
- const results = await Promise.all(candidates.map(async (candidate) => {
907
- const usage = await fetchOpenCodeGoUsage(candidate, fetchApi, options.timers);
908
- return hasConfirmedHeadroom(usage) ? candidate : undefined;
909
- }));
910
- if (!refreshConfig())
911
- return [];
912
- return results.filter((snapshot) => snapshot !== undefined);
913
- }
914
- function selectNextKey(mode, freshConfig, startIndex, currentTime) {
915
- return mode.kind === "quota"
916
- ? blockQuotaAndSelectNext(freshConfig, startIndex, mode.blockedUntil, currentTime, mode.authoritative)
917
- : rotateToNextKey(freshConfig, { now: currentTime });
918
- }
919
- /**
920
- * Block the failed key and select a replacement, re-probing benched keys only when the
921
- * fast path found nothing. Every mutation re-validates the operation snapshot under the
922
- * lock, so a decision invalidated while probes were in flight is cancelled instead of
923
- * being rebased onto the newer state.
924
- */
925
- async function rotateWithRecovery(ctx, operation, currentTime, mode) {
896
+ async function rotateWithRecovery(operation, currentTime, mode) {
926
897
  const startIndex = operation.selection.keyIndex;
927
- const fast = mutateSharedConfig((freshConfig) => {
928
- if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch)) {
929
- return { outcome: "cancelled" };
930
- }
931
- return { outcome: "done", value: selectNextKey(mode, freshConfig, startIndex, currentTime) };
932
- });
933
- if (fast === undefined)
898
+ if (!refreshConfig())
934
899
  return { kind: "unavailable" };
935
- if (fast.outcome === "cancelled")
900
+ if (!isRotationOperationCurrent(operation, config, usageDecisionEpoch))
936
901
  return { kind: "cancelled" };
937
- if (fast.value !== undefined && fast.value !== startIndex) {
902
+ for (const candidateIndex of listRotationCandidates(config, startIndex, currentTime)) {
903
+ if (!refreshConfig())
904
+ return { kind: "unavailable" };
905
+ if (getQuotaBlockedUntil(config, candidateIndex, currentTime) !== undefined)
906
+ continue;
907
+ const candidate = captureSelectionSnapshot(config, currentTime, candidateIndex);
908
+ if (!candidate)
909
+ continue;
910
+ if (config.verifyCandidates) {
911
+ const usage = await fetchOpenCodeGoUsage(candidate, fetchApi, options.timers);
912
+ if (usageDecisionEpoch !== operation.epoch)
913
+ return { kind: "cancelled" };
914
+ if (usage.ok && hasExhaustedWindow(usage)) {
915
+ const blockedUntil = getExhaustedUntil(usage.usage, currentTime, getCooldownMs(config));
916
+ const blocked = mutateSharedConfig((freshConfig) => {
917
+ if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
918
+ return { outcome: "cancelled" };
919
+ if (!matchesSelectionSnapshot(freshConfig, candidate, currentTime))
920
+ return { outcome: "cancelled" };
921
+ setQuotaBlock(freshConfig, candidate.keyIndex, blockedUntil, currentTime);
922
+ return { outcome: "done", value: true };
923
+ });
924
+ if (blocked === undefined)
925
+ return { kind: "unavailable" };
926
+ if (blocked.outcome === "cancelled")
927
+ return { kind: "cancelled" };
928
+ continue;
929
+ }
930
+ }
931
+ const committed = mutateSharedConfig((freshConfig) => {
932
+ if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
933
+ return { outcome: "cancelled" };
934
+ if (!matchesSelectionSnapshot(freshConfig, candidate, currentTime))
935
+ return { outcome: "cancelled" };
936
+ applyRotationMode(mode, freshConfig, startIndex, currentTime);
937
+ delete freshConfig.cooldowns[candidate.keyIndex];
938
+ freshConfig.activeKeyIndex = candidate.keyIndex;
939
+ return { outcome: "done", value: candidate.keyIndex };
940
+ });
941
+ if (committed === undefined)
942
+ return { kind: "unavailable" };
943
+ if (committed.outcome === "cancelled")
944
+ return { kind: "cancelled" };
938
945
  const completion = currentRotationOperation(currentTime);
939
- return completion ? { kind: "rotated", keyIndex: fast.value, completion } : { kind: "cancelled" };
946
+ return completion ? { kind: "rotated", keyIndex: committed.value, completion } : { kind: "cancelled" };
940
947
  }
941
- // Snapshot the state this operation just produced, so a later commit can detect any
942
- // external change to the same credential, block, cooldown or selection.
943
- const retryOperation = currentRotationOperation(currentTime);
944
- const failedKey = captureSelectionSnapshot(config, currentTime, startIndex);
945
- if (!retryOperation || !failedKey)
946
- return { kind: "cancelled" };
947
- const recovered = await probeRecoveredHeadroom(currentTime, startIndex);
948
- if (configError)
949
- return { kind: "unavailable" };
950
- if (usageDecisionEpoch !== operation.epoch)
951
- return { kind: "cancelled" };
952
- if (recovered.length === 0) {
953
- // Still verify the state this operation owns: a shared writer may have moved the
954
- // selection, credential, block or cooldown while the probes were in flight.
955
- const current = matchesSelectionSnapshot(config, failedKey, currentTime)
956
- && isRotationOperationCurrent(retryOperation, config, usageDecisionEpoch);
957
- return current ? { kind: "none", completion: retryOperation } : { kind: "cancelled" };
958
- }
959
- const commit = mutateSharedConfig((freshConfig) => {
960
- if (!isRotationOperationCurrent(retryOperation, freshConfig, usageDecisionEpoch))
961
- return { outcome: "cancelled" };
962
- if (!matchesSelectionSnapshot(freshConfig, failedKey, currentTime))
963
- return { outcome: "cancelled" };
964
- if (!recovered.every((snapshot) => matchesSelectionSnapshot(freshConfig, snapshot, currentTime)))
948
+ const closed = mutateSharedConfig((freshConfig) => {
949
+ if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
965
950
  return { outcome: "cancelled" };
966
- for (const snapshot of recovered) {
967
- delete freshConfig.quotaBlockedUntil[snapshot.keyIndex];
968
- delete freshConfig.cooldowns[snapshot.keyIndex];
969
- }
970
- return { outcome: "done", value: selectNextKey(mode, freshConfig, startIndex, currentTime) };
951
+ applyRotationMode(mode, freshConfig, startIndex, currentTime);
952
+ return { outcome: "done", value: undefined };
971
953
  });
972
- if (commit === undefined)
954
+ if (closed === undefined)
973
955
  return { kind: "unavailable" };
974
- if (commit.outcome === "cancelled")
956
+ if (closed.outcome === "cancelled")
975
957
  return { kind: "cancelled" };
976
- for (const snapshot of recovered) {
977
- ctx.ui.notify(`OpenCode: ${snapshot.keyName} has headroom again → quota block cleared`, "info");
978
- }
979
958
  const completion = currentRotationOperation(currentTime);
980
- if (!completion)
981
- return { kind: "cancelled" };
982
- const selected = commit.value;
983
- return selected === undefined || selected === startIndex
984
- ? { kind: "none", completion }
985
- : { kind: "rotated", keyIndex: selected, completion };
986
- }
987
- /** Guarded startup/reload recovery: clears only blocks whose snapshot is still current. */
988
- async function recoverQuotaBlocksGuarded(ctx, operation, currentTime) {
989
- const recovered = await probeRecoveredHeadroom(currentTime);
990
- if (configError)
991
- return "unavailable";
992
- if (usageDecisionEpoch !== operation.epoch)
993
- return "cancelled";
994
- if (recovered.length === 0) {
995
- return isRotationOperationCurrent(operation, config, usageDecisionEpoch) ? "none" : "cancelled";
996
- }
997
- const commit = mutateSharedConfig((freshConfig) => {
998
- if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
999
- return { outcome: "cancelled" };
1000
- if (!recovered.every((snapshot) => matchesSelectionSnapshot(freshConfig, snapshot, currentTime)))
1001
- return { outcome: "cancelled" };
1002
- for (const snapshot of recovered) {
1003
- delete freshConfig.quotaBlockedUntil[snapshot.keyIndex];
1004
- delete freshConfig.cooldowns[snapshot.keyIndex];
1005
- }
1006
- return { outcome: "done", value: true };
1007
- });
1008
- if (commit === undefined)
1009
- return "unavailable";
1010
- if (commit.outcome === "cancelled")
1011
- return "cancelled";
1012
- for (const snapshot of recovered) {
1013
- ctx.ui.notify(`OpenCode: ${snapshot.keyName} has headroom again → quota block cleared`, "info");
1014
- }
1015
- return "recovered";
959
+ return completion ? { kind: "none", completion } : { kind: "cancelled" };
1016
960
  }
1017
961
  function reportQuotaExhausted(ctx, exhaustedName, currentTime) {
1018
962
  if (configError) {
@@ -1049,8 +993,9 @@ export function createOpencodeGoRotationExtension(options = {}) {
1049
993
  if (!refreshConfig())
1050
994
  return { rotated: false };
1051
995
  const currentTime = now();
1052
- if (config.keys.length <= 1)
1053
- return { rotated: false };
996
+ if (config.keys.length <= 1 || !allowsWatchdogRotation(config)) {
997
+ return { keyName: applyActiveKey(config, ctx.modelRegistry, currentTime), rotated: false };
998
+ }
1054
999
  if (shouldRotateAfterWatchdogTimeout(timeoutInfo, rateLimitAlreadyRotated)) {
1055
1000
  const previousIndex = config.activeKeyIndex;
1056
1001
  const nextIndex = mutateSharedConfig((freshConfig) => rotateToNextKey(freshConfig, { now: currentTime }));
@@ -1119,6 +1064,9 @@ export function createOpencodeGoRotationExtension(options = {}) {
1119
1064
  async function promptAuthImport(ctx) {
1120
1065
  if (!ctx.hasUI || config.keys.length > 0 || config.authImportDeclined)
1121
1066
  return false;
1067
+ ambientKey ??= await resolveEnvKey(ctx);
1068
+ if (ambientKey)
1069
+ return false;
1122
1070
  const authKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
1123
1071
  if (!authKey)
1124
1072
  return false;
@@ -1145,35 +1093,18 @@ export function createOpencodeGoRotationExtension(options = {}) {
1145
1093
  usageStatusCtx = ctx;
1146
1094
  if (!ensureConfig(ctx))
1147
1095
  return;
1148
- // A block recorded in an earlier session can be stale: the plan was topped up, or the
1149
- // window reset before the deadline we stored. Re-check before it decides which key this
1150
- // session uses, rather than benching a key that is usable again -- or leaving every key
1151
- // held by a block with nothing left to rotate to.
1152
- if (config.keys.length > 0) {
1153
- const currentTime = now();
1154
- const activeBlocked = getQuotaBlockedUntil(config, config.activeKeyIndex, currentTime) !== undefined;
1155
- if (activeBlocked || pickAvailableKeyIndex(config, currentTime) === undefined) {
1156
- const operation = currentRotationOperation(currentTime);
1157
- if (!operation)
1158
- return;
1159
- const recovery = await recoverQuotaBlocksGuarded(ctx, operation, currentTime);
1160
- // A startup continuation invalidated while probes were in flight must not
1161
- // clear blocks or re-apply a key on top of the newer decision.
1162
- if (recovery === "cancelled")
1163
- return;
1164
- if (usageDecisionEpoch !== operation.epoch)
1165
- return;
1166
- if (!refreshConfig())
1167
- return;
1168
- }
1169
- }
1170
- // On reload: re-apply active key, skip auto-import
1096
+ ambientKey = config.keys.length === 0 ? await resolveEnvKey(ctx) : undefined;
1171
1097
  if (event.reason === "reload") {
1172
1098
  applySynchronizedActiveKey(ctx);
1173
1099
  syncUsageStatus(ctx, true);
1174
1100
  return;
1175
1101
  }
1176
1102
  if (config.keys.length === 0) {
1103
+ if (ambientKey) {
1104
+ ctx.ui.notify(`OpenCode: Using ${AMBIENT_KEY_NAME} key from ${OPENCODE_KEY_ENV}. Run /opencode add to store a managed copy.`, "info");
1105
+ syncUsageStatus(ctx, true);
1106
+ return;
1107
+ }
1177
1108
  ctx.ui.notify("OpenCode: No keys configured. Run /opencode to add or import keys.", "warning");
1178
1109
  setUsageStatus(undefined);
1179
1110
  return;
@@ -1240,29 +1171,39 @@ export function createOpencodeGoRotationExtension(options = {}) {
1240
1171
  const blockedUntil = authoritativeReset ?? currentTime + getCooldownMs(config);
1241
1172
  const exhaustedName = config.keys[requestState.decision.target.keyIndex]?.name
1242
1173
  || `key-${requestState.decision.target.keyIndex + 1}`;
1174
+ const persistQuotaBlock = () => mutateSharedConfig((freshConfig) => {
1175
+ if (!matchesUsageTarget(freshConfig, requestState.decision.target))
1176
+ return false;
1177
+ if (authoritativeReset === undefined) {
1178
+ setQuotaBlock(freshConfig, requestState.decision.target.keyIndex, blockedUntil, currentTime);
1179
+ }
1180
+ else {
1181
+ freshConfig.quotaBlockedUntil[requestState.decision.target.keyIndex] = authoritativeReset;
1182
+ }
1183
+ return true;
1184
+ });
1243
1185
  if (requestState.responseHandled) {
1244
- const persisted = mutateSharedConfig((freshConfig) => {
1245
- // The handled response may upgrade the reset of its own credential, but never
1246
- // of whatever credential now occupies that index.
1247
- if (!matchesUsageTarget(freshConfig, requestState.decision.target))
1248
- return false;
1249
- if (authoritativeReset === undefined) {
1250
- setQuotaBlock(freshConfig, requestState.decision.target.keyIndex, blockedUntil, currentTime);
1251
- }
1252
- else {
1253
- freshConfig.quotaBlockedUntil[requestState.decision.target.keyIndex] = authoritativeReset;
1254
- }
1255
- return true;
1256
- });
1186
+ const persisted = persistQuotaBlock();
1257
1187
  if (persisted !== true && configError)
1258
1188
  ctx.ui.notify(`OpenCode: ${configError}.`, "error");
1259
1189
  invalidateAutomaticDecisions();
1260
1190
  return;
1261
1191
  }
1192
+ if (!allowsQuotaRotation(config) || (authoritativeReset === undefined && !allowsTransientRotation(config))) {
1193
+ const persisted = persistQuotaBlock();
1194
+ if (persisted !== true && configError)
1195
+ ctx.ui.notify(`OpenCode: ${configError}.`, "error");
1196
+ invalidateAutomaticDecisions();
1197
+ const reason = allowsQuotaRotation(config)
1198
+ ? "no reset time was reported"
1199
+ : `rotationPolicy is ${config.rotationPolicy}`;
1200
+ ctx.ui.notify(`OpenCode: ${exhaustedName} reached its plan quota; not rotating automatically (${reason}).`, "warning");
1201
+ return;
1202
+ }
1262
1203
  const operation = currentRotationOperation(currentTime);
1263
1204
  if (!operation || operation.selection.keyIndex !== requestState.decision.target.keyIndex)
1264
1205
  return;
1265
- const outcome = await rotateWithRecovery(ctx, operation, currentTime, {
1206
+ const outcome = await rotateWithRecovery(operation, currentTime, {
1266
1207
  kind: "quota",
1267
1208
  blockedUntil,
1268
1209
  authoritative: authoritativeReset !== undefined,
@@ -1290,6 +1231,12 @@ export function createOpencodeGoRotationExtension(options = {}) {
1290
1231
  invalidateAutomaticDecisions();
1291
1232
  return;
1292
1233
  }
1234
+ if (!allowsTransientRotation(config)) {
1235
+ invalidateAutomaticDecisions();
1236
+ const limitedName = config.keys[requestState.decision.target.keyIndex]?.name || `key-${requestState.decision.target.keyIndex + 1}`;
1237
+ ctx.ui.notify(`OpenCode: ${limitedName} hit a rate limit; not rotating (rotationPolicy=${config.rotationPolicy}).`, "warning");
1238
+ return;
1239
+ }
1293
1240
  if (config.keys.length <= 1) {
1294
1241
  invalidateAutomaticDecisions();
1295
1242
  ctx.ui.notify("OpenCode: Rate limited — no other keys to rotate to.", "warning");
@@ -1299,7 +1246,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1299
1246
  const operation = currentRotationOperation(currentTime);
1300
1247
  if (!operation || operation.selection.keyIndex !== requestState.decision.target.keyIndex)
1301
1248
  return;
1302
- const outcome = await rotateWithRecovery(ctx, operation, currentTime, { kind: "cooldown" });
1249
+ const outcome = await rotateWithRecovery(operation, currentTime, { kind: "cooldown" });
1303
1250
  if (outcome.kind === "cancelled")
1304
1251
  return;
1305
1252
  if (outcome.kind === "unavailable") {
@@ -1308,7 +1255,6 @@ export function createOpencodeGoRotationExtension(options = {}) {
1308
1255
  ctx.ui.notify(`OpenCode: ${configError}. Automatic rotation was skipped.`, "error");
1309
1256
  return;
1310
1257
  }
1311
- // Never finalize a decision that lost ownership while the rotation was in flight.
1312
1258
  if (!isCompletionCurrent(outcome))
1313
1259
  return;
1314
1260
  if (outcome.kind === "none") {
@@ -1337,7 +1283,6 @@ export function createOpencodeGoRotationExtension(options = {}) {
1337
1283
  const operation = currentRotationOperation(now());
1338
1284
  if (!operation || operation.selection.keyIndex !== decision.target.keyIndex)
1339
1285
  return;
1340
- // Bookkeeping for this response is allowed only while it still owns the request state.
1341
1286
  const markHandledIfOwned = () => {
1342
1287
  if (requestRateLimitState === requestState)
1343
1288
  markResponseRateLimitHandled(decision);
@@ -1351,10 +1296,18 @@ export function createOpencodeGoRotationExtension(options = {}) {
1351
1296
  return;
1352
1297
  const currentTime = now();
1353
1298
  const exhaustedName = config.keys[decision.target.keyIndex]?.name || `key-${decision.target.keyIndex + 1}`;
1354
- if (usage.ok && hasRateLimitedUsageWindow(usage)) {
1355
- const outcome = await rotateWithRecovery(ctx, operation, currentTime, {
1299
+ if (usage.ok && hasExhaustedWindow(usage)) {
1300
+ if (!allowsQuotaRotation(config)) {
1301
+ invalidateAutomaticDecisions();
1302
+ if (event.status === 429)
1303
+ markHandledIfOwned();
1304
+ ctx.ui.notify(`OpenCode: ${exhaustedName} reached its plan quota; not rotating (rotationPolicy=${config.rotationPolicy}).`, "warning");
1305
+ ctx.ui.notify(formatUsageStatus(usage), "warning");
1306
+ return;
1307
+ }
1308
+ const outcome = await rotateWithRecovery(operation, currentTime, {
1356
1309
  kind: "quota",
1357
- blockedUntil: getRateLimitedUntil(usage.usage, currentTime, getCooldownMs(config)),
1310
+ blockedUntil: getExhaustedUntil(usage.usage, currentTime, getCooldownMs(config)),
1358
1311
  authoritative: false,
1359
1312
  });
1360
1313
  if (outcome.kind === "cancelled")
@@ -1380,13 +1333,20 @@ export function createOpencodeGoRotationExtension(options = {}) {
1380
1333
  ctx.ui.notify(formatUsageStatus(usage), "warning");
1381
1334
  return;
1382
1335
  }
1383
- if (event.status === 401)
1336
+ if (event.status === 401) {
1337
+ if (!allowsTransientRotation(config)) {
1338
+ invalidateAutomaticDecisions();
1339
+ ctx.ui.notify(`OpenCode: ${exhaustedName} was rejected with HTTP 401; not rotating (rotationPolicy=${config.rotationPolicy}).`, "warning");
1340
+ }
1341
+ return;
1342
+ }
1343
+ if (!allowsTransientRotation(config))
1384
1344
  return;
1385
1345
  if (config.keys.length <= 1) {
1386
1346
  markHandledIfOwned();
1387
1347
  return;
1388
1348
  }
1389
- const outcome = await rotateWithRecovery(ctx, operation, currentTime, { kind: "cooldown" });
1349
+ const outcome = await rotateWithRecovery(operation, currentTime, { kind: "cooldown" });
1390
1350
  if (outcome.kind === "cancelled")
1391
1351
  return;
1392
1352
  if (outcome.kind === "unavailable") {
@@ -1423,6 +1383,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1423
1383
  handler: async (args, ctx) => {
1424
1384
  if (!ensureConfig(ctx))
1425
1385
  return;
1386
+ ambientKey = config.keys.length === 0 ? ambientKey ?? await resolveEnvKey(ctx) : undefined;
1426
1387
  const parts = args.trim().split(/\s+/);
1427
1388
  const subcommand = parts[0] || "";
1428
1389
  const indexArg = parseInt(parts[1] ?? "", 10);
@@ -1436,7 +1397,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1436
1397
  ctx.ui.notify(`OpenCode: Imported key from auth.json → ${importedName}`, "info");
1437
1398
  }
1438
1399
  if (ctx.mode !== "tui") {
1439
- ctx.ui.notify(formatStatus(config, now()), "info");
1400
+ ctx.ui.notify(formatStatus(config, now(), ambientKey !== undefined), "info");
1440
1401
  break;
1441
1402
  }
1442
1403
  const result = await openOpencodeConfig(ctx);
@@ -1454,7 +1415,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1454
1415
  case "status":
1455
1416
  case "list":
1456
1417
  case "ls": {
1457
- const status = formatStatus(config, now());
1418
+ const status = formatStatus(config, now(), ambientKey !== undefined);
1458
1419
  ctx.ui.notify(status, "info");
1459
1420
  break;
1460
1421
  }
@@ -1466,7 +1427,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1466
1427
  case "usage":
1467
1428
  case "quota": {
1468
1429
  applySynchronizedActiveKey(ctx);
1469
- const usage = await fetchOpenCodeGoUsage(getActiveUsageTarget(config), fetchApi, options.timers);
1430
+ const usage = await fetchOpenCodeGoUsage(getStatusUsageTarget(config), fetchApi, options.timers);
1470
1431
  ctx.ui.notify(formatUsageStatus(usage), usage.ok ? "info" : "warning");
1471
1432
  break;
1472
1433
  }
@@ -1653,8 +1614,51 @@ export function createOpencodeGoRotationExtension(options = {}) {
1653
1614
  ctx.ui.notify(`Watchdog enabled (${seconds}s idle)`, "info");
1654
1615
  break;
1655
1616
  }
1617
+ case "policy": {
1618
+ const value = parts[1];
1619
+ if (value === undefined) {
1620
+ ctx.ui.notify(`Rotation policy: ${config.rotationPolicy} (candidate verification ${config.verifyCandidates ? "on" : "off"})`, "info");
1621
+ return;
1622
+ }
1623
+ const policy = value === "quota" ? "quota-only" : value;
1624
+ if (policy !== "off" && policy !== "quota-only" && policy !== "full") {
1625
+ ctx.ui.notify("Usage: /opencode policy [off|quota-only|full]", "warning");
1626
+ return;
1627
+ }
1628
+ const result = mutateSharedConfig((freshConfig) => {
1629
+ freshConfig.rotationPolicy = policy;
1630
+ return true;
1631
+ });
1632
+ if (result !== true) {
1633
+ if (configError)
1634
+ ctx.ui.notify(`OpenCode: ${configError}.`, "error");
1635
+ return;
1636
+ }
1637
+ invalidateAutomaticDecisions();
1638
+ ctx.ui.notify(`Rotation policy set to ${policy}`, "info");
1639
+ break;
1640
+ }
1641
+ case "verify": {
1642
+ const value = parts[1];
1643
+ if (value !== "on" && value !== "off") {
1644
+ ctx.ui.notify(`Usage: /opencode verify <on|off> (currently ${config.verifyCandidates ? "on" : "off"})`, "info");
1645
+ return;
1646
+ }
1647
+ const enabled = value === "on";
1648
+ const result = mutateSharedConfig((freshConfig) => {
1649
+ freshConfig.verifyCandidates = enabled;
1650
+ return true;
1651
+ });
1652
+ if (result !== true) {
1653
+ if (configError)
1654
+ ctx.ui.notify(`OpenCode: ${configError}.`, "error");
1655
+ return;
1656
+ }
1657
+ ctx.ui.notify(`Candidate verification ${enabled ? "enabled" : "disabled"}`, "info");
1658
+ break;
1659
+ }
1656
1660
  default:
1657
- ctx.ui.notify("Usage: /opencode [config|status|usage|quota|events|use <n>|next|add <name> <key>|rm <n>|reset|cooldown <min>|watchdog [status|on|off|<seconds>]]", "info");
1661
+ ctx.ui.notify("Usage: /opencode [config|status|usage|quota|events|use <n>|next|add <name> <key>|rm <n>|reset|cooldown <min>|policy [off|quota-only|full]|verify <on|off>|watchdog [status|on|off|<seconds>]]", "info");
1658
1662
  }
1659
1663
  },
1660
1664
  });
@@ -1673,6 +1677,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1673
1677
  stopUsageStatusTimer();
1674
1678
  setUsageStatus(undefined);
1675
1679
  usageStatusCtx = undefined;
1680
+ ambientKey = undefined;
1676
1681
  cleanupLifecycleState();
1677
1682
  });
1678
1683
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yugimob/pi-opencode-go-rotation",
3
- "version": "1.7.0",
3
+ "version": "1.7.2",
4
4
  "description": "Rotate between multiple OpenCode Go API keys with reactive 429, rate-limit, and watchdog stall detection, plus live footer usage for the active key",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",