@yugimob/pi-opencode-go-rotation 1.6.2 → 1.7.1

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, 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.
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,17 +22,33 @@ Add your API keys:
22
22
 
23
23
  The first key added becomes active immediately.
24
24
 
25
+ 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
+
27
+ ## Interactive key manager
28
+
29
+ In interactive mode, `/opencode` (or `/opencode config`) opens the key manager overlay. It lists every key with its active, cooldown, or quota-blocked state, and lets you:
30
+
31
+ - Activate a key and clear its cooldown and quota block
32
+ - Rename a key or replace its secret
33
+ - Remove a key
34
+ - Add a key without remembering the command syntax
35
+ - Check a key's usage after the window closes
36
+ - Change the cooldown duration and the watchdog settings
37
+ - Clear every cooldown and quota block
38
+
39
+ Changes are saved as soon as they are confirmed. Outside interactive mode the command prints the text status instead.
40
+
25
41
  ## How it works
26
42
 
27
43
  The extension sets the active key as a runtime override, which takes priority over `OPENCODE_API_KEY` environment variables and `auth.json` credentials.
28
44
 
29
45
  The extension has three recovery paths:
30
46
 
31
- 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.
32
- 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`.
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`.
33
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.
34
50
 
35
- This is still reactive: it does not poll usage or check limits before normal requests.
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.
36
52
 
37
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.
38
54
 
@@ -44,19 +60,21 @@ Usage commands use `https://opencode.ai/zen/go/v1/usage` and stop waiting after
44
60
 
45
61
  ## Footer usage
46
62
 
47
- While the selected model uses the `opencode-go` provider, the extension keeps a status line in pi's footer with the active key's name, the usage windows, and the monthly renewal date:
63
+ While the selected model uses the `opencode-go` provider, the extension keeps a status line in pi's footer with the active key's name, the weekly and monthly usage windows, and the monthly renewal date:
48
64
 
49
65
  ```text
50
- personal · 5h 12% · wk 40% · mo 55% | ↻ Nov 12
66
+ personal: wk 40% · mo 55% | ↻ Nov 12
51
67
  ```
68
+ The rolling 5-hour window is omitted from the footer.
52
69
 
53
- 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.
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.
54
71
 
55
72
  ## Commands
56
73
 
57
74
  | Command | Description |
58
75
  |---------|-------------|
59
- | `/opencode` or `/opencode status` | Show all keys, active key marker, cooldown and quota-blocked status |
76
+ | `/opencode` or `/opencode config` | Open the interactive key manager |
77
+ | `/opencode status` | Show all keys, active key marker, cooldown and quota-blocked status |
60
78
  | `/opencode usage` or `/opencode quota` | Fetch OpenCode Go usage for the active key without showing key material |
61
79
  | `/opencode use <n>` | Switch to key number `n` (1-based) and clear its cooldown and quota block |
62
80
  | `/opencode next` | Advance to the next configured key and clear its cooldown and quota block before activating it |
@@ -82,7 +100,8 @@ Keys are stored in `~/.pi/agent/opencode-keys.json` with file permissions `0600`
82
100
  "watchdogEnabled": true,
83
101
  "watchdogIdleMs": 90000,
84
102
  "cooldowns": {},
85
- "quotaBlockedUntil": {}
103
+ "quotaBlockedUntil": {},
104
+ "authImportDeclined": false
86
105
  }
87
106
  ```
88
107
 
@@ -106,7 +125,8 @@ Set `maxRetries` to at least the number of keys so all keys get a chance before
106
125
  - The watchdog is scoped to the `opencode-go` provider only. Other providers are not aborted or rotated.
107
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`.
108
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.
109
- - When all keys are quota-blocked, automatic rotation stops on the current runtime key until a block expires or a manual command clears one.
128
+ - 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
+ - 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.
110
130
  - 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/).
111
131
  - Keys added via `/opencode add` are stored in plaintext. The config file is created and maintained with `0600` permissions.
112
132
 
@@ -14,6 +14,7 @@ export interface Config {
14
14
  /** Key index → epoch ms when cooldown started */
15
15
  cooldowns: Record<number, number>;
16
16
  quotaBlockedUntil: Record<number, number>;
17
+ authImportDeclined: boolean;
17
18
  }
18
19
  export declare class ConfigLoadError extends Error {
19
20
  readonly path: string;
@@ -27,3 +28,4 @@ export declare function updateConfig<T>(mutator: (config: Config) => T, path?: s
27
28
  result: T;
28
29
  };
29
30
  export declare function writeConfig(config: Config, path?: string): void;
31
+ export declare function reindexAfterRemoval(record: Record<number, number>, removedIndex: number): Record<number, number>;
@@ -26,6 +26,7 @@ export function createEmptyConfig() {
26
26
  watchdogIdleMs: DEFAULT_WATCHDOG_IDLE_MS,
27
27
  cooldowns: {},
28
28
  quotaBlockedUntil: {},
29
+ authImportDeclined: false,
29
30
  };
30
31
  }
31
32
  export function getConfigPath() {
@@ -77,12 +78,16 @@ function parseConfig(value, path) {
77
78
  if (typeof watchdogIdleMs !== "number" || !Number.isFinite(watchdogIdleMs) || watchdogIdleMs < 1) {
78
79
  throw new ConfigLoadError(path, "watchdogIdleMs is invalid");
79
80
  }
81
+ const authImportDeclined = value.authImportDeclined ?? false;
82
+ if (typeof authImportDeclined !== "boolean")
83
+ throw new ConfigLoadError(path, "authImportDeclined is invalid");
80
84
  return {
81
85
  keys,
82
86
  activeKeyIndex,
83
87
  cooldownMinutes,
84
88
  watchdogEnabled,
85
89
  watchdogIdleMs,
90
+ authImportDeclined,
86
91
  cooldowns: parseNumberRecord(value.cooldowns, "cooldowns", path),
87
92
  quotaBlockedUntil: parseNumberRecord(value.quotaBlockedUntil, "quotaBlockedUntil", path),
88
93
  };
@@ -174,3 +179,13 @@ export function updateConfig(mutator, path = getConfigPath()) {
174
179
  export function writeConfig(config, path = getConfigPath()) {
175
180
  withLock(path, () => writeConfigUnlocked(path, config));
176
181
  }
182
+ export function reindexAfterRemoval(record, removedIndex) {
183
+ const shifted = {};
184
+ for (const [key, value] of Object.entries(record)) {
185
+ const index = Number(key);
186
+ if (index === removedIndex)
187
+ continue;
188
+ shifted[index > removedIndex ? index - 1 : index] = value;
189
+ }
190
+ return shifted;
191
+ }
@@ -0,0 +1,17 @@
1
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { type Config } from "./config-store.ts";
3
+ export interface OpencodeConfigResult {
4
+ usageKeyIndex?: number;
5
+ }
6
+ export declare function parsePositiveInteger(value: string, minimum: number): number | undefined;
7
+ export declare function validateNewKey(config: Config, name: string, key: string): string | undefined;
8
+ export declare function keyStatus(config: Config, keyIndex: number, now: number): string;
9
+ export declare function summarizeRestrictions(config: Config, now: number): string;
10
+ export declare function selectKey(config: Config, keyIndex: number): void;
11
+ export declare function clearKeyRestrictions(config: Config, keyIndex: number): void;
12
+ export declare function addKey(config: Config, name: string, key: string): void;
13
+ export declare function renameKey(config: Config, keyIndex: number, name: string): void;
14
+ export declare function replaceKeySecret(config: Config, keyIndex: number, key: string): void;
15
+ export declare function removeKey(config: Config, keyIndex: number): void;
16
+ export declare function clearAllRestrictions(config: Config): void;
17
+ export declare function openOpencodeConfig(ctx: Pick<ExtensionCommandContext, "mode" | "ui">): Promise<OpencodeConfigResult>;