@yugimob/pi-opencode-go-rotation 1.6.1 → 1.7.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/README.md +23 -4
- 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 +78 -80
- package/package.json +11 -2
package/README.md
CHANGED
|
@@ -22,6 +22,22 @@ Add your API keys:
|
|
|
22
22
|
|
|
23
23
|
The first key added becomes active immediately.
|
|
24
24
|
|
|
25
|
+
The extension never imports keys from `auth.json` automatically. When no keys are configured, `/opencode` offers to import the auth.json key once; declining is remembered and it is not asked again.
|
|
26
|
+
|
|
27
|
+
## Interactive key manager
|
|
28
|
+
|
|
29
|
+
In interactive mode, `/opencode` (or `/opencode config`) opens the key manager overlay. It lists every key with its active, cooldown, or quota-blocked state, and lets you:
|
|
30
|
+
|
|
31
|
+
- Activate a key and clear its cooldown and quota block
|
|
32
|
+
- Rename a key or replace its secret
|
|
33
|
+
- Remove a key
|
|
34
|
+
- Add a key without remembering the command syntax
|
|
35
|
+
- Check a key's usage after the window closes
|
|
36
|
+
- Change the cooldown duration and the watchdog settings
|
|
37
|
+
- Clear every cooldown and quota block
|
|
38
|
+
|
|
39
|
+
Changes are saved as soon as they are confirmed. Outside interactive mode the command prints the text status instead.
|
|
40
|
+
|
|
25
41
|
## How it works
|
|
26
42
|
|
|
27
43
|
The extension sets the active key as a runtime override, which takes priority over `OPENCODE_API_KEY` environment variables and `auth.json` credentials.
|
|
@@ -44,11 +60,12 @@ Usage commands use `https://opencode.ai/zen/go/v1/usage` and stop waiting after
|
|
|
44
60
|
|
|
45
61
|
## Footer usage
|
|
46
62
|
|
|
47
|
-
While the selected model uses the `opencode-go` provider, the extension keeps a status line in pi's footer with the active key's name, the usage windows, and the monthly renewal date:
|
|
63
|
+
While the selected model uses the `opencode-go` provider, the extension keeps a status line in pi's footer with the active key's name, the weekly and monthly usage windows, and the monthly renewal date:
|
|
48
64
|
|
|
49
65
|
```text
|
|
50
|
-
personal
|
|
66
|
+
personal: wk 40% · mo 55% | ↻ Nov 12
|
|
51
67
|
```
|
|
68
|
+
The rolling 5-hour window is omitted from the footer.
|
|
52
69
|
|
|
53
70
|
It refreshes on session start, model changes, turns, key rotations, manual key commands, and every 5 minutes. The active key's name leads the line, and switching to another provider clears it.
|
|
54
71
|
|
|
@@ -56,7 +73,8 @@ It refreshes on session start, model changes, turns, key rotations, manual key c
|
|
|
56
73
|
|
|
57
74
|
| Command | Description |
|
|
58
75
|
|---------|-------------|
|
|
59
|
-
| `/opencode` or `/opencode
|
|
76
|
+
| `/opencode` or `/opencode config` | Open the interactive key manager |
|
|
77
|
+
| `/opencode status` | Show all keys, active key marker, cooldown and quota-blocked status |
|
|
60
78
|
| `/opencode usage` or `/opencode quota` | Fetch OpenCode Go usage for the active key without showing key material |
|
|
61
79
|
| `/opencode use <n>` | Switch to key number `n` (1-based) and clear its cooldown and quota block |
|
|
62
80
|
| `/opencode next` | Advance to the next configured key and clear its cooldown and quota block before activating it |
|
|
@@ -82,7 +100,8 @@ Keys are stored in `~/.pi/agent/opencode-keys.json` with file permissions `0600`
|
|
|
82
100
|
"watchdogEnabled": true,
|
|
83
101
|
"watchdogIdleMs": 90000,
|
|
84
102
|
"cooldowns": {},
|
|
85
|
-
"quotaBlockedUntil": {}
|
|
103
|
+
"quotaBlockedUntil": {},
|
|
104
|
+
"authImportDeclined": false
|
|
86
105
|
}
|
|
87
106
|
```
|
|
88
107
|
|
package/dist/config-store.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ export interface Config {
|
|
|
14
14
|
/** Key index → epoch ms when cooldown started */
|
|
15
15
|
cooldowns: Record<number, number>;
|
|
16
16
|
quotaBlockedUntil: Record<number, number>;
|
|
17
|
+
authImportDeclined: boolean;
|
|
17
18
|
}
|
|
18
19
|
export declare class ConfigLoadError extends Error {
|
|
19
20
|
readonly path: string;
|
|
@@ -27,3 +28,4 @@ export declare function updateConfig<T>(mutator: (config: Config) => T, path?: s
|
|
|
27
28
|
result: T;
|
|
28
29
|
};
|
|
29
30
|
export declare function writeConfig(config: Config, path?: string): void;
|
|
31
|
+
export declare function reindexAfterRemoval(record: Record<number, number>, removedIndex: number): Record<number, number>;
|
package/dist/config-store.js
CHANGED
|
@@ -26,6 +26,7 @@ export function createEmptyConfig() {
|
|
|
26
26
|
watchdogIdleMs: DEFAULT_WATCHDOG_IDLE_MS,
|
|
27
27
|
cooldowns: {},
|
|
28
28
|
quotaBlockedUntil: {},
|
|
29
|
+
authImportDeclined: false,
|
|
29
30
|
};
|
|
30
31
|
}
|
|
31
32
|
export function getConfigPath() {
|
|
@@ -77,12 +78,16 @@ function parseConfig(value, path) {
|
|
|
77
78
|
if (typeof watchdogIdleMs !== "number" || !Number.isFinite(watchdogIdleMs) || watchdogIdleMs < 1) {
|
|
78
79
|
throw new ConfigLoadError(path, "watchdogIdleMs is invalid");
|
|
79
80
|
}
|
|
81
|
+
const authImportDeclined = value.authImportDeclined ?? false;
|
|
82
|
+
if (typeof authImportDeclined !== "boolean")
|
|
83
|
+
throw new ConfigLoadError(path, "authImportDeclined is invalid");
|
|
80
84
|
return {
|
|
81
85
|
keys,
|
|
82
86
|
activeKeyIndex,
|
|
83
87
|
cooldownMinutes,
|
|
84
88
|
watchdogEnabled,
|
|
85
89
|
watchdogIdleMs,
|
|
90
|
+
authImportDeclined,
|
|
86
91
|
cooldowns: parseNumberRecord(value.cooldowns, "cooldowns", path),
|
|
87
92
|
quotaBlockedUntil: parseNumberRecord(value.quotaBlockedUntil, "quotaBlockedUntil", path),
|
|
88
93
|
};
|
|
@@ -174,3 +179,13 @@ export function updateConfig(mutator, path = getConfigPath()) {
|
|
|
174
179
|
export function writeConfig(config, path = getConfigPath()) {
|
|
175
180
|
withLock(path, () => writeConfigUnlocked(path, config));
|
|
176
181
|
}
|
|
182
|
+
export function reindexAfterRemoval(record, removedIndex) {
|
|
183
|
+
const shifted = {};
|
|
184
|
+
for (const [key, value] of Object.entries(record)) {
|
|
185
|
+
const index = Number(key);
|
|
186
|
+
if (index === removedIndex)
|
|
187
|
+
continue;
|
|
188
|
+
shifted[index > removedIndex ? index - 1 : index] = value;
|
|
189
|
+
}
|
|
190
|
+
return shifted;
|
|
191
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { type Config } from "./config-store.ts";
|
|
3
|
+
export interface OpencodeConfigResult {
|
|
4
|
+
usageKeyIndex?: number;
|
|
5
|
+
}
|
|
6
|
+
export declare function parsePositiveInteger(value: string, minimum: number): number | undefined;
|
|
7
|
+
export declare function validateNewKey(config: Config, name: string, key: string): string | undefined;
|
|
8
|
+
export declare function keyStatus(config: Config, keyIndex: number, now: number): string;
|
|
9
|
+
export declare function summarizeRestrictions(config: Config, now: number): string;
|
|
10
|
+
export declare function selectKey(config: Config, keyIndex: number): void;
|
|
11
|
+
export declare function clearKeyRestrictions(config: Config, keyIndex: number): void;
|
|
12
|
+
export declare function addKey(config: Config, name: string, key: string): void;
|
|
13
|
+
export declare function renameKey(config: Config, keyIndex: number, name: string): void;
|
|
14
|
+
export declare function replaceKeySecret(config: Config, keyIndex: number, key: string): void;
|
|
15
|
+
export declare function removeKey(config: Config, keyIndex: number): void;
|
|
16
|
+
export declare function clearAllRestrictions(config: Config): void;
|
|
17
|
+
export declare function openOpencodeConfig(ctx: Pick<ExtensionCommandContext, "mode" | "ui">): Promise<OpencodeConfigResult>;
|
|
@@ -0,0 +1,549 @@
|
|
|
1
|
+
import { DEFAULT_COOLDOWN_MINUTES, DEFAULT_WATCHDOG_IDLE_MS, getConfigPath, loadConfig, reindexAfterRemoval, updateConfig, } from "./config-store.js";
|
|
2
|
+
import { formatResetIn } from "./format-time.js";
|
|
3
|
+
let tuiModulePromise;
|
|
4
|
+
async function loadTuiModule() {
|
|
5
|
+
tuiModulePromise ??= import("@earendil-works/pi-tui");
|
|
6
|
+
try {
|
|
7
|
+
return await tuiModulePromise;
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
tuiModulePromise = undefined;
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function parsePositiveInteger(value, minimum) {
|
|
15
|
+
const parsed = Number(value.trim());
|
|
16
|
+
return Number.isInteger(parsed) && parsed >= minimum ? parsed : undefined;
|
|
17
|
+
}
|
|
18
|
+
export function validateNewKey(config, name, key) {
|
|
19
|
+
if (!name)
|
|
20
|
+
return "Enter a name for the key.";
|
|
21
|
+
if (!key)
|
|
22
|
+
return "Enter the API key value.";
|
|
23
|
+
if (config.keys.some((entry) => entry.key === key))
|
|
24
|
+
return "That API key is already configured.";
|
|
25
|
+
if (config.keys.some((entry) => entry.name === name))
|
|
26
|
+
return "That name is already in use.";
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
export function keyStatus(config, keyIndex, now) {
|
|
30
|
+
const parts = [];
|
|
31
|
+
if (keyIndex === config.activeKeyIndex)
|
|
32
|
+
parts.push("active");
|
|
33
|
+
const blockedUntil = quotaBlockedUntil(config, keyIndex, now);
|
|
34
|
+
const cooldownStart = config.cooldowns[keyIndex];
|
|
35
|
+
if (blockedUntil !== undefined) {
|
|
36
|
+
parts.push(`quota-blocked ${formatResetIn(Math.ceil((blockedUntil - now) / 1000))}`);
|
|
37
|
+
}
|
|
38
|
+
else if (cooldownStart !== undefined) {
|
|
39
|
+
const remaining = cooldownRemaining(config, cooldownStart, now);
|
|
40
|
+
if (remaining > 0)
|
|
41
|
+
parts.push(`cooldown ${Math.ceil(remaining / 60_000)}m`);
|
|
42
|
+
}
|
|
43
|
+
return parts.length === 0 ? "ready" : parts.join(" · ");
|
|
44
|
+
}
|
|
45
|
+
export function summarizeRestrictions(config, now) {
|
|
46
|
+
let blocked = 0;
|
|
47
|
+
let cooling = 0;
|
|
48
|
+
for (let index = 0; index < config.keys.length; index++) {
|
|
49
|
+
if (quotaBlockedUntil(config, index, now) !== undefined) {
|
|
50
|
+
blocked++;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const cooldownStart = config.cooldowns[index];
|
|
54
|
+
if (cooldownStart !== undefined && cooldownRemaining(config, cooldownStart, now) > 0)
|
|
55
|
+
cooling++;
|
|
56
|
+
}
|
|
57
|
+
if (blocked === 0 && cooling === 0)
|
|
58
|
+
return "nothing to clear";
|
|
59
|
+
return `${blocked} quota-blocked · ${cooling} cooling`;
|
|
60
|
+
}
|
|
61
|
+
export function selectKey(config, keyIndex) {
|
|
62
|
+
if (config.keys[keyIndex] === undefined)
|
|
63
|
+
return;
|
|
64
|
+
config.activeKeyIndex = keyIndex;
|
|
65
|
+
delete config.cooldowns[keyIndex];
|
|
66
|
+
delete config.quotaBlockedUntil[keyIndex];
|
|
67
|
+
}
|
|
68
|
+
export function clearKeyRestrictions(config, keyIndex) {
|
|
69
|
+
delete config.cooldowns[keyIndex];
|
|
70
|
+
delete config.quotaBlockedUntil[keyIndex];
|
|
71
|
+
}
|
|
72
|
+
export function addKey(config, name, key) {
|
|
73
|
+
config.keys.push({ name, key });
|
|
74
|
+
if (config.keys.length === 1)
|
|
75
|
+
config.activeKeyIndex = 0;
|
|
76
|
+
}
|
|
77
|
+
export function renameKey(config, keyIndex, name) {
|
|
78
|
+
const entry = config.keys[keyIndex];
|
|
79
|
+
if (entry)
|
|
80
|
+
entry.name = name;
|
|
81
|
+
}
|
|
82
|
+
export function replaceKeySecret(config, keyIndex, key) {
|
|
83
|
+
const entry = config.keys[keyIndex];
|
|
84
|
+
if (entry)
|
|
85
|
+
entry.key = key;
|
|
86
|
+
}
|
|
87
|
+
export function removeKey(config, keyIndex) {
|
|
88
|
+
if (config.keys[keyIndex] === undefined)
|
|
89
|
+
return;
|
|
90
|
+
config.keys.splice(keyIndex, 1);
|
|
91
|
+
config.cooldowns = reindexAfterRemoval(config.cooldowns, keyIndex);
|
|
92
|
+
config.quotaBlockedUntil = reindexAfterRemoval(config.quotaBlockedUntil, keyIndex);
|
|
93
|
+
if (keyIndex < config.activeKeyIndex)
|
|
94
|
+
config.activeKeyIndex--;
|
|
95
|
+
else if (config.activeKeyIndex >= config.keys.length)
|
|
96
|
+
config.activeKeyIndex = 0;
|
|
97
|
+
}
|
|
98
|
+
export function clearAllRestrictions(config) {
|
|
99
|
+
config.cooldowns = {};
|
|
100
|
+
config.quotaBlockedUntil = {};
|
|
101
|
+
}
|
|
102
|
+
function quotaBlockedUntil(config, keyIndex, now) {
|
|
103
|
+
const blockedUntil = config.quotaBlockedUntil[keyIndex];
|
|
104
|
+
return typeof blockedUntil === "number" && Number.isFinite(blockedUntil) && blockedUntil > now ? blockedUntil : undefined;
|
|
105
|
+
}
|
|
106
|
+
function cooldownDurationMs(config) {
|
|
107
|
+
return (config.cooldownMinutes || DEFAULT_COOLDOWN_MINUTES) * 60_000;
|
|
108
|
+
}
|
|
109
|
+
function cooldownRemaining(config, cooldownStart, now) {
|
|
110
|
+
return Math.max(0, cooldownDurationMs(config) - (now - cooldownStart));
|
|
111
|
+
}
|
|
112
|
+
function watchdogIdleMs(config) {
|
|
113
|
+
return config.watchdogIdleMs > 0 ? config.watchdogIdleMs : DEFAULT_WATCHDOG_IDLE_MS;
|
|
114
|
+
}
|
|
115
|
+
function rule(tui, theme) {
|
|
116
|
+
return {
|
|
117
|
+
render: (width) => [theme.fg("border", "─".repeat(Math.max(1, width)))],
|
|
118
|
+
invalidate: () => { },
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
function settingsTheme(theme) {
|
|
122
|
+
return {
|
|
123
|
+
label: (text, selected) => (selected ? theme.fg("accent", text) : text),
|
|
124
|
+
value: (text) => {
|
|
125
|
+
if (text === "on" || text === "active")
|
|
126
|
+
return theme.fg("success", text);
|
|
127
|
+
if (text.startsWith("quota-blocked"))
|
|
128
|
+
return theme.fg("warning", text);
|
|
129
|
+
if (text.startsWith("cooldown") || text === "off")
|
|
130
|
+
return theme.fg("dim", text);
|
|
131
|
+
return theme.fg("accent", text);
|
|
132
|
+
},
|
|
133
|
+
description: (text) => theme.fg("muted", text),
|
|
134
|
+
cursor: theme.fg("accent", "> "),
|
|
135
|
+
hint: (text) => theme.fg("dim", text),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function selectTheme(theme) {
|
|
139
|
+
return {
|
|
140
|
+
selectedPrefix: (text) => theme.fg("accent", text),
|
|
141
|
+
selectedText: (text) => theme.fg("accent", text),
|
|
142
|
+
description: (text) => theme.fg("muted", text),
|
|
143
|
+
scrollInfo: (text) => theme.fg("dim", text),
|
|
144
|
+
noMatch: (text) => theme.fg("muted", text),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
function createMenu(tui, theme, items, onSelect, onCancel) {
|
|
148
|
+
const list = new tui.SelectList(items, Math.max(1, items.length), selectTheme(theme));
|
|
149
|
+
list.onSelect = (item) => onSelect(item.value);
|
|
150
|
+
list.onCancel = onCancel;
|
|
151
|
+
return {
|
|
152
|
+
render: (width) => list.render(width),
|
|
153
|
+
invalidate: () => list.invalidate(),
|
|
154
|
+
handleInput: (data) => list.handleInput(data),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
function createConfirm(tui, theme, message, onConfirm, onCancel) {
|
|
158
|
+
return createMenu(tui, theme, [
|
|
159
|
+
{ value: "yes", label: "Yes", description: message },
|
|
160
|
+
{ value: "no", label: "No", description: "Keep the current state." },
|
|
161
|
+
], (value) => (value === "yes" ? onConfirm() : onCancel()), onCancel);
|
|
162
|
+
}
|
|
163
|
+
function createForm(tui, options) {
|
|
164
|
+
const { theme, title, fields, isFocused, submit, cancel } = options;
|
|
165
|
+
const inputs = fields.map((field) => {
|
|
166
|
+
const input = new tui.Input({ placeholder: field.placeholder ?? "" });
|
|
167
|
+
input.setValue(field.value ?? "");
|
|
168
|
+
return input;
|
|
169
|
+
});
|
|
170
|
+
let focusIndex = 0;
|
|
171
|
+
let error = "";
|
|
172
|
+
const render = (width) => {
|
|
173
|
+
const lines = [tui.truncateToWidth(theme.fg("accent", theme.bold(title)), width)];
|
|
174
|
+
fields.forEach((field, index) => {
|
|
175
|
+
const input = inputs[index];
|
|
176
|
+
const selected = index === focusIndex;
|
|
177
|
+
input.focused = isFocused() && selected;
|
|
178
|
+
lines.push(tui.truncateToWidth(`${selected ? theme.fg("accent", "> ") : " "}${theme.fg("muted", field.label)}`, width));
|
|
179
|
+
lines.push(...input.render(Math.max(1, width - 2)).map((line) => tui.truncateToWidth(` ${line}`, width)));
|
|
180
|
+
});
|
|
181
|
+
if (error)
|
|
182
|
+
lines.push(tui.truncateToWidth(theme.fg("error", error), width));
|
|
183
|
+
lines.push(tui.truncateToWidth(theme.fg("dim", "Tab or ↑/↓ switch · Enter submits · Esc cancels"), width));
|
|
184
|
+
return lines;
|
|
185
|
+
};
|
|
186
|
+
const handleInput = (data) => {
|
|
187
|
+
if (tui.matchesKey(data, "escape")) {
|
|
188
|
+
cancel();
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (tui.matchesKey(data, "up") || tui.matchesKey(data, "shift+tab")) {
|
|
192
|
+
focusIndex = (focusIndex + inputs.length - 1) % inputs.length;
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (tui.matchesKey(data, "down") || tui.matchesKey(data, "tab")) {
|
|
196
|
+
focusIndex = (focusIndex + 1) % inputs.length;
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (tui.matchesKey(data, "return")) {
|
|
200
|
+
error = submit(inputs.map((input) => input.getValue())) ?? "";
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
inputs[focusIndex].handleInput(data);
|
|
204
|
+
};
|
|
205
|
+
return {
|
|
206
|
+
render,
|
|
207
|
+
invalidate: () => {
|
|
208
|
+
for (const input of inputs)
|
|
209
|
+
input.invalidate();
|
|
210
|
+
},
|
|
211
|
+
handleInput,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
function createKeyManager(tui, options) {
|
|
215
|
+
const { theme, config, keyIndex, isFocused, persist, rebuild, requestUsage, close } = options;
|
|
216
|
+
const name = config.keys[keyIndex]?.name ?? `key-${keyIndex + 1}`;
|
|
217
|
+
let form;
|
|
218
|
+
let error = "";
|
|
219
|
+
const finish = (selectId) => {
|
|
220
|
+
close();
|
|
221
|
+
rebuild(selectId);
|
|
222
|
+
};
|
|
223
|
+
const showError = (message) => {
|
|
224
|
+
if (message === undefined)
|
|
225
|
+
return false;
|
|
226
|
+
error = message;
|
|
227
|
+
return true;
|
|
228
|
+
};
|
|
229
|
+
const menu = createMenu(tui, theme, [
|
|
230
|
+
{ value: "use", label: "Set active", description: `Use "${name}" for the next request and clear its cooldown and quota block.` },
|
|
231
|
+
{ value: "rename", label: "Rename", description: `Rename "${name}".` },
|
|
232
|
+
{ value: "replace", label: "Replace key", description: "Store a new secret for this entry." },
|
|
233
|
+
{ value: "clear", label: "Clear restrictions", description: "Remove this key's cooldown and quota block." },
|
|
234
|
+
{ value: "usage", label: "Check usage", description: "Fetch plan usage for this key after the window closes." },
|
|
235
|
+
{ value: "remove", label: "Remove", description: `Delete "${name}" from the configuration.` },
|
|
236
|
+
{ value: "back", label: "Back", description: "Return to the key list." },
|
|
237
|
+
], (value) => {
|
|
238
|
+
if (value === "use") {
|
|
239
|
+
if (!showError(persist((fresh) => selectKey(fresh, keyIndex))))
|
|
240
|
+
finish(`key:${keyIndex}`);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (value === "clear") {
|
|
244
|
+
if (!showError(persist((fresh) => clearKeyRestrictions(fresh, keyIndex))))
|
|
245
|
+
finish(`key:${keyIndex}`);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (value === "usage") {
|
|
249
|
+
requestUsage(keyIndex);
|
|
250
|
+
close();
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (value === "back") {
|
|
254
|
+
close();
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
if (value === "rename") {
|
|
258
|
+
form = createForm(tui, {
|
|
259
|
+
theme,
|
|
260
|
+
title: `Rename ${name}`,
|
|
261
|
+
fields: [{ label: "Name", value: name }],
|
|
262
|
+
isFocused,
|
|
263
|
+
submit: (values) => {
|
|
264
|
+
const next = values[0].trim();
|
|
265
|
+
if (!next)
|
|
266
|
+
return "Enter a name.";
|
|
267
|
+
if (next !== name && config.keys.some((entry, index) => index !== keyIndex && entry.name === next)) {
|
|
268
|
+
return "That name is already in use.";
|
|
269
|
+
}
|
|
270
|
+
const saved = persist((fresh) => renameKey(fresh, keyIndex, next));
|
|
271
|
+
if (saved !== undefined)
|
|
272
|
+
return saved;
|
|
273
|
+
finish(`key:${keyIndex}`);
|
|
274
|
+
return undefined;
|
|
275
|
+
},
|
|
276
|
+
cancel: () => {
|
|
277
|
+
form = undefined;
|
|
278
|
+
},
|
|
279
|
+
});
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
if (value === "replace") {
|
|
283
|
+
form = createForm(tui, {
|
|
284
|
+
theme,
|
|
285
|
+
title: `Replace ${name}`,
|
|
286
|
+
fields: [{ label: "New API key", placeholder: "sk-..." }],
|
|
287
|
+
isFocused,
|
|
288
|
+
submit: (values) => {
|
|
289
|
+
const secret = values[0].trim();
|
|
290
|
+
if (!secret)
|
|
291
|
+
return "Enter the API key value.";
|
|
292
|
+
if (config.keys.some((entry, index) => index !== keyIndex && entry.key === secret)) {
|
|
293
|
+
return "That API key is already configured.";
|
|
294
|
+
}
|
|
295
|
+
const saved = persist((fresh) => replaceKeySecret(fresh, keyIndex, secret));
|
|
296
|
+
if (saved !== undefined)
|
|
297
|
+
return saved;
|
|
298
|
+
finish(`key:${keyIndex}`);
|
|
299
|
+
return undefined;
|
|
300
|
+
},
|
|
301
|
+
cancel: () => {
|
|
302
|
+
form = undefined;
|
|
303
|
+
},
|
|
304
|
+
});
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
form = createConfirm(tui, theme, `Delete "${name}"?`, () => {
|
|
308
|
+
const saved = persist((fresh) => removeKey(fresh, keyIndex));
|
|
309
|
+
if (saved !== undefined) {
|
|
310
|
+
error = saved;
|
|
311
|
+
form = undefined;
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
finish(keyIndex > 0 ? `key:${keyIndex - 1}` : undefined);
|
|
315
|
+
}, () => {
|
|
316
|
+
form = undefined;
|
|
317
|
+
});
|
|
318
|
+
}, () => close());
|
|
319
|
+
const active = () => form ?? menu;
|
|
320
|
+
return {
|
|
321
|
+
render: (width) => [...active().render(width), ...(error ? [tui.truncateToWidth(theme.fg("error", error), width)] : [])],
|
|
322
|
+
invalidate: () => active().invalidate?.(),
|
|
323
|
+
handleInput: (data) => active().handleInput?.(data),
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
export async function openOpencodeConfig(ctx) {
|
|
327
|
+
if (ctx.mode !== "tui") {
|
|
328
|
+
ctx.ui.notify("/opencode config requires interactive mode", "error");
|
|
329
|
+
return {};
|
|
330
|
+
}
|
|
331
|
+
const tui = await loadTuiModule();
|
|
332
|
+
if (!tui) {
|
|
333
|
+
ctx.ui.notify("/opencode config is unavailable in this environment", "error");
|
|
334
|
+
return {};
|
|
335
|
+
}
|
|
336
|
+
try {
|
|
337
|
+
loadConfig();
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
ctx.ui.notify(`OpenCode config: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
341
|
+
return {};
|
|
342
|
+
}
|
|
343
|
+
return await ctx.ui.custom((interactive, theme, _keybindings, done) => {
|
|
344
|
+
const result = {};
|
|
345
|
+
const status = new tui.Text(`Config file: ${getConfigPath()}`, 1, 0);
|
|
346
|
+
const container = new tui.Container();
|
|
347
|
+
let focused = false;
|
|
348
|
+
let list;
|
|
349
|
+
const isFocused = () => focused;
|
|
350
|
+
const persist = (mutator) => {
|
|
351
|
+
try {
|
|
352
|
+
updateConfig(mutator);
|
|
353
|
+
status.setText(theme.fg("dim", `Saved to ${getConfigPath()}`));
|
|
354
|
+
return undefined;
|
|
355
|
+
}
|
|
356
|
+
catch (error) {
|
|
357
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
358
|
+
status.setText(theme.fg("error", `Save failed: ${message}`));
|
|
359
|
+
return message;
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
const buildItems = (current) => {
|
|
363
|
+
const now = Date.now();
|
|
364
|
+
const items = [];
|
|
365
|
+
if (current.keys.length === 0) {
|
|
366
|
+
items.push({
|
|
367
|
+
id: "empty",
|
|
368
|
+
label: "No keys configured",
|
|
369
|
+
currentValue: "none",
|
|
370
|
+
description: "Use Add key to register an OpenCode Go API key.",
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
current.keys.forEach((entry, index) => {
|
|
374
|
+
items.push({
|
|
375
|
+
id: `key:${index}`,
|
|
376
|
+
label: `${index + 1}. ${entry.name}`,
|
|
377
|
+
currentValue: keyStatus(current, index, now),
|
|
378
|
+
description: "Enter to set active, rename, replace, clear restrictions, check usage, or remove.",
|
|
379
|
+
submenu: (_value, close) => createKeyManager(tui, {
|
|
380
|
+
theme,
|
|
381
|
+
config: current,
|
|
382
|
+
keyIndex: index,
|
|
383
|
+
isFocused,
|
|
384
|
+
persist,
|
|
385
|
+
rebuild,
|
|
386
|
+
requestUsage: (keyIndex) => {
|
|
387
|
+
result.usageKeyIndex = keyIndex;
|
|
388
|
+
},
|
|
389
|
+
close: () => close(),
|
|
390
|
+
}),
|
|
391
|
+
});
|
|
392
|
+
});
|
|
393
|
+
items.push({
|
|
394
|
+
id: "add",
|
|
395
|
+
label: "Add key",
|
|
396
|
+
currentValue: "new",
|
|
397
|
+
description: "Register another OpenCode Go API key.",
|
|
398
|
+
submenu: (_value, close) => createForm(tui, {
|
|
399
|
+
theme,
|
|
400
|
+
title: "Add key",
|
|
401
|
+
fields: [
|
|
402
|
+
{ label: "Name", placeholder: "personal" },
|
|
403
|
+
{ label: "API key", placeholder: "sk-..." },
|
|
404
|
+
],
|
|
405
|
+
isFocused,
|
|
406
|
+
submit: (values) => {
|
|
407
|
+
const name = values[0].trim();
|
|
408
|
+
const key = values[1].trim();
|
|
409
|
+
const validation = validateNewKey(current, name, key);
|
|
410
|
+
if (validation)
|
|
411
|
+
return validation;
|
|
412
|
+
let addedIndex;
|
|
413
|
+
const saved = persist((fresh) => {
|
|
414
|
+
addKey(fresh, name, key);
|
|
415
|
+
addedIndex = fresh.keys.length - 1;
|
|
416
|
+
});
|
|
417
|
+
if (saved)
|
|
418
|
+
return saved;
|
|
419
|
+
close();
|
|
420
|
+
rebuild(addedIndex === undefined ? undefined : `key:${addedIndex}`);
|
|
421
|
+
return undefined;
|
|
422
|
+
},
|
|
423
|
+
cancel: () => close(),
|
|
424
|
+
}),
|
|
425
|
+
});
|
|
426
|
+
items.push({
|
|
427
|
+
id: "cooldown",
|
|
428
|
+
label: "Cooldown",
|
|
429
|
+
currentValue: `${current.cooldownMinutes || DEFAULT_COOLDOWN_MINUTES} min`,
|
|
430
|
+
description: "Rest period applied to a key after a transient rate limit.",
|
|
431
|
+
submenu: (_value, close) => createForm(tui, {
|
|
432
|
+
theme,
|
|
433
|
+
title: "Cooldown",
|
|
434
|
+
fields: [{ label: "Minutes (at least 1)", value: String(current.cooldownMinutes || DEFAULT_COOLDOWN_MINUTES) }],
|
|
435
|
+
isFocused,
|
|
436
|
+
submit: (values) => {
|
|
437
|
+
const minutes = parsePositiveInteger(values[0], 1);
|
|
438
|
+
if (minutes === undefined)
|
|
439
|
+
return "Enter a whole number of at least 1.";
|
|
440
|
+
const saved = persist((fresh) => {
|
|
441
|
+
fresh.cooldownMinutes = minutes;
|
|
442
|
+
});
|
|
443
|
+
if (saved)
|
|
444
|
+
return saved;
|
|
445
|
+
close();
|
|
446
|
+
rebuild("cooldown");
|
|
447
|
+
return undefined;
|
|
448
|
+
},
|
|
449
|
+
cancel: () => close(),
|
|
450
|
+
}),
|
|
451
|
+
});
|
|
452
|
+
items.push({
|
|
453
|
+
id: "watchdog",
|
|
454
|
+
label: "Watchdog",
|
|
455
|
+
currentValue: current.watchdogEnabled ? "on" : "off",
|
|
456
|
+
values: ["on", "off"],
|
|
457
|
+
description: "Abort and rotate an opencode-go request that stalls with no response or stream activity.",
|
|
458
|
+
});
|
|
459
|
+
items.push({
|
|
460
|
+
id: "watchdogIdle",
|
|
461
|
+
label: "Watchdog idle",
|
|
462
|
+
currentValue: `${Math.ceil(watchdogIdleMs(current) / 1000)}s`,
|
|
463
|
+
description: "Seconds without activity before the watchdog declares a stall.",
|
|
464
|
+
submenu: (_value, close) => createForm(tui, {
|
|
465
|
+
theme,
|
|
466
|
+
title: "Watchdog idle",
|
|
467
|
+
fields: [{ label: "Seconds (at least 1)", value: String(Math.ceil(watchdogIdleMs(current) / 1000)) }],
|
|
468
|
+
isFocused,
|
|
469
|
+
submit: (values) => {
|
|
470
|
+
const seconds = parsePositiveInteger(values[0], 1);
|
|
471
|
+
if (seconds === undefined)
|
|
472
|
+
return "Enter a whole number of at least 1.";
|
|
473
|
+
const saved = persist((fresh) => {
|
|
474
|
+
fresh.watchdogIdleMs = seconds * 1000;
|
|
475
|
+
});
|
|
476
|
+
if (saved)
|
|
477
|
+
return saved;
|
|
478
|
+
close();
|
|
479
|
+
rebuild("watchdogIdle");
|
|
480
|
+
return undefined;
|
|
481
|
+
},
|
|
482
|
+
cancel: () => close(),
|
|
483
|
+
}),
|
|
484
|
+
});
|
|
485
|
+
items.push({
|
|
486
|
+
id: "reset",
|
|
487
|
+
label: "Reset blocks",
|
|
488
|
+
currentValue: summarizeRestrictions(current, now),
|
|
489
|
+
description: "Clear every cooldown and quota block.",
|
|
490
|
+
submenu: (_value, close) => createConfirm(tui, theme, "Clear all cooldowns and quota blocks?", () => {
|
|
491
|
+
const saved = persist((fresh) => clearAllRestrictions(fresh));
|
|
492
|
+
close();
|
|
493
|
+
if (!saved)
|
|
494
|
+
rebuild("reset");
|
|
495
|
+
}, () => close()),
|
|
496
|
+
});
|
|
497
|
+
return items;
|
|
498
|
+
};
|
|
499
|
+
const rebuild = (selectId) => {
|
|
500
|
+
let current;
|
|
501
|
+
try {
|
|
502
|
+
current = loadConfig();
|
|
503
|
+
}
|
|
504
|
+
catch (error) {
|
|
505
|
+
status.setText(theme.fg("error", `Reload failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
506
|
+
interactive.requestRender();
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
const items = buildItems(current);
|
|
510
|
+
list = new tui.SettingsList(items, Math.max(1, Math.min(items.length, 12)), settingsTheme(theme), onChange, () => done(result));
|
|
511
|
+
if (selectId)
|
|
512
|
+
list.selectItem(selectId);
|
|
513
|
+
container.clear();
|
|
514
|
+
container.addChild(rule(tui, theme));
|
|
515
|
+
container.addChild(new tui.Text(theme.fg("accent", theme.bold("OpenCode Go keys")), 1, 0));
|
|
516
|
+
container.addChild(new tui.Text(theme.fg("dim", "Keys, cooldowns, quota blocks, and the stall watchdog. Esc closes."), 1, 0));
|
|
517
|
+
container.addChild(list);
|
|
518
|
+
container.addChild(status);
|
|
519
|
+
container.addChild(rule(tui, theme));
|
|
520
|
+
interactive.requestRender();
|
|
521
|
+
};
|
|
522
|
+
const onChange = (id, value) => {
|
|
523
|
+
if (id !== "watchdog")
|
|
524
|
+
return;
|
|
525
|
+
const enabled = value === "on";
|
|
526
|
+
if (persist((fresh) => {
|
|
527
|
+
fresh.watchdogEnabled = enabled;
|
|
528
|
+
}) === undefined) {
|
|
529
|
+
rebuild("watchdog");
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
rebuild();
|
|
533
|
+
const component = {
|
|
534
|
+
get focused() {
|
|
535
|
+
return focused;
|
|
536
|
+
},
|
|
537
|
+
set focused(value) {
|
|
538
|
+
focused = value;
|
|
539
|
+
},
|
|
540
|
+
render: (width) => container.render(width),
|
|
541
|
+
invalidate: () => container.invalidate(),
|
|
542
|
+
handleInput: (data) => {
|
|
543
|
+
list.handleInput(data);
|
|
544
|
+
interactive.requestRender();
|
|
545
|
+
},
|
|
546
|
+
};
|
|
547
|
+
return component;
|
|
548
|
+
}, { overlay: true, overlayOptions: { anchor: "center", width: "72%", minWidth: 60, maxHeight: "80%" } });
|
|
549
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export function formatResetIn(seconds) {
|
|
2
|
+
if (seconds <= 0)
|
|
3
|
+
return "now";
|
|
4
|
+
const days = Math.floor(seconds / 86_400);
|
|
5
|
+
const hours = Math.floor((seconds % 86_400) / 3_600);
|
|
6
|
+
const minutes = Math.ceil((seconds % 3_600) / 60);
|
|
7
|
+
if (days > 0)
|
|
8
|
+
return hours > 0 ? `${days}d ${hours}h` : `${days}d`;
|
|
9
|
+
if (hours > 0)
|
|
10
|
+
return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
|
|
11
|
+
return minutes > 0 ? `${minutes}m` : "less than 1m";
|
|
12
|
+
}
|
|
13
|
+
export function formatDuration(ms) {
|
|
14
|
+
const seconds = Math.max(0, Math.ceil(ms / 1000));
|
|
15
|
+
if (seconds < 60)
|
|
16
|
+
return `${seconds}s`;
|
|
17
|
+
const minutes = Math.floor(seconds / 60);
|
|
18
|
+
const remainder = seconds % 60;
|
|
19
|
+
return remainder ? `${minutes}m ${remainder}s` : `${minutes}m`;
|
|
20
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import type { ExtensionAPI } from "@
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { formatResetIn } from "./format-time.ts";
|
|
3
|
+
export { formatResetIn };
|
|
2
4
|
export declare function shouldWatchProvider(provider: string | undefined): boolean;
|
|
3
5
|
export type RateLimitKind = "transient" | "fixed-window-quota";
|
|
4
6
|
export declare function classifyRateLimitError(message: string): RateLimitKind | undefined;
|
|
@@ -88,7 +90,6 @@ export declare class ProviderIdleWatchdog {
|
|
|
88
90
|
private clear;
|
|
89
91
|
}
|
|
90
92
|
export declare function parseOpenCodeGoUsage(value: unknown): OpenCodeGoUsageResponse | undefined;
|
|
91
|
-
export declare function formatResetIn(seconds: number): string;
|
|
92
93
|
export declare function formatUsageStatus(result: UsageFetchResult): string;
|
|
93
94
|
export declare function shortUsageWindowLabel(name: string | undefined, index: number): string;
|
|
94
95
|
export interface FooterUsageOptions {
|
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;
|
|
@@ -263,7 +266,8 @@ function sanitizeReasoningPayload(payload) {
|
|
|
263
266
|
}
|
|
264
267
|
const lastAppliedRuntimeKeys = new WeakMap();
|
|
265
268
|
function getRuntimeKeyStore(modelRegistry) {
|
|
266
|
-
const
|
|
269
|
+
const host = modelRegistry;
|
|
270
|
+
const store = host.authStorage ?? host.runtime;
|
|
267
271
|
if (!store)
|
|
268
272
|
throw new Error("Model registry does not expose runtime API key storage");
|
|
269
273
|
return store;
|
|
@@ -540,31 +544,9 @@ function blockQuotaAndSelectNext(config, keyIndex, blockedUntil, now, isAuthorit
|
|
|
540
544
|
config.activeKeyIndex = next;
|
|
541
545
|
return next;
|
|
542
546
|
}
|
|
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
547
|
function formatUsageAmount(value) {
|
|
554
548
|
return value === undefined ? undefined : value.toLocaleString("en-US");
|
|
555
549
|
}
|
|
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
550
|
function formatUsageWindow(window, index) {
|
|
569
551
|
const label = window.name ?? `window ${index + 1}`;
|
|
570
552
|
const details = [`${label}: ${window.status}`];
|
|
@@ -607,19 +589,26 @@ export function shortUsageWindowLabel(name, index) {
|
|
|
607
589
|
return name;
|
|
608
590
|
}
|
|
609
591
|
export function formatFooterUsage(windows, options = {}) {
|
|
610
|
-
const
|
|
592
|
+
const name = options.keyName ?? "opencode-go";
|
|
611
593
|
if (options.error !== undefined)
|
|
612
|
-
return `${
|
|
594
|
+
return `${name}: usage unavailable: ${options.error}`;
|
|
613
595
|
if (windows.length === 0)
|
|
614
|
-
return `${
|
|
615
|
-
const parts =
|
|
596
|
+
return `${name}: no usage windows`;
|
|
597
|
+
const parts = [];
|
|
598
|
+
windows.forEach((window, index) => {
|
|
616
599
|
const label = shortUsageWindowLabel(window.name, index);
|
|
600
|
+
if (label === "5h")
|
|
601
|
+
return;
|
|
617
602
|
const percent = usageWindowPercent(window);
|
|
618
|
-
|
|
603
|
+
parts.push(`${label} ${percent === undefined ? "?" : `${Math.round(percent)}%`}`);
|
|
619
604
|
});
|
|
620
|
-
|
|
605
|
+
if (windows.some((window) => window.status === "rate-limited"))
|
|
606
|
+
parts.push("rate-limited");
|
|
621
607
|
const renewal = monthlyRenewalDate(windows, options.nowMs ?? Date.now());
|
|
622
|
-
|
|
608
|
+
const renewalText = renewal === undefined ? "" : `↻ ${formatRenewalDate(renewal)}`;
|
|
609
|
+
if (parts.length === 0)
|
|
610
|
+
return renewalText ? `${name}: ${renewalText}` : name;
|
|
611
|
+
return `${name}: ${parts.join(" · ")}${renewalText ? ` | ${renewalText}` : ""}`;
|
|
623
612
|
}
|
|
624
613
|
function monthlyRenewalDate(windows, nowMs) {
|
|
625
614
|
const monthly = windows.find((window, index) => shortUsageWindowLabel(window.name, index) === "mo");
|
|
@@ -670,14 +659,6 @@ function formatStatus(config, now = Date.now()) {
|
|
|
670
659
|
return `${marker} ${i + 1}. ${key.name}${tag}`;
|
|
671
660
|
}).join("\n")}\n${watchdogStatus}`;
|
|
672
661
|
}
|
|
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
662
|
function formatTimeoutInfo(info) {
|
|
682
663
|
const status = info.lastStatus === undefined ? "" : `, last HTTP ${info.lastStatus}`;
|
|
683
664
|
return `${info.phase.replaceAll("-", " ")} stalled after ${formatDuration(info.elapsedMs)} (${formatDuration(info.idleForMs)} idle${status})`;
|
|
@@ -922,16 +903,13 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
922
903
|
const candidates = getQuotaBlockedTargets(config, currentTime, skipKeyIndex)
|
|
923
904
|
.map((target) => captureSelectionSnapshot(config, currentTime, target.keyIndex))
|
|
924
905
|
.filter((snapshot) => snapshot !== undefined);
|
|
925
|
-
const
|
|
926
|
-
for (const candidate of candidates) {
|
|
906
|
+
const results = await Promise.all(candidates.map(async (candidate) => {
|
|
927
907
|
const usage = await fetchOpenCodeGoUsage(candidate, fetchApi, options.timers);
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
}
|
|
934
|
-
return recovered;
|
|
908
|
+
return hasConfirmedHeadroom(usage) ? candidate : undefined;
|
|
909
|
+
}));
|
|
910
|
+
if (!refreshConfig())
|
|
911
|
+
return [];
|
|
912
|
+
return results.filter((snapshot) => snapshot !== undefined);
|
|
935
913
|
}
|
|
936
914
|
function selectNextKey(mode, freshConfig, startIndex, currentTime) {
|
|
937
915
|
return mode.kind === "quota"
|
|
@@ -1129,10 +1107,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1129
1107
|
});
|
|
1130
1108
|
watchdog.start();
|
|
1131
1109
|
}
|
|
1132
|
-
async function
|
|
1133
|
-
const authKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
|
|
1134
|
-
if (!authKey)
|
|
1135
|
-
return false;
|
|
1110
|
+
async function importAuthKey(authKey) {
|
|
1136
1111
|
const imported = mutateSharedConfig((freshConfig) => {
|
|
1137
1112
|
if (freshConfig.keys.some((entry) => entry.key === authKey))
|
|
1138
1113
|
return false;
|
|
@@ -1141,6 +1116,25 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1141
1116
|
});
|
|
1142
1117
|
return imported === true;
|
|
1143
1118
|
}
|
|
1119
|
+
async function promptAuthImport(ctx) {
|
|
1120
|
+
if (!ctx.hasUI || config.keys.length > 0 || config.authImportDeclined)
|
|
1121
|
+
return false;
|
|
1122
|
+
const authKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
|
|
1123
|
+
if (!authKey)
|
|
1124
|
+
return false;
|
|
1125
|
+
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?");
|
|
1126
|
+
if (confirmed === true)
|
|
1127
|
+
return await importAuthKey(authKey);
|
|
1128
|
+
const persisted = mutateSharedConfig((freshConfig) => {
|
|
1129
|
+
freshConfig.authImportDeclined = true;
|
|
1130
|
+
return true;
|
|
1131
|
+
});
|
|
1132
|
+
if (persisted === true)
|
|
1133
|
+
ctx.ui.notify("OpenCode: auth.json import declined; /opencode will not ask again.", "info");
|
|
1134
|
+
else if (configError)
|
|
1135
|
+
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1136
|
+
return false;
|
|
1137
|
+
}
|
|
1144
1138
|
pi.on("session_start", async (event, ctx) => {
|
|
1145
1139
|
lastAppliedRuntimeKeys.delete(ctx.modelRegistry);
|
|
1146
1140
|
invalidateAutomaticDecisions();
|
|
@@ -1175,31 +1169,16 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1175
1169
|
}
|
|
1176
1170
|
// On reload: re-apply active key, skip auto-import
|
|
1177
1171
|
if (event.reason === "reload") {
|
|
1178
|
-
|
|
1179
|
-
if (keyName)
|
|
1180
|
-
ctx.ui.notify(`OpenCode: Active key → ${keyName}`, "info");
|
|
1172
|
+
applySynchronizedActiveKey(ctx);
|
|
1181
1173
|
syncUsageStatus(ctx, true);
|
|
1182
1174
|
return;
|
|
1183
1175
|
}
|
|
1184
1176
|
if (config.keys.length === 0) {
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
ctx.ui.notify(`OpenCode: Imported key from auth.json → ${keyName}`, "info");
|
|
1189
|
-
}
|
|
1190
|
-
else if (configError) {
|
|
1191
|
-
ctx.ui.notify(`OpenCode: ${configError}.`, "error");
|
|
1192
|
-
return;
|
|
1193
|
-
}
|
|
1194
|
-
else {
|
|
1195
|
-
ctx.ui.notify("OpenCode: No keys configured. Use /opencode add <name> <key>", "warning");
|
|
1196
|
-
setUsageStatus(undefined);
|
|
1197
|
-
return;
|
|
1198
|
-
}
|
|
1177
|
+
ctx.ui.notify("OpenCode: No keys configured. Run /opencode to add or import keys.", "warning");
|
|
1178
|
+
setUsageStatus(undefined);
|
|
1179
|
+
return;
|
|
1199
1180
|
}
|
|
1200
|
-
|
|
1201
|
-
if (keyName)
|
|
1202
|
-
ctx.ui.notify(`OpenCode: Active key → ${keyName}`, "info");
|
|
1181
|
+
applySynchronizedActiveKey(ctx);
|
|
1203
1182
|
syncUsageStatus(ctx, true);
|
|
1204
1183
|
});
|
|
1205
1184
|
pi.on("model_select", (_event, ctx) => {
|
|
@@ -1445,9 +1424,33 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1445
1424
|
if (!ensureConfig(ctx))
|
|
1446
1425
|
return;
|
|
1447
1426
|
const parts = args.trim().split(/\s+/);
|
|
1448
|
-
const subcommand = parts[0] || "
|
|
1427
|
+
const subcommand = parts[0] || "";
|
|
1449
1428
|
const indexArg = parseInt(parts[1] ?? "", 10);
|
|
1450
1429
|
switch (subcommand) {
|
|
1430
|
+
case "":
|
|
1431
|
+
case "config":
|
|
1432
|
+
case "ui": {
|
|
1433
|
+
if (await promptAuthImport(ctx)) {
|
|
1434
|
+
const importedName = applySynchronizedActiveKey(ctx);
|
|
1435
|
+
if (importedName)
|
|
1436
|
+
ctx.ui.notify(`OpenCode: Imported key from auth.json → ${importedName}`, "info");
|
|
1437
|
+
}
|
|
1438
|
+
if (ctx.mode !== "tui") {
|
|
1439
|
+
ctx.ui.notify(formatStatus(config, now()), "info");
|
|
1440
|
+
break;
|
|
1441
|
+
}
|
|
1442
|
+
const result = await openOpencodeConfig(ctx);
|
|
1443
|
+
if (!ensureConfig(ctx))
|
|
1444
|
+
return;
|
|
1445
|
+
if (result.usageKeyIndex !== undefined) {
|
|
1446
|
+
const target = getUsageTargetForKeyIndex(config, result.usageKeyIndex);
|
|
1447
|
+
const usage = await fetchOpenCodeGoUsage(target, fetchApi, options.timers);
|
|
1448
|
+
ctx.ui.notify(formatUsageStatus(usage), usage.ok ? "info" : "warning");
|
|
1449
|
+
}
|
|
1450
|
+
applySynchronizedActiveKey(ctx);
|
|
1451
|
+
syncUsageStatus(ctx, true);
|
|
1452
|
+
break;
|
|
1453
|
+
}
|
|
1451
1454
|
case "status":
|
|
1452
1455
|
case "list":
|
|
1453
1456
|
case "ls": {
|
|
@@ -1550,13 +1553,8 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1550
1553
|
if (isNaN(removeIndex) || removeIndex < 0 || removeIndex >= freshConfig.keys.length) {
|
|
1551
1554
|
return { error: `Invalid index. Use 1-${freshConfig.keys.length}.` };
|
|
1552
1555
|
}
|
|
1553
|
-
const removed = freshConfig.keys
|
|
1554
|
-
|
|
1555
|
-
freshConfig.quotaBlockedUntil = reindexAfterRemoval(freshConfig.quotaBlockedUntil, removeIndex);
|
|
1556
|
-
if (freshConfig.activeKeyIndex >= freshConfig.keys.length)
|
|
1557
|
-
freshConfig.activeKeyIndex = 0;
|
|
1558
|
-
else if (removeIndex < freshConfig.activeKeyIndex)
|
|
1559
|
-
freshConfig.activeKeyIndex--;
|
|
1556
|
+
const removed = freshConfig.keys[removeIndex];
|
|
1557
|
+
removeKey(freshConfig, removeIndex);
|
|
1560
1558
|
return { removedName: removed.name, count: freshConfig.keys.length };
|
|
1561
1559
|
});
|
|
1562
1560
|
if (!result) {
|
|
@@ -1656,7 +1654,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
|
|
|
1656
1654
|
break;
|
|
1657
1655
|
}
|
|
1658
1656
|
default:
|
|
1659
|
-
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");
|
|
1657
|
+
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");
|
|
1660
1658
|
}
|
|
1661
1659
|
},
|
|
1662
1660
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yugimob/pi-opencode-go-rotation",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"description": "Rotate between multiple OpenCode Go API keys with reactive 429, rate-limit, and watchdog stall detection, plus live footer usage for the active key",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -31,11 +31,18 @@
|
|
|
31
31
|
"author": "Yugimob (https://github.com/YuGiMob)",
|
|
32
32
|
"peerDependencies": {
|
|
33
33
|
"@mariozechner/pi-coding-agent": ">=0.71.1",
|
|
34
|
-
"@earendil-works/pi-coding-agent": "
|
|
34
|
+
"@earendil-works/pi-coding-agent": ">=1.0.0",
|
|
35
|
+
"@earendil-works/pi-tui": "*"
|
|
35
36
|
},
|
|
36
37
|
"peerDependenciesMeta": {
|
|
38
|
+
"@mariozechner/pi-coding-agent": {
|
|
39
|
+
"optional": true
|
|
40
|
+
},
|
|
37
41
|
"@earendil-works/pi-coding-agent": {
|
|
38
42
|
"optional": true
|
|
43
|
+
},
|
|
44
|
+
"@earendil-works/pi-tui": {
|
|
45
|
+
"optional": true
|
|
39
46
|
}
|
|
40
47
|
},
|
|
41
48
|
"keywords": [
|
|
@@ -51,6 +58,8 @@
|
|
|
51
58
|
"access": "public"
|
|
52
59
|
},
|
|
53
60
|
"devDependencies": {
|
|
61
|
+
"@earendil-works/pi-coding-agent": "^1.2.0",
|
|
62
|
+
"@earendil-works/pi-tui": "^1.2.0",
|
|
54
63
|
"@mariozechner/pi-coding-agent": "0.71.1",
|
|
55
64
|
"typescript": "5.9.3"
|
|
56
65
|
}
|