@yugimob/pi-opencode-go-rotation 1.7.1 → 1.7.3
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 +35 -14
- package/dist/config-store.d.ts +3 -1
- package/dist/config-store.js +15 -3
- package/dist/config-ui.js +39 -8
- package/dist/index.js +209 -74
- package/package.json +1 -1
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,
|
|
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,7 +22,11 @@ Add your API keys:
|
|
|
22
22
|
|
|
23
23
|
The first key added becomes active immediately.
|
|
24
24
|
|
|
25
|
-
|
|
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
|
+
|
|
27
|
+
The extension never imports keys from `auth.json` automatically. When no keys are configured, it observes the credential pi resolves from `auth.json` as an unmanaged `auth` key, so status, usage, and the footer work without writing it to the config file. It does not participate in rotation until imported.
|
|
28
|
+
|
|
29
|
+
`/opencode` offers to import the `auth.json` key once. Declining is remembered, and the observed `auth` key keeps working. Run `/opencode import` to import it later without the prompt.
|
|
26
30
|
|
|
27
31
|
## Interactive key manager
|
|
28
32
|
|
|
@@ -33,24 +37,34 @@ In interactive mode, `/opencode` (or `/opencode config`) opens the key manager o
|
|
|
33
37
|
- Remove a key
|
|
34
38
|
- Add a key without remembering the command syntax
|
|
35
39
|
- Check a key's usage after the window closes
|
|
36
|
-
- Change the cooldown duration and the watchdog settings
|
|
40
|
+
- Change the cooldown duration, the rotation policy, candidate verification, and the watchdog settings
|
|
37
41
|
- Clear every cooldown and quota block
|
|
38
42
|
|
|
39
43
|
Changes are saved as soon as they are confirmed. Outside interactive mode the command prints the text status instead.
|
|
40
44
|
|
|
41
45
|
## How it works
|
|
42
46
|
|
|
43
|
-
The extension sets the active key as a runtime override, which takes priority over `OPENCODE_API_KEY` environment variables and `auth.json` credentials.
|
|
47
|
+
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 and an `auth.json` credential are only observed (as `env` and `auth`) and never overridden or persisted.
|
|
48
|
+
|
|
49
|
+
Automatic rotation is governed by `rotationPolicy`:
|
|
50
|
+
|
|
51
|
+
| Policy | Rotates when |
|
|
52
|
+
|--------|--------------|
|
|
53
|
+
| `off` | Never automatically. Usage checks still report and manual `/opencode next` and `/opencode use <n>` still switch. |
|
|
54
|
+
| `quota-only` (default) | OpenCode Go usage confirms an exhausted window, or a fixed-window quota error carries a parseable reset. |
|
|
55
|
+
| `full` | Also on transient rate limits and on watchdog stalls. |
|
|
56
|
+
|
|
57
|
+
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
58
|
|
|
45
59
|
The extension has three recovery paths:
|
|
46
60
|
|
|
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.
|
|
48
|
-
2. **Transient limit errors
|
|
49
|
-
3. **Silent stalls**: when an `opencode-go` provider request has no response or stream activity for the watchdog window, the extension
|
|
61
|
+
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.
|
|
62
|
+
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.
|
|
63
|
+
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
64
|
|
|
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
|
|
65
|
+
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
66
|
|
|
53
|
-
Fixed-window Go plan quota errors reported at message end follow the same
|
|
67
|
+
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
68
|
|
|
55
69
|
Pi's built-in auto-retry picks up the new key on the next request.
|
|
56
70
|
|
|
@@ -67,21 +81,24 @@ personal: wk 40% · mo 55% | ↻ Nov 12
|
|
|
67
81
|
```
|
|
68
82
|
The rolling 5-hour window is omitted from the footer.
|
|
69
83
|
|
|
70
|
-
It refreshes on session start, model changes, turns, key rotations, manual key commands, and every 5 minutes.
|
|
84
|
+
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 key name — or `env`/`auth` for an unmanaged key — leads the line, and switching to another provider clears it.
|
|
71
85
|
|
|
72
86
|
## Commands
|
|
73
87
|
|
|
74
88
|
| Command | Description |
|
|
75
89
|
|---------|-------------|
|
|
76
90
|
| `/opencode` or `/opencode config` | Open the interactive key manager |
|
|
77
|
-
| `/opencode status` | Show all keys, active key marker, cooldown and quota-blocked status |
|
|
91
|
+
| `/opencode status` | Show all keys, active key marker, cooldown and quota-blocked status, or the unmanaged `env`/`auth` key when no managed keys are configured |
|
|
78
92
|
| `/opencode usage` or `/opencode quota` | Fetch OpenCode Go usage for the active key without showing key material |
|
|
79
93
|
| `/opencode use <n>` | Switch to key number `n` (1-based) and clear its cooldown and quota block |
|
|
80
94
|
| `/opencode next` | Advance to the next configured key and clear its cooldown and quota block before activating it |
|
|
81
95
|
| `/opencode add <name> <key>` | Add a new key |
|
|
96
|
+
| `/opencode import` | Import the `auth.json` key into the config even after a declined prompt |
|
|
82
97
|
| `/opencode rm <n>` | Remove key number `n` |
|
|
83
98
|
| `/opencode reset` | Clear all cooldowns and quota blocks |
|
|
84
99
|
| `/opencode cooldown <min>` | Set or view cooldown duration in minutes |
|
|
100
|
+
| `/opencode policy [off\|quota-only\|full]` | Set or view the automatic rotation policy |
|
|
101
|
+
| `/opencode verify <on\|off>` | Enable or disable candidate usage verification before switching |
|
|
85
102
|
| `/opencode events` | Show recent watchdog timeout history (last 10) |
|
|
86
103
|
| `/opencode watchdog [status\|on\|off\|<seconds>]` | Configure silent-stall detection |
|
|
87
104
|
|
|
@@ -99,6 +116,8 @@ Keys are stored in `~/.pi/agent/opencode-keys.json` with file permissions `0600`
|
|
|
99
116
|
"cooldownMinutes": 60,
|
|
100
117
|
"watchdogEnabled": true,
|
|
101
118
|
"watchdogIdleMs": 90000,
|
|
119
|
+
"rotationPolicy": "quota-only",
|
|
120
|
+
"verifyCandidates": false,
|
|
102
121
|
"cooldowns": {},
|
|
103
122
|
"quotaBlockedUntil": {},
|
|
104
123
|
"authImportDeclined": false
|
|
@@ -122,13 +141,15 @@ Set `maxRetries` to at least the number of keys so all keys get a chance before
|
|
|
122
141
|
|
|
123
142
|
## Limitations
|
|
124
143
|
|
|
125
|
-
- The watchdog is scoped to the `opencode-go` provider only. Other providers are not aborted
|
|
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
|
-
-
|
|
144
|
+
- The watchdog is scoped to the `opencode-go` provider only. Other providers are not aborted, and the watchdog rotates only under `rotationPolicy` `full`.
|
|
145
|
+
- 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`.
|
|
146
|
+
- 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.
|
|
147
|
+
- 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
148
|
- 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
149
|
- 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
150
|
- 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
151
|
- Keys added via `/opencode add` are stored in plaintext. The config file is created and maintained with `0600` permissions.
|
|
152
|
+
- An unmanaged `env` or `auth` key is never stored, so it cannot rotate and is not remembered as a managed key; `/opencode add` stores a managed copy, and `/opencode import` stores the `auth.json` credential. A stored `auth.json` credential takes precedence over the environment variable, and the extension follows the credential pi resolves.
|
|
132
153
|
|
|
133
154
|
## License
|
|
134
155
|
|
package/dist/config-store.d.ts
CHANGED
|
@@ -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
|
-
|
|
15
|
+
rotationPolicy: RotationPolicy;
|
|
16
|
+
verifyCandidates: boolean;
|
|
15
17
|
cooldowns: Record<number, number>;
|
|
16
18
|
quotaBlockedUntil: Record<number, number>;
|
|
17
19
|
authImportDeclined: boolean;
|
package/dist/config-store.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
-
|
|
526
|
-
if (
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
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,9 @@ 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_ENV_KEY_NAME = "env";
|
|
8
|
+
const AMBIENT_AUTH_KEY_NAME = "auth";
|
|
6
9
|
const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
|
|
7
10
|
const OPENCODE_GO_USAGE_TIMEOUT_MS = 10_000;
|
|
8
11
|
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 +135,27 @@ function getQuotaBlockedUntil(config, keyIndex, now) {
|
|
|
132
135
|
? blockedUntil
|
|
133
136
|
: undefined;
|
|
134
137
|
}
|
|
138
|
+
function allowsQuotaRotation(config) {
|
|
139
|
+
return config.rotationPolicy !== "off";
|
|
140
|
+
}
|
|
141
|
+
function allowsTransientRotation(config) {
|
|
142
|
+
return config.rotationPolicy === "full";
|
|
143
|
+
}
|
|
144
|
+
function allowsWatchdogRotation(config) {
|
|
145
|
+
return config.rotationPolicy === "full";
|
|
146
|
+
}
|
|
135
147
|
function pickAvailableKeyIndex(config, now = Date.now()) {
|
|
148
|
+
if (config.keys.length === 0)
|
|
149
|
+
return undefined;
|
|
150
|
+
if (!allowsQuotaRotation(config))
|
|
151
|
+
return config.activeKeyIndex;
|
|
136
152
|
const cdMs = getCooldownMs(config);
|
|
137
153
|
for (let i = 0; i < config.keys.length; i++) {
|
|
138
154
|
const idx = (config.activeKeyIndex + i) % config.keys.length;
|
|
139
155
|
if (getQuotaBlockedUntil(config, idx, now) !== undefined)
|
|
140
156
|
continue;
|
|
157
|
+
if (!allowsTransientRotation(config))
|
|
158
|
+
return idx;
|
|
141
159
|
const cooldownStart = config.cooldowns[idx];
|
|
142
160
|
if (cooldownStart === undefined || now - cooldownStart >= cdMs)
|
|
143
161
|
return idx;
|
|
@@ -182,14 +200,8 @@ function rotateToNextKey(config, options = {}) {
|
|
|
182
200
|
delete config.cooldowns[next];
|
|
183
201
|
return next;
|
|
184
202
|
}
|
|
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
203
|
const droppedReasoningDetail = Symbol("dropped-caller-bound-reasoning");
|
|
189
204
|
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
205
|
return details
|
|
194
206
|
.map((detail) => {
|
|
195
207
|
if (!isRecord(detail))
|
|
@@ -201,12 +213,6 @@ function projectReasoningDetails(details) {
|
|
|
201
213
|
})
|
|
202
214
|
.filter((detail) => detail !== droppedReasoningDetail);
|
|
203
215
|
}
|
|
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
216
|
function projectAssistantContent(content) {
|
|
211
217
|
let projected = false;
|
|
212
218
|
const result = [];
|
|
@@ -254,9 +260,6 @@ function sanitizeReasoningPayload(payload) {
|
|
|
254
260
|
if (Array.isArray(message.reasoning_details)) {
|
|
255
261
|
const { reasoning_details: _details, ...visible } = projected;
|
|
256
262
|
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
263
|
projected = reasoning_details.length === 0 ? visible : { ...visible, reasoning_details };
|
|
261
264
|
}
|
|
262
265
|
messages.push(projected);
|
|
@@ -279,7 +282,6 @@ function getRuntimeKeyStore(modelRegistry) {
|
|
|
279
282
|
function ignoreAsyncRefresh(result) {
|
|
280
283
|
void result?.catch(() => { });
|
|
281
284
|
}
|
|
282
|
-
/** Set the active key as runtime override (highest priority in auth chain). */
|
|
283
285
|
function applyActiveKey(config, modelRegistry, now = Date.now()) {
|
|
284
286
|
const idx = pickAvailableKeyIndex(config, now);
|
|
285
287
|
if (idx === undefined)
|
|
@@ -316,11 +318,6 @@ function captureSelectionSnapshot(config, currentTime, keyIndex) {
|
|
|
316
318
|
cooldownStart: config.cooldowns[target.keyIndex],
|
|
317
319
|
};
|
|
318
320
|
}
|
|
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
321
|
function matchesSelectionSnapshot(config, snapshot, currentTime) {
|
|
325
322
|
const entry = config.keys[snapshot.keyIndex];
|
|
326
323
|
if (entry === undefined)
|
|
@@ -617,10 +614,16 @@ function usageWindowPercent(window) {
|
|
|
617
614
|
return (window.used / window.limit) * 100;
|
|
618
615
|
return undefined;
|
|
619
616
|
}
|
|
620
|
-
function formatStatus(config, now = Date.now()) {
|
|
617
|
+
function formatStatus(config, now = Date.now(), ambientKeyName) {
|
|
621
618
|
const watchdogStatus = `Watchdog: ${config.watchdogEnabled ? "on" : "off"} (${Math.ceil(getWatchdogIdleMs(config) / 1000)}s idle)`;
|
|
619
|
+
const policyStatus = `Rotation: ${config.rotationPolicy} (candidate verification ${config.verifyCandidates ? "on" : "off"})`;
|
|
622
620
|
if (config.keys.length === 0) {
|
|
623
|
-
|
|
621
|
+
const keyStatus = ambientKeyName === AMBIENT_ENV_KEY_NAME
|
|
622
|
+
? `Using ${AMBIENT_ENV_KEY_NAME} key from ${OPENCODE_KEY_ENV}.`
|
|
623
|
+
: ambientKeyName === AMBIENT_AUTH_KEY_NAME
|
|
624
|
+
? "Using auth key from auth.json."
|
|
625
|
+
: "No keys configured. Use /opencode add <name> <key>.";
|
|
626
|
+
return `${keyStatus}\n${policyStatus}\n${watchdogStatus}`;
|
|
624
627
|
}
|
|
625
628
|
const cdMs = getCooldownMs(config);
|
|
626
629
|
return `${config.keys.map((key, i) => {
|
|
@@ -637,7 +640,7 @@ function formatStatus(config, now = Date.now()) {
|
|
|
637
640
|
tag = ` [cooldown ${Math.ceil(remaining / 60_000)}m]`;
|
|
638
641
|
}
|
|
639
642
|
return `${marker} ${i + 1}. ${key.name}${tag}`;
|
|
640
|
-
}).join("\n")}\n${watchdogStatus}`;
|
|
643
|
+
}).join("\n")}\n${policyStatus}\n${watchdogStatus}`;
|
|
641
644
|
}
|
|
642
645
|
function formatTimeoutInfo(info) {
|
|
643
646
|
const status = info.lastStatus === undefined ? "" : `, last HTTP ${info.lastStatus}`;
|
|
@@ -658,9 +661,6 @@ function formatWatchdogEvents(events, now = Date.now()) {
|
|
|
658
661
|
})
|
|
659
662
|
.join("\n");
|
|
660
663
|
}
|
|
661
|
-
// ---------------------------------------------------------------------------
|
|
662
|
-
// Extension
|
|
663
|
-
// ---------------------------------------------------------------------------
|
|
664
664
|
export function createOpencodeGoRotationExtension(options = {}) {
|
|
665
665
|
return function opencodeGoRotationExtension(pi) {
|
|
666
666
|
let config = createEmptyConfig();
|
|
@@ -677,8 +677,10 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
677
677
|
let usageStatusTimer;
|
|
678
678
|
let usageStatusDebounce;
|
|
679
679
|
let usageStatusKeyIndex;
|
|
680
|
+
let usageStatusBearerToken;
|
|
680
681
|
let usageStatusFetchedAt = 0;
|
|
681
682
|
let usageStatusInFlight;
|
|
683
|
+
let ambientKey;
|
|
682
684
|
const statusTimerApi = options.timers ?? {
|
|
683
685
|
setTimeout: (callback, ms) => globalThis.setTimeout(callback, ms),
|
|
684
686
|
clearTimeout: (timer) => globalThis.clearTimeout(timer),
|
|
@@ -703,6 +705,24 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
703
705
|
return false;
|
|
704
706
|
}
|
|
705
707
|
}
|
|
708
|
+
async function resolveAmbientKey(ctx, current) {
|
|
709
|
+
if (current.keys.length > 0)
|
|
710
|
+
return undefined;
|
|
711
|
+
const resolved = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
|
|
712
|
+
const envKey = process.env[OPENCODE_KEY_ENV]?.trim();
|
|
713
|
+
if (envKey && (resolved === undefined || resolved === envKey)) {
|
|
714
|
+
return { name: AMBIENT_ENV_KEY_NAME, key: envKey };
|
|
715
|
+
}
|
|
716
|
+
return resolved ? { name: AMBIENT_AUTH_KEY_NAME, key: resolved } : undefined;
|
|
717
|
+
}
|
|
718
|
+
function getAmbientUsageTarget() {
|
|
719
|
+
return ambientKey
|
|
720
|
+
? { keyIndex: -1, keyName: ambientKey.name, bearerToken: ambientKey.key }
|
|
721
|
+
: undefined;
|
|
722
|
+
}
|
|
723
|
+
function getStatusUsageTarget(current) {
|
|
724
|
+
return getActiveUsageTarget(current) ?? getAmbientUsageTarget();
|
|
725
|
+
}
|
|
706
726
|
function mutateSharedConfig(mutator) {
|
|
707
727
|
try {
|
|
708
728
|
const updated = updateConfig(mutator);
|
|
@@ -789,13 +809,14 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
789
809
|
return;
|
|
790
810
|
if (!refreshConfig())
|
|
791
811
|
return;
|
|
792
|
-
|
|
812
|
+
ambientKey = config.keys.length === 0 ? await resolveAmbientKey(ctx, config) : undefined;
|
|
813
|
+
const target = getStatusUsageTarget(config);
|
|
793
814
|
if (!target) {
|
|
794
815
|
setUsageStatus("opencode-go: no keys configured");
|
|
795
816
|
return;
|
|
796
817
|
}
|
|
797
818
|
const currentTime = now();
|
|
798
|
-
const keyChanged = target.keyIndex !== usageStatusKeyIndex;
|
|
819
|
+
const keyChanged = target.keyIndex !== usageStatusKeyIndex || target.bearerToken !== usageStatusBearerToken;
|
|
799
820
|
if (!force && !keyChanged && currentTime - usageStatusFetchedAt < USAGE_STATUS_REFRESH_MS)
|
|
800
821
|
return;
|
|
801
822
|
if (usageStatusInFlight)
|
|
@@ -804,12 +825,13 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
804
825
|
const usage = await fetchOpenCodeGoUsage(target, fetchApi, options.timers);
|
|
805
826
|
const receivedAt = now();
|
|
806
827
|
usageStatusKeyIndex = target.keyIndex;
|
|
828
|
+
usageStatusBearerToken = target.bearerToken;
|
|
807
829
|
usageStatusFetchedAt = receivedAt;
|
|
808
830
|
if (usageStatusCtx !== ctx)
|
|
809
831
|
return;
|
|
810
|
-
if (!refreshConfig() ||
|
|
832
|
+
if (!refreshConfig() || getStatusUsageTarget(config)?.bearerToken !== target.bearerToken)
|
|
811
833
|
return;
|
|
812
|
-
if (usage.ok && hasExhaustedWindow(usage) && getQuotaBlockedUntil(config, target.keyIndex, receivedAt) === undefined) {
|
|
834
|
+
if (target.keyIndex >= 0 && allowsQuotaRotation(config) && usage.ok && hasExhaustedWindow(usage) && getQuotaBlockedUntil(config, target.keyIndex, receivedAt) === undefined) {
|
|
813
835
|
mutateSharedConfig((freshConfig) => {
|
|
814
836
|
if (!matchesUsageTarget(freshConfig, target))
|
|
815
837
|
return;
|
|
@@ -875,7 +897,6 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
875
897
|
function currentRotationOperation(currentTime) {
|
|
876
898
|
return captureRotationOperation(config, currentTime, config.activeKeyIndex, usageDecisionEpoch);
|
|
877
899
|
}
|
|
878
|
-
/** Post-await effects are allowed only while the completed decision still owns the state. */
|
|
879
900
|
function isCompletionCurrent(outcome) {
|
|
880
901
|
return (outcome.kind === "rotated" || outcome.kind === "none")
|
|
881
902
|
&& refreshConfig()
|
|
@@ -895,24 +916,26 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
895
916
|
const candidate = captureSelectionSnapshot(config, currentTime, candidateIndex);
|
|
896
917
|
if (!candidate)
|
|
897
918
|
continue;
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
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")
|
|
919
|
+
if (config.verifyCandidates) {
|
|
920
|
+
const usage = await fetchOpenCodeGoUsage(candidate, fetchApi, options.timers);
|
|
921
|
+
if (usageDecisionEpoch !== operation.epoch)
|
|
914
922
|
return { kind: "cancelled" };
|
|
915
|
-
|
|
923
|
+
if (usage.ok && hasExhaustedWindow(usage)) {
|
|
924
|
+
const blockedUntil = getExhaustedUntil(usage.usage, currentTime, getCooldownMs(config));
|
|
925
|
+
const blocked = mutateSharedConfig((freshConfig) => {
|
|
926
|
+
if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
|
|
927
|
+
return { outcome: "cancelled" };
|
|
928
|
+
if (!matchesSelectionSnapshot(freshConfig, candidate, currentTime))
|
|
929
|
+
return { outcome: "cancelled" };
|
|
930
|
+
setQuotaBlock(freshConfig, candidate.keyIndex, blockedUntil, currentTime);
|
|
931
|
+
return { outcome: "done", value: true };
|
|
932
|
+
});
|
|
933
|
+
if (blocked === undefined)
|
|
934
|
+
return { kind: "unavailable" };
|
|
935
|
+
if (blocked.outcome === "cancelled")
|
|
936
|
+
return { kind: "cancelled" };
|
|
937
|
+
continue;
|
|
938
|
+
}
|
|
916
939
|
}
|
|
917
940
|
const committed = mutateSharedConfig((freshConfig) => {
|
|
918
941
|
if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
|
|
@@ -979,8 +1002,9 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
979
1002
|
if (!refreshConfig())
|
|
980
1003
|
return { rotated: false };
|
|
981
1004
|
const currentTime = now();
|
|
982
|
-
if (config.keys.length <= 1)
|
|
983
|
-
return { rotated: false };
|
|
1005
|
+
if (config.keys.length <= 1 || !allowsWatchdogRotation(config)) {
|
|
1006
|
+
return { keyName: applyActiveKey(config, ctx.modelRegistry, currentTime), rotated: false };
|
|
1007
|
+
}
|
|
984
1008
|
if (shouldRotateAfterWatchdogTimeout(timeoutInfo, rateLimitAlreadyRotated)) {
|
|
985
1009
|
const previousIndex = config.activeKeyIndex;
|
|
986
1010
|
const nextIndex = mutateSharedConfig((freshConfig) => rotateToNextKey(freshConfig, { now: currentTime }));
|
|
@@ -1049,12 +1073,19 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1049
1073
|
async function promptAuthImport(ctx) {
|
|
1050
1074
|
if (!ctx.hasUI || config.keys.length > 0 || config.authImportDeclined)
|
|
1051
1075
|
return false;
|
|
1076
|
+
ambientKey = await resolveAmbientKey(ctx, config);
|
|
1077
|
+
if (ambientKey?.name === AMBIENT_ENV_KEY_NAME)
|
|
1078
|
+
return false;
|
|
1052
1079
|
const authKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
|
|
1053
1080
|
if (!authKey)
|
|
1054
1081
|
return false;
|
|
1055
1082
|
const confirmed = await ctx.ui.confirm("OpenCode Go key found", "An OpenCode Go API key exists in auth.json. Import it into the rotation config?");
|
|
1056
|
-
if (confirmed === true)
|
|
1057
|
-
|
|
1083
|
+
if (confirmed === true) {
|
|
1084
|
+
const imported = await importAuthKey(authKey);
|
|
1085
|
+
if (imported)
|
|
1086
|
+
ambientKey = undefined;
|
|
1087
|
+
return imported;
|
|
1088
|
+
}
|
|
1058
1089
|
const persisted = mutateSharedConfig((freshConfig) => {
|
|
1059
1090
|
freshConfig.authImportDeclined = true;
|
|
1060
1091
|
return true;
|
|
@@ -1075,13 +1106,21 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1075
1106
|
usageStatusCtx = ctx;
|
|
1076
1107
|
if (!ensureConfig(ctx))
|
|
1077
1108
|
return;
|
|
1078
|
-
|
|
1109
|
+
ambientKey = config.keys.length === 0 ? await resolveAmbientKey(ctx, config) : undefined;
|
|
1079
1110
|
if (event.reason === "reload") {
|
|
1080
1111
|
applySynchronizedActiveKey(ctx);
|
|
1081
1112
|
syncUsageStatus(ctx, true);
|
|
1082
1113
|
return;
|
|
1083
1114
|
}
|
|
1084
1115
|
if (config.keys.length === 0) {
|
|
1116
|
+
if (ambientKey) {
|
|
1117
|
+
const message = ambientKey.name === AMBIENT_ENV_KEY_NAME
|
|
1118
|
+
? `OpenCode: Using ${AMBIENT_ENV_KEY_NAME} key from ${OPENCODE_KEY_ENV}. Run /opencode add to store a managed copy.`
|
|
1119
|
+
: "OpenCode: Using auth key from auth.json. Run /opencode to import it into rotation.";
|
|
1120
|
+
ctx.ui.notify(message, "info");
|
|
1121
|
+
syncUsageStatus(ctx, true);
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1085
1124
|
ctx.ui.notify("OpenCode: No keys configured. Run /opencode to add or import keys.", "warning");
|
|
1086
1125
|
setUsageStatus(undefined);
|
|
1087
1126
|
return;
|
|
@@ -1148,23 +1187,33 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1148
1187
|
const blockedUntil = authoritativeReset ?? currentTime + getCooldownMs(config);
|
|
1149
1188
|
const exhaustedName = config.keys[requestState.decision.target.keyIndex]?.name
|
|
1150
1189
|
|| `key-${requestState.decision.target.keyIndex + 1}`;
|
|
1190
|
+
const persistQuotaBlock = () => mutateSharedConfig((freshConfig) => {
|
|
1191
|
+
if (!matchesUsageTarget(freshConfig, requestState.decision.target))
|
|
1192
|
+
return false;
|
|
1193
|
+
if (authoritativeReset === undefined) {
|
|
1194
|
+
setQuotaBlock(freshConfig, requestState.decision.target.keyIndex, blockedUntil, currentTime);
|
|
1195
|
+
}
|
|
1196
|
+
else {
|
|
1197
|
+
freshConfig.quotaBlockedUntil[requestState.decision.target.keyIndex] = authoritativeReset;
|
|
1198
|
+
}
|
|
1199
|
+
return true;
|
|
1200
|
+
});
|
|
1151
1201
|
if (requestState.responseHandled) {
|
|
1152
|
-
const persisted =
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
else {
|
|
1161
|
-
freshConfig.quotaBlockedUntil[requestState.decision.target.keyIndex] = authoritativeReset;
|
|
1162
|
-
}
|
|
1163
|
-
return true;
|
|
1164
|
-
});
|
|
1202
|
+
const persisted = persistQuotaBlock();
|
|
1203
|
+
if (persisted !== true && configError)
|
|
1204
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1205
|
+
invalidateAutomaticDecisions();
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1208
|
+
if (!allowsQuotaRotation(config) || (authoritativeReset === undefined && !allowsTransientRotation(config))) {
|
|
1209
|
+
const persisted = persistQuotaBlock();
|
|
1165
1210
|
if (persisted !== true && configError)
|
|
1166
1211
|
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1167
1212
|
invalidateAutomaticDecisions();
|
|
1213
|
+
const reason = allowsQuotaRotation(config)
|
|
1214
|
+
? "no reset time was reported"
|
|
1215
|
+
: `rotationPolicy is ${config.rotationPolicy}`;
|
|
1216
|
+
ctx.ui.notify(`OpenCode: ${exhaustedName} reached its plan quota; not rotating automatically (${reason}).`, "warning");
|
|
1168
1217
|
return;
|
|
1169
1218
|
}
|
|
1170
1219
|
const operation = currentRotationOperation(currentTime);
|
|
@@ -1198,6 +1247,12 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1198
1247
|
invalidateAutomaticDecisions();
|
|
1199
1248
|
return;
|
|
1200
1249
|
}
|
|
1250
|
+
if (!allowsTransientRotation(config)) {
|
|
1251
|
+
invalidateAutomaticDecisions();
|
|
1252
|
+
const limitedName = config.keys[requestState.decision.target.keyIndex]?.name || `key-${requestState.decision.target.keyIndex + 1}`;
|
|
1253
|
+
ctx.ui.notify(`OpenCode: ${limitedName} hit a rate limit; not rotating (rotationPolicy=${config.rotationPolicy}).`, "warning");
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1201
1256
|
if (config.keys.length <= 1) {
|
|
1202
1257
|
invalidateAutomaticDecisions();
|
|
1203
1258
|
ctx.ui.notify("OpenCode: Rate limited — no other keys to rotate to.", "warning");
|
|
@@ -1216,7 +1271,6 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1216
1271
|
ctx.ui.notify(`OpenCode: ${configError}. Automatic rotation was skipped.`, "error");
|
|
1217
1272
|
return;
|
|
1218
1273
|
}
|
|
1219
|
-
// Never finalize a decision that lost ownership while the rotation was in flight.
|
|
1220
1274
|
if (!isCompletionCurrent(outcome))
|
|
1221
1275
|
return;
|
|
1222
1276
|
if (outcome.kind === "none") {
|
|
@@ -1245,7 +1299,6 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1245
1299
|
const operation = currentRotationOperation(now());
|
|
1246
1300
|
if (!operation || operation.selection.keyIndex !== decision.target.keyIndex)
|
|
1247
1301
|
return;
|
|
1248
|
-
// Bookkeeping for this response is allowed only while it still owns the request state.
|
|
1249
1302
|
const markHandledIfOwned = () => {
|
|
1250
1303
|
if (requestRateLimitState === requestState)
|
|
1251
1304
|
markResponseRateLimitHandled(decision);
|
|
@@ -1260,6 +1313,14 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1260
1313
|
const currentTime = now();
|
|
1261
1314
|
const exhaustedName = config.keys[decision.target.keyIndex]?.name || `key-${decision.target.keyIndex + 1}`;
|
|
1262
1315
|
if (usage.ok && hasExhaustedWindow(usage)) {
|
|
1316
|
+
if (!allowsQuotaRotation(config)) {
|
|
1317
|
+
invalidateAutomaticDecisions();
|
|
1318
|
+
if (event.status === 429)
|
|
1319
|
+
markHandledIfOwned();
|
|
1320
|
+
ctx.ui.notify(`OpenCode: ${exhaustedName} reached its plan quota; not rotating (rotationPolicy=${config.rotationPolicy}).`, "warning");
|
|
1321
|
+
ctx.ui.notify(formatUsageStatus(usage), "warning");
|
|
1322
|
+
return;
|
|
1323
|
+
}
|
|
1263
1324
|
const outcome = await rotateWithRecovery(operation, currentTime, {
|
|
1264
1325
|
kind: "quota",
|
|
1265
1326
|
blockedUntil: getExhaustedUntil(usage.usage, currentTime, getCooldownMs(config)),
|
|
@@ -1288,7 +1349,14 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1288
1349
|
ctx.ui.notify(formatUsageStatus(usage), "warning");
|
|
1289
1350
|
return;
|
|
1290
1351
|
}
|
|
1291
|
-
if (event.status === 401)
|
|
1352
|
+
if (event.status === 401) {
|
|
1353
|
+
if (!allowsTransientRotation(config)) {
|
|
1354
|
+
invalidateAutomaticDecisions();
|
|
1355
|
+
ctx.ui.notify(`OpenCode: ${exhaustedName} was rejected with HTTP 401; not rotating (rotationPolicy=${config.rotationPolicy}).`, "warning");
|
|
1356
|
+
}
|
|
1357
|
+
return;
|
|
1358
|
+
}
|
|
1359
|
+
if (!allowsTransientRotation(config))
|
|
1292
1360
|
return;
|
|
1293
1361
|
if (config.keys.length <= 1) {
|
|
1294
1362
|
markHandledIfOwned();
|
|
@@ -1331,6 +1399,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1331
1399
|
handler: async (args, ctx) => {
|
|
1332
1400
|
if (!ensureConfig(ctx))
|
|
1333
1401
|
return;
|
|
1402
|
+
ambientKey = config.keys.length === 0 ? await resolveAmbientKey(ctx, config) : undefined;
|
|
1334
1403
|
const parts = args.trim().split(/\s+/);
|
|
1335
1404
|
const subcommand = parts[0] || "";
|
|
1336
1405
|
const indexArg = parseInt(parts[1] ?? "", 10);
|
|
@@ -1344,7 +1413,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1344
1413
|
ctx.ui.notify(`OpenCode: Imported key from auth.json → ${importedName}`, "info");
|
|
1345
1414
|
}
|
|
1346
1415
|
if (ctx.mode !== "tui") {
|
|
1347
|
-
ctx.ui.notify(formatStatus(config, now()), "info");
|
|
1416
|
+
ctx.ui.notify(formatStatus(config, now(), ambientKey?.name), "info");
|
|
1348
1417
|
break;
|
|
1349
1418
|
}
|
|
1350
1419
|
const result = await openOpencodeConfig(ctx);
|
|
@@ -1362,7 +1431,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1362
1431
|
case "status":
|
|
1363
1432
|
case "list":
|
|
1364
1433
|
case "ls": {
|
|
1365
|
-
const status = formatStatus(config, now());
|
|
1434
|
+
const status = formatStatus(config, now(), ambientKey?.name);
|
|
1366
1435
|
ctx.ui.notify(status, "info");
|
|
1367
1436
|
break;
|
|
1368
1437
|
}
|
|
@@ -1374,7 +1443,8 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1374
1443
|
case "usage":
|
|
1375
1444
|
case "quota": {
|
|
1376
1445
|
applySynchronizedActiveKey(ctx);
|
|
1377
|
-
|
|
1446
|
+
ambientKey = config.keys.length === 0 ? await resolveAmbientKey(ctx, config) : undefined;
|
|
1447
|
+
const usage = await fetchOpenCodeGoUsage(getStatusUsageTarget(config), fetchApi, options.timers);
|
|
1378
1448
|
ctx.ui.notify(formatUsageStatus(usage), usage.ok ? "info" : "warning");
|
|
1379
1449
|
break;
|
|
1380
1450
|
}
|
|
@@ -1453,6 +1523,27 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1453
1523
|
syncUsageStatus(ctx, true);
|
|
1454
1524
|
break;
|
|
1455
1525
|
}
|
|
1526
|
+
case "import": {
|
|
1527
|
+
const authKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
|
|
1528
|
+
if (!authKey) {
|
|
1529
|
+
ctx.ui.notify("OpenCode: no auth.json key found for opencode-go.", "warning");
|
|
1530
|
+
return;
|
|
1531
|
+
}
|
|
1532
|
+
invalidateAutomaticDecisions();
|
|
1533
|
+
const imported = await importAuthKey(authKey);
|
|
1534
|
+
if (!imported) {
|
|
1535
|
+
if (configError)
|
|
1536
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1537
|
+
else
|
|
1538
|
+
ctx.ui.notify("OpenCode: that auth.json key is already configured.", "info");
|
|
1539
|
+
return;
|
|
1540
|
+
}
|
|
1541
|
+
ambientKey = undefined;
|
|
1542
|
+
const importedName = applyActiveKey(config, ctx.modelRegistry, now()) ?? "auth";
|
|
1543
|
+
ctx.ui.notify(`OpenCode: Imported key from auth.json → ${importedName}`, "info");
|
|
1544
|
+
syncUsageStatus(ctx, true);
|
|
1545
|
+
break;
|
|
1546
|
+
}
|
|
1456
1547
|
case "remove":
|
|
1457
1548
|
case "rm": {
|
|
1458
1549
|
const removeIndex = indexArg - 1;
|
|
@@ -1561,8 +1652,51 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1561
1652
|
ctx.ui.notify(`Watchdog enabled (${seconds}s idle)`, "info");
|
|
1562
1653
|
break;
|
|
1563
1654
|
}
|
|
1655
|
+
case "policy": {
|
|
1656
|
+
const value = parts[1];
|
|
1657
|
+
if (value === undefined) {
|
|
1658
|
+
ctx.ui.notify(`Rotation policy: ${config.rotationPolicy} (candidate verification ${config.verifyCandidates ? "on" : "off"})`, "info");
|
|
1659
|
+
return;
|
|
1660
|
+
}
|
|
1661
|
+
const policy = value === "quota" ? "quota-only" : value;
|
|
1662
|
+
if (policy !== "off" && policy !== "quota-only" && policy !== "full") {
|
|
1663
|
+
ctx.ui.notify("Usage: /opencode policy [off|quota-only|full]", "warning");
|
|
1664
|
+
return;
|
|
1665
|
+
}
|
|
1666
|
+
const result = mutateSharedConfig((freshConfig) => {
|
|
1667
|
+
freshConfig.rotationPolicy = policy;
|
|
1668
|
+
return true;
|
|
1669
|
+
});
|
|
1670
|
+
if (result !== true) {
|
|
1671
|
+
if (configError)
|
|
1672
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1673
|
+
return;
|
|
1674
|
+
}
|
|
1675
|
+
invalidateAutomaticDecisions();
|
|
1676
|
+
ctx.ui.notify(`Rotation policy set to ${policy}`, "info");
|
|
1677
|
+
break;
|
|
1678
|
+
}
|
|
1679
|
+
case "verify": {
|
|
1680
|
+
const value = parts[1];
|
|
1681
|
+
if (value !== "on" && value !== "off") {
|
|
1682
|
+
ctx.ui.notify(`Usage: /opencode verify <on|off> (currently ${config.verifyCandidates ? "on" : "off"})`, "info");
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
const enabled = value === "on";
|
|
1686
|
+
const result = mutateSharedConfig((freshConfig) => {
|
|
1687
|
+
freshConfig.verifyCandidates = enabled;
|
|
1688
|
+
return true;
|
|
1689
|
+
});
|
|
1690
|
+
if (result !== true) {
|
|
1691
|
+
if (configError)
|
|
1692
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1693
|
+
return;
|
|
1694
|
+
}
|
|
1695
|
+
ctx.ui.notify(`Candidate verification ${enabled ? "enabled" : "disabled"}`, "info");
|
|
1696
|
+
break;
|
|
1697
|
+
}
|
|
1564
1698
|
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");
|
|
1699
|
+
ctx.ui.notify("Usage: /opencode [config|status|usage|quota|events|use <n>|next|add <name> <key>|import|rm <n>|reset|cooldown <min>|policy [off|quota-only|full]|verify <on|off>|watchdog [status|on|off|<seconds>]]", "info");
|
|
1566
1700
|
}
|
|
1567
1701
|
},
|
|
1568
1702
|
});
|
|
@@ -1581,6 +1715,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1581
1715
|
stopUsageStatusTimer();
|
|
1582
1716
|
setUsageStatus(undefined);
|
|
1583
1717
|
usageStatusCtx = undefined;
|
|
1718
|
+
ambientKey = undefined;
|
|
1584
1719
|
cleanupLifecycleState();
|
|
1585
1720
|
});
|
|
1586
1721
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yugimob/pi-opencode-go-rotation",
|
|
3
|
-
"version": "1.7.
|
|
3
|
+
"version": "1.7.3",
|
|
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",
|