@yugimob/pi-opencode-go-rotation 0.0.0-stage → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 lnilluv
4
+ Modifications Copyright (c) 2026 Yugimob
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO CONDITIONS OF ANY KIND, WHETHER IN AN
18
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
19
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,115 @@
1
- # Temporary Holding Version
1
+ # pi-opencode-go-rotation
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
4
+
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
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pi install npm:@yugimob/pi-opencode-go-rotation
11
+ ```
12
+
13
+ ## Setup
14
+
15
+ Add your API keys:
16
+
17
+ ```
18
+ /opencode add personal sk-xxxx
19
+ /opencode add work sk-yyyy
20
+ /opencode add backup sk-zzzz
21
+ ```
22
+
23
+ The first key added becomes active immediately.
24
+
25
+ ## How it works
26
+
27
+ The extension sets the active key as a runtime override, which takes priority over `OPENCODE_API_KEY` environment variables and `auth.json` credentials.
28
+
29
+ The extension has three recovery paths:
30
+
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`.
33
+ 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
+
35
+ This is still reactive: it does not poll usage or check limits before normal requests.
36
+
37
+ 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
+
39
+ Pi's built-in auto-retry picks up the new key on the next request.
40
+
41
+ Cooldowns default to 60 minutes. Quota blocks expire at their persisted deadline. Manual `/opencode use <n>` and `/opencode next` clear both restrictions on the selected key.
42
+
43
+ Usage commands use `https://opencode.ai/zen/go/v1/usage` and stop waiting after 10 seconds. A timeout reports `Usage request timed out after 10s.`.
44
+
45
+ ## Footer usage
46
+
47
+ While the selected model uses the `opencode-go` provider, the extension keeps a status line in pi's footer with the active key and its Go windows:
48
+
49
+ ```text
50
+ opencode-go [personal] 5h 12% · wk 40% · mo 55%
51
+ ```
52
+
53
+ It refreshes on session start, model changes, turns, key rotations, manual key commands, and every 5 minutes. Switching to another provider clears the line.
54
+
55
+ ## Commands
56
+
57
+ | Command | Description |
58
+ |---------|-------------|
59
+ | `/opencode` or `/opencode status` | Show all keys, active key marker, cooldown and quota-blocked status |
60
+ | `/opencode usage` or `/opencode quota` | Fetch OpenCode Go usage for the active key without showing key material |
61
+ | `/opencode use <n>` | Switch to key number `n` (1-based) and clear its cooldown and quota block |
62
+ | `/opencode next` | Advance to the next configured key and clear its cooldown and quota block before activating it |
63
+ | `/opencode add <name> <key>` | Add a new key |
64
+ | `/opencode rm <n>` | Remove key number `n` |
65
+ | `/opencode reset` | Clear all cooldowns and quota blocks |
66
+ | `/opencode cooldown <min>` | Set or view cooldown duration in minutes |
67
+ | `/opencode events` | Show recent watchdog timeout history (last 10) |
68
+ | `/opencode watchdog [status\|on\|off\|<seconds>]` | Configure silent-stall detection |
69
+
70
+ ## Configuration
71
+
72
+ Keys are stored in `~/.pi/agent/opencode-keys.json` with file permissions `0600`. Status output shows key names only; it does not display key material.
73
+
74
+ ```json
75
+ {
76
+ "keys": [
77
+ { "name": "personal", "key": "sk-xxx" },
78
+ { "name": "work", "key": "sk-yyy" }
79
+ ],
80
+ "activeKeyIndex": 0,
81
+ "cooldownMinutes": 60,
82
+ "watchdogEnabled": true,
83
+ "watchdogIdleMs": 90000,
84
+ "cooldowns": {},
85
+ "quotaBlockedUntil": {}
86
+ }
87
+ ```
88
+
89
+ ### Retry settings
90
+
91
+ Pair with pi's auto-retry for best results. In `~/.pi/agent/settings.json`:
92
+
93
+ ```json
94
+ {
95
+ "retry": {
96
+ "enabled": true,
97
+ "maxRetries": 3
98
+ }
99
+ }
100
+ ```
101
+
102
+ Set `maxRetries` to at least the number of keys so all keys get a chance before pi gives up.
103
+
104
+ ## Limitations
105
+
106
+ - The watchdog is scoped to the `opencode-go` provider only. Other providers are not aborted or rotated.
107
+ - 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
+ - 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.
110
+ - 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
+ - Keys added via `/opencode add` are stored in plaintext. The config file is created and maintained with `0600` permissions.
112
+
113
+ ## License
114
+
115
+ MIT
@@ -0,0 +1,29 @@
1
+ export declare const CONFIG_PATH_ENV = "PI_OPENCODE_ROTATION_CONFIG";
2
+ export declare const DEFAULT_COOLDOWN_MINUTES = 60;
3
+ export declare const DEFAULT_WATCHDOG_IDLE_MS = 90000;
4
+ export interface KeyEntry {
5
+ name: string;
6
+ key: string;
7
+ }
8
+ export interface Config {
9
+ keys: KeyEntry[];
10
+ activeKeyIndex: number;
11
+ cooldownMinutes: number;
12
+ watchdogEnabled: boolean;
13
+ watchdogIdleMs: number;
14
+ /** Key index → epoch ms when cooldown started */
15
+ cooldowns: Record<number, number>;
16
+ quotaBlockedUntil: Record<number, number>;
17
+ }
18
+ export declare class ConfigLoadError extends Error {
19
+ readonly path: string;
20
+ constructor(path: string, reason: string);
21
+ }
22
+ export declare function createEmptyConfig(): Config;
23
+ export declare function getConfigPath(): string;
24
+ export declare function loadConfig(path?: string): Config;
25
+ export declare function updateConfig<T>(mutator: (config: Config) => T, path?: string): {
26
+ config: Config;
27
+ result: T;
28
+ };
29
+ export declare function writeConfig(config: Config, path?: string): void;
@@ -0,0 +1,176 @@
1
+ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeSync, } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ export const CONFIG_PATH_ENV = "PI_OPENCODE_ROTATION_CONFIG";
6
+ export const DEFAULT_COOLDOWN_MINUTES = 60;
7
+ export const DEFAULT_WATCHDOG_IDLE_MS = 90_000;
8
+ const CONFIG_FILE_MODE = 0o600;
9
+ const LOCK_TIMEOUT_MS = 10_000;
10
+ const LOCK_STALE_MS = 30_000;
11
+ const LOCK_RETRY_MS = 10;
12
+ export class ConfigLoadError extends Error {
13
+ path;
14
+ constructor(path, reason) {
15
+ super(`Invalid OpenCode rotation config at ${path}: ${reason}`);
16
+ this.name = "ConfigLoadError";
17
+ this.path = path;
18
+ }
19
+ }
20
+ export function createEmptyConfig() {
21
+ return {
22
+ keys: [],
23
+ activeKeyIndex: 0,
24
+ cooldownMinutes: DEFAULT_COOLDOWN_MINUTES,
25
+ watchdogEnabled: true,
26
+ watchdogIdleMs: DEFAULT_WATCHDOG_IDLE_MS,
27
+ cooldowns: {},
28
+ quotaBlockedUntil: {},
29
+ };
30
+ }
31
+ export function getConfigPath() {
32
+ return process.env[CONFIG_PATH_ENV] ?? join(homedir(), ".pi", "agent", "opencode-keys.json");
33
+ }
34
+ function isRecord(value) {
35
+ return typeof value === "object" && value !== null && !Array.isArray(value);
36
+ }
37
+ function parseNumberRecord(value, field, path) {
38
+ if (value === undefined)
39
+ return {};
40
+ if (!isRecord(value))
41
+ throw new ConfigLoadError(path, `${field} must be an object`);
42
+ const result = {};
43
+ for (const [key, item] of Object.entries(value)) {
44
+ if (!/^\d+$/.test(key) || typeof item !== "number" || !Number.isFinite(item)) {
45
+ throw new ConfigLoadError(path, `${field} contains an invalid entry`);
46
+ }
47
+ result[Number(key)] = item;
48
+ }
49
+ return result;
50
+ }
51
+ function parseConfig(value, path) {
52
+ if (!isRecord(value))
53
+ throw new ConfigLoadError(path, "root must be an object");
54
+ if (!Array.isArray(value.keys))
55
+ throw new ConfigLoadError(path, "keys must be an array");
56
+ const keys = value.keys.map((entry, index) => {
57
+ if (!isRecord(entry) || typeof entry.name !== "string" || typeof entry.key !== "string" || entry.key.length === 0) {
58
+ throw new ConfigLoadError(path, `keys[${index}] is invalid`);
59
+ }
60
+ return { name: entry.name, key: entry.key };
61
+ });
62
+ const activeKeyIndexValue = value.activeKeyIndex;
63
+ const activeKeyIndex = activeKeyIndexValue === undefined ? 0 : activeKeyIndexValue;
64
+ if (typeof activeKeyIndex !== "number" || !Number.isInteger(activeKeyIndex) || activeKeyIndex < 0 || (keys.length > 0 && activeKeyIndex >= keys.length)) {
65
+ throw new ConfigLoadError(path, "activeKeyIndex is invalid");
66
+ }
67
+ const cooldownMinutesValue = value.cooldownMinutes;
68
+ const cooldownMinutes = cooldownMinutesValue === undefined ? DEFAULT_COOLDOWN_MINUTES : cooldownMinutesValue;
69
+ if (typeof cooldownMinutes !== "number" || !Number.isFinite(cooldownMinutes) || cooldownMinutes < 1) {
70
+ throw new ConfigLoadError(path, "cooldownMinutes is invalid");
71
+ }
72
+ const watchdogEnabled = value.watchdogEnabled ?? true;
73
+ if (typeof watchdogEnabled !== "boolean")
74
+ throw new ConfigLoadError(path, "watchdogEnabled is invalid");
75
+ const watchdogIdleMsValue = value.watchdogIdleMs;
76
+ const watchdogIdleMs = watchdogIdleMsValue === undefined ? DEFAULT_WATCHDOG_IDLE_MS : watchdogIdleMsValue;
77
+ if (typeof watchdogIdleMs !== "number" || !Number.isFinite(watchdogIdleMs) || watchdogIdleMs < 1) {
78
+ throw new ConfigLoadError(path, "watchdogIdleMs is invalid");
79
+ }
80
+ return {
81
+ keys,
82
+ activeKeyIndex,
83
+ cooldownMinutes,
84
+ watchdogEnabled,
85
+ watchdogIdleMs,
86
+ cooldowns: parseNumberRecord(value.cooldowns, "cooldowns", path),
87
+ quotaBlockedUntil: parseNumberRecord(value.quotaBlockedUntil, "quotaBlockedUntil", path),
88
+ };
89
+ }
90
+ function readConfigUnlocked(path) {
91
+ if (!existsSync(path))
92
+ return createEmptyConfig();
93
+ try {
94
+ const value = JSON.parse(readFileSync(path, "utf-8"));
95
+ return parseConfig(value, path);
96
+ }
97
+ catch (error) {
98
+ if (error instanceof ConfigLoadError)
99
+ throw error;
100
+ throw new ConfigLoadError(path, "JSON cannot be read");
101
+ }
102
+ }
103
+ function sleepSync(milliseconds) {
104
+ const buffer = new Int32Array(new SharedArrayBuffer(4));
105
+ Atomics.wait(buffer, 0, 0, milliseconds);
106
+ }
107
+ function acquireLock(path) {
108
+ const lockPath = `${path}.lock`;
109
+ const startedAt = Date.now();
110
+ mkdirSync(dirname(path), { recursive: true });
111
+ while (true) {
112
+ try {
113
+ mkdirSync(lockPath, { mode: 0o700 });
114
+ return lockPath;
115
+ }
116
+ catch (error) {
117
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "EEXIST")
118
+ throw error;
119
+ try {
120
+ if (Date.now() - statSync(lockPath).mtimeMs > LOCK_STALE_MS) {
121
+ rmSync(lockPath, { recursive: true, force: true });
122
+ continue;
123
+ }
124
+ }
125
+ catch {
126
+ // The other process may have released the lock between stat and removal.
127
+ }
128
+ if (Date.now() - startedAt >= LOCK_TIMEOUT_MS) {
129
+ throw new Error(`Timed out waiting for OpenCode rotation config lock: ${lockPath}`);
130
+ }
131
+ sleepSync(LOCK_RETRY_MS);
132
+ }
133
+ }
134
+ }
135
+ function withLock(path, operation) {
136
+ const lockPath = acquireLock(path);
137
+ try {
138
+ return operation();
139
+ }
140
+ finally {
141
+ rmSync(lockPath, { recursive: true, force: true });
142
+ }
143
+ }
144
+ function writeConfigUnlocked(path, config) {
145
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
146
+ const serialized = `${JSON.stringify(config, null, 2)}\n`;
147
+ let descriptor;
148
+ try {
149
+ descriptor = openSync(temporaryPath, "wx", CONFIG_FILE_MODE);
150
+ writeSync(descriptor, serialized, undefined, "utf-8");
151
+ fsyncSync(descriptor);
152
+ closeSync(descriptor);
153
+ descriptor = undefined;
154
+ chmodSync(temporaryPath, CONFIG_FILE_MODE);
155
+ renameSync(temporaryPath, path);
156
+ }
157
+ finally {
158
+ if (descriptor !== undefined)
159
+ closeSync(descriptor);
160
+ rmSync(temporaryPath, { force: true });
161
+ }
162
+ }
163
+ export function loadConfig(path = getConfigPath()) {
164
+ return readConfigUnlocked(path);
165
+ }
166
+ export function updateConfig(mutator, path = getConfigPath()) {
167
+ return withLock(path, () => {
168
+ const config = readConfigUnlocked(path);
169
+ const result = mutator(config);
170
+ writeConfigUnlocked(path, config);
171
+ return { config, result };
172
+ });
173
+ }
174
+ export function writeConfig(config, path = getConfigPath()) {
175
+ withLock(path, () => writeConfigUnlocked(path, config));
176
+ }
@@ -0,0 +1,97 @@
1
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
2
+ export declare function shouldWatchProvider(provider: string | undefined): boolean;
3
+ export type RateLimitKind = "transient" | "fixed-window-quota";
4
+ export declare function classifyRateLimitError(message: string): RateLimitKind | undefined;
5
+ export interface TimerApi {
6
+ setTimeout(callback: () => void, ms: number): unknown;
7
+ clearTimeout(timer: unknown): void;
8
+ }
9
+ export type ProviderActivityPhase = "waiting-for-response" | "waiting-for-stream" | "streaming";
10
+ export interface ProviderTimeoutInfo {
11
+ phase: ProviderActivityPhase;
12
+ idleMs: number;
13
+ elapsedMs: number;
14
+ idleForMs: number;
15
+ lastStatus?: number;
16
+ }
17
+ export declare function shouldRotateAfterWatchdogTimeout(timeoutInfo: ProviderTimeoutInfo, rateLimitAlreadyRotated: boolean): boolean;
18
+ export interface ClockApi {
19
+ now(): number;
20
+ }
21
+ export interface FetchResponseApi {
22
+ ok: boolean;
23
+ status: number;
24
+ json(): Promise<unknown>;
25
+ }
26
+ export type FetchApi = (url: string, init: {
27
+ method: "GET";
28
+ headers: Record<string, string>;
29
+ signal?: AbortSignal;
30
+ }) => Promise<FetchResponseApi>;
31
+ export interface ExtensionOptions {
32
+ timers?: TimerApi;
33
+ clock?: ClockApi;
34
+ fetch?: FetchApi;
35
+ }
36
+ export type OpenCodeGoUsageWindowStatus = "active" | "rate-limited" | "unknown";
37
+ export interface OpenCodeGoUsageWindow {
38
+ name?: string;
39
+ status: OpenCodeGoUsageWindowStatus;
40
+ usagePercent?: number;
41
+ resetInSec?: number;
42
+ used?: number;
43
+ limit?: number;
44
+ remaining?: number;
45
+ resetAt?: string;
46
+ startAt?: string;
47
+ endAt?: string;
48
+ }
49
+ export interface OpenCodeGoUsageResponse {
50
+ windows: OpenCodeGoUsageWindow[];
51
+ }
52
+ type UsageFetchResult = {
53
+ ok: true;
54
+ keyName: string;
55
+ usage: OpenCodeGoUsageResponse;
56
+ } | {
57
+ ok: false;
58
+ keyName?: string;
59
+ message: string;
60
+ };
61
+ export declare class ProviderIdleWatchdog {
62
+ private timer;
63
+ private active;
64
+ private timedOut;
65
+ private phase;
66
+ private startedAt;
67
+ private lastActivityAt;
68
+ private lastStatus;
69
+ private timeoutInfo;
70
+ private readonly options;
71
+ constructor(options: {
72
+ idleMs: number;
73
+ onTimeout: () => void;
74
+ timers?: TimerApi;
75
+ clock?: ClockApi;
76
+ });
77
+ start(): void;
78
+ response(status: number): void;
79
+ streamActivity(): void;
80
+ activity(): void;
81
+ stop(): void;
82
+ consumeTimeoutInfo(): ProviderTimeoutInfo | undefined;
83
+ currentTimeoutInfo(): ProviderTimeoutInfo | undefined;
84
+ private markActivity;
85
+ private now;
86
+ private getTimers;
87
+ private schedule;
88
+ private clear;
89
+ }
90
+ export declare function parseOpenCodeGoUsage(value: unknown): OpenCodeGoUsageResponse | undefined;
91
+ export declare function formatResetIn(seconds: number): string;
92
+ export declare function formatUsageStatus(result: UsageFetchResult): string;
93
+ export declare function shortUsageWindowLabel(name: string | undefined, index: number): string;
94
+ export declare function formatFooterUsage(keyName: string, windows: OpenCodeGoUsageWindow[], error?: string): string;
95
+ export declare function createOpencodeGoRotationExtension(options?: ExtensionOptions): (pi: ExtensionAPI) => void;
96
+ declare const extension: (pi: ExtensionAPI) => void;
97
+ export default extension;