@yugimob/pi-opencode-go-rotation 1.7.1 → 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, verifies a candidate key's usage before switching to it, 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`. 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. Candidate keys are verified 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.
48
- 2. **Transient limit errors**: when the usage endpoint is unavailable, does not report an exhausted 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, verifies and 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
- Checks happen at decision points only: a candidate is verified when 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 records a block if a window is full, so the next request rotates before it fails.
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. If that check finds a window at 100% or rate-limited, the active key is blocked until the window's reset, and the next request moves to another key. 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,13 +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.
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.
128
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`.
129
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.
130
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/).
131
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.
132
150
 
133
151
  ## License
134
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,12 +134,27 @@ function getQuotaBlockedUntil(config, keyIndex, now) {
132
134
  ? blockedUntil
133
135
  : undefined;
134
136
  }
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";
145
+ }
135
146
  function pickAvailableKeyIndex(config, now = Date.now()) {
147
+ if (config.keys.length === 0)
148
+ return undefined;
149
+ if (!allowsQuotaRotation(config))
150
+ return config.activeKeyIndex;
136
151
  const cdMs = getCooldownMs(config);
137
152
  for (let i = 0; i < config.keys.length; i++) {
138
153
  const idx = (config.activeKeyIndex + i) % config.keys.length;
139
154
  if (getQuotaBlockedUntil(config, idx, now) !== undefined)
140
155
  continue;
156
+ if (!allowsTransientRotation(config))
157
+ return idx;
141
158
  const cooldownStart = config.cooldowns[idx];
142
159
  if (cooldownStart === undefined || now - cooldownStart >= cdMs)
143
160
  return idx;
@@ -182,14 +199,8 @@ function rotateToNextKey(config, options = {}) {
182
199
  delete config.cooldowns[next];
183
200
  return next;
184
201
  }
185
- // Key equality detects credential changes, but persisted history has no issuer
186
- // provenance (including after reload). Never replay signed reasoning on this
187
- // rotating route, even before this process observes its first rotation.
188
202
  const droppedReasoningDetail = Symbol("dropped-caller-bound-reasoning");
189
203
  function projectReasoningDetails(details) {
190
- // map/filter, never flatMap: entries that are not plain reasoning detail
191
- // objects (nested arrays, numbers, booleans, ...) must pass through as the
192
- // same element in the same position, with their original shape intact.
193
204
  return details
194
205
  .map((detail) => {
195
206
  if (!isRecord(detail))
@@ -201,12 +212,6 @@ function projectReasoningDetails(details) {
201
212
  })
202
213
  .filter((detail) => detail !== droppedReasoningDetail);
203
214
  }
204
- /**
205
- * Anthropic serializes signed thinking as `thinking` blocks and opaque redacted
206
- * reasoning as `redacted_thinking`. Emit the SDK's own unsigned shape instead: a
207
- * plain text block. Drop entries emptied by that projection, and report an
208
- * assistant message for omission only when the projection emptied it.
209
- */
210
215
  function projectAssistantContent(content) {
211
216
  let projected = false;
212
217
  const result = [];
@@ -254,9 +259,6 @@ function sanitizeReasoningPayload(payload) {
254
259
  if (Array.isArray(message.reasoning_details)) {
255
260
  const { reasoning_details: _details, ...visible } = projected;
256
261
  const reasoning_details = projectReasoningDetails(message.reasoning_details);
257
- // Strip the key entirely when nothing remains to send: an empty array is an
258
- // unvalidated request shape, and this sanitiser exists to emit only shapes the
259
- // provider accepts. Non-detail entries above keep identity/position/shape.
260
262
  projected = reasoning_details.length === 0 ? visible : { ...visible, reasoning_details };
261
263
  }
262
264
  messages.push(projected);
@@ -279,7 +281,6 @@ function getRuntimeKeyStore(modelRegistry) {
279
281
  function ignoreAsyncRefresh(result) {
280
282
  void result?.catch(() => { });
281
283
  }
282
- /** Set the active key as runtime override (highest priority in auth chain). */
283
284
  function applyActiveKey(config, modelRegistry, now = Date.now()) {
284
285
  const idx = pickAvailableKeyIndex(config, now);
285
286
  if (idx === undefined)
@@ -316,11 +317,6 @@ function captureSelectionSnapshot(config, currentTime, keyIndex) {
316
317
  cooldownStart: config.cooldowns[target.keyIndex],
317
318
  };
318
319
  }
319
- /**
320
- * A deferred decision owns one credential, selection, block and cooldown. Every later
321
- * mutation re-checks that exact snapshot under the lock, so an operation that started
322
- * before an external update can never write to the replacement state.
323
- */
324
320
  function matchesSelectionSnapshot(config, snapshot, currentTime) {
325
321
  const entry = config.keys[snapshot.keyIndex];
326
322
  if (entry === undefined)
@@ -617,10 +613,14 @@ function usageWindowPercent(window) {
617
613
  return (window.used / window.limit) * 100;
618
614
  return undefined;
619
615
  }
620
- function formatStatus(config, now = Date.now()) {
616
+ function formatStatus(config, now = Date.now(), ambientKeyApplied = false) {
621
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"})`;
622
619
  if (config.keys.length === 0) {
623
- 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}`;
624
624
  }
625
625
  const cdMs = getCooldownMs(config);
626
626
  return `${config.keys.map((key, i) => {
@@ -637,7 +637,7 @@ function formatStatus(config, now = Date.now()) {
637
637
  tag = ` [cooldown ${Math.ceil(remaining / 60_000)}m]`;
638
638
  }
639
639
  return `${marker} ${i + 1}. ${key.name}${tag}`;
640
- }).join("\n")}\n${watchdogStatus}`;
640
+ }).join("\n")}\n${policyStatus}\n${watchdogStatus}`;
641
641
  }
642
642
  function formatTimeoutInfo(info) {
643
643
  const status = info.lastStatus === undefined ? "" : `, last HTTP ${info.lastStatus}`;
@@ -658,9 +658,6 @@ function formatWatchdogEvents(events, now = Date.now()) {
658
658
  })
659
659
  .join("\n");
660
660
  }
661
- // ---------------------------------------------------------------------------
662
- // Extension
663
- // ---------------------------------------------------------------------------
664
661
  export function createOpencodeGoRotationExtension(options = {}) {
665
662
  return function opencodeGoRotationExtension(pi) {
666
663
  let config = createEmptyConfig();
@@ -679,6 +676,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
679
676
  let usageStatusKeyIndex;
680
677
  let usageStatusFetchedAt = 0;
681
678
  let usageStatusInFlight;
679
+ let ambientKey;
682
680
  const statusTimerApi = options.timers ?? {
683
681
  setTimeout: (callback, ms) => globalThis.setTimeout(callback, ms),
684
682
  clearTimeout: (timer) => globalThis.clearTimeout(timer),
@@ -703,6 +701,21 @@ export function createOpencodeGoRotationExtension(options = {}) {
703
701
  return false;
704
702
  }
705
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
+ }
706
719
  function mutateSharedConfig(mutator) {
707
720
  try {
708
721
  const updated = updateConfig(mutator);
@@ -789,7 +802,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
789
802
  return;
790
803
  if (!refreshConfig())
791
804
  return;
792
- const target = getActiveUsageTarget(config);
805
+ const target = getStatusUsageTarget(config);
793
806
  if (!target) {
794
807
  setUsageStatus("opencode-go: no keys configured");
795
808
  return;
@@ -807,9 +820,9 @@ export function createOpencodeGoRotationExtension(options = {}) {
807
820
  usageStatusFetchedAt = receivedAt;
808
821
  if (usageStatusCtx !== ctx)
809
822
  return;
810
- if (!refreshConfig() || getActiveUsageTarget(config)?.keyIndex !== target.keyIndex)
823
+ if (!refreshConfig() || getStatusUsageTarget(config)?.bearerToken !== target.bearerToken)
811
824
  return;
812
- if (usage.ok && hasExhaustedWindow(usage) && getQuotaBlockedUntil(config, target.keyIndex, receivedAt) === undefined) {
825
+ if (target.keyIndex >= 0 && allowsQuotaRotation(config) && usage.ok && hasExhaustedWindow(usage) && getQuotaBlockedUntil(config, target.keyIndex, receivedAt) === undefined) {
813
826
  mutateSharedConfig((freshConfig) => {
814
827
  if (!matchesUsageTarget(freshConfig, target))
815
828
  return;
@@ -875,7 +888,6 @@ export function createOpencodeGoRotationExtension(options = {}) {
875
888
  function currentRotationOperation(currentTime) {
876
889
  return captureRotationOperation(config, currentTime, config.activeKeyIndex, usageDecisionEpoch);
877
890
  }
878
- /** Post-await effects are allowed only while the completed decision still owns the state. */
879
891
  function isCompletionCurrent(outcome) {
880
892
  return (outcome.kind === "rotated" || outcome.kind === "none")
881
893
  && refreshConfig()
@@ -895,24 +907,26 @@ export function createOpencodeGoRotationExtension(options = {}) {
895
907
  const candidate = captureSelectionSnapshot(config, currentTime, candidateIndex);
896
908
  if (!candidate)
897
909
  continue;
898
- const usage = await fetchOpenCodeGoUsage(candidate, fetchApi, options.timers);
899
- if (usageDecisionEpoch !== operation.epoch)
900
- return { kind: "cancelled" };
901
- if (usage.ok && hasExhaustedWindow(usage)) {
902
- const blockedUntil = getExhaustedUntil(usage.usage, currentTime, getCooldownMs(config));
903
- const blocked = mutateSharedConfig((freshConfig) => {
904
- if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
905
- return { outcome: "cancelled" };
906
- if (!matchesSelectionSnapshot(freshConfig, candidate, currentTime))
907
- return { outcome: "cancelled" };
908
- setQuotaBlock(freshConfig, candidate.keyIndex, blockedUntil, currentTime);
909
- return { outcome: "done", value: true };
910
- });
911
- if (blocked === undefined)
912
- return { kind: "unavailable" };
913
- if (blocked.outcome === "cancelled")
910
+ if (config.verifyCandidates) {
911
+ const usage = await fetchOpenCodeGoUsage(candidate, fetchApi, options.timers);
912
+ if (usageDecisionEpoch !== operation.epoch)
914
913
  return { kind: "cancelled" };
915
- continue;
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
+ }
916
930
  }
917
931
  const committed = mutateSharedConfig((freshConfig) => {
918
932
  if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
@@ -979,8 +993,9 @@ export function createOpencodeGoRotationExtension(options = {}) {
979
993
  if (!refreshConfig())
980
994
  return { rotated: false };
981
995
  const currentTime = now();
982
- if (config.keys.length <= 1)
983
- return { rotated: false };
996
+ if (config.keys.length <= 1 || !allowsWatchdogRotation(config)) {
997
+ return { keyName: applyActiveKey(config, ctx.modelRegistry, currentTime), rotated: false };
998
+ }
984
999
  if (shouldRotateAfterWatchdogTimeout(timeoutInfo, rateLimitAlreadyRotated)) {
985
1000
  const previousIndex = config.activeKeyIndex;
986
1001
  const nextIndex = mutateSharedConfig((freshConfig) => rotateToNextKey(freshConfig, { now: currentTime }));
@@ -1049,6 +1064,9 @@ export function createOpencodeGoRotationExtension(options = {}) {
1049
1064
  async function promptAuthImport(ctx) {
1050
1065
  if (!ctx.hasUI || config.keys.length > 0 || config.authImportDeclined)
1051
1066
  return false;
1067
+ ambientKey ??= await resolveEnvKey(ctx);
1068
+ if (ambientKey)
1069
+ return false;
1052
1070
  const authKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
1053
1071
  if (!authKey)
1054
1072
  return false;
@@ -1075,13 +1093,18 @@ export function createOpencodeGoRotationExtension(options = {}) {
1075
1093
  usageStatusCtx = ctx;
1076
1094
  if (!ensureConfig(ctx))
1077
1095
  return;
1078
- // On reload: re-apply active key, skip auto-import
1096
+ ambientKey = config.keys.length === 0 ? await resolveEnvKey(ctx) : undefined;
1079
1097
  if (event.reason === "reload") {
1080
1098
  applySynchronizedActiveKey(ctx);
1081
1099
  syncUsageStatus(ctx, true);
1082
1100
  return;
1083
1101
  }
1084
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
+ }
1085
1108
  ctx.ui.notify("OpenCode: No keys configured. Run /opencode to add or import keys.", "warning");
1086
1109
  setUsageStatus(undefined);
1087
1110
  return;
@@ -1148,25 +1171,35 @@ export function createOpencodeGoRotationExtension(options = {}) {
1148
1171
  const blockedUntil = authoritativeReset ?? currentTime + getCooldownMs(config);
1149
1172
  const exhaustedName = config.keys[requestState.decision.target.keyIndex]?.name
1150
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
+ });
1151
1185
  if (requestState.responseHandled) {
1152
- const persisted = mutateSharedConfig((freshConfig) => {
1153
- // The handled response may upgrade the reset of its own credential, but never
1154
- // of whatever credential now occupies that index.
1155
- if (!matchesUsageTarget(freshConfig, requestState.decision.target))
1156
- return false;
1157
- if (authoritativeReset === undefined) {
1158
- setQuotaBlock(freshConfig, requestState.decision.target.keyIndex, blockedUntil, currentTime);
1159
- }
1160
- else {
1161
- freshConfig.quotaBlockedUntil[requestState.decision.target.keyIndex] = authoritativeReset;
1162
- }
1163
- return true;
1164
- });
1186
+ const persisted = persistQuotaBlock();
1165
1187
  if (persisted !== true && configError)
1166
1188
  ctx.ui.notify(`OpenCode: ${configError}.`, "error");
1167
1189
  invalidateAutomaticDecisions();
1168
1190
  return;
1169
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
+ }
1170
1203
  const operation = currentRotationOperation(currentTime);
1171
1204
  if (!operation || operation.selection.keyIndex !== requestState.decision.target.keyIndex)
1172
1205
  return;
@@ -1198,6 +1231,12 @@ export function createOpencodeGoRotationExtension(options = {}) {
1198
1231
  invalidateAutomaticDecisions();
1199
1232
  return;
1200
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
+ }
1201
1240
  if (config.keys.length <= 1) {
1202
1241
  invalidateAutomaticDecisions();
1203
1242
  ctx.ui.notify("OpenCode: Rate limited — no other keys to rotate to.", "warning");
@@ -1216,7 +1255,6 @@ export function createOpencodeGoRotationExtension(options = {}) {
1216
1255
  ctx.ui.notify(`OpenCode: ${configError}. Automatic rotation was skipped.`, "error");
1217
1256
  return;
1218
1257
  }
1219
- // Never finalize a decision that lost ownership while the rotation was in flight.
1220
1258
  if (!isCompletionCurrent(outcome))
1221
1259
  return;
1222
1260
  if (outcome.kind === "none") {
@@ -1245,7 +1283,6 @@ export function createOpencodeGoRotationExtension(options = {}) {
1245
1283
  const operation = currentRotationOperation(now());
1246
1284
  if (!operation || operation.selection.keyIndex !== decision.target.keyIndex)
1247
1285
  return;
1248
- // Bookkeeping for this response is allowed only while it still owns the request state.
1249
1286
  const markHandledIfOwned = () => {
1250
1287
  if (requestRateLimitState === requestState)
1251
1288
  markResponseRateLimitHandled(decision);
@@ -1260,6 +1297,14 @@ export function createOpencodeGoRotationExtension(options = {}) {
1260
1297
  const currentTime = now();
1261
1298
  const exhaustedName = config.keys[decision.target.keyIndex]?.name || `key-${decision.target.keyIndex + 1}`;
1262
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
+ }
1263
1308
  const outcome = await rotateWithRecovery(operation, currentTime, {
1264
1309
  kind: "quota",
1265
1310
  blockedUntil: getExhaustedUntil(usage.usage, currentTime, getCooldownMs(config)),
@@ -1288,7 +1333,14 @@ export function createOpencodeGoRotationExtension(options = {}) {
1288
1333
  ctx.ui.notify(formatUsageStatus(usage), "warning");
1289
1334
  return;
1290
1335
  }
1291
- 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))
1292
1344
  return;
1293
1345
  if (config.keys.length <= 1) {
1294
1346
  markHandledIfOwned();
@@ -1331,6 +1383,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1331
1383
  handler: async (args, ctx) => {
1332
1384
  if (!ensureConfig(ctx))
1333
1385
  return;
1386
+ ambientKey = config.keys.length === 0 ? ambientKey ?? await resolveEnvKey(ctx) : undefined;
1334
1387
  const parts = args.trim().split(/\s+/);
1335
1388
  const subcommand = parts[0] || "";
1336
1389
  const indexArg = parseInt(parts[1] ?? "", 10);
@@ -1344,7 +1397,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1344
1397
  ctx.ui.notify(`OpenCode: Imported key from auth.json → ${importedName}`, "info");
1345
1398
  }
1346
1399
  if (ctx.mode !== "tui") {
1347
- ctx.ui.notify(formatStatus(config, now()), "info");
1400
+ ctx.ui.notify(formatStatus(config, now(), ambientKey !== undefined), "info");
1348
1401
  break;
1349
1402
  }
1350
1403
  const result = await openOpencodeConfig(ctx);
@@ -1362,7 +1415,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1362
1415
  case "status":
1363
1416
  case "list":
1364
1417
  case "ls": {
1365
- const status = formatStatus(config, now());
1418
+ const status = formatStatus(config, now(), ambientKey !== undefined);
1366
1419
  ctx.ui.notify(status, "info");
1367
1420
  break;
1368
1421
  }
@@ -1374,7 +1427,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1374
1427
  case "usage":
1375
1428
  case "quota": {
1376
1429
  applySynchronizedActiveKey(ctx);
1377
- const usage = await fetchOpenCodeGoUsage(getActiveUsageTarget(config), fetchApi, options.timers);
1430
+ const usage = await fetchOpenCodeGoUsage(getStatusUsageTarget(config), fetchApi, options.timers);
1378
1431
  ctx.ui.notify(formatUsageStatus(usage), usage.ok ? "info" : "warning");
1379
1432
  break;
1380
1433
  }
@@ -1561,8 +1614,51 @@ export function createOpencodeGoRotationExtension(options = {}) {
1561
1614
  ctx.ui.notify(`Watchdog enabled (${seconds}s idle)`, "info");
1562
1615
  break;
1563
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
+ }
1564
1660
  default:
1565
- 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");
1566
1662
  }
1567
1663
  },
1568
1664
  });
@@ -1581,6 +1677,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1581
1677
  stopUsageStatusTimer();
1582
1678
  setUsageStatus(undefined);
1583
1679
  usageStatusCtx = undefined;
1680
+ ambientKey = undefined;
1584
1681
  cleanupLifecycleState();
1585
1682
  });
1586
1683
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yugimob/pi-opencode-go-rotation",
3
- "version": "1.7.1",
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",