@yugimob/pi-opencode-go-rotation 0.0.0-stage → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +19 -0
- package/README.md +114 -2
- package/dist/config-store.d.ts +29 -0
- package/dist/config-store.js +176 -0
- package/dist/index.d.ts +97 -0
- package/dist/index.js +1659 -0
- package/package.json +55 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1659 @@
|
|
|
1
|
+
import { ConfigLoadError, DEFAULT_COOLDOWN_MINUTES, DEFAULT_WATCHDOG_IDLE_MS, createEmptyConfig, loadConfig, updateConfig, } from "./config-store.js";
|
|
2
|
+
const PROVIDER = "opencode-go";
|
|
3
|
+
const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
|
|
4
|
+
const OPENCODE_GO_USAGE_TIMEOUT_MS = 10_000;
|
|
5
|
+
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;
|
|
6
|
+
const TRANSIENT_RATE_LIMIT_RE = /\b429\b|rate.?limit|too many requests|quota|usage limit|limit reached/i;
|
|
7
|
+
const USAGE_STATUS_KEY = "opencode-go-usage";
|
|
8
|
+
const USAGE_STATUS_REFRESH_MS = 60_000;
|
|
9
|
+
const USAGE_STATUS_STALE_MS = 300_000;
|
|
10
|
+
const USAGE_STATUS_DEBOUNCE_MS = 2_000;
|
|
11
|
+
function getCooldownMs(config) {
|
|
12
|
+
return (config.cooldownMinutes || DEFAULT_COOLDOWN_MINUTES) * 60_000;
|
|
13
|
+
}
|
|
14
|
+
function getWatchdogIdleMs(config) {
|
|
15
|
+
return config.watchdogIdleMs > 0 ? config.watchdogIdleMs : DEFAULT_WATCHDOG_IDLE_MS;
|
|
16
|
+
}
|
|
17
|
+
export function shouldWatchProvider(provider) {
|
|
18
|
+
return provider === PROVIDER;
|
|
19
|
+
}
|
|
20
|
+
export function classifyRateLimitError(message) {
|
|
21
|
+
if (FIXED_WINDOW_QUOTA_RE.test(message))
|
|
22
|
+
return "fixed-window-quota";
|
|
23
|
+
if (TRANSIENT_RATE_LIMIT_RE.test(message))
|
|
24
|
+
return "transient";
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
export function shouldRotateAfterWatchdogTimeout(timeoutInfo, rateLimitAlreadyRotated) {
|
|
28
|
+
return timeoutInfo.lastStatus !== 401 && (timeoutInfo.lastStatus !== 429 || !rateLimitAlreadyRotated);
|
|
29
|
+
}
|
|
30
|
+
export class ProviderIdleWatchdog {
|
|
31
|
+
timer;
|
|
32
|
+
active = false;
|
|
33
|
+
timedOut = false;
|
|
34
|
+
phase = "waiting-for-response";
|
|
35
|
+
startedAt = 0;
|
|
36
|
+
lastActivityAt = 0;
|
|
37
|
+
lastStatus;
|
|
38
|
+
timeoutInfo;
|
|
39
|
+
options;
|
|
40
|
+
constructor(options) {
|
|
41
|
+
this.options = options;
|
|
42
|
+
}
|
|
43
|
+
start() {
|
|
44
|
+
const now = this.now();
|
|
45
|
+
this.active = true;
|
|
46
|
+
this.timedOut = false;
|
|
47
|
+
this.timeoutInfo = undefined;
|
|
48
|
+
this.phase = "waiting-for-response";
|
|
49
|
+
this.startedAt = now;
|
|
50
|
+
this.lastActivityAt = now;
|
|
51
|
+
this.lastStatus = undefined;
|
|
52
|
+
this.schedule();
|
|
53
|
+
}
|
|
54
|
+
response(status) {
|
|
55
|
+
if (!this.active || this.timedOut)
|
|
56
|
+
return;
|
|
57
|
+
this.phase = "waiting-for-stream";
|
|
58
|
+
this.lastStatus = status;
|
|
59
|
+
this.markActivity();
|
|
60
|
+
}
|
|
61
|
+
streamActivity() {
|
|
62
|
+
if (!this.active || this.timedOut)
|
|
63
|
+
return;
|
|
64
|
+
this.phase = "streaming";
|
|
65
|
+
this.markActivity();
|
|
66
|
+
}
|
|
67
|
+
activity() {
|
|
68
|
+
if (!this.active || this.timedOut)
|
|
69
|
+
return;
|
|
70
|
+
this.markActivity();
|
|
71
|
+
}
|
|
72
|
+
stop() {
|
|
73
|
+
this.active = false;
|
|
74
|
+
this.clear();
|
|
75
|
+
}
|
|
76
|
+
consumeTimeoutInfo() {
|
|
77
|
+
const result = this.timeoutInfo;
|
|
78
|
+
this.timeoutInfo = undefined;
|
|
79
|
+
this.timedOut = false;
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
currentTimeoutInfo() {
|
|
83
|
+
return this.timeoutInfo;
|
|
84
|
+
}
|
|
85
|
+
markActivity() {
|
|
86
|
+
this.lastActivityAt = this.now();
|
|
87
|
+
this.schedule();
|
|
88
|
+
}
|
|
89
|
+
now() {
|
|
90
|
+
return this.options.clock?.now() ?? Date.now();
|
|
91
|
+
}
|
|
92
|
+
getTimers() {
|
|
93
|
+
return this.options.timers ?? {
|
|
94
|
+
setTimeout: (callback, ms) => globalThis.setTimeout(callback, ms),
|
|
95
|
+
clearTimeout: (timer) => globalThis.clearTimeout(timer),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
schedule() {
|
|
99
|
+
this.clear();
|
|
100
|
+
const timers = this.getTimers();
|
|
101
|
+
this.timer = timers.setTimeout(() => {
|
|
102
|
+
if (!this.active || this.timedOut)
|
|
103
|
+
return;
|
|
104
|
+
const now = this.now();
|
|
105
|
+
this.timeoutInfo = {
|
|
106
|
+
phase: this.phase,
|
|
107
|
+
idleMs: this.options.idleMs,
|
|
108
|
+
elapsedMs: Math.max(0, now - this.startedAt),
|
|
109
|
+
idleForMs: Math.max(0, now - this.lastActivityAt),
|
|
110
|
+
lastStatus: this.lastStatus,
|
|
111
|
+
};
|
|
112
|
+
this.timedOut = true;
|
|
113
|
+
this.active = false;
|
|
114
|
+
this.timer = undefined;
|
|
115
|
+
this.options.onTimeout();
|
|
116
|
+
}, this.options.idleMs);
|
|
117
|
+
}
|
|
118
|
+
clear() {
|
|
119
|
+
if (this.timer === undefined)
|
|
120
|
+
return;
|
|
121
|
+
const timers = this.getTimers();
|
|
122
|
+
timers.clearTimeout(this.timer);
|
|
123
|
+
this.timer = undefined;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function getQuotaBlockedUntil(config, keyIndex, now) {
|
|
127
|
+
const blockedUntil = config.quotaBlockedUntil[keyIndex];
|
|
128
|
+
return typeof blockedUntil === "number" && Number.isFinite(blockedUntil) && blockedUntil > now
|
|
129
|
+
? blockedUntil
|
|
130
|
+
: undefined;
|
|
131
|
+
}
|
|
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
|
+
function pickAvailableKeyIndex(config, now = Date.now()) {
|
|
147
|
+
const cdMs = getCooldownMs(config);
|
|
148
|
+
for (let i = 0; i < config.keys.length; i++) {
|
|
149
|
+
const idx = (config.activeKeyIndex + i) % config.keys.length;
|
|
150
|
+
if (getQuotaBlockedUntil(config, idx, now) !== undefined)
|
|
151
|
+
continue;
|
|
152
|
+
const cooldownStart = config.cooldowns[idx];
|
|
153
|
+
if (cooldownStart === undefined || now - cooldownStart >= cdMs)
|
|
154
|
+
return idx;
|
|
155
|
+
}
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
function rotateToNextKey(config, options = {}) {
|
|
159
|
+
if (config.keys.length === 0)
|
|
160
|
+
return undefined;
|
|
161
|
+
const now = options.now ?? Date.now();
|
|
162
|
+
config.cooldowns[config.activeKeyIndex] = now;
|
|
163
|
+
const next = pickAvailableKeyIndex(config, now);
|
|
164
|
+
if (next !== undefined) {
|
|
165
|
+
config.activeKeyIndex = next;
|
|
166
|
+
return next;
|
|
167
|
+
}
|
|
168
|
+
for (let offset = 1; offset <= config.keys.length; offset++) {
|
|
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;
|
|
177
|
+
}
|
|
178
|
+
// Key equality detects credential changes, but persisted history has no issuer
|
|
179
|
+
// provenance (including after reload). Never replay signed reasoning on this
|
|
180
|
+
// rotating route, even before this process observes its first rotation.
|
|
181
|
+
const droppedReasoningDetail = Symbol("dropped-caller-bound-reasoning");
|
|
182
|
+
function projectReasoningDetails(details) {
|
|
183
|
+
// map/filter, never flatMap: entries that are not plain reasoning detail
|
|
184
|
+
// objects (nested arrays, numbers, booleans, ...) must pass through as the
|
|
185
|
+
// same element in the same position, with their original shape intact.
|
|
186
|
+
return details
|
|
187
|
+
.map((detail) => {
|
|
188
|
+
if (!isRecord(detail))
|
|
189
|
+
return detail;
|
|
190
|
+
if (detail.type === "reasoning.encrypted")
|
|
191
|
+
return droppedReasoningDetail;
|
|
192
|
+
const { signature: _signature, ...unsigned } = detail;
|
|
193
|
+
return unsigned;
|
|
194
|
+
})
|
|
195
|
+
.filter((detail) => detail !== droppedReasoningDetail);
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Anthropic serializes signed thinking as `thinking` blocks and opaque redacted
|
|
199
|
+
* reasoning as `redacted_thinking`. Emit the SDK's own unsigned shape instead: a
|
|
200
|
+
* plain text block. Drop entries emptied by that projection, and report an
|
|
201
|
+
* assistant message for omission only when the projection emptied it.
|
|
202
|
+
*/
|
|
203
|
+
function projectAssistantContent(content) {
|
|
204
|
+
let projected = false;
|
|
205
|
+
const result = [];
|
|
206
|
+
for (const block of content) {
|
|
207
|
+
if (!isRecord(block)) {
|
|
208
|
+
result.push(block);
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (block.type === "thinking") {
|
|
212
|
+
projected = true;
|
|
213
|
+
const thinking = typeof block.thinking === "string" ? block.thinking : "";
|
|
214
|
+
if (block.redacted !== true && thinking.trim().length > 0)
|
|
215
|
+
result.push({ type: "text", text: thinking });
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
if (block.type === "redacted_thinking") {
|
|
219
|
+
projected = true;
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
result.push(block);
|
|
223
|
+
}
|
|
224
|
+
if (!projected)
|
|
225
|
+
return content;
|
|
226
|
+
return result.length === 0 ? undefined : result;
|
|
227
|
+
}
|
|
228
|
+
function sanitizeReasoningPayload(payload) {
|
|
229
|
+
if (!isRecord(payload))
|
|
230
|
+
return payload;
|
|
231
|
+
const request = { ...payload };
|
|
232
|
+
if (Array.isArray(request.messages)) {
|
|
233
|
+
const messages = [];
|
|
234
|
+
for (const message of request.messages) {
|
|
235
|
+
if (!isRecord(message) || message.role !== "assistant") {
|
|
236
|
+
messages.push(message);
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
let projected = message;
|
|
240
|
+
if (Array.isArray(message.content)) {
|
|
241
|
+
const content = projectAssistantContent(message.content);
|
|
242
|
+
if (content === undefined)
|
|
243
|
+
continue;
|
|
244
|
+
if (content !== message.content)
|
|
245
|
+
projected = { ...projected, content };
|
|
246
|
+
}
|
|
247
|
+
if (Array.isArray(message.reasoning_details)) {
|
|
248
|
+
const { reasoning_details: _details, ...visible } = projected;
|
|
249
|
+
const reasoning_details = projectReasoningDetails(message.reasoning_details);
|
|
250
|
+
// Strip the key entirely when nothing remains to send: an empty array is an
|
|
251
|
+
// unvalidated request shape, and this sanitiser exists to emit only shapes the
|
|
252
|
+
// provider accepts. Non-detail entries above keep identity/position/shape.
|
|
253
|
+
projected = reasoning_details.length === 0 ? visible : { ...visible, reasoning_details };
|
|
254
|
+
}
|
|
255
|
+
messages.push(projected);
|
|
256
|
+
}
|
|
257
|
+
request.messages = messages;
|
|
258
|
+
}
|
|
259
|
+
if (Array.isArray(request.input)) {
|
|
260
|
+
request.input = request.input.filter((item) => !isRecord(item) || item.type !== "reasoning");
|
|
261
|
+
}
|
|
262
|
+
return request;
|
|
263
|
+
}
|
|
264
|
+
const lastAppliedRuntimeKeys = new WeakMap();
|
|
265
|
+
function getRuntimeKeyStore(modelRegistry) {
|
|
266
|
+
const store = modelRegistry.authStorage ?? modelRegistry.runtime;
|
|
267
|
+
if (!store)
|
|
268
|
+
throw new Error("Model registry does not expose runtime API key storage");
|
|
269
|
+
return store;
|
|
270
|
+
}
|
|
271
|
+
function ignoreAsyncRefresh(result) {
|
|
272
|
+
void result?.catch(() => { });
|
|
273
|
+
}
|
|
274
|
+
/** Set the active key as runtime override (highest priority in auth chain). */
|
|
275
|
+
function applyActiveKey(config, modelRegistry, now = Date.now()) {
|
|
276
|
+
const idx = pickAvailableKeyIndex(config, now);
|
|
277
|
+
if (idx === undefined)
|
|
278
|
+
return undefined;
|
|
279
|
+
if (config.activeKeyIndex !== idx)
|
|
280
|
+
config.activeKeyIndex = idx;
|
|
281
|
+
const key = config.keys[idx].key;
|
|
282
|
+
if (lastAppliedRuntimeKeys.get(modelRegistry) !== key) {
|
|
283
|
+
lastAppliedRuntimeKeys.set(modelRegistry, key);
|
|
284
|
+
ignoreAsyncRefresh(getRuntimeKeyStore(modelRegistry).setRuntimeApiKey(PROVIDER, key));
|
|
285
|
+
}
|
|
286
|
+
return config.keys[idx].name || `key-${idx + 1}`;
|
|
287
|
+
}
|
|
288
|
+
function getUsageTargetForKeyIndex(config, keyIndex) {
|
|
289
|
+
const entry = config.keys[keyIndex];
|
|
290
|
+
if (!entry)
|
|
291
|
+
return undefined;
|
|
292
|
+
return {
|
|
293
|
+
keyIndex,
|
|
294
|
+
keyName: entry.name || `key-${keyIndex + 1}`,
|
|
295
|
+
bearerToken: entry.key,
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
function getActiveUsageTarget(config) {
|
|
299
|
+
return getUsageTargetForKeyIndex(config, config.activeKeyIndex);
|
|
300
|
+
}
|
|
301
|
+
function captureSelectionSnapshot(config, currentTime, keyIndex) {
|
|
302
|
+
const target = getUsageTargetForKeyIndex(config, keyIndex);
|
|
303
|
+
if (!target)
|
|
304
|
+
return undefined;
|
|
305
|
+
return {
|
|
306
|
+
...target,
|
|
307
|
+
blockedUntil: getQuotaBlockedUntil(config, target.keyIndex, currentTime),
|
|
308
|
+
cooldownStart: config.cooldowns[target.keyIndex],
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* A deferred decision owns one credential, selection, block and cooldown. Every later
|
|
313
|
+
* mutation re-checks that exact snapshot under the lock, so an operation that started
|
|
314
|
+
* before an external update can never write to the replacement state.
|
|
315
|
+
*/
|
|
316
|
+
function matchesSelectionSnapshot(config, snapshot, currentTime) {
|
|
317
|
+
const entry = config.keys[snapshot.keyIndex];
|
|
318
|
+
if (entry === undefined)
|
|
319
|
+
return false;
|
|
320
|
+
if ((entry.name || `key-${snapshot.keyIndex + 1}`) !== snapshot.keyName)
|
|
321
|
+
return false;
|
|
322
|
+
if (entry.key !== snapshot.bearerToken)
|
|
323
|
+
return false;
|
|
324
|
+
if (getQuotaBlockedUntil(config, snapshot.keyIndex, currentTime) !== snapshot.blockedUntil)
|
|
325
|
+
return false;
|
|
326
|
+
return config.cooldowns[snapshot.keyIndex] === snapshot.cooldownStart;
|
|
327
|
+
}
|
|
328
|
+
function captureRotationOperation(config, currentTime, keyIndex, epoch) {
|
|
329
|
+
const selection = captureSelectionSnapshot(config, currentTime, keyIndex);
|
|
330
|
+
return selection ? { epoch, currentTime, selection } : undefined;
|
|
331
|
+
}
|
|
332
|
+
function isRotationOperationCurrent(operation, config, epoch) {
|
|
333
|
+
return epoch === operation.epoch
|
|
334
|
+
&& config.activeKeyIndex === operation.selection.keyIndex
|
|
335
|
+
&& matchesSelectionSnapshot(config, operation.selection, operation.currentTime);
|
|
336
|
+
}
|
|
337
|
+
function isRecord(value) {
|
|
338
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
339
|
+
}
|
|
340
|
+
function readString(record, keys) {
|
|
341
|
+
for (const key of keys) {
|
|
342
|
+
const value = record[key];
|
|
343
|
+
if (typeof value === "string")
|
|
344
|
+
return value;
|
|
345
|
+
}
|
|
346
|
+
return undefined;
|
|
347
|
+
}
|
|
348
|
+
function readNumber(record, keys) {
|
|
349
|
+
for (const key of keys) {
|
|
350
|
+
const value = record[key];
|
|
351
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
352
|
+
return value;
|
|
353
|
+
}
|
|
354
|
+
return undefined;
|
|
355
|
+
}
|
|
356
|
+
function parseOpenCodeGoUsageWindow(value) {
|
|
357
|
+
if (!isRecord(value))
|
|
358
|
+
return undefined;
|
|
359
|
+
const status = value.status === "ok" || value.status === "active"
|
|
360
|
+
? "active"
|
|
361
|
+
: value.status === "rate-limited" ? "rate-limited" : "unknown";
|
|
362
|
+
const name = readString(value, ["name", "window", "period", "label"]);
|
|
363
|
+
const usagePercent = readNumber(value, ["usagePercent", "usage_percent", "percent"]);
|
|
364
|
+
const resetInSec = readNumber(value, ["resetInSec", "reset_in_sec", "resetSeconds", "reset_seconds"]);
|
|
365
|
+
const used = readNumber(value, ["used", "usage", "usedTokens"]);
|
|
366
|
+
const limit = readNumber(value, ["limit", "quota", "total"]);
|
|
367
|
+
const remaining = readNumber(value, ["remaining", "remainingTokens"]);
|
|
368
|
+
const resetAt = readString(value, ["resetAt", "reset_at", "resetsAt", "resets_at"]);
|
|
369
|
+
const startAt = readString(value, ["startAt", "start_at", "startsAt", "starts_at"]);
|
|
370
|
+
const endAt = readString(value, ["endAt", "end_at", "endsAt", "ends_at"]);
|
|
371
|
+
return {
|
|
372
|
+
status,
|
|
373
|
+
...(name === undefined ? {} : { name }),
|
|
374
|
+
...(usagePercent === undefined ? {} : { usagePercent }),
|
|
375
|
+
...(resetInSec === undefined ? {} : { resetInSec }),
|
|
376
|
+
...(used === undefined ? {} : { used }),
|
|
377
|
+
...(limit === undefined ? {} : { limit }),
|
|
378
|
+
...(remaining === undefined ? {} : { remaining }),
|
|
379
|
+
...(resetAt === undefined ? {} : { resetAt }),
|
|
380
|
+
...(startAt === undefined ? {} : { startAt }),
|
|
381
|
+
...(endAt === undefined ? {} : { endAt }),
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
export function parseOpenCodeGoUsage(value) {
|
|
385
|
+
if (!isRecord(value))
|
|
386
|
+
return undefined;
|
|
387
|
+
const windows = [];
|
|
388
|
+
if (Array.isArray(value.windows)) {
|
|
389
|
+
for (const window of value.windows) {
|
|
390
|
+
const parsed = parseOpenCodeGoUsageWindow(window);
|
|
391
|
+
if (!parsed)
|
|
392
|
+
return undefined;
|
|
393
|
+
windows.push(parsed);
|
|
394
|
+
}
|
|
395
|
+
return { windows };
|
|
396
|
+
}
|
|
397
|
+
if (!isRecord(value.usage))
|
|
398
|
+
return undefined;
|
|
399
|
+
for (const [name, window] of Object.entries(value.usage)) {
|
|
400
|
+
const parsed = parseOpenCodeGoUsageWindow(window);
|
|
401
|
+
if (!parsed)
|
|
402
|
+
return undefined;
|
|
403
|
+
windows.push(parsed.name === undefined ? { ...parsed, name } : parsed);
|
|
404
|
+
}
|
|
405
|
+
return { windows };
|
|
406
|
+
}
|
|
407
|
+
async function fetchOpenCodeGoUsage(target, fetchApi, timers) {
|
|
408
|
+
if (!target)
|
|
409
|
+
return { ok: false, message: "No OpenCode keys configured." };
|
|
410
|
+
const controller = new AbortController();
|
|
411
|
+
const timeoutFailure = { ok: false, keyName: target.keyName, message: "Usage request timed out after 10s." };
|
|
412
|
+
const timerApi = timers ?? {
|
|
413
|
+
setTimeout: (callback, ms) => globalThis.setTimeout(callback, ms),
|
|
414
|
+
clearTimeout: (timer) => globalThis.clearTimeout(timer),
|
|
415
|
+
};
|
|
416
|
+
let didTimeout = false;
|
|
417
|
+
let timeout;
|
|
418
|
+
const request = (async () => {
|
|
419
|
+
try {
|
|
420
|
+
const response = await fetchApi(OPENCODE_GO_USAGE_URL, {
|
|
421
|
+
method: "GET",
|
|
422
|
+
headers: {
|
|
423
|
+
Accept: "application/json",
|
|
424
|
+
Authorization: `Bearer ${target.bearerToken}`,
|
|
425
|
+
},
|
|
426
|
+
signal: controller.signal,
|
|
427
|
+
});
|
|
428
|
+
if (!response.ok) {
|
|
429
|
+
return { ok: false, keyName: target.keyName, message: `Usage request failed with HTTP ${response.status}.` };
|
|
430
|
+
}
|
|
431
|
+
const usage = parseOpenCodeGoUsage(await response.json());
|
|
432
|
+
if (!usage)
|
|
433
|
+
return { ok: false, keyName: target.keyName, message: "Usage response did not match the expected OpenCode Go shape." };
|
|
434
|
+
return { ok: true, keyName: target.keyName, usage };
|
|
435
|
+
}
|
|
436
|
+
catch {
|
|
437
|
+
if (didTimeout)
|
|
438
|
+
return timeoutFailure;
|
|
439
|
+
return { ok: false, keyName: target.keyName, message: "Usage request failed." };
|
|
440
|
+
}
|
|
441
|
+
})();
|
|
442
|
+
const timedOut = new Promise((resolve) => {
|
|
443
|
+
timeout = timerApi.setTimeout(() => {
|
|
444
|
+
didTimeout = true;
|
|
445
|
+
controller.abort();
|
|
446
|
+
resolve(timeoutFailure);
|
|
447
|
+
}, OPENCODE_GO_USAGE_TIMEOUT_MS);
|
|
448
|
+
});
|
|
449
|
+
try {
|
|
450
|
+
return await Promise.race([request, timedOut]);
|
|
451
|
+
}
|
|
452
|
+
finally {
|
|
453
|
+
timerApi.clearTimeout(timeout);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
function captureUsageDecision(config, epoch) {
|
|
457
|
+
const target = getActiveUsageTarget(config);
|
|
458
|
+
return target ? { epoch, target } : undefined;
|
|
459
|
+
}
|
|
460
|
+
function isValidUsageDecisionTarget(decision, config, epoch) {
|
|
461
|
+
return epoch === decision.epoch && matchesUsageTarget(config, decision.target);
|
|
462
|
+
}
|
|
463
|
+
function matchesUsageTarget(config, target) {
|
|
464
|
+
const entry = config.keys[target.keyIndex];
|
|
465
|
+
return entry !== undefined
|
|
466
|
+
&& (entry.name || `key-${target.keyIndex + 1}`) === target.keyName
|
|
467
|
+
&& entry.key === target.bearerToken;
|
|
468
|
+
}
|
|
469
|
+
function hasRateLimitedUsageWindow(result) {
|
|
470
|
+
return result.ok && result.usage.windows.some((window) => window.status === "rate-limited");
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* A recorded block can go stale: the plan was topped up, or the window reset before the
|
|
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");
|
|
482
|
+
}
|
|
483
|
+
function getRateLimitedUntil(usage, now, fallbackMs) {
|
|
484
|
+
let blockedUntil = now;
|
|
485
|
+
for (const window of usage.windows) {
|
|
486
|
+
if (window.status !== "rate-limited")
|
|
487
|
+
continue;
|
|
488
|
+
const resetTimes = [];
|
|
489
|
+
if (window.resetInSec !== undefined) {
|
|
490
|
+
const reset = now + window.resetInSec * 1000;
|
|
491
|
+
if (Number.isFinite(reset) && reset > now)
|
|
492
|
+
resetTimes.push(reset);
|
|
493
|
+
}
|
|
494
|
+
for (const timestamp of [window.resetAt, window.endAt]) {
|
|
495
|
+
if (!timestamp)
|
|
496
|
+
continue;
|
|
497
|
+
const parsed = Date.parse(timestamp);
|
|
498
|
+
if (Number.isFinite(parsed) && parsed > now)
|
|
499
|
+
resetTimes.push(parsed);
|
|
500
|
+
}
|
|
501
|
+
blockedUntil = Math.max(blockedUntil, resetTimes.length > 0 ? Math.max(...resetTimes) : now + fallbackMs);
|
|
502
|
+
}
|
|
503
|
+
return blockedUntil > now ? blockedUntil : now + fallbackMs;
|
|
504
|
+
}
|
|
505
|
+
function parseFixedWindowQuotaReset(message, now) {
|
|
506
|
+
const resetText = message.match(/\b(?:will\s+)?resets?(?:\s+at|\s+on)?\s+([^.;\n]+)/i)?.[1];
|
|
507
|
+
if (resetText) {
|
|
508
|
+
const parsed = Date.parse(resetText.trim());
|
|
509
|
+
if (Number.isFinite(parsed) && parsed > now)
|
|
510
|
+
return parsed;
|
|
511
|
+
}
|
|
512
|
+
return undefined;
|
|
513
|
+
}
|
|
514
|
+
function getEarliestQuotaReset(config, now) {
|
|
515
|
+
const resets = Object.values(config.quotaBlockedUntil).filter((reset) => typeof reset === "number" && Number.isFinite(reset) && reset > now);
|
|
516
|
+
return resets.length > 0 ? Math.min(...resets) : undefined;
|
|
517
|
+
}
|
|
518
|
+
function setQuotaBlock(config, keyIndex, blockedUntil, now) {
|
|
519
|
+
config.quotaBlockedUntil[keyIndex] = Math.max(getQuotaBlockedUntil(config, keyIndex, now) ?? 0, blockedUntil);
|
|
520
|
+
}
|
|
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
|
+
function formatUsageAmount(value) {
|
|
554
|
+
return value === undefined ? undefined : value.toLocaleString("en-US");
|
|
555
|
+
}
|
|
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
|
+
function formatUsageWindow(window, index) {
|
|
569
|
+
const label = window.name ?? `window ${index + 1}`;
|
|
570
|
+
const details = [`${label}: ${window.status}`];
|
|
571
|
+
const used = formatUsageAmount(window.used);
|
|
572
|
+
const limit = formatUsageAmount(window.limit);
|
|
573
|
+
const remaining = formatUsageAmount(window.remaining);
|
|
574
|
+
if (window.usagePercent !== undefined)
|
|
575
|
+
details.push(`${Math.round(window.usagePercent)}% used`);
|
|
576
|
+
if (used !== undefined && limit !== undefined)
|
|
577
|
+
details.push(`${used}/${limit} used`);
|
|
578
|
+
else if (used !== undefined)
|
|
579
|
+
details.push(`${used} used`);
|
|
580
|
+
if (remaining !== undefined)
|
|
581
|
+
details.push(`${remaining} remaining`);
|
|
582
|
+
if (window.resetInSec !== undefined)
|
|
583
|
+
details.push(`resets in ${formatResetIn(window.resetInSec)}`);
|
|
584
|
+
else if (window.resetAt)
|
|
585
|
+
details.push(`resets ${window.resetAt}`);
|
|
586
|
+
else if (window.endAt)
|
|
587
|
+
details.push(`ends ${window.endAt}`);
|
|
588
|
+
return details.join("; ");
|
|
589
|
+
}
|
|
590
|
+
export function formatUsageStatus(result) {
|
|
591
|
+
if (!result.ok) {
|
|
592
|
+
return `OpenCode usage unavailable${result.keyName ? ` for ${result.keyName}` : ""}: ${result.message}`;
|
|
593
|
+
}
|
|
594
|
+
if (result.usage.windows.length === 0)
|
|
595
|
+
return `OpenCode usage for ${result.keyName}: no usage windows returned.`;
|
|
596
|
+
return [`OpenCode usage for ${result.keyName}:`, ...result.usage.windows.map(formatUsageWindow)].join("\n");
|
|
597
|
+
}
|
|
598
|
+
export function shortUsageWindowLabel(name, index) {
|
|
599
|
+
if (!name)
|
|
600
|
+
return `w${index + 1}`;
|
|
601
|
+
if (/roll|5.?h|hour/i.test(name))
|
|
602
|
+
return "5h";
|
|
603
|
+
if (/week|wk/i.test(name))
|
|
604
|
+
return "wk";
|
|
605
|
+
if (/month|mo/i.test(name))
|
|
606
|
+
return "mo";
|
|
607
|
+
return name;
|
|
608
|
+
}
|
|
609
|
+
export function formatFooterUsage(keyName, windows, error) {
|
|
610
|
+
if (error !== undefined)
|
|
611
|
+
return `opencode-go [${keyName}] ${error}`;
|
|
612
|
+
if (windows.length === 0)
|
|
613
|
+
return `opencode-go [${keyName}] no usage data`;
|
|
614
|
+
const parts = windows.map((window, index) => {
|
|
615
|
+
const label = shortUsageWindowLabel(window.name, index);
|
|
616
|
+
const percent = usageWindowPercent(window);
|
|
617
|
+
return `${label} ${percent === undefined ? "?" : `${Math.round(percent)}%`}`;
|
|
618
|
+
});
|
|
619
|
+
const rateLimited = windows.some((window) => window.status === "rate-limited");
|
|
620
|
+
return `opencode-go [${keyName}] ${parts.join(" · ")}${rateLimited ? " · rate-limited" : ""}`;
|
|
621
|
+
}
|
|
622
|
+
function usageWindowPercent(window) {
|
|
623
|
+
if (window.usagePercent !== undefined)
|
|
624
|
+
return window.usagePercent;
|
|
625
|
+
if (window.used !== undefined && window.limit !== undefined && window.limit > 0)
|
|
626
|
+
return (window.used / window.limit) * 100;
|
|
627
|
+
return undefined;
|
|
628
|
+
}
|
|
629
|
+
function formatStatus(config, now = Date.now()) {
|
|
630
|
+
const watchdogStatus = `Watchdog: ${config.watchdogEnabled ? "on" : "off"} (${Math.ceil(getWatchdogIdleMs(config) / 1000)}s idle)`;
|
|
631
|
+
if (config.keys.length === 0) {
|
|
632
|
+
return `No keys configured. Use /opencode add <name> <key>.\n${watchdogStatus}`;
|
|
633
|
+
}
|
|
634
|
+
const cdMs = getCooldownMs(config);
|
|
635
|
+
return `${config.keys.map((key, i) => {
|
|
636
|
+
const marker = i === config.activeKeyIndex ? "→" : " ";
|
|
637
|
+
const cooldownStart = config.cooldowns[i];
|
|
638
|
+
let tag = "";
|
|
639
|
+
const quotaReset = getQuotaBlockedUntil(config, i, now);
|
|
640
|
+
if (quotaReset !== undefined) {
|
|
641
|
+
tag = ` [quota-blocked ${formatResetIn(Math.ceil((quotaReset - now) / 1000))}]`;
|
|
642
|
+
}
|
|
643
|
+
else if (cooldownStart !== undefined) {
|
|
644
|
+
const remaining = cdMs - (now - cooldownStart);
|
|
645
|
+
if (remaining > 0)
|
|
646
|
+
tag = ` [cooldown ${Math.ceil(remaining / 60_000)}m]`;
|
|
647
|
+
}
|
|
648
|
+
return `${marker} ${i + 1}. ${key.name}${tag}`;
|
|
649
|
+
}).join("\n")}\n${watchdogStatus}`;
|
|
650
|
+
}
|
|
651
|
+
function formatDuration(ms) {
|
|
652
|
+
const seconds = Math.max(0, Math.ceil(ms / 1000));
|
|
653
|
+
if (seconds < 60)
|
|
654
|
+
return `${seconds}s`;
|
|
655
|
+
const minutes = Math.floor(seconds / 60);
|
|
656
|
+
const remainder = seconds % 60;
|
|
657
|
+
return remainder ? `${minutes}m ${remainder}s` : `${minutes}m`;
|
|
658
|
+
}
|
|
659
|
+
function formatTimeoutInfo(info) {
|
|
660
|
+
const status = info.lastStatus === undefined ? "" : `, last HTTP ${info.lastStatus}`;
|
|
661
|
+
return `${info.phase.replaceAll("-", " ")} stalled after ${formatDuration(info.elapsedMs)} (${formatDuration(info.idleForMs)} idle${status})`;
|
|
662
|
+
}
|
|
663
|
+
function formatWatchdogEvents(events, now = Date.now()) {
|
|
664
|
+
if (events.length === 0)
|
|
665
|
+
return "No OpenCode Go watchdog timeouts recorded this session.";
|
|
666
|
+
return events
|
|
667
|
+
.slice()
|
|
668
|
+
.reverse()
|
|
669
|
+
.map((event, index) => {
|
|
670
|
+
const age = formatDuration(now - event.time);
|
|
671
|
+
const key = event.keyName ? ` key=${event.keyName}` : "";
|
|
672
|
+
const rotation = event.rotatedTo ? ` rotated=${event.rotatedTo}` : event.activeKey ? ` using=${event.activeKey}` : " rotated=none";
|
|
673
|
+
const status = event.lastStatus === undefined ? "" : ` status=${event.lastStatus}`;
|
|
674
|
+
return `${index + 1}. ${age} ago ${event.phase.replaceAll("-", " ")}${status}${key}${rotation} elapsed=${formatDuration(event.elapsedMs)} idle=${formatDuration(event.idleForMs)}`;
|
|
675
|
+
})
|
|
676
|
+
.join("\n");
|
|
677
|
+
}
|
|
678
|
+
// ---------------------------------------------------------------------------
|
|
679
|
+
// Extension
|
|
680
|
+
// ---------------------------------------------------------------------------
|
|
681
|
+
export function createOpencodeGoRotationExtension(options = {}) {
|
|
682
|
+
return function opencodeGoRotationExtension(pi) {
|
|
683
|
+
let config = createEmptyConfig();
|
|
684
|
+
let configError;
|
|
685
|
+
let watchdog;
|
|
686
|
+
let watchdogAbortPending = false;
|
|
687
|
+
let watchdogAbortMessage;
|
|
688
|
+
let watchdogTimeoutInfo;
|
|
689
|
+
let watchdogRequestTimedOut = false;
|
|
690
|
+
let usageDecisionEpoch = 0;
|
|
691
|
+
let requestRateLimitState;
|
|
692
|
+
const watchdogEvents = [];
|
|
693
|
+
let usageStatusCtx;
|
|
694
|
+
let usageStatusTimer;
|
|
695
|
+
let usageStatusDebounce;
|
|
696
|
+
let usageStatusKeyIndex;
|
|
697
|
+
let usageStatusFetchedAt = 0;
|
|
698
|
+
let usageStatusInFlight;
|
|
699
|
+
const statusTimerApi = options.timers ?? {
|
|
700
|
+
setTimeout: (callback, ms) => globalThis.setTimeout(callback, ms),
|
|
701
|
+
clearTimeout: (timer) => globalThis.clearTimeout(timer),
|
|
702
|
+
};
|
|
703
|
+
const now = () => options.clock?.now() ?? Date.now();
|
|
704
|
+
const fetchApi = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
705
|
+
function formatConfigError(error) {
|
|
706
|
+
if (error instanceof ConfigLoadError)
|
|
707
|
+
return error.message;
|
|
708
|
+
if (error instanceof Error)
|
|
709
|
+
return error.message;
|
|
710
|
+
return "Unknown configuration error";
|
|
711
|
+
}
|
|
712
|
+
function refreshConfig() {
|
|
713
|
+
try {
|
|
714
|
+
config = loadConfig();
|
|
715
|
+
configError = undefined;
|
|
716
|
+
return true;
|
|
717
|
+
}
|
|
718
|
+
catch (error) {
|
|
719
|
+
configError = formatConfigError(error);
|
|
720
|
+
return false;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
function mutateSharedConfig(mutator) {
|
|
724
|
+
try {
|
|
725
|
+
const updated = updateConfig(mutator);
|
|
726
|
+
config = updated.config;
|
|
727
|
+
configError = undefined;
|
|
728
|
+
return updated.result;
|
|
729
|
+
}
|
|
730
|
+
catch (error) {
|
|
731
|
+
configError = formatConfigError(error);
|
|
732
|
+
return undefined;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
function ensureConfig(ctx) {
|
|
736
|
+
if (refreshConfig())
|
|
737
|
+
return true;
|
|
738
|
+
ctx.ui.notify(`OpenCode: ${configError}. No configuration was changed.`, "error");
|
|
739
|
+
return false;
|
|
740
|
+
}
|
|
741
|
+
function setUsageStatus(text) {
|
|
742
|
+
const ctx = usageStatusCtx;
|
|
743
|
+
if (!ctx)
|
|
744
|
+
return;
|
|
745
|
+
try {
|
|
746
|
+
if (ctx.hasUI)
|
|
747
|
+
ctx.ui.setStatus(USAGE_STATUS_KEY, text);
|
|
748
|
+
}
|
|
749
|
+
catch {
|
|
750
|
+
usageStatusCtx = undefined;
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
function stopUsageStatusTimer() {
|
|
754
|
+
if (usageStatusTimer !== undefined) {
|
|
755
|
+
statusTimerApi.clearTimeout(usageStatusTimer);
|
|
756
|
+
usageStatusTimer = undefined;
|
|
757
|
+
}
|
|
758
|
+
if (usageStatusDebounce !== undefined) {
|
|
759
|
+
statusTimerApi.clearTimeout(usageStatusDebounce);
|
|
760
|
+
usageStatusDebounce = undefined;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
function startUsageStatusTimer() {
|
|
764
|
+
if (usageStatusTimer !== undefined)
|
|
765
|
+
return;
|
|
766
|
+
usageStatusTimer = statusTimerApi.setTimeout(() => {
|
|
767
|
+
usageStatusTimer = undefined;
|
|
768
|
+
const ctx = usageStatusCtx;
|
|
769
|
+
if (!ctx || !ctx.hasUI || !shouldWatchProvider(ctx.model?.provider))
|
|
770
|
+
return;
|
|
771
|
+
fireUsageStatusRefresh(ctx);
|
|
772
|
+
startUsageStatusTimer();
|
|
773
|
+
}, USAGE_STATUS_STALE_MS);
|
|
774
|
+
}
|
|
775
|
+
function fireUsageStatusRefresh(ctx, force = false) {
|
|
776
|
+
void refreshUsageStatus(ctx, force).catch(() => undefined);
|
|
777
|
+
}
|
|
778
|
+
function syncUsageStatus(ctx, force = false) {
|
|
779
|
+
usageStatusCtx = ctx;
|
|
780
|
+
if (shouldWatchProvider(ctx.model?.provider)) {
|
|
781
|
+
startUsageStatusTimer();
|
|
782
|
+
fireUsageStatusRefresh(ctx, force);
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
stopUsageStatusTimer();
|
|
786
|
+
setUsageStatus(undefined);
|
|
787
|
+
}
|
|
788
|
+
function scheduleUsageStatusRefresh(ctx) {
|
|
789
|
+
usageStatusCtx = ctx;
|
|
790
|
+
if (!shouldWatchProvider(ctx.model?.provider)) {
|
|
791
|
+
stopUsageStatusTimer();
|
|
792
|
+
setUsageStatus(undefined);
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
startUsageStatusTimer();
|
|
796
|
+
if (usageStatusDebounce !== undefined)
|
|
797
|
+
statusTimerApi.clearTimeout(usageStatusDebounce);
|
|
798
|
+
usageStatusDebounce = statusTimerApi.setTimeout(() => {
|
|
799
|
+
usageStatusDebounce = undefined;
|
|
800
|
+
fireUsageStatusRefresh(ctx);
|
|
801
|
+
}, USAGE_STATUS_DEBOUNCE_MS);
|
|
802
|
+
}
|
|
803
|
+
async function refreshUsageStatus(ctx, force = false) {
|
|
804
|
+
usageStatusCtx = ctx;
|
|
805
|
+
if (!ctx.hasUI)
|
|
806
|
+
return;
|
|
807
|
+
if (!refreshConfig())
|
|
808
|
+
return;
|
|
809
|
+
const target = getActiveUsageTarget(config);
|
|
810
|
+
if (!target) {
|
|
811
|
+
setUsageStatus("opencode-go: no keys configured");
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
const currentTime = now();
|
|
815
|
+
const keyChanged = target.keyIndex !== usageStatusKeyIndex;
|
|
816
|
+
if (!force && !keyChanged && currentTime - usageStatusFetchedAt < USAGE_STATUS_REFRESH_MS)
|
|
817
|
+
return;
|
|
818
|
+
if (usageStatusInFlight)
|
|
819
|
+
return;
|
|
820
|
+
const request = (async () => {
|
|
821
|
+
const usage = await fetchOpenCodeGoUsage(target, fetchApi, options.timers);
|
|
822
|
+
usageStatusKeyIndex = target.keyIndex;
|
|
823
|
+
usageStatusFetchedAt = now();
|
|
824
|
+
if (usageStatusCtx !== ctx)
|
|
825
|
+
return;
|
|
826
|
+
if (!refreshConfig() || getActiveUsageTarget(config)?.keyIndex !== target.keyIndex)
|
|
827
|
+
return;
|
|
828
|
+
setUsageStatus(usage.ok ? formatFooterUsage(target.keyName, usage.usage.windows) : formatFooterUsage(target.keyName, [], usage.message));
|
|
829
|
+
})();
|
|
830
|
+
usageStatusInFlight = request;
|
|
831
|
+
try {
|
|
832
|
+
await request;
|
|
833
|
+
}
|
|
834
|
+
finally {
|
|
835
|
+
if (usageStatusInFlight === request)
|
|
836
|
+
usageStatusInFlight = undefined;
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
function applySynchronizedActiveKey(ctx) {
|
|
840
|
+
if (!refreshConfig())
|
|
841
|
+
return undefined;
|
|
842
|
+
const availableIndex = pickAvailableKeyIndex(config, now());
|
|
843
|
+
if (availableIndex !== undefined && availableIndex !== config.activeKeyIndex) {
|
|
844
|
+
const selectedIndex = mutateSharedConfig((freshConfig) => {
|
|
845
|
+
const freshAvailableIndex = pickAvailableKeyIndex(freshConfig, now());
|
|
846
|
+
if (freshAvailableIndex !== undefined)
|
|
847
|
+
freshConfig.activeKeyIndex = freshAvailableIndex;
|
|
848
|
+
return freshAvailableIndex;
|
|
849
|
+
});
|
|
850
|
+
if (selectedIndex === undefined)
|
|
851
|
+
return undefined;
|
|
852
|
+
}
|
|
853
|
+
return applyActiveKey(config, ctx.modelRegistry, now());
|
|
854
|
+
}
|
|
855
|
+
function invalidateAutomaticDecisions() {
|
|
856
|
+
usageDecisionEpoch++;
|
|
857
|
+
}
|
|
858
|
+
function beginProviderRequest(ctx) {
|
|
859
|
+
invalidateAutomaticDecisions();
|
|
860
|
+
if (applySynchronizedActiveKey(ctx) === undefined) {
|
|
861
|
+
requestRateLimitState = undefined;
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
const decision = captureUsageDecision(config, usageDecisionEpoch);
|
|
865
|
+
requestRateLimitState = decision ? { decision, responseHandled: false } : undefined;
|
|
866
|
+
}
|
|
867
|
+
function getCurrentRequestRateLimitState() {
|
|
868
|
+
if (!requestRateLimitState)
|
|
869
|
+
return undefined;
|
|
870
|
+
return isValidUsageDecisionTarget(requestRateLimitState.decision, config, usageDecisionEpoch)
|
|
871
|
+
? requestRateLimitState
|
|
872
|
+
: undefined;
|
|
873
|
+
}
|
|
874
|
+
function markResponseRateLimitHandled(decision) {
|
|
875
|
+
requestRateLimitState = {
|
|
876
|
+
decision: { ...decision, epoch: usageDecisionEpoch },
|
|
877
|
+
responseHandled: true,
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
function currentRotationOperation(currentTime) {
|
|
881
|
+
return captureRotationOperation(config, currentTime, config.activeKeyIndex, usageDecisionEpoch);
|
|
882
|
+
}
|
|
883
|
+
/** Post-await effects are allowed only while the completed decision still owns the state. */
|
|
884
|
+
function isCompletionCurrent(outcome) {
|
|
885
|
+
return (outcome.kind === "rotated" || outcome.kind === "none")
|
|
886
|
+
&& refreshConfig()
|
|
887
|
+
&& isRotationOperationCurrent(outcome.completion, config, usageDecisionEpoch);
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* A benched key can become usable again after we recorded its block. Probe the blocked
|
|
891
|
+
* keys without mutating anything; only a positive reading is collected as candidate
|
|
892
|
+
* headroom. The probes are data-only, so a stale result can never be applied without the
|
|
893
|
+
* guarded commit re-checking the credential, block and cooldown it was sampled from.
|
|
894
|
+
*/
|
|
895
|
+
async function probeRecoveredHeadroom(currentTime, skipKeyIndex) {
|
|
896
|
+
if (!refreshConfig())
|
|
897
|
+
return [];
|
|
898
|
+
const candidates = getQuotaBlockedTargets(config, currentTime, skipKeyIndex)
|
|
899
|
+
.map((target) => captureSelectionSnapshot(config, currentTime, target.keyIndex))
|
|
900
|
+
.filter((snapshot) => snapshot !== undefined);
|
|
901
|
+
const recovered = [];
|
|
902
|
+
for (const candidate of candidates) {
|
|
903
|
+
const usage = await fetchOpenCodeGoUsage(candidate, fetchApi, options.timers);
|
|
904
|
+
if (hasConfirmedHeadroom(usage))
|
|
905
|
+
recovered.push(candidate);
|
|
906
|
+
// Keep the in-memory config aligned with writers active during the probes.
|
|
907
|
+
if (!refreshConfig())
|
|
908
|
+
break;
|
|
909
|
+
}
|
|
910
|
+
return recovered;
|
|
911
|
+
}
|
|
912
|
+
function selectNextKey(mode, freshConfig, startIndex, currentTime) {
|
|
913
|
+
return mode.kind === "quota"
|
|
914
|
+
? blockQuotaAndSelectNext(freshConfig, startIndex, mode.blockedUntil, currentTime, mode.authoritative)
|
|
915
|
+
: rotateToNextKey(freshConfig, { now: currentTime });
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* Block the failed key and select a replacement, re-probing benched keys only when the
|
|
919
|
+
* fast path found nothing. Every mutation re-validates the operation snapshot under the
|
|
920
|
+
* lock, so a decision invalidated while probes were in flight is cancelled instead of
|
|
921
|
+
* being rebased onto the newer state.
|
|
922
|
+
*/
|
|
923
|
+
async function rotateWithRecovery(ctx, operation, currentTime, mode) {
|
|
924
|
+
const startIndex = operation.selection.keyIndex;
|
|
925
|
+
const fast = mutateSharedConfig((freshConfig) => {
|
|
926
|
+
if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch)) {
|
|
927
|
+
return { outcome: "cancelled" };
|
|
928
|
+
}
|
|
929
|
+
return { outcome: "done", value: selectNextKey(mode, freshConfig, startIndex, currentTime) };
|
|
930
|
+
});
|
|
931
|
+
if (fast === undefined)
|
|
932
|
+
return { kind: "unavailable" };
|
|
933
|
+
if (fast.outcome === "cancelled")
|
|
934
|
+
return { kind: "cancelled" };
|
|
935
|
+
if (fast.value !== undefined && fast.value !== startIndex) {
|
|
936
|
+
const completion = currentRotationOperation(currentTime);
|
|
937
|
+
return completion ? { kind: "rotated", keyIndex: fast.value, completion } : { kind: "cancelled" };
|
|
938
|
+
}
|
|
939
|
+
// Snapshot the state this operation just produced, so a later commit can detect any
|
|
940
|
+
// external change to the same credential, block, cooldown or selection.
|
|
941
|
+
const retryOperation = currentRotationOperation(currentTime);
|
|
942
|
+
const failedKey = captureSelectionSnapshot(config, currentTime, startIndex);
|
|
943
|
+
if (!retryOperation || !failedKey)
|
|
944
|
+
return { kind: "cancelled" };
|
|
945
|
+
const recovered = await probeRecoveredHeadroom(currentTime, startIndex);
|
|
946
|
+
if (configError)
|
|
947
|
+
return { kind: "unavailable" };
|
|
948
|
+
if (usageDecisionEpoch !== operation.epoch)
|
|
949
|
+
return { kind: "cancelled" };
|
|
950
|
+
if (recovered.length === 0) {
|
|
951
|
+
// Still verify the state this operation owns: a shared writer may have moved the
|
|
952
|
+
// selection, credential, block or cooldown while the probes were in flight.
|
|
953
|
+
const current = matchesSelectionSnapshot(config, failedKey, currentTime)
|
|
954
|
+
&& isRotationOperationCurrent(retryOperation, config, usageDecisionEpoch);
|
|
955
|
+
return current ? { kind: "none", completion: retryOperation } : { kind: "cancelled" };
|
|
956
|
+
}
|
|
957
|
+
const commit = mutateSharedConfig((freshConfig) => {
|
|
958
|
+
if (!isRotationOperationCurrent(retryOperation, freshConfig, usageDecisionEpoch))
|
|
959
|
+
return { outcome: "cancelled" };
|
|
960
|
+
if (!matchesSelectionSnapshot(freshConfig, failedKey, currentTime))
|
|
961
|
+
return { outcome: "cancelled" };
|
|
962
|
+
if (!recovered.every((snapshot) => matchesSelectionSnapshot(freshConfig, snapshot, currentTime)))
|
|
963
|
+
return { outcome: "cancelled" };
|
|
964
|
+
for (const snapshot of recovered) {
|
|
965
|
+
delete freshConfig.quotaBlockedUntil[snapshot.keyIndex];
|
|
966
|
+
delete freshConfig.cooldowns[snapshot.keyIndex];
|
|
967
|
+
}
|
|
968
|
+
return { outcome: "done", value: selectNextKey(mode, freshConfig, startIndex, currentTime) };
|
|
969
|
+
});
|
|
970
|
+
if (commit === undefined)
|
|
971
|
+
return { kind: "unavailable" };
|
|
972
|
+
if (commit.outcome === "cancelled")
|
|
973
|
+
return { kind: "cancelled" };
|
|
974
|
+
for (const snapshot of recovered) {
|
|
975
|
+
ctx.ui.notify(`OpenCode: ${snapshot.keyName} has headroom again → quota block cleared`, "info");
|
|
976
|
+
}
|
|
977
|
+
const completion = currentRotationOperation(currentTime);
|
|
978
|
+
if (!completion)
|
|
979
|
+
return { kind: "cancelled" };
|
|
980
|
+
const selected = commit.value;
|
|
981
|
+
return selected === undefined || selected === startIndex
|
|
982
|
+
? { kind: "none", completion }
|
|
983
|
+
: { kind: "rotated", keyIndex: selected, completion };
|
|
984
|
+
}
|
|
985
|
+
/** Guarded startup/reload recovery: clears only blocks whose snapshot is still current. */
|
|
986
|
+
async function recoverQuotaBlocksGuarded(ctx, operation, currentTime) {
|
|
987
|
+
const recovered = await probeRecoveredHeadroom(currentTime);
|
|
988
|
+
if (configError)
|
|
989
|
+
return "unavailable";
|
|
990
|
+
if (usageDecisionEpoch !== operation.epoch)
|
|
991
|
+
return "cancelled";
|
|
992
|
+
if (recovered.length === 0) {
|
|
993
|
+
return isRotationOperationCurrent(operation, config, usageDecisionEpoch) ? "none" : "cancelled";
|
|
994
|
+
}
|
|
995
|
+
const commit = mutateSharedConfig((freshConfig) => {
|
|
996
|
+
if (!isRotationOperationCurrent(operation, freshConfig, usageDecisionEpoch))
|
|
997
|
+
return { outcome: "cancelled" };
|
|
998
|
+
if (!recovered.every((snapshot) => matchesSelectionSnapshot(freshConfig, snapshot, currentTime)))
|
|
999
|
+
return { outcome: "cancelled" };
|
|
1000
|
+
for (const snapshot of recovered) {
|
|
1001
|
+
delete freshConfig.quotaBlockedUntil[snapshot.keyIndex];
|
|
1002
|
+
delete freshConfig.cooldowns[snapshot.keyIndex];
|
|
1003
|
+
}
|
|
1004
|
+
return { outcome: "done", value: true };
|
|
1005
|
+
});
|
|
1006
|
+
if (commit === undefined)
|
|
1007
|
+
return "unavailable";
|
|
1008
|
+
if (commit.outcome === "cancelled")
|
|
1009
|
+
return "cancelled";
|
|
1010
|
+
for (const snapshot of recovered) {
|
|
1011
|
+
ctx.ui.notify(`OpenCode: ${snapshot.keyName} has headroom again → quota block cleared`, "info");
|
|
1012
|
+
}
|
|
1013
|
+
return "recovered";
|
|
1014
|
+
}
|
|
1015
|
+
function reportQuotaExhausted(ctx, exhaustedName, currentTime) {
|
|
1016
|
+
if (configError) {
|
|
1017
|
+
ctx.ui.notify(`OpenCode: ${configError}. Automatic rotation was skipped.`, "error");
|
|
1018
|
+
return;
|
|
1019
|
+
}
|
|
1020
|
+
invalidateAutomaticDecisions();
|
|
1021
|
+
const earliestReset = getEarliestQuotaReset(config, currentTime);
|
|
1022
|
+
const reset = earliestReset === undefined
|
|
1023
|
+
? "an unknown reset time"
|
|
1024
|
+
: formatResetIn(Math.ceil((earliestReset - currentTime) / 1000));
|
|
1025
|
+
ctx.ui.notify(`OpenCode: ${exhaustedName} reached its plan quota; all configured keys are quota-blocked. Earliest reset in ${reset}.`, "warning");
|
|
1026
|
+
}
|
|
1027
|
+
function stopWatchdog() {
|
|
1028
|
+
const timeoutInfo = watchdog?.consumeTimeoutInfo();
|
|
1029
|
+
watchdog?.stop();
|
|
1030
|
+
watchdog = undefined;
|
|
1031
|
+
return timeoutInfo;
|
|
1032
|
+
}
|
|
1033
|
+
function resetWatchdogAbortState() {
|
|
1034
|
+
watchdogAbortPending = false;
|
|
1035
|
+
watchdogAbortMessage = undefined;
|
|
1036
|
+
watchdogTimeoutInfo = undefined;
|
|
1037
|
+
}
|
|
1038
|
+
function clearWatchdogTimeoutGuard() {
|
|
1039
|
+
watchdogRequestTimedOut = false;
|
|
1040
|
+
}
|
|
1041
|
+
function recordWatchdogEvent(event) {
|
|
1042
|
+
watchdogEvents.push(event);
|
|
1043
|
+
while (watchdogEvents.length > 10)
|
|
1044
|
+
watchdogEvents.shift();
|
|
1045
|
+
}
|
|
1046
|
+
function rotateForWatchdog(ctx, timeoutInfo, rateLimitAlreadyRotated) {
|
|
1047
|
+
if (!refreshConfig())
|
|
1048
|
+
return { rotated: false };
|
|
1049
|
+
const currentTime = now();
|
|
1050
|
+
if (config.keys.length <= 1)
|
|
1051
|
+
return { rotated: false };
|
|
1052
|
+
if (shouldRotateAfterWatchdogTimeout(timeoutInfo, rateLimitAlreadyRotated)) {
|
|
1053
|
+
const previousIndex = config.activeKeyIndex;
|
|
1054
|
+
const nextIndex = mutateSharedConfig((freshConfig) => rotateToNextKey(freshConfig, { now: currentTime }));
|
|
1055
|
+
if (nextIndex === undefined)
|
|
1056
|
+
return { keyName: applyActiveKey(config, ctx.modelRegistry, currentTime), rotated: false };
|
|
1057
|
+
const rotated = nextIndex !== previousIndex;
|
|
1058
|
+
if (rotated)
|
|
1059
|
+
invalidateAutomaticDecisions();
|
|
1060
|
+
return { keyName: applyActiveKey(config, ctx.modelRegistry, currentTime), rotated };
|
|
1061
|
+
}
|
|
1062
|
+
return { keyName: applyActiveKey(config, ctx.modelRegistry, currentTime), rotated: false };
|
|
1063
|
+
}
|
|
1064
|
+
function startWatchdog(ctx) {
|
|
1065
|
+
if (!refreshConfig())
|
|
1066
|
+
return;
|
|
1067
|
+
applyActiveKey(config, ctx.modelRegistry, now());
|
|
1068
|
+
stopWatchdog();
|
|
1069
|
+
resetWatchdogAbortState();
|
|
1070
|
+
clearWatchdogTimeoutGuard();
|
|
1071
|
+
if (!config.watchdogEnabled)
|
|
1072
|
+
return;
|
|
1073
|
+
const idleMs = getWatchdogIdleMs(config);
|
|
1074
|
+
watchdog = new ProviderIdleWatchdog({
|
|
1075
|
+
idleMs,
|
|
1076
|
+
onTimeout: () => {
|
|
1077
|
+
const rateLimitAlreadyHandled = getCurrentRequestRateLimitState()?.responseHandled ?? false;
|
|
1078
|
+
invalidateAutomaticDecisions();
|
|
1079
|
+
watchdogRequestTimedOut = true;
|
|
1080
|
+
const timeoutInfo = watchdog?.currentTimeoutInfo() ?? {
|
|
1081
|
+
phase: "waiting-for-response",
|
|
1082
|
+
idleMs,
|
|
1083
|
+
elapsedMs: idleMs,
|
|
1084
|
+
idleForMs: idleMs,
|
|
1085
|
+
};
|
|
1086
|
+
const previousKey = config.keys[config.activeKeyIndex]?.name;
|
|
1087
|
+
const rotation = rotateForWatchdog(ctx, timeoutInfo, rateLimitAlreadyHandled);
|
|
1088
|
+
watchdogTimeoutInfo = timeoutInfo;
|
|
1089
|
+
recordWatchdogEvent({
|
|
1090
|
+
time: now(),
|
|
1091
|
+
keyName: previousKey,
|
|
1092
|
+
rotatedTo: rotation.rotated ? rotation.keyName : undefined,
|
|
1093
|
+
activeKey: rotation.keyName,
|
|
1094
|
+
...timeoutInfo,
|
|
1095
|
+
});
|
|
1096
|
+
watchdogAbortPending = true;
|
|
1097
|
+
watchdogAbortMessage = rotation.keyName
|
|
1098
|
+
? `OpenCode Go timeout: ${formatTimeoutInfo(timeoutInfo)}; ${rotation.rotated ? "rotated to" : "using"} ${rotation.keyName}; retrying.`
|
|
1099
|
+
: `OpenCode Go timeout: ${formatTimeoutInfo(timeoutInfo)}; no other key available.`;
|
|
1100
|
+
ctx.ui.notify(watchdogAbortMessage, rotation.keyName ? "info" : "warning");
|
|
1101
|
+
ctx.abort();
|
|
1102
|
+
},
|
|
1103
|
+
timers: options.timers,
|
|
1104
|
+
clock: options.clock,
|
|
1105
|
+
});
|
|
1106
|
+
watchdog.start();
|
|
1107
|
+
}
|
|
1108
|
+
async function autoImportFromAuth(ctx) {
|
|
1109
|
+
const authKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
|
|
1110
|
+
if (!authKey)
|
|
1111
|
+
return false;
|
|
1112
|
+
const imported = mutateSharedConfig((freshConfig) => {
|
|
1113
|
+
if (freshConfig.keys.some((entry) => entry.key === authKey))
|
|
1114
|
+
return false;
|
|
1115
|
+
freshConfig.keys.push({ name: "auth", key: authKey });
|
|
1116
|
+
return true;
|
|
1117
|
+
});
|
|
1118
|
+
return imported === true;
|
|
1119
|
+
}
|
|
1120
|
+
pi.on("session_start", async (event, ctx) => {
|
|
1121
|
+
lastAppliedRuntimeKeys.delete(ctx.modelRegistry);
|
|
1122
|
+
invalidateAutomaticDecisions();
|
|
1123
|
+
requestRateLimitState = undefined;
|
|
1124
|
+
clearWatchdogTimeoutGuard();
|
|
1125
|
+
setUsageStatus(undefined);
|
|
1126
|
+
stopUsageStatusTimer();
|
|
1127
|
+
usageStatusCtx = ctx;
|
|
1128
|
+
if (!ensureConfig(ctx))
|
|
1129
|
+
return;
|
|
1130
|
+
// A block recorded in an earlier session can be stale: the plan was topped up, or the
|
|
1131
|
+
// window reset before the deadline we stored. Re-check before it decides which key this
|
|
1132
|
+
// session uses, rather than benching a key that is usable again -- or leaving every key
|
|
1133
|
+
// held by a block with nothing left to rotate to.
|
|
1134
|
+
if (config.keys.length > 0) {
|
|
1135
|
+
const currentTime = now();
|
|
1136
|
+
const activeBlocked = getQuotaBlockedUntil(config, config.activeKeyIndex, currentTime) !== undefined;
|
|
1137
|
+
if (activeBlocked || pickAvailableKeyIndex(config, currentTime) === undefined) {
|
|
1138
|
+
const operation = currentRotationOperation(currentTime);
|
|
1139
|
+
if (!operation)
|
|
1140
|
+
return;
|
|
1141
|
+
const recovery = await recoverQuotaBlocksGuarded(ctx, operation, currentTime);
|
|
1142
|
+
// A startup continuation invalidated while probes were in flight must not
|
|
1143
|
+
// clear blocks or re-apply a key on top of the newer decision.
|
|
1144
|
+
if (recovery === "cancelled")
|
|
1145
|
+
return;
|
|
1146
|
+
if (usageDecisionEpoch !== operation.epoch)
|
|
1147
|
+
return;
|
|
1148
|
+
if (!refreshConfig())
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
// On reload: re-apply active key, skip auto-import
|
|
1153
|
+
if (event.reason === "reload") {
|
|
1154
|
+
const keyName = applySynchronizedActiveKey(ctx);
|
|
1155
|
+
if (keyName)
|
|
1156
|
+
ctx.ui.notify(`OpenCode: Active key → ${keyName}`, "info");
|
|
1157
|
+
syncUsageStatus(ctx, true);
|
|
1158
|
+
return;
|
|
1159
|
+
}
|
|
1160
|
+
if (config.keys.length === 0) {
|
|
1161
|
+
if (await autoImportFromAuth(ctx)) {
|
|
1162
|
+
const keyName = applySynchronizedActiveKey(ctx);
|
|
1163
|
+
if (keyName)
|
|
1164
|
+
ctx.ui.notify(`OpenCode: Imported key from auth.json → ${keyName}`, "info");
|
|
1165
|
+
}
|
|
1166
|
+
else if (configError) {
|
|
1167
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
else {
|
|
1171
|
+
ctx.ui.notify("OpenCode: No keys configured. Use /opencode add <name> <key>", "warning");
|
|
1172
|
+
setUsageStatus(undefined);
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
const keyName = applySynchronizedActiveKey(ctx);
|
|
1177
|
+
if (keyName)
|
|
1178
|
+
ctx.ui.notify(`OpenCode: Active key → ${keyName}`, "info");
|
|
1179
|
+
syncUsageStatus(ctx, true);
|
|
1180
|
+
});
|
|
1181
|
+
pi.on("model_select", (_event, ctx) => {
|
|
1182
|
+
syncUsageStatus(ctx, true);
|
|
1183
|
+
});
|
|
1184
|
+
pi.on("before_provider_request", (event, ctx) => {
|
|
1185
|
+
syncUsageStatus(ctx);
|
|
1186
|
+
if (!shouldWatchProvider(ctx.model?.provider)) {
|
|
1187
|
+
invalidateAutomaticDecisions();
|
|
1188
|
+
requestRateLimitState = undefined;
|
|
1189
|
+
stopWatchdog();
|
|
1190
|
+
resetWatchdogAbortState();
|
|
1191
|
+
clearWatchdogTimeoutGuard();
|
|
1192
|
+
return;
|
|
1193
|
+
}
|
|
1194
|
+
beginProviderRequest(ctx);
|
|
1195
|
+
startWatchdog(ctx);
|
|
1196
|
+
return sanitizeReasoningPayload(event.payload);
|
|
1197
|
+
});
|
|
1198
|
+
pi.on("message_update", (event) => {
|
|
1199
|
+
const message = event.message;
|
|
1200
|
+
if (message.role !== "assistant" || !shouldWatchProvider(message.provider))
|
|
1201
|
+
return;
|
|
1202
|
+
watchdog?.streamActivity();
|
|
1203
|
+
});
|
|
1204
|
+
pi.on("message_end", async (event, ctx) => {
|
|
1205
|
+
const message = event.message;
|
|
1206
|
+
if (message.role !== "assistant" || message.provider !== PROVIDER)
|
|
1207
|
+
return;
|
|
1208
|
+
const timeoutInfo = stopWatchdog() ?? watchdogTimeoutInfo;
|
|
1209
|
+
if (timeoutInfo || watchdogAbortPending) {
|
|
1210
|
+
const errorMessage = watchdogAbortMessage ?? `OpenCode Go timeout: ${timeoutInfo ? formatTimeoutInfo(timeoutInfo) : "no provider activity"}; retrying.`;
|
|
1211
|
+
resetWatchdogAbortState();
|
|
1212
|
+
return {
|
|
1213
|
+
message: {
|
|
1214
|
+
...message,
|
|
1215
|
+
stopReason: "error",
|
|
1216
|
+
errorMessage,
|
|
1217
|
+
},
|
|
1218
|
+
};
|
|
1219
|
+
}
|
|
1220
|
+
if (message.stopReason !== "error") {
|
|
1221
|
+
invalidateAutomaticDecisions();
|
|
1222
|
+
return;
|
|
1223
|
+
}
|
|
1224
|
+
const rateLimitKind = classifyRateLimitError(message.errorMessage ?? "");
|
|
1225
|
+
if (!rateLimitKind) {
|
|
1226
|
+
invalidateAutomaticDecisions();
|
|
1227
|
+
return;
|
|
1228
|
+
}
|
|
1229
|
+
if (!refreshConfig())
|
|
1230
|
+
return;
|
|
1231
|
+
const requestState = getCurrentRequestRateLimitState();
|
|
1232
|
+
if (!requestState)
|
|
1233
|
+
return;
|
|
1234
|
+
if (rateLimitKind === "fixed-window-quota") {
|
|
1235
|
+
const currentTime = now();
|
|
1236
|
+
const authoritativeReset = parseFixedWindowQuotaReset(message.errorMessage ?? "", currentTime);
|
|
1237
|
+
const blockedUntil = authoritativeReset ?? currentTime + getCooldownMs(config);
|
|
1238
|
+
const exhaustedName = config.keys[requestState.decision.target.keyIndex]?.name
|
|
1239
|
+
|| `key-${requestState.decision.target.keyIndex + 1}`;
|
|
1240
|
+
if (requestState.responseHandled) {
|
|
1241
|
+
const persisted = mutateSharedConfig((freshConfig) => {
|
|
1242
|
+
// The handled response may upgrade the reset of its own credential, but never
|
|
1243
|
+
// of whatever credential now occupies that index.
|
|
1244
|
+
if (!matchesUsageTarget(freshConfig, requestState.decision.target))
|
|
1245
|
+
return false;
|
|
1246
|
+
if (authoritativeReset === undefined) {
|
|
1247
|
+
setQuotaBlock(freshConfig, requestState.decision.target.keyIndex, blockedUntil, currentTime);
|
|
1248
|
+
}
|
|
1249
|
+
else {
|
|
1250
|
+
freshConfig.quotaBlockedUntil[requestState.decision.target.keyIndex] = authoritativeReset;
|
|
1251
|
+
}
|
|
1252
|
+
return true;
|
|
1253
|
+
});
|
|
1254
|
+
if (persisted !== true && configError)
|
|
1255
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1256
|
+
invalidateAutomaticDecisions();
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
const operation = currentRotationOperation(currentTime);
|
|
1260
|
+
if (!operation || operation.selection.keyIndex !== requestState.decision.target.keyIndex)
|
|
1261
|
+
return;
|
|
1262
|
+
const outcome = await rotateWithRecovery(ctx, operation, currentTime, {
|
|
1263
|
+
kind: "quota",
|
|
1264
|
+
blockedUntil,
|
|
1265
|
+
authoritative: authoritativeReset !== undefined,
|
|
1266
|
+
});
|
|
1267
|
+
if (outcome.kind === "cancelled")
|
|
1268
|
+
return;
|
|
1269
|
+
if (outcome.kind === "unavailable") {
|
|
1270
|
+
if (usageDecisionEpoch !== operation.epoch)
|
|
1271
|
+
return;
|
|
1272
|
+
reportQuotaExhausted(ctx, exhaustedName, currentTime);
|
|
1273
|
+
return;
|
|
1274
|
+
}
|
|
1275
|
+
if (!isCompletionCurrent(outcome))
|
|
1276
|
+
return;
|
|
1277
|
+
if (outcome.kind === "none") {
|
|
1278
|
+
reportQuotaExhausted(ctx, exhaustedName, currentTime);
|
|
1279
|
+
return;
|
|
1280
|
+
}
|
|
1281
|
+
invalidateAutomaticDecisions();
|
|
1282
|
+
const keyName = applyActiveKey(config, ctx.modelRegistry, currentTime) ?? `key-${outcome.keyIndex + 1}`;
|
|
1283
|
+
ctx.ui.notify(`OpenCode: ${exhaustedName} reached its plan quota → rotated to ${keyName}`, "info");
|
|
1284
|
+
return;
|
|
1285
|
+
}
|
|
1286
|
+
if (requestState.responseHandled) {
|
|
1287
|
+
invalidateAutomaticDecisions();
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
if (config.keys.length <= 1) {
|
|
1291
|
+
invalidateAutomaticDecisions();
|
|
1292
|
+
ctx.ui.notify("OpenCode: Rate limited — no other keys to rotate to.", "warning");
|
|
1293
|
+
return;
|
|
1294
|
+
}
|
|
1295
|
+
const currentTime = now();
|
|
1296
|
+
const operation = currentRotationOperation(currentTime);
|
|
1297
|
+
if (!operation || operation.selection.keyIndex !== requestState.decision.target.keyIndex)
|
|
1298
|
+
return;
|
|
1299
|
+
const outcome = await rotateWithRecovery(ctx, operation, currentTime, { kind: "cooldown" });
|
|
1300
|
+
if (outcome.kind === "cancelled")
|
|
1301
|
+
return;
|
|
1302
|
+
if (outcome.kind === "unavailable") {
|
|
1303
|
+
if (usageDecisionEpoch !== operation.epoch)
|
|
1304
|
+
return;
|
|
1305
|
+
ctx.ui.notify(`OpenCode: ${configError}. Automatic rotation was skipped.`, "error");
|
|
1306
|
+
return;
|
|
1307
|
+
}
|
|
1308
|
+
// Never finalize a decision that lost ownership while the rotation was in flight.
|
|
1309
|
+
if (!isCompletionCurrent(outcome))
|
|
1310
|
+
return;
|
|
1311
|
+
if (outcome.kind === "none") {
|
|
1312
|
+
invalidateAutomaticDecisions();
|
|
1313
|
+
ctx.ui.notify("OpenCode: Rate limited; all other keys are quota-blocked.", "warning");
|
|
1314
|
+
return;
|
|
1315
|
+
}
|
|
1316
|
+
invalidateAutomaticDecisions();
|
|
1317
|
+
const keyName = applyActiveKey(config, ctx.modelRegistry, currentTime);
|
|
1318
|
+
ctx.ui.notify(`OpenCode: Rate-limited → rotated to ${keyName ?? `key-${outcome.keyIndex + 1}`}`, "info");
|
|
1319
|
+
});
|
|
1320
|
+
pi.on("after_provider_response", async (event, ctx) => {
|
|
1321
|
+
if (ctx.model?.provider !== PROVIDER)
|
|
1322
|
+
return;
|
|
1323
|
+
watchdog?.response(event.status);
|
|
1324
|
+
if (event.status !== 429 && event.status !== 401)
|
|
1325
|
+
return;
|
|
1326
|
+
if (watchdogRequestTimedOut)
|
|
1327
|
+
return;
|
|
1328
|
+
if (!refreshConfig())
|
|
1329
|
+
return;
|
|
1330
|
+
const requestState = getCurrentRequestRateLimitState();
|
|
1331
|
+
if (!requestState)
|
|
1332
|
+
return;
|
|
1333
|
+
const decision = requestState.decision;
|
|
1334
|
+
const operation = currentRotationOperation(now());
|
|
1335
|
+
if (!operation || operation.selection.keyIndex !== decision.target.keyIndex)
|
|
1336
|
+
return;
|
|
1337
|
+
// Bookkeeping for this response is allowed only while it still owns the request state.
|
|
1338
|
+
const markHandledIfOwned = () => {
|
|
1339
|
+
if (requestRateLimitState === requestState)
|
|
1340
|
+
markResponseRateLimitHandled(decision);
|
|
1341
|
+
};
|
|
1342
|
+
if (event.status === 401)
|
|
1343
|
+
requestRateLimitState = undefined;
|
|
1344
|
+
const usage = await fetchOpenCodeGoUsage(decision.target, fetchApi, options.timers);
|
|
1345
|
+
if (!refreshConfig())
|
|
1346
|
+
return;
|
|
1347
|
+
if (!isRotationOperationCurrent(operation, config, usageDecisionEpoch))
|
|
1348
|
+
return;
|
|
1349
|
+
const currentTime = now();
|
|
1350
|
+
const exhaustedName = config.keys[decision.target.keyIndex]?.name || `key-${decision.target.keyIndex + 1}`;
|
|
1351
|
+
if (usage.ok && hasRateLimitedUsageWindow(usage)) {
|
|
1352
|
+
const outcome = await rotateWithRecovery(ctx, operation, currentTime, {
|
|
1353
|
+
kind: "quota",
|
|
1354
|
+
blockedUntil: getRateLimitedUntil(usage.usage, currentTime, getCooldownMs(config)),
|
|
1355
|
+
authoritative: false,
|
|
1356
|
+
});
|
|
1357
|
+
if (outcome.kind === "cancelled")
|
|
1358
|
+
return;
|
|
1359
|
+
if (outcome.kind === "unavailable") {
|
|
1360
|
+
if (usageDecisionEpoch !== operation.epoch)
|
|
1361
|
+
return;
|
|
1362
|
+
reportQuotaExhausted(ctx, exhaustedName, currentTime);
|
|
1363
|
+
}
|
|
1364
|
+
else if (!isCompletionCurrent(outcome)) {
|
|
1365
|
+
return;
|
|
1366
|
+
}
|
|
1367
|
+
else if (outcome.kind === "rotated") {
|
|
1368
|
+
invalidateAutomaticDecisions();
|
|
1369
|
+
const keyName = applyActiveKey(config, ctx.modelRegistry, currentTime) ?? `key-${outcome.keyIndex + 1}`;
|
|
1370
|
+
ctx.ui.notify(`OpenCode: ${exhaustedName} reached its plan quota → rotated to ${keyName}`, "info");
|
|
1371
|
+
}
|
|
1372
|
+
else {
|
|
1373
|
+
reportQuotaExhausted(ctx, exhaustedName, currentTime);
|
|
1374
|
+
}
|
|
1375
|
+
if (event.status === 429)
|
|
1376
|
+
markHandledIfOwned();
|
|
1377
|
+
ctx.ui.notify(formatUsageStatus(usage), "warning");
|
|
1378
|
+
return;
|
|
1379
|
+
}
|
|
1380
|
+
if (event.status === 401)
|
|
1381
|
+
return;
|
|
1382
|
+
if (config.keys.length <= 1) {
|
|
1383
|
+
markHandledIfOwned();
|
|
1384
|
+
return;
|
|
1385
|
+
}
|
|
1386
|
+
const outcome = await rotateWithRecovery(ctx, operation, currentTime, { kind: "cooldown" });
|
|
1387
|
+
if (outcome.kind === "cancelled")
|
|
1388
|
+
return;
|
|
1389
|
+
if (outcome.kind === "unavailable") {
|
|
1390
|
+
if (usageDecisionEpoch !== operation.epoch)
|
|
1391
|
+
return;
|
|
1392
|
+
if (configError)
|
|
1393
|
+
ctx.ui.notify(`OpenCode: ${configError}. Automatic rotation was skipped.`, "error");
|
|
1394
|
+
else {
|
|
1395
|
+
invalidateAutomaticDecisions();
|
|
1396
|
+
markHandledIfOwned();
|
|
1397
|
+
ctx.ui.notify("OpenCode: HTTP 429; all other keys are quota-blocked.", "warning");
|
|
1398
|
+
}
|
|
1399
|
+
return;
|
|
1400
|
+
}
|
|
1401
|
+
if (!isCompletionCurrent(outcome))
|
|
1402
|
+
return;
|
|
1403
|
+
if (outcome.kind === "none") {
|
|
1404
|
+
if (configError)
|
|
1405
|
+
ctx.ui.notify(`OpenCode: ${configError}. Automatic rotation was skipped.`, "error");
|
|
1406
|
+
else {
|
|
1407
|
+
invalidateAutomaticDecisions();
|
|
1408
|
+
markHandledIfOwned();
|
|
1409
|
+
ctx.ui.notify("OpenCode: HTTP 429; all other keys are quota-blocked.", "warning");
|
|
1410
|
+
}
|
|
1411
|
+
return;
|
|
1412
|
+
}
|
|
1413
|
+
invalidateAutomaticDecisions();
|
|
1414
|
+
markHandledIfOwned();
|
|
1415
|
+
const keyName = applyActiveKey(config, ctx.modelRegistry, currentTime);
|
|
1416
|
+
ctx.ui.notify(`OpenCode: Proactive rate-limit detection (HTTP 429) → rotated to ${keyName ?? `key-${outcome.keyIndex + 1}`}`, "info");
|
|
1417
|
+
});
|
|
1418
|
+
pi.registerCommand("opencode", {
|
|
1419
|
+
description: "Manage OpenCode API key rotation",
|
|
1420
|
+
handler: async (args, ctx) => {
|
|
1421
|
+
if (!ensureConfig(ctx))
|
|
1422
|
+
return;
|
|
1423
|
+
const parts = args.trim().split(/\s+/);
|
|
1424
|
+
const subcommand = parts[0] || "status";
|
|
1425
|
+
const indexArg = parseInt(parts[1] ?? "", 10);
|
|
1426
|
+
switch (subcommand) {
|
|
1427
|
+
case "status":
|
|
1428
|
+
case "list":
|
|
1429
|
+
case "ls": {
|
|
1430
|
+
const status = formatStatus(config, now());
|
|
1431
|
+
ctx.ui.notify(status, "info");
|
|
1432
|
+
break;
|
|
1433
|
+
}
|
|
1434
|
+
case "events":
|
|
1435
|
+
case "timeouts": {
|
|
1436
|
+
ctx.ui.notify(formatWatchdogEvents(watchdogEvents, now()), "info");
|
|
1437
|
+
break;
|
|
1438
|
+
}
|
|
1439
|
+
case "usage":
|
|
1440
|
+
case "quota": {
|
|
1441
|
+
applySynchronizedActiveKey(ctx);
|
|
1442
|
+
const usage = await fetchOpenCodeGoUsage(getActiveUsageTarget(config), fetchApi, options.timers);
|
|
1443
|
+
ctx.ui.notify(formatUsageStatus(usage), usage.ok ? "info" : "warning");
|
|
1444
|
+
break;
|
|
1445
|
+
}
|
|
1446
|
+
case "use": {
|
|
1447
|
+
const targetIndex = indexArg - 1;
|
|
1448
|
+
invalidateAutomaticDecisions();
|
|
1449
|
+
const result = mutateSharedConfig((freshConfig) => {
|
|
1450
|
+
if (isNaN(targetIndex) || targetIndex < 0 || targetIndex >= freshConfig.keys.length) {
|
|
1451
|
+
return { error: `Invalid index. Use 1-${freshConfig.keys.length}.` };
|
|
1452
|
+
}
|
|
1453
|
+
freshConfig.activeKeyIndex = targetIndex;
|
|
1454
|
+
delete freshConfig.cooldowns[targetIndex];
|
|
1455
|
+
delete freshConfig.quotaBlockedUntil[targetIndex];
|
|
1456
|
+
return { index: targetIndex };
|
|
1457
|
+
});
|
|
1458
|
+
if (!result) {
|
|
1459
|
+
if (configError)
|
|
1460
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1461
|
+
return;
|
|
1462
|
+
}
|
|
1463
|
+
if ("error" in result && typeof result.error === "string") {
|
|
1464
|
+
ctx.ui.notify(result.error, "warning");
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
const keyName = applyActiveKey(config, ctx.modelRegistry, now());
|
|
1468
|
+
ctx.ui.notify(`Switched to ${keyName}`, "info");
|
|
1469
|
+
syncUsageStatus(ctx, true);
|
|
1470
|
+
break;
|
|
1471
|
+
}
|
|
1472
|
+
case "next": {
|
|
1473
|
+
invalidateAutomaticDecisions();
|
|
1474
|
+
const result = mutateSharedConfig((freshConfig) => {
|
|
1475
|
+
if (freshConfig.keys.length === 0)
|
|
1476
|
+
return { error: "No keys configured. Use /opencode add <name> <key>." };
|
|
1477
|
+
freshConfig.activeKeyIndex = (freshConfig.activeKeyIndex + 1) % freshConfig.keys.length;
|
|
1478
|
+
delete freshConfig.cooldowns[freshConfig.activeKeyIndex];
|
|
1479
|
+
delete freshConfig.quotaBlockedUntil[freshConfig.activeKeyIndex];
|
|
1480
|
+
return { index: freshConfig.activeKeyIndex };
|
|
1481
|
+
});
|
|
1482
|
+
if (!result) {
|
|
1483
|
+
if (configError)
|
|
1484
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1485
|
+
return;
|
|
1486
|
+
}
|
|
1487
|
+
if ("error" in result && typeof result.error === "string") {
|
|
1488
|
+
ctx.ui.notify(result.error, "warning");
|
|
1489
|
+
return;
|
|
1490
|
+
}
|
|
1491
|
+
const keyName = applyActiveKey(config, ctx.modelRegistry, now());
|
|
1492
|
+
ctx.ui.notify(`Switched to ${keyName}`, "info");
|
|
1493
|
+
syncUsageStatus(ctx, true);
|
|
1494
|
+
break;
|
|
1495
|
+
}
|
|
1496
|
+
case "add": {
|
|
1497
|
+
const name = parts[1];
|
|
1498
|
+
const key = parts[2];
|
|
1499
|
+
if (!name || !key) {
|
|
1500
|
+
ctx.ui.notify("Usage: /opencode add <name> <key>", "warning");
|
|
1501
|
+
return;
|
|
1502
|
+
}
|
|
1503
|
+
invalidateAutomaticDecisions();
|
|
1504
|
+
const count = mutateSharedConfig((freshConfig) => {
|
|
1505
|
+
freshConfig.keys.push({ name, key });
|
|
1506
|
+
if (freshConfig.keys.length === 1)
|
|
1507
|
+
freshConfig.activeKeyIndex = 0;
|
|
1508
|
+
return freshConfig.keys.length;
|
|
1509
|
+
});
|
|
1510
|
+
if (count === undefined) {
|
|
1511
|
+
if (configError)
|
|
1512
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1513
|
+
return;
|
|
1514
|
+
}
|
|
1515
|
+
if (count === 1)
|
|
1516
|
+
applyActiveKey(config, ctx.modelRegistry, now());
|
|
1517
|
+
ctx.ui.notify(`Added "${name}" (${count} keys)`, "info");
|
|
1518
|
+
syncUsageStatus(ctx, true);
|
|
1519
|
+
break;
|
|
1520
|
+
}
|
|
1521
|
+
case "remove":
|
|
1522
|
+
case "rm": {
|
|
1523
|
+
const removeIndex = indexArg - 1;
|
|
1524
|
+
invalidateAutomaticDecisions();
|
|
1525
|
+
const result = mutateSharedConfig((freshConfig) => {
|
|
1526
|
+
if (isNaN(removeIndex) || removeIndex < 0 || removeIndex >= freshConfig.keys.length) {
|
|
1527
|
+
return { error: `Invalid index. Use 1-${freshConfig.keys.length}.` };
|
|
1528
|
+
}
|
|
1529
|
+
const removed = freshConfig.keys.splice(removeIndex, 1)[0];
|
|
1530
|
+
freshConfig.cooldowns = reindexAfterRemoval(freshConfig.cooldowns, removeIndex);
|
|
1531
|
+
freshConfig.quotaBlockedUntil = reindexAfterRemoval(freshConfig.quotaBlockedUntil, removeIndex);
|
|
1532
|
+
if (freshConfig.activeKeyIndex >= freshConfig.keys.length)
|
|
1533
|
+
freshConfig.activeKeyIndex = 0;
|
|
1534
|
+
else if (removeIndex < freshConfig.activeKeyIndex)
|
|
1535
|
+
freshConfig.activeKeyIndex--;
|
|
1536
|
+
return { removedName: removed.name, count: freshConfig.keys.length };
|
|
1537
|
+
});
|
|
1538
|
+
if (!result) {
|
|
1539
|
+
if (configError)
|
|
1540
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1541
|
+
return;
|
|
1542
|
+
}
|
|
1543
|
+
if ("error" in result && typeof result.error === "string") {
|
|
1544
|
+
ctx.ui.notify(result.error, "warning");
|
|
1545
|
+
return;
|
|
1546
|
+
}
|
|
1547
|
+
if (config.keys.length > 0)
|
|
1548
|
+
applyActiveKey(config, ctx.modelRegistry, now());
|
|
1549
|
+
else {
|
|
1550
|
+
lastAppliedRuntimeKeys.delete(ctx.modelRegistry);
|
|
1551
|
+
ignoreAsyncRefresh(getRuntimeKeyStore(ctx.modelRegistry).removeRuntimeApiKey(PROVIDER));
|
|
1552
|
+
}
|
|
1553
|
+
ctx.ui.notify(`Removed "${result.removedName}" (${result.count} left)`, "info");
|
|
1554
|
+
syncUsageStatus(ctx, true);
|
|
1555
|
+
break;
|
|
1556
|
+
}
|
|
1557
|
+
case "reset": {
|
|
1558
|
+
invalidateAutomaticDecisions();
|
|
1559
|
+
const result = mutateSharedConfig((freshConfig) => {
|
|
1560
|
+
freshConfig.cooldowns = {};
|
|
1561
|
+
freshConfig.quotaBlockedUntil = {};
|
|
1562
|
+
return true;
|
|
1563
|
+
});
|
|
1564
|
+
if (result !== true) {
|
|
1565
|
+
if (configError)
|
|
1566
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1567
|
+
return;
|
|
1568
|
+
}
|
|
1569
|
+
ctx.ui.notify("All cooldowns and quota blocks cleared", "info");
|
|
1570
|
+
syncUsageStatus(ctx, true);
|
|
1571
|
+
break;
|
|
1572
|
+
}
|
|
1573
|
+
case "cooldown": {
|
|
1574
|
+
const minutes = parseInt(parts[1], 10);
|
|
1575
|
+
if (isNaN(minutes) || minutes < 1) {
|
|
1576
|
+
ctx.ui.notify(`Cooldown: ${config.cooldownMinutes || DEFAULT_COOLDOWN_MINUTES} min`, "info");
|
|
1577
|
+
return;
|
|
1578
|
+
}
|
|
1579
|
+
const result = mutateSharedConfig((freshConfig) => {
|
|
1580
|
+
freshConfig.cooldownMinutes = minutes;
|
|
1581
|
+
return true;
|
|
1582
|
+
});
|
|
1583
|
+
if (result !== true) {
|
|
1584
|
+
if (configError)
|
|
1585
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1586
|
+
return;
|
|
1587
|
+
}
|
|
1588
|
+
ctx.ui.notify(`Cooldown set to ${minutes} min`, "info");
|
|
1589
|
+
break;
|
|
1590
|
+
}
|
|
1591
|
+
case "watchdog": {
|
|
1592
|
+
const value = parts[1];
|
|
1593
|
+
if (!value || value === "status") {
|
|
1594
|
+
const events = formatWatchdogEvents(watchdogEvents, now());
|
|
1595
|
+
ctx.ui.notify(`Watchdog: ${config.watchdogEnabled ? "on" : "off"} (${Math.ceil(getWatchdogIdleMs(config) / 1000)}s idle)\n${events}`, "info");
|
|
1596
|
+
return;
|
|
1597
|
+
}
|
|
1598
|
+
if (value === "on" || value === "off") {
|
|
1599
|
+
const enabled = value === "on";
|
|
1600
|
+
const result = mutateSharedConfig((freshConfig) => {
|
|
1601
|
+
freshConfig.watchdogEnabled = enabled;
|
|
1602
|
+
return true;
|
|
1603
|
+
});
|
|
1604
|
+
if (result !== true) {
|
|
1605
|
+
if (configError)
|
|
1606
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1607
|
+
return;
|
|
1608
|
+
}
|
|
1609
|
+
if (!enabled) {
|
|
1610
|
+
stopWatchdog();
|
|
1611
|
+
resetWatchdogAbortState();
|
|
1612
|
+
}
|
|
1613
|
+
ctx.ui.notify(enabled ? `Watchdog enabled (${Math.ceil(getWatchdogIdleMs(config) / 1000)}s idle)` : "Watchdog disabled", "info");
|
|
1614
|
+
return;
|
|
1615
|
+
}
|
|
1616
|
+
const seconds = parseInt(value, 10);
|
|
1617
|
+
if (isNaN(seconds) || seconds < 1) {
|
|
1618
|
+
ctx.ui.notify("Usage: /opencode watchdog [status|on|off|<seconds>]", "warning");
|
|
1619
|
+
return;
|
|
1620
|
+
}
|
|
1621
|
+
const result = mutateSharedConfig((freshConfig) => {
|
|
1622
|
+
freshConfig.watchdogEnabled = true;
|
|
1623
|
+
freshConfig.watchdogIdleMs = seconds * 1000;
|
|
1624
|
+
return true;
|
|
1625
|
+
});
|
|
1626
|
+
if (result !== true) {
|
|
1627
|
+
if (configError)
|
|
1628
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1629
|
+
return;
|
|
1630
|
+
}
|
|
1631
|
+
ctx.ui.notify(`Watchdog enabled (${seconds}s idle)`, "info");
|
|
1632
|
+
break;
|
|
1633
|
+
}
|
|
1634
|
+
default:
|
|
1635
|
+
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");
|
|
1636
|
+
}
|
|
1637
|
+
},
|
|
1638
|
+
});
|
|
1639
|
+
function cleanupLifecycleState() {
|
|
1640
|
+
invalidateAutomaticDecisions();
|
|
1641
|
+
requestRateLimitState = undefined;
|
|
1642
|
+
stopWatchdog();
|
|
1643
|
+
resetWatchdogAbortState();
|
|
1644
|
+
clearWatchdogTimeoutGuard();
|
|
1645
|
+
}
|
|
1646
|
+
pi.on("agent_end", (_event, ctx) => {
|
|
1647
|
+
cleanupLifecycleState();
|
|
1648
|
+
scheduleUsageStatusRefresh(ctx);
|
|
1649
|
+
});
|
|
1650
|
+
pi.on("session_shutdown", () => {
|
|
1651
|
+
stopUsageStatusTimer();
|
|
1652
|
+
setUsageStatus(undefined);
|
|
1653
|
+
usageStatusCtx = undefined;
|
|
1654
|
+
cleanupLifecycleState();
|
|
1655
|
+
});
|
|
1656
|
+
};
|
|
1657
|
+
}
|
|
1658
|
+
const extension = createOpencodeGoRotationExtension();
|
|
1659
|
+
export default extension;
|