@yugimob/pi-opencode-go-rotation 1.7.0 → 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 +7 -6
- package/dist/index.js +115 -207
- 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, 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
|
|
|
@@ -44,11 +44,11 @@ The extension sets the active key as a runtime override, which takes priority ov
|
|
|
44
44
|
|
|
45
45
|
The extension has three recovery paths:
|
|
46
46
|
|
|
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`.
|
|
48
|
-
2. **Transient limit errors**: when the usage endpoint is unavailable, does not report
|
|
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
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.
|
|
50
50
|
|
|
51
|
-
|
|
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.
|
|
52
52
|
|
|
53
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.
|
|
54
54
|
|
|
@@ -67,7 +67,7 @@ personal: wk 40% · mo 55% | ↻ Nov 12
|
|
|
67
67
|
```
|
|
68
68
|
The rolling 5-hour window is omitted from the footer.
|
|
69
69
|
|
|
70
|
-
It refreshes on session start, model changes, turns, key rotations, manual key commands, and every 5 minutes. The active key's name leads the line, and switching to another provider clears it.
|
|
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.
|
|
71
71
|
|
|
72
72
|
## Commands
|
|
73
73
|
|
|
@@ -125,7 +125,8 @@ Set `maxRetries` to at least the number of keys so all keys get a chance before
|
|
|
125
125
|
- The watchdog is scoped to the `opencode-go` provider only. Other providers are not aborted or rotated.
|
|
126
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
127
|
- When all non-quota-blocked keys are transiently cooling down, the extension may clear the next eligible key's cooldown. It never automatically clears or force-selects a quota-blocked key.
|
|
128
|
-
- When all keys are quota-blocked, automatic rotation stops on the current runtime key
|
|
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.
|
|
129
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/).
|
|
130
131
|
- Keys added via `/opencode add` are stored in plaintext. The config file is created and maintained with `0600` permissions.
|
|
131
132
|
|
package/dist/index.js
CHANGED
|
@@ -132,20 +132,6 @@ function getQuotaBlockedUntil(config, keyIndex, now) {
|
|
|
132
132
|
? blockedUntil
|
|
133
133
|
: undefined;
|
|
134
134
|
}
|
|
135
|
-
/** Keys held by a live recorded block, optionally ignoring the key that just failed. */
|
|
136
|
-
function getQuotaBlockedTargets(config, now, skipKeyIndex) {
|
|
137
|
-
const targets = [];
|
|
138
|
-
for (let keyIndex = 0; keyIndex < config.keys.length; keyIndex++) {
|
|
139
|
-
if (keyIndex === skipKeyIndex)
|
|
140
|
-
continue;
|
|
141
|
-
if (getQuotaBlockedUntil(config, keyIndex, now) === undefined)
|
|
142
|
-
continue;
|
|
143
|
-
const target = getUsageTargetForKeyIndex(config, keyIndex);
|
|
144
|
-
if (target)
|
|
145
|
-
targets.push(target);
|
|
146
|
-
}
|
|
147
|
-
return targets;
|
|
148
|
-
}
|
|
149
135
|
function pickAvailableKeyIndex(config, now = Date.now()) {
|
|
150
136
|
const cdMs = getCooldownMs(config);
|
|
151
137
|
for (let i = 0; i < config.keys.length; i++) {
|
|
@@ -158,25 +144,43 @@ function pickAvailableKeyIndex(config, now = Date.now()) {
|
|
|
158
144
|
}
|
|
159
145
|
return undefined;
|
|
160
146
|
}
|
|
147
|
+
function listRotationCandidates(config, startIndex, currentTime) {
|
|
148
|
+
const preferred = [];
|
|
149
|
+
const cooling = [];
|
|
150
|
+
const cooldownMs = getCooldownMs(config);
|
|
151
|
+
for (let offset = 1; offset < config.keys.length; offset++) {
|
|
152
|
+
const keyIndex = (startIndex + offset) % config.keys.length;
|
|
153
|
+
if (getQuotaBlockedUntil(config, keyIndex, currentTime) !== undefined)
|
|
154
|
+
continue;
|
|
155
|
+
const cooldownStart = config.cooldowns[keyIndex];
|
|
156
|
+
if (cooldownStart === undefined || currentTime - cooldownStart >= cooldownMs)
|
|
157
|
+
preferred.push(keyIndex);
|
|
158
|
+
else
|
|
159
|
+
cooling.push(keyIndex);
|
|
160
|
+
}
|
|
161
|
+
return [...preferred, ...cooling];
|
|
162
|
+
}
|
|
163
|
+
function applyRotationMode(mode, config, keyIndex, currentTime) {
|
|
164
|
+
if (mode.kind === "quota") {
|
|
165
|
+
if (mode.authoritative)
|
|
166
|
+
config.quotaBlockedUntil[keyIndex] = mode.blockedUntil;
|
|
167
|
+
else
|
|
168
|
+
setQuotaBlock(config, keyIndex, mode.blockedUntil, currentTime);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
config.cooldowns[keyIndex] = currentTime;
|
|
172
|
+
}
|
|
161
173
|
function rotateToNextKey(config, options = {}) {
|
|
162
174
|
if (config.keys.length === 0)
|
|
163
175
|
return undefined;
|
|
164
176
|
const now = options.now ?? Date.now();
|
|
165
177
|
config.cooldowns[config.activeKeyIndex] = now;
|
|
166
|
-
const next =
|
|
167
|
-
if (next
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const candidate = (config.activeKeyIndex + offset) % config.keys.length;
|
|
173
|
-
if (getQuotaBlockedUntil(config, candidate, now) !== undefined)
|
|
174
|
-
continue;
|
|
175
|
-
config.activeKeyIndex = candidate;
|
|
176
|
-
delete config.cooldowns[candidate];
|
|
177
|
-
return candidate;
|
|
178
|
-
}
|
|
179
|
-
return undefined;
|
|
178
|
+
const next = listRotationCandidates(config, config.activeKeyIndex, now)[0];
|
|
179
|
+
if (next === undefined)
|
|
180
|
+
return undefined;
|
|
181
|
+
config.activeKeyIndex = next;
|
|
182
|
+
delete config.cooldowns[next];
|
|
183
|
+
return next;
|
|
180
184
|
}
|
|
181
185
|
// Key equality detects credential changes, but persisted history has no issuer
|
|
182
186
|
// provenance (including after reload). Never replay signed reasoning on this
|
|
@@ -470,24 +474,22 @@ function matchesUsageTarget(config, target) {
|
|
|
470
474
|
&& (entry.name || `key-${target.keyIndex + 1}`) === target.keyName
|
|
471
475
|
&& entry.key === target.bearerToken;
|
|
472
476
|
}
|
|
473
|
-
function
|
|
474
|
-
|
|
477
|
+
function usageWindowExhausted(window) {
|
|
478
|
+
if (window.status === "rate-limited")
|
|
479
|
+
return true;
|
|
480
|
+
if (window.usagePercent !== undefined && window.usagePercent >= 100)
|
|
481
|
+
return true;
|
|
482
|
+
if (window.used !== undefined && window.limit !== undefined && window.limit > 0 && window.used >= window.limit)
|
|
483
|
+
return true;
|
|
484
|
+
return window.remaining !== undefined && window.remaining <= 0;
|
|
475
485
|
}
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
* deadline we stored. Only a clean reading releases it -- a failed or unrecognised usage
|
|
479
|
-
* response is not evidence of headroom. A response with no windows, or with any window
|
|
480
|
-
* that is not positively active, stays conservative and keeps the recorded block.
|
|
481
|
-
*/
|
|
482
|
-
function hasConfirmedHeadroom(result) {
|
|
483
|
-
return result.ok
|
|
484
|
-
&& result.usage.windows.length > 0
|
|
485
|
-
&& result.usage.windows.every((window) => window.status === "active");
|
|
486
|
+
function hasExhaustedWindow(result) {
|
|
487
|
+
return result.ok && result.usage.windows.some(usageWindowExhausted);
|
|
486
488
|
}
|
|
487
|
-
function
|
|
489
|
+
function getExhaustedUntil(usage, now, fallbackMs) {
|
|
488
490
|
let blockedUntil = now;
|
|
489
491
|
for (const window of usage.windows) {
|
|
490
|
-
if (window
|
|
492
|
+
if (!usageWindowExhausted(window))
|
|
491
493
|
continue;
|
|
492
494
|
const resetTimes = [];
|
|
493
495
|
if (window.resetInSec !== undefined) {
|
|
@@ -522,28 +524,6 @@ function getEarliestQuotaReset(config, now) {
|
|
|
522
524
|
function setQuotaBlock(config, keyIndex, blockedUntil, now) {
|
|
523
525
|
config.quotaBlockedUntil[keyIndex] = Math.max(getQuotaBlockedUntil(config, keyIndex, now) ?? 0, blockedUntil);
|
|
524
526
|
}
|
|
525
|
-
function blockQuotaAndSelectNext(config, keyIndex, blockedUntil, now, isAuthoritative = false) {
|
|
526
|
-
if (isAuthoritative) {
|
|
527
|
-
config.quotaBlockedUntil[keyIndex] = blockedUntil;
|
|
528
|
-
}
|
|
529
|
-
else {
|
|
530
|
-
setQuotaBlock(config, keyIndex, blockedUntil, now);
|
|
531
|
-
}
|
|
532
|
-
let next = pickAvailableKeyIndex(config, now);
|
|
533
|
-
if (next === undefined) {
|
|
534
|
-
for (let offset = 1; offset <= config.keys.length; offset++) {
|
|
535
|
-
const candidate = (keyIndex + offset) % config.keys.length;
|
|
536
|
-
if (getQuotaBlockedUntil(config, candidate, now) !== undefined)
|
|
537
|
-
continue;
|
|
538
|
-
next = candidate;
|
|
539
|
-
delete config.cooldowns[candidate];
|
|
540
|
-
break;
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
if (next !== undefined)
|
|
544
|
-
config.activeKeyIndex = next;
|
|
545
|
-
return next;
|
|
546
|
-
}
|
|
547
527
|
function formatUsageAmount(value) {
|
|
548
528
|
return value === undefined ? undefined : value.toLocaleString("en-US");
|
|
549
529
|
}
|
|
@@ -822,15 +802,25 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
822
802
|
return;
|
|
823
803
|
const request = (async () => {
|
|
824
804
|
const usage = await fetchOpenCodeGoUsage(target, fetchApi, options.timers);
|
|
805
|
+
const receivedAt = now();
|
|
825
806
|
usageStatusKeyIndex = target.keyIndex;
|
|
826
|
-
usageStatusFetchedAt =
|
|
807
|
+
usageStatusFetchedAt = receivedAt;
|
|
827
808
|
if (usageStatusCtx !== ctx)
|
|
828
809
|
return;
|
|
829
810
|
if (!refreshConfig() || getActiveUsageTarget(config)?.keyIndex !== target.keyIndex)
|
|
830
811
|
return;
|
|
812
|
+
if (usage.ok && hasExhaustedWindow(usage) && getQuotaBlockedUntil(config, target.keyIndex, receivedAt) === undefined) {
|
|
813
|
+
mutateSharedConfig((freshConfig) => {
|
|
814
|
+
if (!matchesUsageTarget(freshConfig, target))
|
|
815
|
+
return;
|
|
816
|
+
if (getQuotaBlockedUntil(freshConfig, target.keyIndex, receivedAt) !== undefined)
|
|
817
|
+
return;
|
|
818
|
+
setQuotaBlock(freshConfig, target.keyIndex, getExhaustedUntil(usage.usage, receivedAt, getCooldownMs(freshConfig)), receivedAt);
|
|
819
|
+
});
|
|
820
|
+
}
|
|
831
821
|
setUsageStatus(usage.ok
|
|
832
|
-
? formatFooterUsage(usage.usage.windows, { keyName: target.keyName, nowMs:
|
|
833
|
-
: formatFooterUsage([], { keyName: target.keyName, nowMs:
|
|
822
|
+
? formatFooterUsage(usage.usage.windows, { keyName: target.keyName, nowMs: receivedAt })
|
|
823
|
+
: formatFooterUsage([], { keyName: target.keyName, nowMs: receivedAt, error: usage.message }));
|
|
834
824
|
})();
|
|
835
825
|
usageStatusInFlight = request;
|
|
836
826
|
try {
|
|
@@ -891,128 +881,68 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
891
881
|
&& refreshConfig()
|
|
892
882
|
&& isRotationOperationCurrent(outcome.completion, config, usageDecisionEpoch);
|
|
893
883
|
}
|
|
894
|
-
|
|
895
|
-
* A benched key can become usable again after we recorded its block. Probe the blocked
|
|
896
|
-
* keys without mutating anything; only a positive reading is collected as candidate
|
|
897
|
-
* headroom. The probes are data-only, so a stale result can never be applied without the
|
|
898
|
-
* guarded commit re-checking the credential, block and cooldown it was sampled from.
|
|
899
|
-
*/
|
|
900
|
-
async function probeRecoveredHeadroom(currentTime, skipKeyIndex) {
|
|
901
|
-
if (!refreshConfig())
|
|
902
|
-
return [];
|
|
903
|
-
const candidates = getQuotaBlockedTargets(config, currentTime, skipKeyIndex)
|
|
904
|
-
.map((target) => captureSelectionSnapshot(config, currentTime, target.keyIndex))
|
|
905
|
-
.filter((snapshot) => snapshot !== undefined);
|
|
906
|
-
const results = await Promise.all(candidates.map(async (candidate) => {
|
|
907
|
-
const usage = await fetchOpenCodeGoUsage(candidate, fetchApi, options.timers);
|
|
908
|
-
return hasConfirmedHeadroom(usage) ? candidate : undefined;
|
|
909
|
-
}));
|
|
910
|
-
if (!refreshConfig())
|
|
911
|
-
return [];
|
|
912
|
-
return results.filter((snapshot) => snapshot !== undefined);
|
|
913
|
-
}
|
|
914
|
-
function selectNextKey(mode, freshConfig, startIndex, currentTime) {
|
|
915
|
-
return mode.kind === "quota"
|
|
916
|
-
? blockQuotaAndSelectNext(freshConfig, startIndex, mode.blockedUntil, currentTime, mode.authoritative)
|
|
917
|
-
: rotateToNextKey(freshConfig, { now: currentTime });
|
|
918
|
-
}
|
|
919
|
-
/**
|
|
920
|
-
* Block the failed key and select a replacement, re-probing benched keys only when the
|
|
921
|
-
* fast path found nothing. Every mutation re-validates the operation snapshot under the
|
|
922
|
-
* lock, so a decision invalidated while probes were in flight is cancelled instead of
|
|
923
|
-
* being rebased onto the newer state.
|
|
924
|
-
*/
|
|
925
|
-
async function rotateWithRecovery(ctx, operation, currentTime, mode) {
|
|
884
|
+
async function rotateWithRecovery(operation, currentTime, mode) {
|
|
926
885
|
const startIndex = operation.selection.keyIndex;
|
|
927
|
-
|
|
928
|
-
if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch)) {
|
|
929
|
-
return { outcome: "cancelled" };
|
|
930
|
-
}
|
|
931
|
-
return { outcome: "done", value: selectNextKey(mode, freshConfig, startIndex, currentTime) };
|
|
932
|
-
});
|
|
933
|
-
if (fast === undefined)
|
|
886
|
+
if (!refreshConfig())
|
|
934
887
|
return { kind: "unavailable" };
|
|
935
|
-
if (
|
|
888
|
+
if (!isRotationOperationCurrent(operation, config, usageDecisionEpoch))
|
|
936
889
|
return { kind: "cancelled" };
|
|
937
|
-
|
|
890
|
+
for (const candidateIndex of listRotationCandidates(config, startIndex, currentTime)) {
|
|
891
|
+
if (!refreshConfig())
|
|
892
|
+
return { kind: "unavailable" };
|
|
893
|
+
if (getQuotaBlockedUntil(config, candidateIndex, currentTime) !== undefined)
|
|
894
|
+
continue;
|
|
895
|
+
const candidate = captureSelectionSnapshot(config, currentTime, candidateIndex);
|
|
896
|
+
if (!candidate)
|
|
897
|
+
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")
|
|
914
|
+
return { kind: "cancelled" };
|
|
915
|
+
continue;
|
|
916
|
+
}
|
|
917
|
+
const committed = mutateSharedConfig((freshConfig) => {
|
|
918
|
+
if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
|
|
919
|
+
return { outcome: "cancelled" };
|
|
920
|
+
if (!matchesSelectionSnapshot(freshConfig, candidate, currentTime))
|
|
921
|
+
return { outcome: "cancelled" };
|
|
922
|
+
applyRotationMode(mode, freshConfig, startIndex, currentTime);
|
|
923
|
+
delete freshConfig.cooldowns[candidate.keyIndex];
|
|
924
|
+
freshConfig.activeKeyIndex = candidate.keyIndex;
|
|
925
|
+
return { outcome: "done", value: candidate.keyIndex };
|
|
926
|
+
});
|
|
927
|
+
if (committed === undefined)
|
|
928
|
+
return { kind: "unavailable" };
|
|
929
|
+
if (committed.outcome === "cancelled")
|
|
930
|
+
return { kind: "cancelled" };
|
|
938
931
|
const completion = currentRotationOperation(currentTime);
|
|
939
|
-
return completion ? { kind: "rotated", keyIndex:
|
|
940
|
-
}
|
|
941
|
-
// Snapshot the state this operation just produced, so a later commit can detect any
|
|
942
|
-
// external change to the same credential, block, cooldown or selection.
|
|
943
|
-
const retryOperation = currentRotationOperation(currentTime);
|
|
944
|
-
const failedKey = captureSelectionSnapshot(config, currentTime, startIndex);
|
|
945
|
-
if (!retryOperation || !failedKey)
|
|
946
|
-
return { kind: "cancelled" };
|
|
947
|
-
const recovered = await probeRecoveredHeadroom(currentTime, startIndex);
|
|
948
|
-
if (configError)
|
|
949
|
-
return { kind: "unavailable" };
|
|
950
|
-
if (usageDecisionEpoch !== operation.epoch)
|
|
951
|
-
return { kind: "cancelled" };
|
|
952
|
-
if (recovered.length === 0) {
|
|
953
|
-
// Still verify the state this operation owns: a shared writer may have moved the
|
|
954
|
-
// selection, credential, block or cooldown while the probes were in flight.
|
|
955
|
-
const current = matchesSelectionSnapshot(config, failedKey, currentTime)
|
|
956
|
-
&& isRotationOperationCurrent(retryOperation, config, usageDecisionEpoch);
|
|
957
|
-
return current ? { kind: "none", completion: retryOperation } : { kind: "cancelled" };
|
|
932
|
+
return completion ? { kind: "rotated", keyIndex: committed.value, completion } : { kind: "cancelled" };
|
|
958
933
|
}
|
|
959
|
-
const
|
|
960
|
-
if (!isRotationOperationCurrent(
|
|
961
|
-
return { outcome: "cancelled" };
|
|
962
|
-
if (!matchesSelectionSnapshot(freshConfig, failedKey, currentTime))
|
|
963
|
-
return { outcome: "cancelled" };
|
|
964
|
-
if (!recovered.every((snapshot) => matchesSelectionSnapshot(freshConfig, snapshot, currentTime)))
|
|
934
|
+
const closed = mutateSharedConfig((freshConfig) => {
|
|
935
|
+
if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
|
|
965
936
|
return { outcome: "cancelled" };
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
delete freshConfig.cooldowns[snapshot.keyIndex];
|
|
969
|
-
}
|
|
970
|
-
return { outcome: "done", value: selectNextKey(mode, freshConfig, startIndex, currentTime) };
|
|
937
|
+
applyRotationMode(mode, freshConfig, startIndex, currentTime);
|
|
938
|
+
return { outcome: "done", value: undefined };
|
|
971
939
|
});
|
|
972
|
-
if (
|
|
940
|
+
if (closed === undefined)
|
|
973
941
|
return { kind: "unavailable" };
|
|
974
|
-
if (
|
|
942
|
+
if (closed.outcome === "cancelled")
|
|
975
943
|
return { kind: "cancelled" };
|
|
976
|
-
for (const snapshot of recovered) {
|
|
977
|
-
ctx.ui.notify(`OpenCode: ${snapshot.keyName} has headroom again → quota block cleared`, "info");
|
|
978
|
-
}
|
|
979
944
|
const completion = currentRotationOperation(currentTime);
|
|
980
|
-
|
|
981
|
-
return { kind: "cancelled" };
|
|
982
|
-
const selected = commit.value;
|
|
983
|
-
return selected === undefined || selected === startIndex
|
|
984
|
-
? { kind: "none", completion }
|
|
985
|
-
: { kind: "rotated", keyIndex: selected, completion };
|
|
986
|
-
}
|
|
987
|
-
/** Guarded startup/reload recovery: clears only blocks whose snapshot is still current. */
|
|
988
|
-
async function recoverQuotaBlocksGuarded(ctx, operation, currentTime) {
|
|
989
|
-
const recovered = await probeRecoveredHeadroom(currentTime);
|
|
990
|
-
if (configError)
|
|
991
|
-
return "unavailable";
|
|
992
|
-
if (usageDecisionEpoch !== operation.epoch)
|
|
993
|
-
return "cancelled";
|
|
994
|
-
if (recovered.length === 0) {
|
|
995
|
-
return isRotationOperationCurrent(operation, config, usageDecisionEpoch) ? "none" : "cancelled";
|
|
996
|
-
}
|
|
997
|
-
const commit = mutateSharedConfig((freshConfig) => {
|
|
998
|
-
if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
|
|
999
|
-
return { outcome: "cancelled" };
|
|
1000
|
-
if (!recovered.every((snapshot) => matchesSelectionSnapshot(freshConfig, snapshot, currentTime)))
|
|
1001
|
-
return { outcome: "cancelled" };
|
|
1002
|
-
for (const snapshot of recovered) {
|
|
1003
|
-
delete freshConfig.quotaBlockedUntil[snapshot.keyIndex];
|
|
1004
|
-
delete freshConfig.cooldowns[snapshot.keyIndex];
|
|
1005
|
-
}
|
|
1006
|
-
return { outcome: "done", value: true };
|
|
1007
|
-
});
|
|
1008
|
-
if (commit === undefined)
|
|
1009
|
-
return "unavailable";
|
|
1010
|
-
if (commit.outcome === "cancelled")
|
|
1011
|
-
return "cancelled";
|
|
1012
|
-
for (const snapshot of recovered) {
|
|
1013
|
-
ctx.ui.notify(`OpenCode: ${snapshot.keyName} has headroom again → quota block cleared`, "info");
|
|
1014
|
-
}
|
|
1015
|
-
return "recovered";
|
|
945
|
+
return completion ? { kind: "none", completion } : { kind: "cancelled" };
|
|
1016
946
|
}
|
|
1017
947
|
function reportQuotaExhausted(ctx, exhaustedName, currentTime) {
|
|
1018
948
|
if (configError) {
|
|
@@ -1145,28 +1075,6 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1145
1075
|
usageStatusCtx = ctx;
|
|
1146
1076
|
if (!ensureConfig(ctx))
|
|
1147
1077
|
return;
|
|
1148
|
-
// A block recorded in an earlier session can be stale: the plan was topped up, or the
|
|
1149
|
-
// window reset before the deadline we stored. Re-check before it decides which key this
|
|
1150
|
-
// session uses, rather than benching a key that is usable again -- or leaving every key
|
|
1151
|
-
// held by a block with nothing left to rotate to.
|
|
1152
|
-
if (config.keys.length > 0) {
|
|
1153
|
-
const currentTime = now();
|
|
1154
|
-
const activeBlocked = getQuotaBlockedUntil(config, config.activeKeyIndex, currentTime) !== undefined;
|
|
1155
|
-
if (activeBlocked || pickAvailableKeyIndex(config, currentTime) === undefined) {
|
|
1156
|
-
const operation = currentRotationOperation(currentTime);
|
|
1157
|
-
if (!operation)
|
|
1158
|
-
return;
|
|
1159
|
-
const recovery = await recoverQuotaBlocksGuarded(ctx, operation, currentTime);
|
|
1160
|
-
// A startup continuation invalidated while probes were in flight must not
|
|
1161
|
-
// clear blocks or re-apply a key on top of the newer decision.
|
|
1162
|
-
if (recovery === "cancelled")
|
|
1163
|
-
return;
|
|
1164
|
-
if (usageDecisionEpoch !== operation.epoch)
|
|
1165
|
-
return;
|
|
1166
|
-
if (!refreshConfig())
|
|
1167
|
-
return;
|
|
1168
|
-
}
|
|
1169
|
-
}
|
|
1170
1078
|
// On reload: re-apply active key, skip auto-import
|
|
1171
1079
|
if (event.reason === "reload") {
|
|
1172
1080
|
applySynchronizedActiveKey(ctx);
|
|
@@ -1262,7 +1170,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1262
1170
|
const operation = currentRotationOperation(currentTime);
|
|
1263
1171
|
if (!operation || operation.selection.keyIndex !== requestState.decision.target.keyIndex)
|
|
1264
1172
|
return;
|
|
1265
|
-
const outcome = await rotateWithRecovery(
|
|
1173
|
+
const outcome = await rotateWithRecovery(operation, currentTime, {
|
|
1266
1174
|
kind: "quota",
|
|
1267
1175
|
blockedUntil,
|
|
1268
1176
|
authoritative: authoritativeReset !== undefined,
|
|
@@ -1299,7 +1207,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1299
1207
|
const operation = currentRotationOperation(currentTime);
|
|
1300
1208
|
if (!operation || operation.selection.keyIndex !== requestState.decision.target.keyIndex)
|
|
1301
1209
|
return;
|
|
1302
|
-
const outcome = await rotateWithRecovery(
|
|
1210
|
+
const outcome = await rotateWithRecovery(operation, currentTime, { kind: "cooldown" });
|
|
1303
1211
|
if (outcome.kind === "cancelled")
|
|
1304
1212
|
return;
|
|
1305
1213
|
if (outcome.kind === "unavailable") {
|
|
@@ -1351,10 +1259,10 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1351
1259
|
return;
|
|
1352
1260
|
const currentTime = now();
|
|
1353
1261
|
const exhaustedName = config.keys[decision.target.keyIndex]?.name || `key-${decision.target.keyIndex + 1}`;
|
|
1354
|
-
if (usage.ok &&
|
|
1355
|
-
const outcome = await rotateWithRecovery(
|
|
1262
|
+
if (usage.ok && hasExhaustedWindow(usage)) {
|
|
1263
|
+
const outcome = await rotateWithRecovery(operation, currentTime, {
|
|
1356
1264
|
kind: "quota",
|
|
1357
|
-
blockedUntil:
|
|
1265
|
+
blockedUntil: getExhaustedUntil(usage.usage, currentTime, getCooldownMs(config)),
|
|
1358
1266
|
authoritative: false,
|
|
1359
1267
|
});
|
|
1360
1268
|
if (outcome.kind === "cancelled")
|
|
@@ -1386,7 +1294,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1386
1294
|
markHandledIfOwned();
|
|
1387
1295
|
return;
|
|
1388
1296
|
}
|
|
1389
|
-
const outcome = await rotateWithRecovery(
|
|
1297
|
+
const outcome = await rotateWithRecovery(operation, currentTime, { kind: "cooldown" });
|
|
1390
1298
|
if (outcome.kind === "cancelled")
|
|
1391
1299
|
return;
|
|
1392
1300
|
if (outcome.kind === "unavailable") {
|
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.1",
|
|
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",
|