@yugimob/pi-opencode-go-rotation 1.6.2 → 1.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -10
- package/dist/config-store.d.ts +2 -0
- package/dist/config-store.js +15 -0
- package/dist/config-ui.d.ts +17 -0
- package/dist/config-ui.js +549 -0
- package/dist/format-time.d.ts +2 -0
- package/dist/format-time.js +20 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +185 -272
- package/package.json +11 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { ConfigLoadError, DEFAULT_COOLDOWN_MINUTES, DEFAULT_WATCHDOG_IDLE_MS, createEmptyConfig, loadConfig, updateConfig, } from "./config-store.js";
|
|
2
|
+
import { openOpencodeConfig, removeKey } from "./config-ui.js";
|
|
3
|
+
import { formatDuration, formatResetIn } from "./format-time.js";
|
|
4
|
+
export { formatResetIn };
|
|
2
5
|
const PROVIDER = "opencode-go";
|
|
3
6
|
const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
|
|
4
7
|
const OPENCODE_GO_USAGE_TIMEOUT_MS = 10_000;
|
|
@@ -129,20 +132,6 @@ function getQuotaBlockedUntil(config, keyIndex, now) {
|
|
|
129
132
|
? blockedUntil
|
|
130
133
|
: undefined;
|
|
131
134
|
}
|
|
132
|
-
/** Keys held by a live recorded block, optionally ignoring the key that just failed. */
|
|
133
|
-
function getQuotaBlockedTargets(config, now, skipKeyIndex) {
|
|
134
|
-
const targets = [];
|
|
135
|
-
for (let keyIndex = 0; keyIndex < config.keys.length; keyIndex++) {
|
|
136
|
-
if (keyIndex === skipKeyIndex)
|
|
137
|
-
continue;
|
|
138
|
-
if (getQuotaBlockedUntil(config, keyIndex, now) === undefined)
|
|
139
|
-
continue;
|
|
140
|
-
const target = getUsageTargetForKeyIndex(config, keyIndex);
|
|
141
|
-
if (target)
|
|
142
|
-
targets.push(target);
|
|
143
|
-
}
|
|
144
|
-
return targets;
|
|
145
|
-
}
|
|
146
135
|
function pickAvailableKeyIndex(config, now = Date.now()) {
|
|
147
136
|
const cdMs = getCooldownMs(config);
|
|
148
137
|
for (let i = 0; i < config.keys.length; i++) {
|
|
@@ -155,25 +144,43 @@ function pickAvailableKeyIndex(config, now = Date.now()) {
|
|
|
155
144
|
}
|
|
156
145
|
return undefined;
|
|
157
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
|
+
}
|
|
158
173
|
function rotateToNextKey(config, options = {}) {
|
|
159
174
|
if (config.keys.length === 0)
|
|
160
175
|
return undefined;
|
|
161
176
|
const now = options.now ?? Date.now();
|
|
162
177
|
config.cooldowns[config.activeKeyIndex] = now;
|
|
163
|
-
const next =
|
|
164
|
-
if (next
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
const candidate = (config.activeKeyIndex + offset) % config.keys.length;
|
|
170
|
-
if (getQuotaBlockedUntil(config, candidate, now) !== undefined)
|
|
171
|
-
continue;
|
|
172
|
-
config.activeKeyIndex = candidate;
|
|
173
|
-
delete config.cooldowns[candidate];
|
|
174
|
-
return candidate;
|
|
175
|
-
}
|
|
176
|
-
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;
|
|
177
184
|
}
|
|
178
185
|
// Key equality detects credential changes, but persisted history has no issuer
|
|
179
186
|
// provenance (including after reload). Never replay signed reasoning on this
|
|
@@ -263,7 +270,8 @@ function sanitizeReasoningPayload(payload) {
|
|
|
263
270
|
}
|
|
264
271
|
const lastAppliedRuntimeKeys = new WeakMap();
|
|
265
272
|
function getRuntimeKeyStore(modelRegistry) {
|
|
266
|
-
const
|
|
273
|
+
const host = modelRegistry;
|
|
274
|
+
const store = host.authStorage ?? host.runtime;
|
|
267
275
|
if (!store)
|
|
268
276
|
throw new Error("Model registry does not expose runtime API key storage");
|
|
269
277
|
return store;
|
|
@@ -466,24 +474,22 @@ function matchesUsageTarget(config, target) {
|
|
|
466
474
|
&& (entry.name || `key-${target.keyIndex + 1}`) === target.keyName
|
|
467
475
|
&& entry.key === target.bearerToken;
|
|
468
476
|
}
|
|
469
|
-
function
|
|
470
|
-
|
|
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;
|
|
471
485
|
}
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
* deadline we stored. Only a clean reading releases it -- a failed or unrecognised usage
|
|
475
|
-
* response is not evidence of headroom. A response with no windows, or with any window
|
|
476
|
-
* that is not positively active, stays conservative and keeps the recorded block.
|
|
477
|
-
*/
|
|
478
|
-
function hasConfirmedHeadroom(result) {
|
|
479
|
-
return result.ok
|
|
480
|
-
&& result.usage.windows.length > 0
|
|
481
|
-
&& result.usage.windows.every((window) => window.status === "active");
|
|
486
|
+
function hasExhaustedWindow(result) {
|
|
487
|
+
return result.ok && result.usage.windows.some(usageWindowExhausted);
|
|
482
488
|
}
|
|
483
|
-
function
|
|
489
|
+
function getExhaustedUntil(usage, now, fallbackMs) {
|
|
484
490
|
let blockedUntil = now;
|
|
485
491
|
for (const window of usage.windows) {
|
|
486
|
-
if (window
|
|
492
|
+
if (!usageWindowExhausted(window))
|
|
487
493
|
continue;
|
|
488
494
|
const resetTimes = [];
|
|
489
495
|
if (window.resetInSec !== undefined) {
|
|
@@ -518,53 +524,9 @@ function getEarliestQuotaReset(config, now) {
|
|
|
518
524
|
function setQuotaBlock(config, keyIndex, blockedUntil, now) {
|
|
519
525
|
config.quotaBlockedUntil[keyIndex] = Math.max(getQuotaBlockedUntil(config, keyIndex, now) ?? 0, blockedUntil);
|
|
520
526
|
}
|
|
521
|
-
function blockQuotaAndSelectNext(config, keyIndex, blockedUntil, now, isAuthoritative = false) {
|
|
522
|
-
if (isAuthoritative) {
|
|
523
|
-
config.quotaBlockedUntil[keyIndex] = blockedUntil;
|
|
524
|
-
}
|
|
525
|
-
else {
|
|
526
|
-
setQuotaBlock(config, keyIndex, blockedUntil, now);
|
|
527
|
-
}
|
|
528
|
-
let next = pickAvailableKeyIndex(config, now);
|
|
529
|
-
if (next === undefined) {
|
|
530
|
-
for (let offset = 1; offset <= config.keys.length; offset++) {
|
|
531
|
-
const candidate = (keyIndex + offset) % config.keys.length;
|
|
532
|
-
if (getQuotaBlockedUntil(config, candidate, now) !== undefined)
|
|
533
|
-
continue;
|
|
534
|
-
next = candidate;
|
|
535
|
-
delete config.cooldowns[candidate];
|
|
536
|
-
break;
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
if (next !== undefined)
|
|
540
|
-
config.activeKeyIndex = next;
|
|
541
|
-
return next;
|
|
542
|
-
}
|
|
543
|
-
function reindexAfterRemoval(record, removedIndex) {
|
|
544
|
-
const shifted = {};
|
|
545
|
-
for (const [key, value] of Object.entries(record)) {
|
|
546
|
-
const index = Number(key);
|
|
547
|
-
if (index === removedIndex)
|
|
548
|
-
continue;
|
|
549
|
-
shifted[index > removedIndex ? index - 1 : index] = value;
|
|
550
|
-
}
|
|
551
|
-
return shifted;
|
|
552
|
-
}
|
|
553
527
|
function formatUsageAmount(value) {
|
|
554
528
|
return value === undefined ? undefined : value.toLocaleString("en-US");
|
|
555
529
|
}
|
|
556
|
-
export function formatResetIn(seconds) {
|
|
557
|
-
if (seconds <= 0)
|
|
558
|
-
return "now";
|
|
559
|
-
const days = Math.floor(seconds / 86_400);
|
|
560
|
-
const hours = Math.floor((seconds % 86_400) / 3_600);
|
|
561
|
-
const minutes = Math.ceil((seconds % 3_600) / 60);
|
|
562
|
-
if (days > 0)
|
|
563
|
-
return hours > 0 ? `${days}d ${hours}h` : `${days}d`;
|
|
564
|
-
if (hours > 0)
|
|
565
|
-
return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
|
|
566
|
-
return minutes > 0 ? `${minutes}m` : "less than 1m";
|
|
567
|
-
}
|
|
568
530
|
function formatUsageWindow(window, index) {
|
|
569
531
|
const label = window.name ?? `window ${index + 1}`;
|
|
570
532
|
const details = [`${label}: ${window.status}`];
|
|
@@ -607,19 +569,26 @@ export function shortUsageWindowLabel(name, index) {
|
|
|
607
569
|
return name;
|
|
608
570
|
}
|
|
609
571
|
export function formatFooterUsage(windows, options = {}) {
|
|
610
|
-
const
|
|
572
|
+
const name = options.keyName ?? "opencode-go";
|
|
611
573
|
if (options.error !== undefined)
|
|
612
|
-
return `${
|
|
574
|
+
return `${name}: usage unavailable: ${options.error}`;
|
|
613
575
|
if (windows.length === 0)
|
|
614
|
-
return `${
|
|
615
|
-
const parts =
|
|
576
|
+
return `${name}: no usage windows`;
|
|
577
|
+
const parts = [];
|
|
578
|
+
windows.forEach((window, index) => {
|
|
616
579
|
const label = shortUsageWindowLabel(window.name, index);
|
|
580
|
+
if (label === "5h")
|
|
581
|
+
return;
|
|
617
582
|
const percent = usageWindowPercent(window);
|
|
618
|
-
|
|
583
|
+
parts.push(`${label} ${percent === undefined ? "?" : `${Math.round(percent)}%`}`);
|
|
619
584
|
});
|
|
620
|
-
|
|
585
|
+
if (windows.some((window) => window.status === "rate-limited"))
|
|
586
|
+
parts.push("rate-limited");
|
|
621
587
|
const renewal = monthlyRenewalDate(windows, options.nowMs ?? Date.now());
|
|
622
|
-
|
|
588
|
+
const renewalText = renewal === undefined ? "" : `↻ ${formatRenewalDate(renewal)}`;
|
|
589
|
+
if (parts.length === 0)
|
|
590
|
+
return renewalText ? `${name}: ${renewalText}` : name;
|
|
591
|
+
return `${name}: ${parts.join(" · ")}${renewalText ? ` | ${renewalText}` : ""}`;
|
|
623
592
|
}
|
|
624
593
|
function monthlyRenewalDate(windows, nowMs) {
|
|
625
594
|
const monthly = windows.find((window, index) => shortUsageWindowLabel(window.name, index) === "mo");
|
|
@@ -670,14 +639,6 @@ function formatStatus(config, now = Date.now()) {
|
|
|
670
639
|
return `${marker} ${i + 1}. ${key.name}${tag}`;
|
|
671
640
|
}).join("\n")}\n${watchdogStatus}`;
|
|
672
641
|
}
|
|
673
|
-
function formatDuration(ms) {
|
|
674
|
-
const seconds = Math.max(0, Math.ceil(ms / 1000));
|
|
675
|
-
if (seconds < 60)
|
|
676
|
-
return `${seconds}s`;
|
|
677
|
-
const minutes = Math.floor(seconds / 60);
|
|
678
|
-
const remainder = seconds % 60;
|
|
679
|
-
return remainder ? `${minutes}m ${remainder}s` : `${minutes}m`;
|
|
680
|
-
}
|
|
681
642
|
function formatTimeoutInfo(info) {
|
|
682
643
|
const status = info.lastStatus === undefined ? "" : `, last HTTP ${info.lastStatus}`;
|
|
683
644
|
return `${info.phase.replaceAll("-", " ")} stalled after ${formatDuration(info.elapsedMs)} (${formatDuration(info.idleForMs)} idle${status})`;
|
|
@@ -841,15 +802,25 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
841
802
|
return;
|
|
842
803
|
const request = (async () => {
|
|
843
804
|
const usage = await fetchOpenCodeGoUsage(target, fetchApi, options.timers);
|
|
805
|
+
const receivedAt = now();
|
|
844
806
|
usageStatusKeyIndex = target.keyIndex;
|
|
845
|
-
usageStatusFetchedAt =
|
|
807
|
+
usageStatusFetchedAt = receivedAt;
|
|
846
808
|
if (usageStatusCtx !== ctx)
|
|
847
809
|
return;
|
|
848
810
|
if (!refreshConfig() || getActiveUsageTarget(config)?.keyIndex !== target.keyIndex)
|
|
849
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
|
+
}
|
|
850
821
|
setUsageStatus(usage.ok
|
|
851
|
-
? formatFooterUsage(usage.usage.windows, { keyName: target.keyName, nowMs:
|
|
852
|
-
: 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 }));
|
|
853
824
|
})();
|
|
854
825
|
usageStatusInFlight = request;
|
|
855
826
|
try {
|
|
@@ -910,128 +881,68 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
910
881
|
&& refreshConfig()
|
|
911
882
|
&& isRotationOperationCurrent(outcome.completion, config, usageDecisionEpoch);
|
|
912
883
|
}
|
|
913
|
-
|
|
914
|
-
* A benched key can become usable again after we recorded its block. Probe the blocked
|
|
915
|
-
* keys without mutating anything; only a positive reading is collected as candidate
|
|
916
|
-
* headroom. The probes are data-only, so a stale result can never be applied without the
|
|
917
|
-
* guarded commit re-checking the credential, block and cooldown it was sampled from.
|
|
918
|
-
*/
|
|
919
|
-
async function probeRecoveredHeadroom(currentTime, skipKeyIndex) {
|
|
920
|
-
if (!refreshConfig())
|
|
921
|
-
return [];
|
|
922
|
-
const candidates = getQuotaBlockedTargets(config, currentTime, skipKeyIndex)
|
|
923
|
-
.map((target) => captureSelectionSnapshot(config, currentTime, target.keyIndex))
|
|
924
|
-
.filter((snapshot) => snapshot !== undefined);
|
|
925
|
-
const results = await Promise.all(candidates.map(async (candidate) => {
|
|
926
|
-
const usage = await fetchOpenCodeGoUsage(candidate, fetchApi, options.timers);
|
|
927
|
-
return hasConfirmedHeadroom(usage) ? candidate : undefined;
|
|
928
|
-
}));
|
|
929
|
-
if (!refreshConfig())
|
|
930
|
-
return [];
|
|
931
|
-
return results.filter((snapshot) => snapshot !== undefined);
|
|
932
|
-
}
|
|
933
|
-
function selectNextKey(mode, freshConfig, startIndex, currentTime) {
|
|
934
|
-
return mode.kind === "quota"
|
|
935
|
-
? blockQuotaAndSelectNext(freshConfig, startIndex, mode.blockedUntil, currentTime, mode.authoritative)
|
|
936
|
-
: rotateToNextKey(freshConfig, { now: currentTime });
|
|
937
|
-
}
|
|
938
|
-
/**
|
|
939
|
-
* Block the failed key and select a replacement, re-probing benched keys only when the
|
|
940
|
-
* fast path found nothing. Every mutation re-validates the operation snapshot under the
|
|
941
|
-
* lock, so a decision invalidated while probes were in flight is cancelled instead of
|
|
942
|
-
* being rebased onto the newer state.
|
|
943
|
-
*/
|
|
944
|
-
async function rotateWithRecovery(ctx, operation, currentTime, mode) {
|
|
884
|
+
async function rotateWithRecovery(operation, currentTime, mode) {
|
|
945
885
|
const startIndex = operation.selection.keyIndex;
|
|
946
|
-
|
|
947
|
-
if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch)) {
|
|
948
|
-
return { outcome: "cancelled" };
|
|
949
|
-
}
|
|
950
|
-
return { outcome: "done", value: selectNextKey(mode, freshConfig, startIndex, currentTime) };
|
|
951
|
-
});
|
|
952
|
-
if (fast === undefined)
|
|
886
|
+
if (!refreshConfig())
|
|
953
887
|
return { kind: "unavailable" };
|
|
954
|
-
if (
|
|
888
|
+
if (!isRotationOperationCurrent(operation, config, usageDecisionEpoch))
|
|
955
889
|
return { kind: "cancelled" };
|
|
956
|
-
|
|
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" };
|
|
957
931
|
const completion = currentRotationOperation(currentTime);
|
|
958
|
-
return completion ? { kind: "rotated", keyIndex:
|
|
959
|
-
}
|
|
960
|
-
// Snapshot the state this operation just produced, so a later commit can detect any
|
|
961
|
-
// external change to the same credential, block, cooldown or selection.
|
|
962
|
-
const retryOperation = currentRotationOperation(currentTime);
|
|
963
|
-
const failedKey = captureSelectionSnapshot(config, currentTime, startIndex);
|
|
964
|
-
if (!retryOperation || !failedKey)
|
|
965
|
-
return { kind: "cancelled" };
|
|
966
|
-
const recovered = await probeRecoveredHeadroom(currentTime, startIndex);
|
|
967
|
-
if (configError)
|
|
968
|
-
return { kind: "unavailable" };
|
|
969
|
-
if (usageDecisionEpoch !== operation.epoch)
|
|
970
|
-
return { kind: "cancelled" };
|
|
971
|
-
if (recovered.length === 0) {
|
|
972
|
-
// Still verify the state this operation owns: a shared writer may have moved the
|
|
973
|
-
// selection, credential, block or cooldown while the probes were in flight.
|
|
974
|
-
const current = matchesSelectionSnapshot(config, failedKey, currentTime)
|
|
975
|
-
&& isRotationOperationCurrent(retryOperation, config, usageDecisionEpoch);
|
|
976
|
-
return current ? { kind: "none", completion: retryOperation } : { kind: "cancelled" };
|
|
932
|
+
return completion ? { kind: "rotated", keyIndex: committed.value, completion } : { kind: "cancelled" };
|
|
977
933
|
}
|
|
978
|
-
const
|
|
979
|
-
if (!isRotationOperationCurrent(
|
|
980
|
-
return { outcome: "cancelled" };
|
|
981
|
-
if (!matchesSelectionSnapshot(freshConfig, failedKey, currentTime))
|
|
982
|
-
return { outcome: "cancelled" };
|
|
983
|
-
if (!recovered.every((snapshot) => matchesSelectionSnapshot(freshConfig, snapshot, currentTime)))
|
|
934
|
+
const closed = mutateSharedConfig((freshConfig) => {
|
|
935
|
+
if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
|
|
984
936
|
return { outcome: "cancelled" };
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
delete freshConfig.cooldowns[snapshot.keyIndex];
|
|
988
|
-
}
|
|
989
|
-
return { outcome: "done", value: selectNextKey(mode, freshConfig, startIndex, currentTime) };
|
|
937
|
+
applyRotationMode(mode, freshConfig, startIndex, currentTime);
|
|
938
|
+
return { outcome: "done", value: undefined };
|
|
990
939
|
});
|
|
991
|
-
if (
|
|
940
|
+
if (closed === undefined)
|
|
992
941
|
return { kind: "unavailable" };
|
|
993
|
-
if (
|
|
942
|
+
if (closed.outcome === "cancelled")
|
|
994
943
|
return { kind: "cancelled" };
|
|
995
|
-
for (const snapshot of recovered) {
|
|
996
|
-
ctx.ui.notify(`OpenCode: ${snapshot.keyName} has headroom again → quota block cleared`, "info");
|
|
997
|
-
}
|
|
998
944
|
const completion = currentRotationOperation(currentTime);
|
|
999
|
-
|
|
1000
|
-
return { kind: "cancelled" };
|
|
1001
|
-
const selected = commit.value;
|
|
1002
|
-
return selected === undefined || selected === startIndex
|
|
1003
|
-
? { kind: "none", completion }
|
|
1004
|
-
: { kind: "rotated", keyIndex: selected, completion };
|
|
1005
|
-
}
|
|
1006
|
-
/** Guarded startup/reload recovery: clears only blocks whose snapshot is still current. */
|
|
1007
|
-
async function recoverQuotaBlocksGuarded(ctx, operation, currentTime) {
|
|
1008
|
-
const recovered = await probeRecoveredHeadroom(currentTime);
|
|
1009
|
-
if (configError)
|
|
1010
|
-
return "unavailable";
|
|
1011
|
-
if (usageDecisionEpoch !== operation.epoch)
|
|
1012
|
-
return "cancelled";
|
|
1013
|
-
if (recovered.length === 0) {
|
|
1014
|
-
return isRotationOperationCurrent(operation, config, usageDecisionEpoch) ? "none" : "cancelled";
|
|
1015
|
-
}
|
|
1016
|
-
const commit = mutateSharedConfig((freshConfig) => {
|
|
1017
|
-
if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
|
|
1018
|
-
return { outcome: "cancelled" };
|
|
1019
|
-
if (!recovered.every((snapshot) => matchesSelectionSnapshot(freshConfig, snapshot, currentTime)))
|
|
1020
|
-
return { outcome: "cancelled" };
|
|
1021
|
-
for (const snapshot of recovered) {
|
|
1022
|
-
delete freshConfig.quotaBlockedUntil[snapshot.keyIndex];
|
|
1023
|
-
delete freshConfig.cooldowns[snapshot.keyIndex];
|
|
1024
|
-
}
|
|
1025
|
-
return { outcome: "done", value: true };
|
|
1026
|
-
});
|
|
1027
|
-
if (commit === undefined)
|
|
1028
|
-
return "unavailable";
|
|
1029
|
-
if (commit.outcome === "cancelled")
|
|
1030
|
-
return "cancelled";
|
|
1031
|
-
for (const snapshot of recovered) {
|
|
1032
|
-
ctx.ui.notify(`OpenCode: ${snapshot.keyName} has headroom again → quota block cleared`, "info");
|
|
1033
|
-
}
|
|
1034
|
-
return "recovered";
|
|
945
|
+
return completion ? { kind: "none", completion } : { kind: "cancelled" };
|
|
1035
946
|
}
|
|
1036
947
|
function reportQuotaExhausted(ctx, exhaustedName, currentTime) {
|
|
1037
948
|
if (configError) {
|
|
@@ -1126,10 +1037,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1126
1037
|
});
|
|
1127
1038
|
watchdog.start();
|
|
1128
1039
|
}
|
|
1129
|
-
async function
|
|
1130
|
-
const authKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
|
|
1131
|
-
if (!authKey)
|
|
1132
|
-
return false;
|
|
1040
|
+
async function importAuthKey(authKey) {
|
|
1133
1041
|
const imported = mutateSharedConfig((freshConfig) => {
|
|
1134
1042
|
if (freshConfig.keys.some((entry) => entry.key === authKey))
|
|
1135
1043
|
return false;
|
|
@@ -1138,6 +1046,25 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1138
1046
|
});
|
|
1139
1047
|
return imported === true;
|
|
1140
1048
|
}
|
|
1049
|
+
async function promptAuthImport(ctx) {
|
|
1050
|
+
if (!ctx.hasUI || config.keys.length > 0 || config.authImportDeclined)
|
|
1051
|
+
return false;
|
|
1052
|
+
const authKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
|
|
1053
|
+
if (!authKey)
|
|
1054
|
+
return false;
|
|
1055
|
+
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
|
+
return await importAuthKey(authKey);
|
|
1058
|
+
const persisted = mutateSharedConfig((freshConfig) => {
|
|
1059
|
+
freshConfig.authImportDeclined = true;
|
|
1060
|
+
return true;
|
|
1061
|
+
});
|
|
1062
|
+
if (persisted === true)
|
|
1063
|
+
ctx.ui.notify("OpenCode: auth.json import declined; /opencode will not ask again.", "info");
|
|
1064
|
+
else if (configError)
|
|
1065
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1066
|
+
return false;
|
|
1067
|
+
}
|
|
1141
1068
|
pi.on("session_start", async (event, ctx) => {
|
|
1142
1069
|
lastAppliedRuntimeKeys.delete(ctx.modelRegistry);
|
|
1143
1070
|
invalidateAutomaticDecisions();
|
|
@@ -1148,28 +1075,6 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1148
1075
|
usageStatusCtx = ctx;
|
|
1149
1076
|
if (!ensureConfig(ctx))
|
|
1150
1077
|
return;
|
|
1151
|
-
// A block recorded in an earlier session can be stale: the plan was topped up, or the
|
|
1152
|
-
// window reset before the deadline we stored. Re-check before it decides which key this
|
|
1153
|
-
// session uses, rather than benching a key that is usable again -- or leaving every key
|
|
1154
|
-
// held by a block with nothing left to rotate to.
|
|
1155
|
-
if (config.keys.length > 0) {
|
|
1156
|
-
const currentTime = now();
|
|
1157
|
-
const activeBlocked = getQuotaBlockedUntil(config, config.activeKeyIndex, currentTime) !== undefined;
|
|
1158
|
-
if (activeBlocked || pickAvailableKeyIndex(config, currentTime) === undefined) {
|
|
1159
|
-
const operation = currentRotationOperation(currentTime);
|
|
1160
|
-
if (!operation)
|
|
1161
|
-
return;
|
|
1162
|
-
const recovery = await recoverQuotaBlocksGuarded(ctx, operation, currentTime);
|
|
1163
|
-
// A startup continuation invalidated while probes were in flight must not
|
|
1164
|
-
// clear blocks or re-apply a key on top of the newer decision.
|
|
1165
|
-
if (recovery === "cancelled")
|
|
1166
|
-
return;
|
|
1167
|
-
if (usageDecisionEpoch !== operation.epoch)
|
|
1168
|
-
return;
|
|
1169
|
-
if (!refreshConfig())
|
|
1170
|
-
return;
|
|
1171
|
-
}
|
|
1172
|
-
}
|
|
1173
1078
|
// On reload: re-apply active key, skip auto-import
|
|
1174
1079
|
if (event.reason === "reload") {
|
|
1175
1080
|
applySynchronizedActiveKey(ctx);
|
|
@@ -1177,20 +1082,9 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1177
1082
|
return;
|
|
1178
1083
|
}
|
|
1179
1084
|
if (config.keys.length === 0) {
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
ctx.ui.notify(`OpenCode: Imported key from auth.json → ${keyName}`, "info");
|
|
1184
|
-
}
|
|
1185
|
-
else if (configError) {
|
|
1186
|
-
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1187
|
-
return;
|
|
1188
|
-
}
|
|
1189
|
-
else {
|
|
1190
|
-
ctx.ui.notify("OpenCode: No keys configured. Use /opencode add <name> <key>", "warning");
|
|
1191
|
-
setUsageStatus(undefined);
|
|
1192
|
-
return;
|
|
1193
|
-
}
|
|
1085
|
+
ctx.ui.notify("OpenCode: No keys configured. Run /opencode to add or import keys.", "warning");
|
|
1086
|
+
setUsageStatus(undefined);
|
|
1087
|
+
return;
|
|
1194
1088
|
}
|
|
1195
1089
|
applySynchronizedActiveKey(ctx);
|
|
1196
1090
|
syncUsageStatus(ctx, true);
|
|
@@ -1276,7 +1170,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1276
1170
|
const operation = currentRotationOperation(currentTime);
|
|
1277
1171
|
if (!operation || operation.selection.keyIndex !== requestState.decision.target.keyIndex)
|
|
1278
1172
|
return;
|
|
1279
|
-
const outcome = await rotateWithRecovery(
|
|
1173
|
+
const outcome = await rotateWithRecovery(operation, currentTime, {
|
|
1280
1174
|
kind: "quota",
|
|
1281
1175
|
blockedUntil,
|
|
1282
1176
|
authoritative: authoritativeReset !== undefined,
|
|
@@ -1313,7 +1207,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1313
1207
|
const operation = currentRotationOperation(currentTime);
|
|
1314
1208
|
if (!operation || operation.selection.keyIndex !== requestState.decision.target.keyIndex)
|
|
1315
1209
|
return;
|
|
1316
|
-
const outcome = await rotateWithRecovery(
|
|
1210
|
+
const outcome = await rotateWithRecovery(operation, currentTime, { kind: "cooldown" });
|
|
1317
1211
|
if (outcome.kind === "cancelled")
|
|
1318
1212
|
return;
|
|
1319
1213
|
if (outcome.kind === "unavailable") {
|
|
@@ -1365,10 +1259,10 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1365
1259
|
return;
|
|
1366
1260
|
const currentTime = now();
|
|
1367
1261
|
const exhaustedName = config.keys[decision.target.keyIndex]?.name || `key-${decision.target.keyIndex + 1}`;
|
|
1368
|
-
if (usage.ok &&
|
|
1369
|
-
const outcome = await rotateWithRecovery(
|
|
1262
|
+
if (usage.ok && hasExhaustedWindow(usage)) {
|
|
1263
|
+
const outcome = await rotateWithRecovery(operation, currentTime, {
|
|
1370
1264
|
kind: "quota",
|
|
1371
|
-
blockedUntil:
|
|
1265
|
+
blockedUntil: getExhaustedUntil(usage.usage, currentTime, getCooldownMs(config)),
|
|
1372
1266
|
authoritative: false,
|
|
1373
1267
|
});
|
|
1374
1268
|
if (outcome.kind === "cancelled")
|
|
@@ -1400,7 +1294,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1400
1294
|
markHandledIfOwned();
|
|
1401
1295
|
return;
|
|
1402
1296
|
}
|
|
1403
|
-
const outcome = await rotateWithRecovery(
|
|
1297
|
+
const outcome = await rotateWithRecovery(operation, currentTime, { kind: "cooldown" });
|
|
1404
1298
|
if (outcome.kind === "cancelled")
|
|
1405
1299
|
return;
|
|
1406
1300
|
if (outcome.kind === "unavailable") {
|
|
@@ -1438,9 +1332,33 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1438
1332
|
if (!ensureConfig(ctx))
|
|
1439
1333
|
return;
|
|
1440
1334
|
const parts = args.trim().split(/\s+/);
|
|
1441
|
-
const subcommand = parts[0] || "
|
|
1335
|
+
const subcommand = parts[0] || "";
|
|
1442
1336
|
const indexArg = parseInt(parts[1] ?? "", 10);
|
|
1443
1337
|
switch (subcommand) {
|
|
1338
|
+
case "":
|
|
1339
|
+
case "config":
|
|
1340
|
+
case "ui": {
|
|
1341
|
+
if (await promptAuthImport(ctx)) {
|
|
1342
|
+
const importedName = applySynchronizedActiveKey(ctx);
|
|
1343
|
+
if (importedName)
|
|
1344
|
+
ctx.ui.notify(`OpenCode: Imported key from auth.json → ${importedName}`, "info");
|
|
1345
|
+
}
|
|
1346
|
+
if (ctx.mode !== "tui") {
|
|
1347
|
+
ctx.ui.notify(formatStatus(config, now()), "info");
|
|
1348
|
+
break;
|
|
1349
|
+
}
|
|
1350
|
+
const result = await openOpencodeConfig(ctx);
|
|
1351
|
+
if (!ensureConfig(ctx))
|
|
1352
|
+
return;
|
|
1353
|
+
if (result.usageKeyIndex !== undefined) {
|
|
1354
|
+
const target = getUsageTargetForKeyIndex(config, result.usageKeyIndex);
|
|
1355
|
+
const usage = await fetchOpenCodeGoUsage(target, fetchApi, options.timers);
|
|
1356
|
+
ctx.ui.notify(formatUsageStatus(usage), usage.ok ? "info" : "warning");
|
|
1357
|
+
}
|
|
1358
|
+
applySynchronizedActiveKey(ctx);
|
|
1359
|
+
syncUsageStatus(ctx, true);
|
|
1360
|
+
break;
|
|
1361
|
+
}
|
|
1444
1362
|
case "status":
|
|
1445
1363
|
case "list":
|
|
1446
1364
|
case "ls": {
|
|
@@ -1543,13 +1461,8 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1543
1461
|
if (isNaN(removeIndex) || removeIndex < 0 || removeIndex >= freshConfig.keys.length) {
|
|
1544
1462
|
return { error: `Invalid index. Use 1-${freshConfig.keys.length}.` };
|
|
1545
1463
|
}
|
|
1546
|
-
const removed = freshConfig.keys
|
|
1547
|
-
|
|
1548
|
-
freshConfig.quotaBlockedUntil = reindexAfterRemoval(freshConfig.quotaBlockedUntil, removeIndex);
|
|
1549
|
-
if (freshConfig.activeKeyIndex >= freshConfig.keys.length)
|
|
1550
|
-
freshConfig.activeKeyIndex = 0;
|
|
1551
|
-
else if (removeIndex < freshConfig.activeKeyIndex)
|
|
1552
|
-
freshConfig.activeKeyIndex--;
|
|
1464
|
+
const removed = freshConfig.keys[removeIndex];
|
|
1465
|
+
removeKey(freshConfig, removeIndex);
|
|
1553
1466
|
return { removedName: removed.name, count: freshConfig.keys.length };
|
|
1554
1467
|
});
|
|
1555
1468
|
if (!result) {
|
|
@@ -1649,7 +1562,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1649
1562
|
break;
|
|
1650
1563
|
}
|
|
1651
1564
|
default:
|
|
1652
|
-
ctx.ui.notify("Usage: /opencode [status|usage|quota|events|use <n>|next|add <name> <key>|rm <n>|reset|cooldown <min>|watchdog [status|on|off|<seconds>]]", "info");
|
|
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");
|
|
1653
1566
|
}
|
|
1654
1567
|
},
|
|
1655
1568
|
});
|