omni-notify-mcp 1.3.396 → 1.3.397
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.
|
@@ -0,0 +1,2184 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
3
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
4
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
5
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
return path;
|
|
9
|
+
};
|
|
10
|
+
const fs = require("fs");
|
|
11
|
+
const os = require("os");
|
|
12
|
+
const path = require("path");
|
|
13
|
+
const { spawn, spawnSync } = require("child_process");
|
|
14
|
+
// GATE: the room, in percent, at or under which the live account's own figure is shown as running low — the same band the room column already paints CRITICAL/LOW; DeepAgent's tick moves nothing at this boundary, the pad's Claude tick moves the live work off it only to a subscription above it, and no move onto or off a key answers to it
|
|
15
|
+
const WARN_BAND_ROOM_PCT = 25;
|
|
16
|
+
/**
|
|
17
|
+
* @typedef {object} AccountState
|
|
18
|
+
* @property {string} identityId
|
|
19
|
+
* @property {string} label
|
|
20
|
+
* @property {number | null} room
|
|
21
|
+
* @property {boolean} refused
|
|
22
|
+
* @property {number | null} [refillsAt] ms epoch when every window this account has spent has reset
|
|
23
|
+
* @property {boolean} [setupRefused] its room was read through its vaulted login because the server refused its setup token, which is the credential a switch makes live
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* @typedef {"switchSubscription" | "switchByok" | "switchBackFromSubscription"} MoveKind
|
|
27
|
+
* @typedef {{ kind: MoveKind, to: string, from: string, at: number, recheckAt?: number }} Move
|
|
28
|
+
*/
|
|
29
|
+
/**
|
|
30
|
+
* @typedef {object} DecisionInput
|
|
31
|
+
* @property {string} providerId
|
|
32
|
+
* @property {AccountState[]} accounts
|
|
33
|
+
* @property {string | undefined} liveIdentityId
|
|
34
|
+
* @property {boolean} liveFailed
|
|
35
|
+
* @property {boolean} [liveLoggedOut] the box carries no usable login at all
|
|
36
|
+
* @property {boolean} onByok
|
|
37
|
+
* @property {Move | undefined} lastMove
|
|
38
|
+
* @property {number} readAt
|
|
39
|
+
* @property {boolean} switchEnabled
|
|
40
|
+
* @property {boolean} byokEnabled
|
|
41
|
+
* @property {boolean} [arming]
|
|
42
|
+
* @property {string} [chosenIdentityId] the subscription HP's DeepAgent choice names for this box (`chosenSubscriptionOf`), the one a box is returned to while switching is off
|
|
43
|
+
*/
|
|
44
|
+
/**
|
|
45
|
+
* @typedef {{ kind: "none", why: string }
|
|
46
|
+
* | { kind: "warn", identityId: string, label: string, roomPct: number }
|
|
47
|
+
* | { kind: "switchSubscription", identityId: string, label: string, reason: string }
|
|
48
|
+
* | { kind: "switchByok", reason: string }
|
|
49
|
+
* | { kind: "switchBackFromSubscription", identityId: string, label: string, reason: string }} AutoSwitchAction
|
|
50
|
+
*/
|
|
51
|
+
const CLI_PROVIDER = "anthropic";
|
|
52
|
+
// #2709 — the pair, each its OWN box: `autoSwitch` alone moves work between subscriptions, `byokFallback` alone lets it move onto a key, so Auto can mean subscriptions only.
|
|
53
|
+
const AUTO_BOX = "autoSwitch";
|
|
54
|
+
const BYOK_BOX = "byokFallback";
|
|
55
|
+
/**
|
|
56
|
+
* #2073 — THE effort `claude-provider.sh`'s unattended failover writes into every `modelSettings` row a routed
|
|
57
|
+
* key's models carry. It is declared here, not as a literal inside that script, because this is the module the
|
|
58
|
+
* script already requires beside it. DeepAgent's panel switch keeps its own `ROUTED_EFFORT_LEVEL` (plan.ts):
|
|
59
|
+
* the two must agree, and claude-provider-regression.sh proves the script reads THIS one by changing it here
|
|
60
|
+
* and observing the shipped switch write the changed level.
|
|
61
|
+
*/
|
|
62
|
+
const ROUTED_EFFORT_LEVEL = "xhigh";
|
|
63
|
+
// GATE: how long a prompt's refusal counts as "this account just refused me" — inside it the account is treated as spent, and beyond it the 30-second tick returns to judging by the usage reading, so a one-off refusal does not hold an agent on a key for ever
|
|
64
|
+
const REFUSAL_WINDOW_MS = 10 * 60 * 1000;
|
|
65
|
+
/** @param {string} home */
|
|
66
|
+
function settingsPath(home) {
|
|
67
|
+
return path.join(home, ".bullseye", "auto-switch", "settings.json");
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* One box of this provider's pair, answered on its own: absent is off, and a value that is neither true nor false is refused by name.
|
|
71
|
+
* @param {string} home
|
|
72
|
+
* @param {string} providerId
|
|
73
|
+
* @param {string} name
|
|
74
|
+
* @returns {boolean}
|
|
75
|
+
*/
|
|
76
|
+
function readBox(home, providerId, name) {
|
|
77
|
+
const file = settingsPath(home);
|
|
78
|
+
const text = unlessErr("ENOENT", () => fs.readFileSync(file, "utf8"));
|
|
79
|
+
if (text === undefined)
|
|
80
|
+
return false;
|
|
81
|
+
const saved = JSON.parse(text)[providerId] || {};
|
|
82
|
+
if (saved[name] === undefined)
|
|
83
|
+
return false;
|
|
84
|
+
if (typeof saved[name] !== "boolean") {
|
|
85
|
+
throw new Error(`${providerId}.${name} in ${file} is ${JSON.stringify(saved[name])}, not true or false — fix that file and run the same command again`);
|
|
86
|
+
}
|
|
87
|
+
return saved[name];
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Whether this provider's subscriptions are switched between at all.
|
|
91
|
+
* @param {string} home
|
|
92
|
+
* @param {string} providerId
|
|
93
|
+
* @returns {boolean}
|
|
94
|
+
*/
|
|
95
|
+
function readAuto(home, providerId) {
|
|
96
|
+
return readBox(home, providerId, AUTO_BOX);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Whether this provider's work may also move onto a key once every subscription is spent.
|
|
100
|
+
* @param {string} home
|
|
101
|
+
* @param {string} providerId
|
|
102
|
+
* @returns {boolean}
|
|
103
|
+
*/
|
|
104
|
+
function readByokFallback(home, providerId) {
|
|
105
|
+
return readBox(home, providerId, BYOK_BOX);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* One field of one provider in the machine's auto-switch settings file, written atomically beside the rest.
|
|
109
|
+
* @param {string} home
|
|
110
|
+
* @param {string} providerId
|
|
111
|
+
* @param {string} name
|
|
112
|
+
* @param {boolean | string} value
|
|
113
|
+
*/
|
|
114
|
+
function writeProviderField(home, providerId, name, value) {
|
|
115
|
+
const file = settingsPath(home);
|
|
116
|
+
let all = {};
|
|
117
|
+
try {
|
|
118
|
+
all = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
119
|
+
}
|
|
120
|
+
catch (cause) {
|
|
121
|
+
if ( /** @type {NodeJS.ErrnoException} */(cause).code !== "ENOENT")
|
|
122
|
+
throw cause;
|
|
123
|
+
}
|
|
124
|
+
all[providerId] = { ...(all[providerId] || {}), [name]: value };
|
|
125
|
+
writeAtomically(file, JSON.stringify(all, null, 2) + "\n");
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* @param {string} home
|
|
129
|
+
* @param {string} providerId
|
|
130
|
+
* @param {boolean} on
|
|
131
|
+
*/
|
|
132
|
+
function writeAuto(home, providerId, on) {
|
|
133
|
+
writeProviderField(home, providerId, AUTO_BOX, on);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* @param {string} home
|
|
137
|
+
* @param {string} providerId
|
|
138
|
+
* @param {boolean} on
|
|
139
|
+
*/
|
|
140
|
+
function writeByokFallback(home, providerId, on) {
|
|
141
|
+
writeProviderField(home, providerId, BYOK_BOX, on);
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* THE KEY TO FALL BACK TO (#1818) — the operator's own choice of WHICH BYOK key a fail-over moves to,
|
|
145
|
+
* kept in the SAME machine file as the two boxes because it is the same policy: the boxes say WHEN to
|
|
146
|
+
* fall back, this says WHERE TO. Meni 2026-10-15: *"User MUST be able to control the preferred byok key
|
|
147
|
+
* of CHOICE to failover !!! and only if it runs out of $$ switch to the other one!!!"*.
|
|
148
|
+
*
|
|
149
|
+
* An empty string is "he has not chosen" — the caller then takes the first usable key, exactly as it did
|
|
150
|
+
* before this field existed. A stored value names a KEY by the id DeepAgent's own list gives it ("deepseek",
|
|
151
|
+
* "deepseek-2"); an id no longer on the machine is not an error here, it is the absence the caller reports.
|
|
152
|
+
*
|
|
153
|
+
* @param {string} home
|
|
154
|
+
* @param {string} providerId
|
|
155
|
+
* @returns {string} the key id he chose, or "" when none was chosen
|
|
156
|
+
*/
|
|
157
|
+
function readByokKey(home, providerId) {
|
|
158
|
+
const text = unlessErr("ENOENT", () => fs.readFileSync(settingsPath(home), "utf8"));
|
|
159
|
+
if (text === undefined)
|
|
160
|
+
return "";
|
|
161
|
+
const saved = JSON.parse(text)[providerId] || {};
|
|
162
|
+
if (saved.byokKey === undefined)
|
|
163
|
+
return "";
|
|
164
|
+
if (typeof saved.byokKey !== "string") {
|
|
165
|
+
throw new Error(`${providerId}.byokKey in ${settingsPath(home)} is ${JSON.stringify(saved.byokKey)}, not a key id — fix that file and run the same command again`);
|
|
166
|
+
}
|
|
167
|
+
return saved.byokKey;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* @param {string} home
|
|
171
|
+
* @param {string} providerId
|
|
172
|
+
* @param {string} keyId the key to fall back to, or "" to clear the choice
|
|
173
|
+
*/
|
|
174
|
+
function writeByokKey(home, providerId, keyId) {
|
|
175
|
+
writeProviderField(home, providerId, "byokKey", keyId);
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* @param {string} home
|
|
179
|
+
* @param {string} providerId
|
|
180
|
+
*/
|
|
181
|
+
function refusalPath(home, providerId) {
|
|
182
|
+
return path.join(home, ".bullseye", "auto-switch", `${providerId}.refused.json`);
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Records that a real prompt was refused by this provider's live subscription.
|
|
186
|
+
*
|
|
187
|
+
* @param {string} home
|
|
188
|
+
* @param {string} providerId
|
|
189
|
+
* @param {string} reason
|
|
190
|
+
* @param {number} [at]
|
|
191
|
+
*/
|
|
192
|
+
function markRefused(home, providerId, reason, at = Date.now()) {
|
|
193
|
+
writeAtomically(refusalPath(home, providerId), JSON.stringify({ at, reason }));
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* @param {string} home
|
|
197
|
+
* @param {string} providerId
|
|
198
|
+
* @returns {{ at: number, reason: string } | undefined}
|
|
199
|
+
*/
|
|
200
|
+
function readRefusal(home, providerId) {
|
|
201
|
+
const file = refusalPath(home, providerId);
|
|
202
|
+
let text;
|
|
203
|
+
try {
|
|
204
|
+
text = fs.readFileSync(file, "utf8");
|
|
205
|
+
}
|
|
206
|
+
catch (cause) {
|
|
207
|
+
if ( /** @type {NodeJS.ErrnoException} */(cause).code === "ENOENT")
|
|
208
|
+
return undefined;
|
|
209
|
+
throw cause;
|
|
210
|
+
}
|
|
211
|
+
let record;
|
|
212
|
+
try {
|
|
213
|
+
record = JSON.parse(text);
|
|
214
|
+
}
|
|
215
|
+
catch (notJson) {
|
|
216
|
+
if (!(notJson instanceof SyntaxError))
|
|
217
|
+
throw notJson;
|
|
218
|
+
record = undefined;
|
|
219
|
+
}
|
|
220
|
+
if (!record || typeof record.at !== "number" || typeof record.reason !== "string") {
|
|
221
|
+
throw Object.assign(new Error(`${file} does not record a refusal (${text.slice(0, 200)}) — delete it and the next refusal writes it again`), { code: "REFUSAL_UNREADABLE" });
|
|
222
|
+
}
|
|
223
|
+
return record;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* @param {string} home
|
|
227
|
+
* @param {string} providerId
|
|
228
|
+
*/
|
|
229
|
+
function clearRefusal(home, providerId) {
|
|
230
|
+
fs.rmSync(refusalPath(home, providerId), { force: true });
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* @param {{ at: number, reason: string } | undefined} refusal
|
|
234
|
+
* @param {number} now
|
|
235
|
+
*/
|
|
236
|
+
function refusalIsFresh(refusal, now) {
|
|
237
|
+
return refusal !== undefined && now - refusal.at <= REFUSAL_WINDOW_MS;
|
|
238
|
+
}
|
|
239
|
+
function isSubscriptionQuota(record) {
|
|
240
|
+
return record.isApiErrorMessage === true && record.error === "rate_limit" && record.apiErrorStatus === 429
|
|
241
|
+
&& record.quotaLimits && record.quotaLimits.status === "rejected"
|
|
242
|
+
&& (record.quotaLimits.rateLimitType === "five_hour" || record.quotaLimits.rateLimitType === "seven_day");
|
|
243
|
+
}
|
|
244
|
+
// GATE: how many times the rename into place is tried while another handle holds the destination — 250 ms apart, so a reader's momentary hold is waited out and a hold that outlasts every try is refused as the real refusal it is
|
|
245
|
+
const HELD_RENAME_TRIES = 8;
|
|
246
|
+
/**
|
|
247
|
+
* Replaces a file's bytes whole, retried while the TARGET is held open.
|
|
248
|
+
*
|
|
249
|
+
* Windows refuses a rename whose destination has an open handle — `EPERM: operation not permitted,
|
|
250
|
+
* rename '…tmp' -> '…'` — and the hold is momentary: the pad reads these files on its own tick
|
|
251
|
+
* (`read_text_past_a_replace` retries its READ for the same reason), so the very next try after the
|
|
252
|
+
* reader closes lands. Without the retry that instant is reported as the WRITE's own failure, and for
|
|
253
|
+
* `claude-last.json` / `engine-last.json` that is the pad judging a switch that worked as a job that
|
|
254
|
+
* "did not finish its work". Same shape as `prune-superseded.js`'s held-rename retry.
|
|
255
|
+
* @param {string} file @param {string} text
|
|
256
|
+
*/
|
|
257
|
+
function writeAtomically(file, text) {
|
|
258
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
259
|
+
const staged = `${file}.${process.pid}.tmp`;
|
|
260
|
+
try {
|
|
261
|
+
fs.writeFileSync(staged, text);
|
|
262
|
+
for (let attempt = 1;; attempt += 1) {
|
|
263
|
+
try {
|
|
264
|
+
fs.renameSync(staged, file);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
catch (cause) {
|
|
268
|
+
if ((cause.code !== "EPERM" && cause.code !== "EBUSY") || attempt === HELD_RENAME_TRIES)
|
|
269
|
+
throw cause;
|
|
270
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 250);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
finally {
|
|
275
|
+
// A refused write leaves bytes that are neither version beside the pad's own records; the target is intact either way, so this is the residue to clear.
|
|
276
|
+
fs.rmSync(staged, { force: true });
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/** @param {AccountState} a */
|
|
280
|
+
function spent(a) {
|
|
281
|
+
return a.refused || (a.room !== null && a.room <= 0);
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* @param {AccountState[]} accounts
|
|
285
|
+
* @returns {AccountState | undefined}
|
|
286
|
+
*/
|
|
287
|
+
function blockingSubscription(accounts) {
|
|
288
|
+
return accounts.find((a) => !spent(a));
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* @param {AccountState} a
|
|
292
|
+
* @returns {string}
|
|
293
|
+
*/
|
|
294
|
+
function heldBy(a) {
|
|
295
|
+
return a.setupRefused === true ? `${a.label} has room but the server refuses its setup token` : `${a.label} could not be read`;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* @param {AccountState[]} accounts
|
|
299
|
+
* @param {number} [above] only accounts holding MORE room than this
|
|
300
|
+
* @returns {AccountState | undefined}
|
|
301
|
+
*/
|
|
302
|
+
function mostRoom(accounts, above = 0) {
|
|
303
|
+
/** @type {AccountState | undefined} */
|
|
304
|
+
let best;
|
|
305
|
+
for (const a of accounts) {
|
|
306
|
+
if (a.room === null || a.room <= above || a.refused || a.setupRefused === true)
|
|
307
|
+
continue;
|
|
308
|
+
if (best === undefined || a.room > /** @type {number} */ (best.room))
|
|
309
|
+
best = a;
|
|
310
|
+
}
|
|
311
|
+
return best;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* @param {string} why
|
|
315
|
+
* @returns {AutoSwitchAction}
|
|
316
|
+
*/
|
|
317
|
+
function none(why) {
|
|
318
|
+
return { kind: "none", why };
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Switching off means no move AWAY from the chosen subscription when it runs out of room; it never means a box that
|
|
322
|
+
* drifted off HP's choice stays there. A box not running the chosen subscription, while the chosen one has room and
|
|
323
|
+
* the server accepts its setup token, is moved onto it; a box on it, on a key (a deliberate pick), or whose chosen one has none, stays.
|
|
324
|
+
* @param {DecisionInput} input
|
|
325
|
+
* @returns {AutoSwitchAction}
|
|
326
|
+
*/
|
|
327
|
+
function returnToChoice(input) {
|
|
328
|
+
const { providerId, accounts, liveIdentityId, onByok, lastMove, readAt, chosenIdentityId } = input;
|
|
329
|
+
const off = `automatic switching is off (${providerId}.autoSwitch in ~/.bullseye/auto-switch/settings.json)`;
|
|
330
|
+
if (chosenIdentityId === undefined)
|
|
331
|
+
return none(off);
|
|
332
|
+
const chosen = accounts.find((a) => a.identityId === chosenIdentityId);
|
|
333
|
+
if (chosen === undefined)
|
|
334
|
+
return none(`${off}, and the subscription chosen on HP (${chosenIdentityId}) is not one of this box's accounts`);
|
|
335
|
+
if (lastMove !== undefined && lastMove.at > readAt) {
|
|
336
|
+
return none(`${lastMove.to} went live after these readings were taken — deciding again on fresh ones`);
|
|
337
|
+
}
|
|
338
|
+
if (onByok)
|
|
339
|
+
return none(`${off}, and the live work is on a key, which nothing automatic put there`);
|
|
340
|
+
if (input.liveLoggedOut !== true && liveIdentityId === chosen.identityId)
|
|
341
|
+
return none(`${off}, and ${chosen.label} is the subscription chosen on HP and is live`);
|
|
342
|
+
if (spent(chosen) || chosen.room === null || chosen.setupRefused === true) {
|
|
343
|
+
return none(`${off}, and ${chosen.label}, the subscription chosen on HP, has no usable room, so the live work is not moved`);
|
|
344
|
+
}
|
|
345
|
+
const reason = `${chosen.label} is the subscription chosen on HP and has ${chosen.room}% room — moved back though switching is off`;
|
|
346
|
+
return { kind: "switchSubscription", identityId: chosen.identityId, label: chosen.label, reason };
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* @param {DecisionInput} input
|
|
350
|
+
* @returns {AutoSwitchAction}
|
|
351
|
+
*/
|
|
352
|
+
function decide(input) {
|
|
353
|
+
const { providerId, accounts, liveIdentityId, liveFailed, onByok, lastMove, readAt, switchEnabled, byokEnabled } = input;
|
|
354
|
+
if (!switchEnabled)
|
|
355
|
+
return returnToChoice(input);
|
|
356
|
+
if (lastMove !== undefined && lastMove.at > readAt) {
|
|
357
|
+
return none(`${lastMove.to} went live after these readings were taken — deciding again on fresh ones`);
|
|
358
|
+
}
|
|
359
|
+
const best = mostRoom(accounts);
|
|
360
|
+
if (input.arming === true)
|
|
361
|
+
return arm(input, best);
|
|
362
|
+
if (onByok) {
|
|
363
|
+
if (best !== undefined) {
|
|
364
|
+
return { kind: "switchBackFromSubscription", identityId: best.identityId, label: best.label, reason: `${best.label} has room again` };
|
|
365
|
+
}
|
|
366
|
+
const unread = blockingSubscription(accounts);
|
|
367
|
+
return none(unread !== undefined
|
|
368
|
+
? `${heldBy(unread)}, so the live work stays on the key until that changes`
|
|
369
|
+
: "every subscription is still spent");
|
|
370
|
+
}
|
|
371
|
+
if (input.liveLoggedOut === true) {
|
|
372
|
+
if (best === undefined)
|
|
373
|
+
return byokEnabled && accounts.every(spent)
|
|
374
|
+
? { kind: "switchByok", reason: "no account is logged in and every subscription is spent" }
|
|
375
|
+
: none("no account is logged in and no subscription can be made live");
|
|
376
|
+
return { kind: "switchSubscription", identityId: best.identityId, label: best.label, reason: `no account is logged in — ${best.label} has the most room` };
|
|
377
|
+
}
|
|
378
|
+
const live = accounts.find((a) => a.identityId === liveIdentityId);
|
|
379
|
+
if (live === undefined) {
|
|
380
|
+
// A subscription with room outranks the key when the live work is not on one of this provider's accounts -- a
|
|
381
|
+
// login kept outside the roster, say. The forward path to an account is never gated behind every subscription
|
|
382
|
+
// being spent; only the fall-back ONTO a key is. (A key carrying the work is handled above, by the onByok branch.)
|
|
383
|
+
if (best !== undefined) {
|
|
384
|
+
return { kind: "switchSubscription", identityId: best.identityId, label: best.label, reason: `${best.label} has the most room and no subscription is live` };
|
|
385
|
+
}
|
|
386
|
+
return byokEnabled && accounts.length > 0 && accounts.every(spent)
|
|
387
|
+
? { kind: "switchByok", reason: "the live account is not in the list and every subscription is spent" }
|
|
388
|
+
: none("the account live now is not one of this provider's subscriptions");
|
|
389
|
+
}
|
|
390
|
+
if (!liveFailed && !spent(live)) {
|
|
391
|
+
if (live.room === null)
|
|
392
|
+
return none(`${live.label} could not be read`);
|
|
393
|
+
if (live.room <= WARN_BAND_ROOM_PCT)
|
|
394
|
+
return { kind: "warn", identityId: live.identityId, label: live.label, roomPct: live.room };
|
|
395
|
+
return none(`${live.label} still has room (${live.room}%)`);
|
|
396
|
+
}
|
|
397
|
+
if (best !== undefined) {
|
|
398
|
+
return { kind: "switchSubscription", identityId: best.identityId, label: best.label, reason: `${live.label} is spent — ${best.label} has room` };
|
|
399
|
+
}
|
|
400
|
+
const unread = blockingSubscription(accounts);
|
|
401
|
+
if (unread !== undefined)
|
|
402
|
+
return none(`${heldBy(unread)}, so nothing is moved until that changes`);
|
|
403
|
+
if (byokEnabled) {
|
|
404
|
+
return { kind: "switchByok", reason: `${live.label} is spent and every other subscription of this provider is spent too` };
|
|
405
|
+
}
|
|
406
|
+
return none(`every subscription is spent and falling back to a key is off (${providerId}.byokFallback in ~/.bullseye/auto-switch/settings.json)`);
|
|
407
|
+
}
|
|
408
|
+
// GATE: the agent tier kinds a subscription Meni already pays for serves — every other kind a chain names bills a key per token and is ranked after all of them
|
|
409
|
+
const SUBSCRIPTION_TIER_KINDS = Object.freeze(["claude-cli", "claude", "codex-cli", "copilot-cli"]);
|
|
410
|
+
// GATE: the agent tier kinds a Claude subscription serves — a chain naming one of them gains the key rung, last
|
|
411
|
+
const CLAUDE_TIER_KINDS = Object.freeze(["claude-cli", "claude"]);
|
|
412
|
+
// GATE: the key rung each kind of call gains behind a Claude tier — a text ask on the box's paid pair, an act through the claude CLI on it
|
|
413
|
+
const KEY_RUNGS = Object.freeze({ ask: "configured-byok", act: "claude-byok" });
|
|
414
|
+
/**
|
|
415
|
+
* The key rung a chain gains, or undefined: the rung of its `kind` when the chain names a Claude tier and does not
|
|
416
|
+
* already declare that rung itself. Whether it is then offered is Meni's `claude.byokFallback` box, read only for a
|
|
417
|
+
* chain that has a rung to offer.
|
|
418
|
+
* @param {{ chain: string[], kinds?: Record<string, string>, kind?: string }} input
|
|
419
|
+
* @returns {string | undefined}
|
|
420
|
+
*/
|
|
421
|
+
function keyRungOf({ chain, kinds = {}, kind }) {
|
|
422
|
+
const rung = kind === undefined ? undefined : KEY_RUNGS[kind];
|
|
423
|
+
return rung !== undefined && !chain.includes(rung) && chain.some((tier) => CLAUDE_TIER_KINDS.includes(kinds[tier] || tier)) ? rung : undefined;
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* THE one cross-provider ranking every AI chain runs in, Python, shell and Java alike (Meni 2026-11-15: "we always use the
|
|
427
|
+
* besy avail agentic provider that first uses sub and only if all is exhusted we use BYOK"): every tier a subscription
|
|
428
|
+
* serves, in the chain's declared order, then every tier a key bills, in its declared order, then the chain's key rung
|
|
429
|
+
* (`keyRungOf`) last, each tier once, and only while Meni's `claude.byokFallback` box is on. A tier the answer holds that
|
|
430
|
+
* the chain did not declare is that rung, which its caller asks only on a box that configures a paid pair. Room is weighed
|
|
431
|
+
* inside each subscription tier, account by account, by the chain that runs it. An explicit provider choice is never
|
|
432
|
+
* ranked: the caller that names one runs it as named.
|
|
433
|
+
* @param {{ chain: string[], kinds?: Record<string, string>, kind?: string, keyFallback: boolean }} input `kinds` maps a tier to its kind when its name is not its kind; `kind` is `ask` or `act`, absent for a chain that never gains a key rung; `keyFallback` is `readByokFallback(home, "claude")`
|
|
434
|
+
* @returns {string[]}
|
|
435
|
+
*/
|
|
436
|
+
function subscriptionFirst({ chain, kinds = {}, kind, keyFallback }) {
|
|
437
|
+
const paid = (tier) => SUBSCRIPTION_TIER_KINDS.includes(kinds[tier] || tier);
|
|
438
|
+
const rung = keyFallback ? keyRungOf({ chain, kinds, kind }) : undefined;
|
|
439
|
+
return [...new Set([...chain.filter(paid), ...chain.filter((tier) => !paid(tier)), ...(rung === undefined ? [] : [rung])])];
|
|
440
|
+
}
|
|
441
|
+
/** Where DeepAgent's server answers on this machine. */
|
|
442
|
+
const DEEPAGENT_DOOR = "http://127.0.0.1:7473";
|
|
443
|
+
/** Its MCP door — every dispatcher asks it for each provider's token room (`provider_room`). */
|
|
444
|
+
const DEEPAGENT_MCP_URL = `${DEEPAGENT_DOOR}/mcp`;
|
|
445
|
+
// GATE: how long one `provider_room` read may take before it is a failed reading — twenty seconds, the span ChatGPT's own answer needs for every Codex subscription; past it the room is "could not be read" and the caller keeps its own landing.
|
|
446
|
+
const ROOM_READ_TIMEOUT_MS = 20_000;
|
|
447
|
+
/** The agent CLIs whose subscriptions `provider_room` reads; OpenCode runs on keys and is never among them. */
|
|
448
|
+
const ROOM_PROVIDERS = Object.freeze(["claude", "codex", "copilot"]);
|
|
449
|
+
/** `provider_room` answered anything but a reading: the door gave no answer, a non-200, or a body that is no reading. */
|
|
450
|
+
class RoomReadError extends Error {
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* @typedef {{ state: "room" } | { state: "out", resetsAtMs: number | undefined } | { state: "unread", reason: string }} RoomReading
|
|
454
|
+
* @typedef {Partial<Record<string, RoomReading>>} ProviderRooms
|
|
455
|
+
*/
|
|
456
|
+
/** @param {string} provider */
|
|
457
|
+
function runsOnKeys(provider) {
|
|
458
|
+
return provider === "opencode";
|
|
459
|
+
}
|
|
460
|
+
/** @param {string} provider @param {ProviderRooms} rooms */
|
|
461
|
+
function billsAKey(provider, rooms) {
|
|
462
|
+
return runsOnKeys(provider) || rooms[provider]?.state === "out";
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* One provider's token room out of its `provider_room` entry: some left, spent until a refill, or a reading that could not be taken (never read as spent).
|
|
466
|
+
* @param {any} provider @param {number} now @returns {RoomReading}
|
|
467
|
+
*/
|
|
468
|
+
function roomReadingOf(provider, now) {
|
|
469
|
+
// NULL-OK: field provider is OPTIONAL and therefore it is ok to check for NULL
|
|
470
|
+
if (provider === undefined || provider.state !== "read" || !Array.isArray(provider.accounts)) {
|
|
471
|
+
return { state: "unread", reason: typeof provider?.reason === "string" ? provider.reason : "the provider was not read" };
|
|
472
|
+
}
|
|
473
|
+
const accounts = provider.accounts;
|
|
474
|
+
if (accounts.some((a) => a.state === "read" && a.refused !== true && (a.unlimited === true || (typeof a.roomPct === "number" && a.roomPct > 0))))
|
|
475
|
+
return { state: "room" };
|
|
476
|
+
if (accounts.length === 0 || !accounts.every((a) => a.state === "read" && typeof a.roomPct === "number"))
|
|
477
|
+
return { state: "unread", reason: "an account's room could not be read" };
|
|
478
|
+
if (accounts.some((a) => a.refused !== true && typeof a.resetsAt === "number" && a.resetsAt <= now))
|
|
479
|
+
return { state: "unread", reason: "the reading predates an account's refill" };
|
|
480
|
+
const refills = accounts.filter((a) => a.refused !== true).map((a) => a.resetsAt).filter((r) => typeof r === "number");
|
|
481
|
+
return { state: "out", resetsAtMs: refills.length === 0 ? undefined : Math.min(...refills) };
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* The room of each provider a dispatcher can land on, out of `provider_room`'s own answer. A provider the answer does not carry is unread, never out.
|
|
485
|
+
* @param {{ providers?: Record<string, any> }} answer @param {number} now @returns {ProviderRooms}
|
|
486
|
+
*/
|
|
487
|
+
function roomsOf(answer, now) {
|
|
488
|
+
return Object.fromEntries(ROOM_PROVIDERS.map((id) => [id, roomReadingOf(answer.providers?.[id], now)]));
|
|
489
|
+
}
|
|
490
|
+
/** Every provider unread, with the reason the whole reading failed. @param {string} reason @returns {ProviderRooms} */
|
|
491
|
+
function unreadRooms(reason) {
|
|
492
|
+
return Object.fromEntries(ROOM_PROVIDERS.map((id) => [id, { state: "unread", reason }]));
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* THE one pick of an agent CLI when the caller named none: of `order` the ones `startable` can run, a provider with room
|
|
496
|
+
* first, and `subscriptionFirst` ranking a subscription with room before anything that bills a key.
|
|
497
|
+
* @param {readonly string[]} order @param {ProviderRooms} rooms @param {readonly string[]} startable @returns {string}
|
|
498
|
+
*/
|
|
499
|
+
function autoProvider(order, rooms, startable) {
|
|
500
|
+
const candidates = order.filter((p) => startable.includes(p));
|
|
501
|
+
const tierOf = (p) => (billsAKey(p, rooms) ? p + "-byok" : p + "-cli");
|
|
502
|
+
const rank = (p) => (rooms[p]?.state === "room" ? 0 : 1);
|
|
503
|
+
const chain = [...candidates].sort((x, y) => rank(x) - rank(y)).map(tierOf);
|
|
504
|
+
const first = subscriptionFirst({ chain, keyFallback: false })[0];
|
|
505
|
+
return candidates.find((p) => tierOf(p) === first);
|
|
506
|
+
}
|
|
507
|
+
/** @param {string} url @param {string} project @returns {Promise<{ status: number, body: string }>} */
|
|
508
|
+
async function roomDoorAnswer(url, project) {
|
|
509
|
+
try {
|
|
510
|
+
const res = await fetch(url, {
|
|
511
|
+
method: "POST",
|
|
512
|
+
headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "x-deepagent-project": project },
|
|
513
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "provider_room", arguments: {} } }),
|
|
514
|
+
signal: AbortSignal.timeout(ROOM_READ_TIMEOUT_MS),
|
|
515
|
+
});
|
|
516
|
+
return { status: res.status, body: await res.text() };
|
|
517
|
+
}
|
|
518
|
+
catch (err) {
|
|
519
|
+
if (!(err instanceof TypeError) && !(err instanceof Error && err.name === "TimeoutError"))
|
|
520
|
+
throw err;
|
|
521
|
+
const cause = err.cause instanceof Error ? ` (${err.cause.message})` : "";
|
|
522
|
+
throw new RoomReadError(`DeepAgent's door at ${url} gave no answer: ${err.message}${cause}`);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
/** @param {string} text @param {string} what */
|
|
526
|
+
function roomParsedOf(text, what) {
|
|
527
|
+
try {
|
|
528
|
+
return JSON.parse(text);
|
|
529
|
+
}
|
|
530
|
+
catch (err) {
|
|
531
|
+
if (!(err instanceof SyntaxError))
|
|
532
|
+
throw err;
|
|
533
|
+
throw new RoomReadError(`provider_room's ${what} is not JSON (${err.message}): ${text.slice(0, 200)}`);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* Asks DeepAgent's `provider_room` over its MCP door, for the folder `project` names. Throws RoomReadError when the door answers anything but a reading.
|
|
538
|
+
* @param {string} project @param {string} [url] @param {() => number} [now] @returns {Promise<ProviderRooms>}
|
|
539
|
+
*/
|
|
540
|
+
async function readProviderRooms(project, url = DEEPAGENT_MCP_URL, now = Date.now) {
|
|
541
|
+
const { status, body } = await roomDoorAnswer(url, project);
|
|
542
|
+
if (status !== 200)
|
|
543
|
+
throw new RoomReadError(`provider_room answered HTTP ${status}: ${body.slice(0, 200)}`);
|
|
544
|
+
const reply = roomParsedOf(body, "reply");
|
|
545
|
+
const text = reply.result?.content?.[0]?.text;
|
|
546
|
+
if (reply.result === undefined || reply.result.isError === true || text === undefined)
|
|
547
|
+
throw new RoomReadError(`provider_room gave no reading: ${(text ?? reply.error?.message ?? body).slice(0, 200)}`);
|
|
548
|
+
return roomsOf(roomParsedOf(text, "reading"), now());
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Whether the live work has an account with room to run on, worked out from the readings alone and never from a
|
|
552
|
+
* decision's words: covered when the live account read room, uncovered when it read spent (or nobody is logged in and
|
|
553
|
+
* every account read spent), unknown when the reading that would say was not taken or failed (#10553).
|
|
554
|
+
* @param {AccountState[]} accounts
|
|
555
|
+
* @param {string | undefined} liveIdentityId
|
|
556
|
+
* @param {boolean} loggedOut
|
|
557
|
+
* @returns {{ state: "covered" | "uncovered" | "unknown", why: string }}
|
|
558
|
+
*/
|
|
559
|
+
function coverageOf(accounts, liveIdentityId, loggedOut) {
|
|
560
|
+
if (loggedOut) {
|
|
561
|
+
if (accounts.length === 0)
|
|
562
|
+
return { state: "unknown", why: "no account is logged in and this provider has no subscription to read" };
|
|
563
|
+
const unread = accounts.find((a) => !a.refused && a.room === null);
|
|
564
|
+
if (unread !== undefined)
|
|
565
|
+
return { state: "unknown", why: `no account is logged in and ${unread.label} could not be read` };
|
|
566
|
+
const withRoom = accounts.filter((a) => !spent(a));
|
|
567
|
+
if (withRoom.length > 0) {
|
|
568
|
+
return { state: "uncovered", why: `no account is logged in, though ${withRoom.map((a) => `${a.label} has ${a.room}% room`).join(" and ")}` };
|
|
569
|
+
}
|
|
570
|
+
return { state: "uncovered", why: "no account is logged in and every subscription is spent" };
|
|
571
|
+
}
|
|
572
|
+
const live = accounts.find((a) => a.identityId === liveIdentityId);
|
|
573
|
+
if (live === undefined)
|
|
574
|
+
return { state: "unknown", why: "the account live now is not one of this provider's subscriptions, so its room was not read" };
|
|
575
|
+
if (spent(live))
|
|
576
|
+
return { state: "uncovered", why: `${live.label}, the account carrying the live work, is spent` };
|
|
577
|
+
if (live.room === null)
|
|
578
|
+
return { state: "unknown", why: `${live.label}, the account carrying the live work, could not be read` };
|
|
579
|
+
return { state: "covered", why: `${live.label} carries the live work with ${live.room}% room` };
|
|
580
|
+
}
|
|
581
|
+
// GATE: how many times in all one reading that failed TRANSIENTLY (no answer from the network, a timeout, an HTTP 5xx) is tried before it is reported unread
|
|
582
|
+
const TRANSIENT_TRIES = 3;
|
|
583
|
+
// GATE: the wait before the second try of a transiently failed reading, doubled before each try after it
|
|
584
|
+
const TRANSIENT_FIRST_WAIT_MS = 1000;
|
|
585
|
+
/**
|
|
586
|
+
* A reading that failed TRANSIENTLY - its error carries `transient: true` - is tried again after a doubling wait, so one
|
|
587
|
+
* vendor 5xx or network blip is never reported as an account or a key that could not be read; any other failure is the
|
|
588
|
+
* reading's own answer and is thrown at once, and a transient one still failing after the last try is thrown naming how
|
|
589
|
+
* many tries it had (#10553).
|
|
590
|
+
* @template T
|
|
591
|
+
* @param {() => Promise<T>} read
|
|
592
|
+
* @returns {Promise<T>}
|
|
593
|
+
*/
|
|
594
|
+
async function transientRetried(read) {
|
|
595
|
+
for (let tried = 1;; tried += 1) {
|
|
596
|
+
try {
|
|
597
|
+
return await read();
|
|
598
|
+
}
|
|
599
|
+
catch (failed) {
|
|
600
|
+
if (!(failed && failed.transient === true))
|
|
601
|
+
throw failed;
|
|
602
|
+
if (tried >= TRANSIENT_TRIES) {
|
|
603
|
+
throw new Error(`${failed.message} (failed the same way on all ${tried} tries)`, { cause: failed });
|
|
604
|
+
}
|
|
605
|
+
await new Promise((resolve) => setTimeout(resolve, TRANSIENT_FIRST_WAIT_MS * 2 ** (tried - 1)));
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* @param {DecisionInput} input
|
|
611
|
+
* @param {AccountState | undefined} best
|
|
612
|
+
* @returns {AutoSwitchAction}
|
|
613
|
+
*/
|
|
614
|
+
function arm(input, best) {
|
|
615
|
+
const { accounts, liveIdentityId, onByok, byokEnabled, providerId } = input;
|
|
616
|
+
if (best !== undefined) {
|
|
617
|
+
const reason = `Auto is on — ${best.label} has the most room (${best.room}%)`;
|
|
618
|
+
if (onByok)
|
|
619
|
+
return { kind: "switchBackFromSubscription", identityId: best.identityId, label: best.label, reason };
|
|
620
|
+
if (best.identityId === liveIdentityId)
|
|
621
|
+
return none(`${best.label} is live and has the most room (${best.room}%)`);
|
|
622
|
+
return { kind: "switchSubscription", identityId: best.identityId, label: best.label, reason };
|
|
623
|
+
}
|
|
624
|
+
const unread = blockingSubscription(accounts);
|
|
625
|
+
if (unread !== undefined)
|
|
626
|
+
return none(`${heldBy(unread)}, so nothing is moved until that changes`);
|
|
627
|
+
if (!byokEnabled)
|
|
628
|
+
return none(`every ${providerId} subscription is spent and this switcher does not move the work onto a key`);
|
|
629
|
+
return { kind: "switchByok", reason: accounts.length === 0 ? "Auto is on and this provider has no subscription" : "Auto is on — every subscription of this provider is spent" };
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* @param {AccountState[]} accounts
|
|
633
|
+
* @returns {number}
|
|
634
|
+
*/
|
|
635
|
+
function firstRefillAt(accounts) {
|
|
636
|
+
if (blockingSubscription(accounts) !== undefined)
|
|
637
|
+
return 0;
|
|
638
|
+
let first = 0;
|
|
639
|
+
for (const a of accounts) {
|
|
640
|
+
if (typeof a.refillsAt !== "number")
|
|
641
|
+
continue;
|
|
642
|
+
if (first === 0 || a.refillsAt < first)
|
|
643
|
+
first = a.refillsAt;
|
|
644
|
+
}
|
|
645
|
+
return first;
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* @param {string} home
|
|
649
|
+
* @param {string} providerId
|
|
650
|
+
*/
|
|
651
|
+
function movePath(home, providerId) {
|
|
652
|
+
return path.join(home, ".bullseye", "auto-switch", `${providerId}.json`);
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* @param {string} home
|
|
656
|
+
* @param {string} providerId
|
|
657
|
+
* @returns {Move | undefined}
|
|
658
|
+
*/
|
|
659
|
+
function readMove(home, providerId) {
|
|
660
|
+
const file = movePath(home, providerId);
|
|
661
|
+
const text = unlessErr("ENOENT", () => fs.readFileSync(file, "utf8"));
|
|
662
|
+
if (text === undefined)
|
|
663
|
+
return undefined;
|
|
664
|
+
const move = JSON.parse(text);
|
|
665
|
+
if (!move || typeof move.at !== "number" || typeof move.kind !== "string" || typeof move.to !== "string") {
|
|
666
|
+
throw new Error(`${file} does not record a move (${text.slice(0, 200)}) — delete it and the next move writes it again`);
|
|
667
|
+
}
|
|
668
|
+
return move;
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* @param {string} home
|
|
672
|
+
* @param {string} providerId
|
|
673
|
+
* @param {Move} move
|
|
674
|
+
*/
|
|
675
|
+
function recordMove(home, providerId, move) {
|
|
676
|
+
writeAtomically(movePath(home, providerId), JSON.stringify(move));
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* @param {string} home
|
|
680
|
+
* @param {string} providerId
|
|
681
|
+
*/
|
|
682
|
+
function forgetMove(home, providerId) {
|
|
683
|
+
fs.rmSync(movePath(home, providerId), { force: true });
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* @param {string} home
|
|
687
|
+
* @param {string} providerId
|
|
688
|
+
*/
|
|
689
|
+
function roomPath(home, providerId) {
|
|
690
|
+
return path.join(home, ".bullseye", "auto-switch", `${providerId}.room.json`);
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* @typedef {object} AccountRoomRecord
|
|
694
|
+
* @property {string} label
|
|
695
|
+
* @property {number | null} room
|
|
696
|
+
* @property {boolean} refused
|
|
697
|
+
* @property {number | null} refillsAt
|
|
698
|
+
* @property {number | null} fivePct
|
|
699
|
+
* @property {number | null} weekPct
|
|
700
|
+
* @property {string} [setupRefused]
|
|
701
|
+
* @property {string} [unreadable]
|
|
702
|
+
*/
|
|
703
|
+
/**
|
|
704
|
+
* @param {string} home
|
|
705
|
+
* @param {string} providerId
|
|
706
|
+
* @param {{ readAt: number, live: string, liveAt: number, pending: string, liveKeyFunded?: boolean, accounts: AccountRoomRecord[] }} room the identity this pass decided to move the live work to, or "" when it moves nothing
|
|
707
|
+
*/
|
|
708
|
+
function recordRoom(home, providerId, room) {
|
|
709
|
+
writeAtomically(roomPath(home, providerId), JSON.stringify(room));
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* Whether the key carrying the live work has funds, as the room record states it: the balance reading's status word
|
|
713
|
+
* (`go` funded, `dead` unfunded) as a boolean, and no field at all when the work is on a subscription or the balance could not be read.
|
|
714
|
+
* @param {string} fundsStatus
|
|
715
|
+
* @returns {{ liveKeyFunded?: boolean }}
|
|
716
|
+
*/
|
|
717
|
+
function keyFundsRecord(fundsStatus) {
|
|
718
|
+
if (fundsStatus === "go")
|
|
719
|
+
return { liveKeyFunded: true };
|
|
720
|
+
if (fundsStatus === "dead")
|
|
721
|
+
return { liveKeyFunded: false };
|
|
722
|
+
return {};
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* The identity a switch just made live, written onto the newest reading so its readers see the move the moment it lands.
|
|
726
|
+
* @param {string} home
|
|
727
|
+
* @param {string} providerId
|
|
728
|
+
* @param {string} live
|
|
729
|
+
* @param {string} fundsStatus the balance status of `live` when it is a key, "" otherwise
|
|
730
|
+
*/
|
|
731
|
+
function recordRoomLive(home, providerId, live, fundsStatus) {
|
|
732
|
+
const file = roomPath(home, providerId);
|
|
733
|
+
const text = unlessErr("ENOENT", () => fs.readFileSync(file, "utf8"));
|
|
734
|
+
if (text === undefined)
|
|
735
|
+
return;
|
|
736
|
+
const { liveKeyFunded: _stale, ...room } = JSON.parse(text);
|
|
737
|
+
writeAtomically(file, JSON.stringify({ ...room, live, liveAt: Date.now(), pending: "", ...keyFundsRecord(fundsStatus) }));
|
|
738
|
+
}
|
|
739
|
+
const CREDIT_KEY_PROVIDER = "claude-api";
|
|
740
|
+
/**
|
|
741
|
+
* @typedef {object} KeyPlan
|
|
742
|
+
* @property {string[]} order
|
|
743
|
+
* @property {{ id: string, reason: string }[]} skipped
|
|
744
|
+
* @property {string[]} pending
|
|
745
|
+
* @property {Record<string, string[]>} [models]
|
|
746
|
+
* @property {number} at
|
|
747
|
+
*/
|
|
748
|
+
/**
|
|
749
|
+
* @param {string} home
|
|
750
|
+
* @param {string} providerId
|
|
751
|
+
*/
|
|
752
|
+
function keyPlanPath(home, providerId) {
|
|
753
|
+
return path.join(home, ".bullseye", "auto-switch", `${providerId}.keyplan.json`);
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* @param {string} home
|
|
757
|
+
* @param {string} providerId
|
|
758
|
+
* @param {Omit<KeyPlan, "at">} plan
|
|
759
|
+
*/
|
|
760
|
+
function recordKeyPlan(home, providerId, plan) {
|
|
761
|
+
const file = keyPlanPath(home, providerId);
|
|
762
|
+
const text = unlessErr("ENOENT", () => fs.readFileSync(file, "utf8"));
|
|
763
|
+
if (text !== undefined && text.replace(/,"at":\d+\}$/, "}") === JSON.stringify(plan))
|
|
764
|
+
return;
|
|
765
|
+
writeAtomically(file, JSON.stringify({ ...plan, at: Date.now() }));
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* @param {string} home
|
|
769
|
+
* @param {string} providerId
|
|
770
|
+
* @returns {KeyPlan | undefined}
|
|
771
|
+
*/
|
|
772
|
+
function readKeyPlan(home, providerId) {
|
|
773
|
+
const file = keyPlanPath(home, providerId);
|
|
774
|
+
const text = unlessErr("ENOENT", () => fs.readFileSync(file, "utf8"));
|
|
775
|
+
if (text === undefined)
|
|
776
|
+
return undefined;
|
|
777
|
+
let plan;
|
|
778
|
+
try {
|
|
779
|
+
plan = JSON.parse(text);
|
|
780
|
+
}
|
|
781
|
+
catch (notJson) {
|
|
782
|
+
if (!(notJson instanceof SyntaxError))
|
|
783
|
+
throw notJson;
|
|
784
|
+
throw Object.assign(new Error(`${file} is not JSON (${notJson.message}) — DeepAgent rewrites it on its next Console pass`), { code: "KEYPLAN_UNREADABLE" });
|
|
785
|
+
}
|
|
786
|
+
const ids = (/** @type {unknown} */ list) => Array.isArray(list) && list.every((id) => typeof id === "string" && id !== "");
|
|
787
|
+
const named = (/** @type {unknown} */ list) => Array.isArray(list) && list.every((row) => row && typeof row.id === "string" && row.id !== "" && typeof row.reason === "string" && row.reason !== "");
|
|
788
|
+
const models = (/** @type {unknown} */ map, /** @type {string[]} */ order) => map === undefined || (map !== null && typeof map === "object" && !Array.isArray(map) && Object.values(map).every(ids) && order.every((id) => Object.hasOwn(map, id)));
|
|
789
|
+
if (plan === null || typeof plan !== "object" || typeof plan.at !== "number" || !ids(plan.order) || !ids(plan.pending) || !named(plan.skipped) || !models(plan.models, plan.order)) {
|
|
790
|
+
throw Object.assign(new Error(`${file} is not a fall-back plan (it needs at, order, skipped and pending, and when it names models a model list for every key in order): ${text.slice(0, 200)} — DeepAgent rewrites it on its next Console pass`), { code: "KEYPLAN_UNREADABLE" });
|
|
791
|
+
}
|
|
792
|
+
return plan;
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* @typedef {"claude" | "copilot" | "codex" | "opencode"} AgentCliId
|
|
796
|
+
* @typedef {{ id: AgentCliId, label: string, protocol: "anthropic" | "openai", subscriptionProvider: string, responsesApi?: true }} AgentCli
|
|
797
|
+
*/
|
|
798
|
+
/** @type {readonly AgentCli[]} */
|
|
799
|
+
const AGENT_CLIS = Object.freeze([
|
|
800
|
+
Object.freeze({ id: "claude", label: "Claude Code", protocol: "anthropic", subscriptionProvider: "anthropic" }),
|
|
801
|
+
Object.freeze({ id: "copilot", label: "GitHub Copilot", protocol: "openai", subscriptionProvider: "github" }),
|
|
802
|
+
Object.freeze({ id: "codex", label: "OpenAI Codex", protocol: "openai", subscriptionProvider: "openai", responsesApi: true }),
|
|
803
|
+
Object.freeze({ id: "opencode", label: "OpenCode", protocol: "anthropic", subscriptionProvider: "opencode" }),
|
|
804
|
+
]);
|
|
805
|
+
const OPENCODE_PROVIDER = "opencode";
|
|
806
|
+
// GATE: the two routes OpenCode can be put on — its own accounts first (free tier, then Go/Zen when it has one) with the key behind them, or the key alone; a stored route of any other name is refused
|
|
807
|
+
const OPENCODE_ROUTES = Object.freeze(["subscription", "byok"]);
|
|
808
|
+
/**
|
|
809
|
+
* Which route the operator put OpenCode on, read by every launcher on its next turn: absent is `subscription` (its own accounts first, the key behind them).
|
|
810
|
+
* @param {string} home
|
|
811
|
+
* @returns {"subscription" | "byok"}
|
|
812
|
+
*/
|
|
813
|
+
function readOpencodeRoute(home) {
|
|
814
|
+
const text = unlessErr("ENOENT", () => fs.readFileSync(settingsPath(home), "utf8"));
|
|
815
|
+
if (text === undefined)
|
|
816
|
+
return "subscription";
|
|
817
|
+
const saved = JSON.parse(text)[OPENCODE_PROVIDER] || {};
|
|
818
|
+
if (saved.route === undefined)
|
|
819
|
+
return "subscription";
|
|
820
|
+
if (!OPENCODE_ROUTES.includes(saved.route)) {
|
|
821
|
+
throw new Error(`${OPENCODE_PROVIDER}.route in ${settingsPath(home)} is ${JSON.stringify(saved.route)}, not one of ${OPENCODE_ROUTES.join(" or ")} — fix that file and run the same command again`);
|
|
822
|
+
}
|
|
823
|
+
return saved.route;
|
|
824
|
+
}
|
|
825
|
+
/**
|
|
826
|
+
* @param {string} home
|
|
827
|
+
* @param {"subscription" | "byok"} route
|
|
828
|
+
*/
|
|
829
|
+
function writeOpencodeRoute(home, route) {
|
|
830
|
+
if (!OPENCODE_ROUTES.includes(route))
|
|
831
|
+
throw new Error(`OpenCode has no route called ${JSON.stringify(route)} — it is ${OPENCODE_ROUTES.join(" or ")}`);
|
|
832
|
+
writeProviderField(home, OPENCODE_PROVIDER, "route", route);
|
|
833
|
+
}
|
|
834
|
+
/**
|
|
835
|
+
* The model the operator picked for OpenCode, as the launcher's `wanted` reads it (`opencode/<free model>` for the free tier, a bare model id for a key); "" when none was picked.
|
|
836
|
+
* @param {string} home
|
|
837
|
+
* @returns {string}
|
|
838
|
+
*/
|
|
839
|
+
function readOpencodeModel(home) {
|
|
840
|
+
const text = unlessErr("ENOENT", () => fs.readFileSync(settingsPath(home), "utf8"));
|
|
841
|
+
if (text === undefined)
|
|
842
|
+
return "";
|
|
843
|
+
const saved = JSON.parse(text)[OPENCODE_PROVIDER] || {};
|
|
844
|
+
if (saved.model === undefined)
|
|
845
|
+
return "";
|
|
846
|
+
if (typeof saved.model !== "string") {
|
|
847
|
+
throw new Error(`${OPENCODE_PROVIDER}.model in ${settingsPath(home)} is ${JSON.stringify(saved.model)}, not a model id — fix that file and run the same command again`);
|
|
848
|
+
}
|
|
849
|
+
return saved.model;
|
|
850
|
+
}
|
|
851
|
+
/**
|
|
852
|
+
* @param {string} home
|
|
853
|
+
* @param {string} model the model to run, or "" to clear the pick
|
|
854
|
+
*/
|
|
855
|
+
function writeOpencodeModel(home, model) {
|
|
856
|
+
writeProviderField(home, OPENCODE_PROVIDER, "model", model);
|
|
857
|
+
}
|
|
858
|
+
// GATE: the key kinds OpenCode is handed, each with the OpenCode provider it names, the ONE environment variable that carries the key and the vendor address it is sent to; a key of any other kind is never offered to OpenCode
|
|
859
|
+
const OPENCODE_KEY_KINDS = Object.freeze({ "claude-api": Object.freeze({ provider: "anthropic", env: "ANTHROPIC_API_KEY", baseEnv: "ANTHROPIC_BASE_URL", base: "https://api.anthropic.com/v1" }) });
|
|
860
|
+
const OPENCODE_FREE_ID = "opencode-free";
|
|
861
|
+
/** OpenCode's own model catalogue, the file the CLI keeps from models.dev — where its free tier's models are named. */
|
|
862
|
+
function opencodeCatalogPath(home) {
|
|
863
|
+
return path.join(process.env.XDG_CACHE_HOME || path.join(home, ".cache"), "opencode", "models.json");
|
|
864
|
+
}
|
|
865
|
+
const OPENCODE_CATALOGUE_UNREADABLE = "OPENCODE_CATALOGUE_UNREADABLE";
|
|
866
|
+
/** The free models each catalogue file named when last parsed, by the file's write stamp: the catalogue is megabytes, and every row of every page that draws the free tier reads it, so a file that has not been written since is not parsed again. */
|
|
867
|
+
const FREE_MODELS_READ = new Map();
|
|
868
|
+
function unreadableCatalogue(file, why) {
|
|
869
|
+
return Object.assign(new Error(`${file} cannot be read as opencode's model catalogue (${why}) — the opencode CLI rewrites it on its next run`), { code: OPENCODE_CATALOGUE_UNREADABLE });
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* The models OpenCode's own free tier runs with no key: its catalogue's own-provider models priced at nothing that call tools and are not deprecated, newest first; undefined while the CLI has never written its catalogue.
|
|
873
|
+
* @param {string} home
|
|
874
|
+
* @returns {string[] | undefined}
|
|
875
|
+
*/
|
|
876
|
+
function opencodeFreeModels(home) {
|
|
877
|
+
const file = opencodeCatalogPath(home);
|
|
878
|
+
const written = unlessErr("ENOENT", () => fs.statSync(file));
|
|
879
|
+
if (written === undefined)
|
|
880
|
+
return undefined;
|
|
881
|
+
const stamp = `${written.mtimeMs}:${written.size}`;
|
|
882
|
+
const known = FREE_MODELS_READ.get(file);
|
|
883
|
+
if (known !== undefined && known.stamp === stamp)
|
|
884
|
+
return [...known.models];
|
|
885
|
+
const text = unlessErr("ENOENT", () => fs.readFileSync(file, "utf8"));
|
|
886
|
+
if (text === undefined)
|
|
887
|
+
return undefined;
|
|
888
|
+
let parsed;
|
|
889
|
+
try {
|
|
890
|
+
parsed = JSON.parse(text);
|
|
891
|
+
}
|
|
892
|
+
catch (cause) {
|
|
893
|
+
if (!(cause instanceof SyntaxError))
|
|
894
|
+
throw cause;
|
|
895
|
+
throw unreadableCatalogue(file, cause.message);
|
|
896
|
+
}
|
|
897
|
+
const own = parsed === null || typeof parsed !== "object" ? undefined : parsed[OPENCODE_PROVIDER];
|
|
898
|
+
if (own === undefined || own === null || typeof own.models !== "object" || own.models === null)
|
|
899
|
+
throw unreadableCatalogue(file, `it names no ${OPENCODE_PROVIDER} provider with models`);
|
|
900
|
+
const models = Object.entries(own.models)
|
|
901
|
+
.filter(([, m]) => m !== null && typeof m === "object" && m.cost !== undefined && m.cost !== null && m.cost.input === 0 && m.cost.output === 0 && m.tool_call === true && m.status !== "deprecated")
|
|
902
|
+
.sort(([, a], [, b]) => String(b.release_date).localeCompare(String(a.release_date)))
|
|
903
|
+
.map(([id]) => id);
|
|
904
|
+
FREE_MODELS_READ.set(file, { stamp, models });
|
|
905
|
+
return [...models];
|
|
906
|
+
}
|
|
907
|
+
/** The refusal one free model carries when the provider failed a turn on it: the free tier's own id and the model, so only that model is passed over. */
|
|
908
|
+
function opencodeFreeModelRefusalId(model) {
|
|
909
|
+
return `${OPENCODE_FREE_ID}.${model}`;
|
|
910
|
+
}
|
|
911
|
+
function keyRefusalId(identityId) {
|
|
912
|
+
return `key.${identityId}`;
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* @param {string} home
|
|
916
|
+
* @param {string} identityId
|
|
917
|
+
* @param {string} reason
|
|
918
|
+
* @param {number} [at]
|
|
919
|
+
*/
|
|
920
|
+
function markKeyRefused(home, identityId, reason, at = Date.now()) {
|
|
921
|
+
markRefused(home, keyRefusalId(identityId), reason, at);
|
|
922
|
+
}
|
|
923
|
+
/** A settings value the shared reader refuses because what it holds cannot be read: a login map that is no map, a comment never closed, an identity list that is no list, a record with no id, two records sharing an id. */
|
|
924
|
+
class UnreadableSettings extends Error {
|
|
925
|
+
}
|
|
926
|
+
class NoOpenCodeKey extends Error {
|
|
927
|
+
constructor(message) {
|
|
928
|
+
super(message);
|
|
929
|
+
this.code = "OPENCODE_NO_KEY";
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
function identitiesHere() {
|
|
933
|
+
let read;
|
|
934
|
+
try {
|
|
935
|
+
read = deepagentSettings();
|
|
936
|
+
}
|
|
937
|
+
catch (absent) {
|
|
938
|
+
if (!(absent instanceof workspaceStore().SettingsUndefined))
|
|
939
|
+
throw absent;
|
|
940
|
+
throw new NoOpenCodeKey(`${absent.message}, so this machine holds no DeepAgent key OpenCode could be handed`);
|
|
941
|
+
}
|
|
942
|
+
const records = read.values[IDENTITY_RECORDS];
|
|
943
|
+
if (!Array.isArray(records))
|
|
944
|
+
throw new NoOpenCodeKey(`${read.file} holds no ${IDENTITY_RECORDS} list, so this machine holds no DeepAgent key OpenCode could be handed`);
|
|
945
|
+
return records;
|
|
946
|
+
}
|
|
947
|
+
/**
|
|
948
|
+
* @param {string} home
|
|
949
|
+
* @param {string | undefined} wanted
|
|
950
|
+
* @param {number} [now]
|
|
951
|
+
* @param {any[]} [identities]
|
|
952
|
+
* @returns {{ identityId: string, named: string, model: string, env: Record<string, string>, modelRefusalId?: string }}
|
|
953
|
+
*/
|
|
954
|
+
function opencodeRoute(home, wanted, now = Date.now(), identities = identitiesHere()) {
|
|
955
|
+
const passed = [];
|
|
956
|
+
const byok = readOpencodeRoute(home) === "byok";
|
|
957
|
+
const picked = readOpencodeModel(home) || undefined;
|
|
958
|
+
const fits = picked !== undefined && !(byok && splitWanted(picked).asked === OPENCODE_PROVIDER);
|
|
959
|
+
const asked = wanted ?? (fits ? picked : undefined);
|
|
960
|
+
if (byok)
|
|
961
|
+
return opencodeKeyRoute(home, asked, now, identities, passed);
|
|
962
|
+
return opencodeFreeRoute(home, asked, now, passed) ?? opencodeKeyRoute(home, asked, now, identities, passed);
|
|
963
|
+
}
|
|
964
|
+
function opencodeStoreEnv(home) {
|
|
965
|
+
const store = path.join(home, ".bullseye", "opencode");
|
|
966
|
+
return { XDG_DATA_HOME: path.join(store, "data"), XDG_STATE_HOME: path.join(store, "state") };
|
|
967
|
+
}
|
|
968
|
+
function splitWanted(wanted) {
|
|
969
|
+
const cut = wanted === undefined ? -1 : wanted.indexOf("/");
|
|
970
|
+
return { asked: cut === -1 ? undefined : wanted.slice(0, cut), bare: cut === -1 ? wanted : wanted.slice(cut + 1) };
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* OpenCode's free tier as every surface reads it — the route, DeepAgent's panel row and provider_room: the free models its catalogue names, the ones with no fresh failure, each failed one with why, and why the whole tier is passed over when it is.
|
|
974
|
+
* @param {string} home
|
|
975
|
+
* @param {number} [now]
|
|
976
|
+
* @returns {{ models: string[], working: string[], failed: Record<string, string>, passed?: string }}
|
|
977
|
+
*/
|
|
978
|
+
function opencodeFreeState(home, now = Date.now()) {
|
|
979
|
+
let models;
|
|
980
|
+
try {
|
|
981
|
+
models = opencodeFreeModels(home);
|
|
982
|
+
}
|
|
983
|
+
catch (cause) {
|
|
984
|
+
// OWNER: a catalogue the opencode CLI left unreadable passes the free tier over exactly as a refusal does — the read's own words are the state every surface shows, and the turn runs on the keys
|
|
985
|
+
if (cause.code !== OPENCODE_CATALOGUE_UNREADABLE)
|
|
986
|
+
throw cause;
|
|
987
|
+
return { models: [], working: [], failed: {}, passed: cause.message };
|
|
988
|
+
}
|
|
989
|
+
// NULL-OK: field models is OPTIONAL and therefore it is ok to check for NULL
|
|
990
|
+
if (models === undefined)
|
|
991
|
+
return { models: [], working: [], failed: {}, passed: `the opencode CLI has not written its model catalogue (${opencodeCatalogPath(home)}) yet` };
|
|
992
|
+
const tier = readRefusal(home, keyRefusalId(OPENCODE_FREE_ID));
|
|
993
|
+
if (refusalIsFresh(tier, now))
|
|
994
|
+
return { models, working: [], failed: {}, passed: `refused a turn ${Math.round((now - tier.at) / 1000)}s ago — ${tier.reason}` };
|
|
995
|
+
const failed = {};
|
|
996
|
+
for (const model of models) {
|
|
997
|
+
const broke = readRefusal(home, keyRefusalId(opencodeFreeModelRefusalId(model)));
|
|
998
|
+
if (refusalIsFresh(broke, now))
|
|
999
|
+
failed[model] = `failed a turn ${Math.round((now - broke.at) / 1000)}s ago — ${broke.reason}`;
|
|
1000
|
+
}
|
|
1001
|
+
const working = models.filter((model) => !Object.hasOwn(failed, model));
|
|
1002
|
+
if (models.length === 0)
|
|
1003
|
+
return { models, working, failed, passed: "its catalogue names no free model that calls tools" };
|
|
1004
|
+
if (working.length === 0)
|
|
1005
|
+
return { models, working, failed, passed: `every free model failed a turn: ${models.map((m) => `${m} ${failed[m]}`).join("; ")}` };
|
|
1006
|
+
return { models, working, failed };
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* OpenCode's own free tier, the first step of the route: its newest working free model, or the free model asked for by name, or undefined with why it was passed over written into `passed`.
|
|
1010
|
+
* A model asked with no provider that is no free model names only the model the key step runs, so the free tier still runs first; a model asked under another provider skips the free tier.
|
|
1011
|
+
*/
|
|
1012
|
+
function opencodeFreeRoute(home, wanted, now, passed) {
|
|
1013
|
+
const { asked, bare } = splitWanted(wanted);
|
|
1014
|
+
if (asked !== undefined && asked !== OPENCODE_PROVIDER) {
|
|
1015
|
+
passed.push(`OpenCode free: ${wanted} is asked of ${asked}, not of OpenCode's free tier`);
|
|
1016
|
+
return undefined;
|
|
1017
|
+
}
|
|
1018
|
+
const state = opencodeFreeState(home, now);
|
|
1019
|
+
if (state.passed !== undefined) {
|
|
1020
|
+
passed.push(`OpenCode free: ${state.passed}`);
|
|
1021
|
+
return undefined;
|
|
1022
|
+
}
|
|
1023
|
+
const named = bare !== undefined && state.models.includes(bare);
|
|
1024
|
+
if (asked === OPENCODE_PROVIDER && !named) {
|
|
1025
|
+
passed.push(`OpenCode free: ${wanted} is not one of its free models`);
|
|
1026
|
+
return undefined;
|
|
1027
|
+
}
|
|
1028
|
+
const model = named ? bare : state.working[0];
|
|
1029
|
+
if (Object.hasOwn(state.failed, model)) {
|
|
1030
|
+
passed.push(`OpenCode free ${model}: ${state.failed[model]}`);
|
|
1031
|
+
return undefined;
|
|
1032
|
+
}
|
|
1033
|
+
return { identityId: OPENCODE_FREE_ID, named: "OpenCode free", model: `${OPENCODE_PROVIDER}/${model}`, env: opencodeStoreEnv(home), modelRefusalId: opencodeFreeModelRefusalId(model) };
|
|
1034
|
+
}
|
|
1035
|
+
// GATE: the HTTP statuses on which the provider refused THIS key or account (unauthorized, payment, forbidden, rate-limited) — the turn moves to the next route; any other failure is not the key's
|
|
1036
|
+
const OPENCODE_KEY_REFUSAL_STATUSES = Object.freeze(new Set([401, 402, 403, 429]));
|
|
1037
|
+
const OPENCODE_KEY_REFUSAL_WORDS = /credit balance is too low|insufficient (?:balance|funds|credit|quota)|out of (?:funds|credit)|invalid x-api-key/i;
|
|
1038
|
+
/**
|
|
1039
|
+
* An error OpenCode reported in one of its JSON events, read once for every reader — BN, the shared OpenCodeTurn and DeepAgent's Test: the provider's own message,
|
|
1040
|
+
* its HTTP status when it sent one, whether it refused the key or account, and the line every surface shows.
|
|
1041
|
+
* @param {{ name?: string, data?: { message?: string, statusCode?: number } } | undefined} error
|
|
1042
|
+
* @returns {{ message: string, status: number | undefined, keyRefusal: boolean, said: string }}
|
|
1043
|
+
*/
|
|
1044
|
+
function opencodeEventError(error) {
|
|
1045
|
+
const data = error?.data ?? {};
|
|
1046
|
+
const message = data.message ?? error?.name ?? "the CLI reported an error";
|
|
1047
|
+
const status = typeof data.statusCode === "number" ? data.statusCode : undefined;
|
|
1048
|
+
return { message, status, keyRefusal: (status !== undefined && OPENCODE_KEY_REFUSAL_STATUSES.has(status)) || OPENCODE_KEY_REFUSAL_WORDS.test(message), said: status === undefined ? message : `${message} (HTTP ${status})` };
|
|
1049
|
+
}
|
|
1050
|
+
/**
|
|
1051
|
+
* What a failure on a free model means for the turn, decided once for every OpenCode runner (BN, the shared OpenCodeTurn and through it ai_failover):
|
|
1052
|
+
* the first failure passes that model over and the turn moves on to the next free model; the same status and message on a second free model is the free tier itself failing —
|
|
1053
|
+
* every free model goes through OpenCode's one gateway — so the whole tier is passed over and the turn goes onto the Claude keys. A failure with no status is ruled the same way.
|
|
1054
|
+
* @param {{ last: { status: number | undefined, message: string } | undefined }} memory the turn's own record of the free model that failed last
|
|
1055
|
+
* @param {string} refusalId the refusal id of the free model that failed now
|
|
1056
|
+
* @param {number | undefined} status
|
|
1057
|
+
* @param {string} message
|
|
1058
|
+
* @param {(id: string, reason: string) => void} refused where the refusal is recorded
|
|
1059
|
+
* @returns {"model" | "tier"}
|
|
1060
|
+
*/
|
|
1061
|
+
function opencodeFreeFailure(memory, refusalId, status, message, refused) {
|
|
1062
|
+
const last = memory.last;
|
|
1063
|
+
const reason = status === undefined ? message : `${message} (HTTP ${status})`;
|
|
1064
|
+
if (last === undefined || last.status !== status || last.message !== message) {
|
|
1065
|
+
memory.last = { status, message };
|
|
1066
|
+
refused(refusalId, reason);
|
|
1067
|
+
return "model";
|
|
1068
|
+
}
|
|
1069
|
+
refused(OPENCODE_FREE_ID, reason);
|
|
1070
|
+
return "tier";
|
|
1071
|
+
}
|
|
1072
|
+
/** What the next attempt of a turn is told when the last one never answered: the key was refused, or the free model failed. */
|
|
1073
|
+
function opencodeRetryPrompt(movedOff) {
|
|
1074
|
+
return movedOff === "key"
|
|
1075
|
+
? "The provider refused the key your last reply was being written on, so that reply never arrived. Carry on from the last message."
|
|
1076
|
+
: "The model your last reply was being written on failed, so that reply never arrived. Carry on from the last message.";
|
|
1077
|
+
}
|
|
1078
|
+
/** The OpenCode vocabulary a runner that cannot load this file itself is handed: the shared OpenCodeTurn takes it as its spec's `rules`. */
|
|
1079
|
+
const OPENCODE_RULES = Object.freeze({ eventError: opencodeEventError, freeFailure: opencodeFreeFailure, retryPrompt: opencodeRetryPrompt });
|
|
1080
|
+
/** The Claude API keys of DeepAgent's published OpenCode plan, the step after the free tier: the first one with no fresh refusal that runs the asked model. */
|
|
1081
|
+
function opencodeKeyRoute(home, wanted, now = Date.now(), identities = identitiesHere(), passed = []) {
|
|
1082
|
+
const { asked, bare } = splitWanted(wanted);
|
|
1083
|
+
const storeEnv = opencodeStoreEnv(home);
|
|
1084
|
+
const plan = readKeyPlan(home, OPENCODE_PROVIDER);
|
|
1085
|
+
if (plan === undefined) {
|
|
1086
|
+
throw new NoOpenCodeKey(`${passed.length === 0 ? "" : `${passed.join("; ")}; and `}DeepAgent has published no OpenCode key plan on this machine (${keyPlanPath(home, OPENCODE_PROVIDER)}), so no key is known to run OpenCode on — DeepAgent's panel publishes it on its next Console pass`);
|
|
1087
|
+
}
|
|
1088
|
+
if (plan.models === undefined) {
|
|
1089
|
+
throw new NoOpenCodeKey(`the OpenCode key plan DeepAgent published (${keyPlanPath(home, OPENCODE_PROVIDER)}) names no key's models, so no model is known to be allowed — DeepAgent's panel republishes it on its next Console pass`);
|
|
1090
|
+
}
|
|
1091
|
+
passed.push(...plan.skipped.map((row) => `${row.id}: ${row.reason}`), ...plan.pending.map((id) => `${id}: its Console credit read has not finished`));
|
|
1092
|
+
for (const id of plan.order) {
|
|
1093
|
+
const identity = identities.find((row) => row.id === id);
|
|
1094
|
+
if (identity === undefined) {
|
|
1095
|
+
passed.push(`${id}: no longer in DeepAgent's list`);
|
|
1096
|
+
continue;
|
|
1097
|
+
}
|
|
1098
|
+
const kind = OPENCODE_KEY_KINDS[identity.providerType];
|
|
1099
|
+
const key = typeof identity.key === "string" ? identity.key.trim() : "";
|
|
1100
|
+
const named = `${identity.label} …${key.slice(-4)}`;
|
|
1101
|
+
if (kind === undefined || key === "") {
|
|
1102
|
+
passed.push(`${named}: ${kind === undefined ? `a ${identity.providerType} key is not one OpenCode is handed` : "it holds no key"}`);
|
|
1103
|
+
continue;
|
|
1104
|
+
}
|
|
1105
|
+
const refusal = readRefusal(home, keyRefusalId(id));
|
|
1106
|
+
if (refusalIsFresh(refusal, now)) {
|
|
1107
|
+
passed.push(`${named}: refused a turn ${Math.round((now - refusal.at) / 1000)}s ago — ${refusal.reason}`);
|
|
1108
|
+
continue;
|
|
1109
|
+
}
|
|
1110
|
+
const allowed = plan.models[id];
|
|
1111
|
+
const model = asked !== undefined && asked !== kind.provider ? undefined : bare === undefined ? allowed[0] : allowed.find((m) => m === bare);
|
|
1112
|
+
if (model === undefined) {
|
|
1113
|
+
passed.push(`${named}: ${bare === undefined ? "DeepAgent allows it no model" : `DeepAgent does not allow it ${wanted}`}`);
|
|
1114
|
+
continue;
|
|
1115
|
+
}
|
|
1116
|
+
return { identityId: id, named, model: `${kind.provider}/${model}`, env: { [kind.env]: key, [kind.baseEnv]: kind.base, ...storeEnv } };
|
|
1117
|
+
}
|
|
1118
|
+
throw new NoOpenCodeKey(`no key DeepAgent holds can run OpenCode now — ${passed.join("; ") || "its OpenCode key plan names no key"}`);
|
|
1119
|
+
}
|
|
1120
|
+
/**
|
|
1121
|
+
* @param {Move | undefined} move
|
|
1122
|
+
* @param {number} now
|
|
1123
|
+
*/
|
|
1124
|
+
function failbackDue(move, now) {
|
|
1125
|
+
return move !== undefined && move.kind === "switchByok" && now >= (move.recheckAt || 0);
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* @param {string} home
|
|
1129
|
+
* @returns {boolean}
|
|
1130
|
+
*/
|
|
1131
|
+
function keyIsLive(home) {
|
|
1132
|
+
const file = path.join(home, ".claude", "settings.json");
|
|
1133
|
+
let text;
|
|
1134
|
+
try {
|
|
1135
|
+
text = fs.readFileSync(file, "utf8");
|
|
1136
|
+
}
|
|
1137
|
+
catch (cause) {
|
|
1138
|
+
if ( /** @type {NodeJS.ErrnoException} */(cause).code === "ENOENT")
|
|
1139
|
+
return false;
|
|
1140
|
+
throw cause;
|
|
1141
|
+
}
|
|
1142
|
+
let env;
|
|
1143
|
+
try {
|
|
1144
|
+
env = JSON.parse(text).env || {};
|
|
1145
|
+
}
|
|
1146
|
+
catch (notJson) {
|
|
1147
|
+
throw new Error(`${file} is not valid JSON (${notJson.message}) — fix that file and the next prompt reads it again`);
|
|
1148
|
+
}
|
|
1149
|
+
return Boolean(env.ANTHROPIC_BASE_URL);
|
|
1150
|
+
}
|
|
1151
|
+
/** @param {string} home @param {string} sessionId @param {"wait" | "done"} kind */
|
|
1152
|
+
function appliedPath(home, sessionId, kind) {
|
|
1153
|
+
return path.join(home, ".bullseye", "auto-switch", "applied", `${sessionId.replace(/[^\w.-]/g, "_")}.${kind}`);
|
|
1154
|
+
}
|
|
1155
|
+
/**
|
|
1156
|
+
* @param {string} home
|
|
1157
|
+
* @param {{ session_id?: string }} event
|
|
1158
|
+
*/
|
|
1159
|
+
function markApplied(home, event) {
|
|
1160
|
+
if (typeof event.session_id !== "string")
|
|
1161
|
+
throw new Error("the ConfigChange hook handed over no session_id");
|
|
1162
|
+
if (!fs.existsSync(appliedPath(home, event.session_id, "wait")))
|
|
1163
|
+
return;
|
|
1164
|
+
writeAtomically(appliedPath(home, event.session_id, "done"), String(Date.now()));
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
* The PATH one http hook posts to, which is the whole of WHICH handler the URL names. The query string
|
|
1168
|
+
* carries the pad's own token — the handler the settings wire is `…/hook/applied?token=…` — and a reader
|
|
1169
|
+
* that tested the entire string against `/hook/applied$` therefore answered false for the one hook that
|
|
1170
|
+
* WAS wired, refusing the key move on the failure path. A string that is no URL at all names no handler.
|
|
1171
|
+
* @param {string} url
|
|
1172
|
+
* @returns {string | undefined}
|
|
1173
|
+
*/
|
|
1174
|
+
function httpHookPath(url) {
|
|
1175
|
+
return URL.canParse(url) ? new URL(url).pathname : undefined;
|
|
1176
|
+
}
|
|
1177
|
+
/**
|
|
1178
|
+
* Whether the user settings carry a ConfigChange handler that delivers the "applied" signal — the mark
|
|
1179
|
+
* that a rewritten settings file is live for the session waiting on it.
|
|
1180
|
+
*
|
|
1181
|
+
* TWO SHAPES DELIVER IT AND BOTH MUST COUNT: an HTTP handler on the control pad (`/hook/applied`, whose
|
|
1182
|
+
* server calls `markApplied`) and a command handler running `autoSwitch.js applied`. This read ONLY the
|
|
1183
|
+
* command shape, so the HTTP handler the settings actually carry was invisible: measured 2026-10-07,
|
|
1184
|
+
* `claude-provider.sh failover` decided `switchByok` correctly on a session limit and then refused to
|
|
1185
|
+
* move the live work because it "wires no ConfigChange hook running autoSwitch.js applied" — the one
|
|
1186
|
+
* route that existed was the one this could not see (#7964).
|
|
1187
|
+
*
|
|
1188
|
+
* @param {string} home
|
|
1189
|
+
*/
|
|
1190
|
+
function appliedHookWired(home) {
|
|
1191
|
+
const settings = JSON.parse(fs.readFileSync(path.join(home, ".claude", "settings.json"), "utf8"));
|
|
1192
|
+
const groups = (settings.hooks && settings.hooks.ConfigChange) || [];
|
|
1193
|
+
return groups.some((g) => (g.hooks || []).some((h) => {
|
|
1194
|
+
if (h.type === "http")
|
|
1195
|
+
return typeof h.url === "string" && httpHookPath(h.url) === "/hook/applied";
|
|
1196
|
+
return typeof h.command === "string" && (/autoSwitch\.js"?\s+applied\b/.test(h.command) ||
|
|
1197
|
+
(/(?:^|[/\\])node(?:\.exe)?$/i.test(h.command) && Array.isArray(h.args) &&
|
|
1198
|
+
/(?:^|[/\\])autoSwitch\.js$/.test(h.args[0]) && h.args[1] === "applied"));
|
|
1199
|
+
}));
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* @param {string} home
|
|
1203
|
+
*/
|
|
1204
|
+
function reapplySettings(home) {
|
|
1205
|
+
const file = path.join(home, ".claude", "settings.json");
|
|
1206
|
+
writeAtomically(file, fs.readFileSync(file, "utf8"));
|
|
1207
|
+
}
|
|
1208
|
+
/** @param {string} home @param {string} sessionId */
|
|
1209
|
+
function expectApplied(home, sessionId) {
|
|
1210
|
+
writeAtomically(appliedPath(home, sessionId, "wait"), String(Date.now()));
|
|
1211
|
+
}
|
|
1212
|
+
/** @param {string} home */
|
|
1213
|
+
function sessionsDir(home) {
|
|
1214
|
+
return path.join(home, ".claude", "sessions");
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* @param {string} home
|
|
1218
|
+
* @param {string} sessionId
|
|
1219
|
+
* @returns {number | "none" | "unsettled"}
|
|
1220
|
+
*/
|
|
1221
|
+
function sessionPid(home, sessionId) {
|
|
1222
|
+
const dir = sessionsDir(home);
|
|
1223
|
+
let names;
|
|
1224
|
+
try {
|
|
1225
|
+
names = fs.readdirSync(dir);
|
|
1226
|
+
}
|
|
1227
|
+
catch (cause) {
|
|
1228
|
+
if ( /** @type {NodeJS.ErrnoException} */(cause).code === "ENOENT")
|
|
1229
|
+
return "none";
|
|
1230
|
+
throw cause;
|
|
1231
|
+
}
|
|
1232
|
+
let unsettled = false;
|
|
1233
|
+
for (const name of names) {
|
|
1234
|
+
const pid = /^(\d+)\.json$/.exec(name);
|
|
1235
|
+
if (pid === null)
|
|
1236
|
+
continue;
|
|
1237
|
+
let record;
|
|
1238
|
+
try {
|
|
1239
|
+
record = JSON.parse(fs.readFileSync(path.join(dir, name), "utf8"));
|
|
1240
|
+
}
|
|
1241
|
+
catch (cause) {
|
|
1242
|
+
// OWNER: a session rewrites its record while this reads it (a half-written file), or closes and removes it between the listing and the read — the half-written one is decided by the watch event its completing write raises, the removed one held no live session
|
|
1243
|
+
if (cause instanceof SyntaxError)
|
|
1244
|
+
unsettled = true;
|
|
1245
|
+
else if ( /** @type {NodeJS.ErrnoException} */(cause).code !== "ENOENT")
|
|
1246
|
+
throw cause;
|
|
1247
|
+
continue;
|
|
1248
|
+
}
|
|
1249
|
+
if (record.sessionId === sessionId)
|
|
1250
|
+
return Number(pid[1]);
|
|
1251
|
+
}
|
|
1252
|
+
return unsettled ? "unsettled" : "none";
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* @param {string} home
|
|
1256
|
+
* @param {string} sessionId
|
|
1257
|
+
* @param {number} since
|
|
1258
|
+
* @returns {Promise<"applied" | "gone">}
|
|
1259
|
+
*/
|
|
1260
|
+
function whenApplied(home, sessionId, since) {
|
|
1261
|
+
const done = appliedPath(home, sessionId, "done");
|
|
1262
|
+
const landed = () => {
|
|
1263
|
+
let at;
|
|
1264
|
+
try {
|
|
1265
|
+
at = Number(fs.readFileSync(done, "utf8"));
|
|
1266
|
+
}
|
|
1267
|
+
catch (cause) {
|
|
1268
|
+
if ( /** @type {NodeJS.ErrnoException} */(cause).code === "ENOENT")
|
|
1269
|
+
return false;
|
|
1270
|
+
throw cause;
|
|
1271
|
+
}
|
|
1272
|
+
return at >= since;
|
|
1273
|
+
};
|
|
1274
|
+
/** @type {number | undefined} */
|
|
1275
|
+
let holder;
|
|
1276
|
+
/** @returns {"applied" | "gone" | undefined} */
|
|
1277
|
+
const outcome = () => {
|
|
1278
|
+
if (landed())
|
|
1279
|
+
return "applied";
|
|
1280
|
+
if (holder === undefined) {
|
|
1281
|
+
const found = sessionPid(home, sessionId);
|
|
1282
|
+
if (found === "unsettled")
|
|
1283
|
+
return undefined;
|
|
1284
|
+
if (found === "none")
|
|
1285
|
+
return "gone";
|
|
1286
|
+
holder = found;
|
|
1287
|
+
}
|
|
1288
|
+
return fs.existsSync(path.join(sessionsDir(home), `${holder}.json`)) && workspaceStore().alive(holder) ? undefined : "gone";
|
|
1289
|
+
};
|
|
1290
|
+
const finish = () => {
|
|
1291
|
+
fs.rmSync(done, { force: true });
|
|
1292
|
+
fs.rmSync(appliedPath(home, sessionId, "wait"), { force: true });
|
|
1293
|
+
};
|
|
1294
|
+
return new Promise((resolve, reject) => {
|
|
1295
|
+
const first = outcome();
|
|
1296
|
+
if (first !== undefined) {
|
|
1297
|
+
finish();
|
|
1298
|
+
return resolve(first);
|
|
1299
|
+
}
|
|
1300
|
+
/** @type {fs.FSWatcher[]} */
|
|
1301
|
+
const watchers = [];
|
|
1302
|
+
const check = () => {
|
|
1303
|
+
let now;
|
|
1304
|
+
try {
|
|
1305
|
+
now = outcome();
|
|
1306
|
+
}
|
|
1307
|
+
catch (cause) {
|
|
1308
|
+
watchers.forEach((w) => w.close());
|
|
1309
|
+
return reject(cause);
|
|
1310
|
+
}
|
|
1311
|
+
if (now === undefined)
|
|
1312
|
+
return;
|
|
1313
|
+
watchers.forEach((w) => w.close());
|
|
1314
|
+
finish();
|
|
1315
|
+
resolve(now);
|
|
1316
|
+
};
|
|
1317
|
+
watchers.push(fs.watch(path.dirname(done), check), fs.watch(sessionsDir(home), check));
|
|
1318
|
+
check();
|
|
1319
|
+
});
|
|
1320
|
+
}
|
|
1321
|
+
/**
|
|
1322
|
+
* @template T
|
|
1323
|
+
* @param {string} code @param {() => T} act
|
|
1324
|
+
* @returns {T | undefined}
|
|
1325
|
+
*/
|
|
1326
|
+
function unlessErr(code, act) {
|
|
1327
|
+
try {
|
|
1328
|
+
return act();
|
|
1329
|
+
}
|
|
1330
|
+
catch (cause) {
|
|
1331
|
+
if ( /** @type {NodeJS.ErrnoException} */(cause).code === code)
|
|
1332
|
+
return undefined;
|
|
1333
|
+
throw cause;
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
/** @param {string} home @param {string} line how a fail-back ended, appended to the log the box's own account switch already writes */
|
|
1337
|
+
function logSwitch(home, line) {
|
|
1338
|
+
const file = path.join(home, ".bullseye", "claude-switch.log");
|
|
1339
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
1340
|
+
fs.appendFileSync(file, `auto-switch: ${new Date().toISOString()} ${line.replace(/\s+/g, " ").trim()}\n`);
|
|
1341
|
+
}
|
|
1342
|
+
/**
|
|
1343
|
+
* The prompt hook's fail-back check (#3654): a fail-back that is due is handed to this box's one decider by a detached
|
|
1344
|
+
* `failback-run`, so the prompt never waits on it and the hook never moves the account itself.
|
|
1345
|
+
* @param {string} home @returns {number} the exit code
|
|
1346
|
+
*/
|
|
1347
|
+
function failbackCheck(home) {
|
|
1348
|
+
if (!readAuto(home, CLI_PROVIDER))
|
|
1349
|
+
return 0;
|
|
1350
|
+
const move = readMove(home, CLI_PROVIDER);
|
|
1351
|
+
const unnamed = move === undefined || move.kind !== "switchByok";
|
|
1352
|
+
if (!failbackDue(move, Date.now()) && !(unnamed && keyIsLive(home)))
|
|
1353
|
+
return 0;
|
|
1354
|
+
spawn(process.execPath, [__filename, "failback-run", home], { detached: true, stdio: "ignore", windowsHide: true }).unref();
|
|
1355
|
+
return 0;
|
|
1356
|
+
}
|
|
1357
|
+
/** @param {string} home @returns {string} the home as one spelling, so two spellings of one folder compare equal */
|
|
1358
|
+
function sameHome(home) {
|
|
1359
|
+
const resolved = path.resolve(home);
|
|
1360
|
+
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
1361
|
+
}
|
|
1362
|
+
/** DeepAgent's resident server, the one process that decides this box's accounts while it answers (#3654). */
|
|
1363
|
+
const DECIDER_DOOR = process.env.BULLSEYE_DECIDER_DOOR || DEEPAGENT_DOOR;
|
|
1364
|
+
// GATE: how long a mover waits for DeepAgent's server to answer before it reads the server as not deciding and the pad decides
|
|
1365
|
+
const DECIDER_ASK_MS = 5000;
|
|
1366
|
+
/**
|
|
1367
|
+
* #3654 — WHO DECIDES THIS BOX'S ACCOUNT FOR `providerId` RIGHT NOW: DeepAgent's resident server while it answers
|
|
1368
|
+
* and has promised its next pass, else the pad. Exactly one answer, so the pad, the window and the hook never move
|
|
1369
|
+
* alongside the server. A server that is stopped, wedged past its own promised deadline, or a release that does
|
|
1370
|
+
* not decide (no `/decider` door) leaves the pad deciding; any other answer is not documented and throws. The server
|
|
1371
|
+
* decides the accounts of its own home only, so an asker working on another home (a scratch home) is the pad's.
|
|
1372
|
+
* @param {string} providerId @param {typeof fetch} [fetchImpl]
|
|
1373
|
+
* @returns {Promise<{ decider: "deepagent-server", pid: number, deadline: number, why: string } | { decider: "pad", why: string }>}
|
|
1374
|
+
*/
|
|
1375
|
+
async function whoDecides(providerId, fetchImpl = fetch) {
|
|
1376
|
+
let reply;
|
|
1377
|
+
try {
|
|
1378
|
+
reply = await fetchImpl(`${DECIDER_DOOR}/decider`, { signal: AbortSignal.timeout(DECIDER_ASK_MS) });
|
|
1379
|
+
}
|
|
1380
|
+
catch (cause) {
|
|
1381
|
+
const code = /** @type {any} */ (cause).cause?.code ?? /** @type {any} */ (cause).name;
|
|
1382
|
+
if (code === "ECONNREFUSED")
|
|
1383
|
+
return { decider: "pad", why: `nothing answers ${DECIDER_DOOR} — DeepAgent's server is stopped` };
|
|
1384
|
+
if (code === "TimeoutError")
|
|
1385
|
+
return { decider: "pad", why: `DeepAgent's server did not answer ${DECIDER_DOOR}/decider within ${DECIDER_ASK_MS / 1000}s` };
|
|
1386
|
+
throw cause;
|
|
1387
|
+
}
|
|
1388
|
+
if (reply.status === 404)
|
|
1389
|
+
return { decider: "pad", why: `the DeepAgent server on ${DECIDER_DOOR} is a release that does not decide accounts` };
|
|
1390
|
+
if (!reply.ok)
|
|
1391
|
+
throw new Error(`DeepAgent's server answered GET /decider with HTTP ${reply.status}: ${(await reply.text()).slice(0, 300)}`);
|
|
1392
|
+
const said = await reply.json();
|
|
1393
|
+
const provider = said.providers[providerId];
|
|
1394
|
+
if (provider === undefined)
|
|
1395
|
+
throw new Error(`DeepAgent's server (pid ${said.pid}) names no ${providerId} in its /decider answer`);
|
|
1396
|
+
if (!provider.decides)
|
|
1397
|
+
return { decider: "pad", why: `DeepAgent's server (pid ${said.pid}) does not decide ${providerId}: ${provider.why}` };
|
|
1398
|
+
const home = process.env.HOME || os.homedir();
|
|
1399
|
+
if (sameHome(said.home) !== sameHome(home))
|
|
1400
|
+
return { decider: "pad", why: `DeepAgent's server (pid ${said.pid}) decides the accounts of ${said.home}, not of ${home}` };
|
|
1401
|
+
if (Date.now() > said.deadline)
|
|
1402
|
+
return { decider: "pad", why: `DeepAgent's server (pid ${said.pid}) promised its next pass by ${new Date(said.deadline).toISOString()} and has not made it` };
|
|
1403
|
+
return { decider: "deepagent-server", pid: said.pid, deadline: said.deadline, why: `DeepAgent's server (pid ${said.pid}) decides ${providerId} — last pass ${said.lastPassAt ? new Date(said.lastPassAt).toISOString() : "running now"}, next by ${new Date(said.deadline).toISOString()}` };
|
|
1404
|
+
}
|
|
1405
|
+
/**
|
|
1406
|
+
* Something that sees a move due asks the decider to make it now, and never makes it itself (#3654): DeepAgent's
|
|
1407
|
+
* server runs that provider's pass at once; while the pad decides, the pad's own next pass makes it.
|
|
1408
|
+
* @param {string} providerId @param {string} trigger what saw the move due
|
|
1409
|
+
* @param {string[]} [fundsRefused] keys the asker recorded refusing a prompt for funds, which the server's pass cannot read itself
|
|
1410
|
+
* @param {typeof fetch} [fetchImpl]
|
|
1411
|
+
* @returns {Promise<{ handed: true, why: string } | { handed: false, why: string }>} handed: false when the pad decides
|
|
1412
|
+
*/
|
|
1413
|
+
async function handToDecider(providerId, trigger, fundsRefused = [], fetchImpl = fetch) {
|
|
1414
|
+
const who = await whoDecides(providerId, fetchImpl);
|
|
1415
|
+
if (who.decider === "pad")
|
|
1416
|
+
return { handed: false, why: who.why };
|
|
1417
|
+
const reply = await fetchImpl(`${DECIDER_DOOR}/decide`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ trigger, provider: providerId, fundsRefused }), signal: AbortSignal.timeout(DECIDER_ASK_MS) });
|
|
1418
|
+
if (!reply.ok)
|
|
1419
|
+
throw new Error(`DeepAgent's server answered POST /decide with HTTP ${reply.status}: ${(await reply.text()).slice(0, 300)}`);
|
|
1420
|
+
return { handed: true, why: `handed to ${who.why}` };
|
|
1421
|
+
}
|
|
1422
|
+
/**
|
|
1423
|
+
* #3654 — a refused Claude Code prompt's failover is made by this box's one decider. While DeepAgent's server decides
|
|
1424
|
+
* Claude Code it runs the failover and hands back what it printed, the note that wakes the session; while the pad
|
|
1425
|
+
* decides, or the server has not made the failover by the deadline it promised, the hook makes it itself as the pad's
|
|
1426
|
+
* own mover.
|
|
1427
|
+
* @param {string} event the StopFailure hook's event, as it arrived
|
|
1428
|
+
* @param {typeof fetch} [fetchImpl]
|
|
1429
|
+
* @returns {Promise<{ handled: false, why: string } | { handled: true, exit: number, said: string }>}
|
|
1430
|
+
*/
|
|
1431
|
+
async function failoverByDecider(event, fetchImpl = fetch) {
|
|
1432
|
+
const who = await whoDecides(CLI_PROVIDER, fetchImpl);
|
|
1433
|
+
if (who.decider === "pad")
|
|
1434
|
+
return { handled: false, why: who.why };
|
|
1435
|
+
let reply;
|
|
1436
|
+
try {
|
|
1437
|
+
reply = await fetchImpl(`${DECIDER_DOOR}/failover`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ event }), signal: AbortSignal.timeout(Math.max(DECIDER_ASK_MS, who.deadline - Date.now())) });
|
|
1438
|
+
}
|
|
1439
|
+
catch (cause) {
|
|
1440
|
+
if ( /** @type {any} */(cause).name !== "TimeoutError")
|
|
1441
|
+
throw cause;
|
|
1442
|
+
return { handled: false, why: `${who.why}, and it had not made this failover by ${new Date(who.deadline).toISOString()}` };
|
|
1443
|
+
}
|
|
1444
|
+
if (!reply.ok)
|
|
1445
|
+
throw new Error(`DeepAgent's server answered POST /failover with HTTP ${reply.status}: ${(await reply.text()).slice(0, 300)}`);
|
|
1446
|
+
const ran = await reply.json();
|
|
1447
|
+
if (!ran.handled)
|
|
1448
|
+
return { handled: false, why: `DeepAgent's server (pid ${who.pid}) stopped deciding Claude Code before this failover reached it` };
|
|
1449
|
+
return ran;
|
|
1450
|
+
}
|
|
1451
|
+
// GATE: how long the one real call that proves a switch may take before the switch reads as FAILED
|
|
1452
|
+
const PROOF_TIMEOUT_MS = 90000;
|
|
1453
|
+
const TRANSIENT_PROOF_REPLY = /Attention Required|Cloudflare|\b(?:429|50[0-4]|52\d)\b|Too Many Requests|overloaded|ECONNRESET|ETIMEDOUT|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EPIPE|fetch failed|socket hang up|network error|timed out/i;
|
|
1454
|
+
const NO_ROOM_REPLY = /402|positive balance|insufficient (?:balance|funds|credit|quota)|out of (?:funds|credit)|credit balance|quota/i;
|
|
1455
|
+
const PROOF_SPAWN = { encoding: "utf8", windowsHide: true, cwd: os.tmpdir(), timeout: PROOF_TIMEOUT_MS };
|
|
1456
|
+
/**
|
|
1457
|
+
* @param {string} home
|
|
1458
|
+
* @returns {{ onKey: boolean, account: string }} where the live route stands, and the email the CLI records for it.
|
|
1459
|
+
* A key route has no subscription account; a login that has recorded none yet is NOT a key route, so the two are
|
|
1460
|
+
* told apart here rather than by an account string that is empty for both.
|
|
1461
|
+
*/
|
|
1462
|
+
function liveRoute(home) {
|
|
1463
|
+
if (keyIsLive(home))
|
|
1464
|
+
return { onKey: true, account: "" };
|
|
1465
|
+
const file = path.join(home, ".claude.json");
|
|
1466
|
+
if (!fs.existsSync(file))
|
|
1467
|
+
return { onKey: false, account: "" };
|
|
1468
|
+
const global = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
1469
|
+
return { onKey: false, account: (global.oauthAccount || {}).emailAddress || "" };
|
|
1470
|
+
}
|
|
1471
|
+
/**
|
|
1472
|
+
* #10918 — a switch is done only when a real model call through the switched route has been answered (a TRANSIENT failure - Cloudflare 403 Attention Required, 5xx, 429, network - is tried again with backoff, any other is terminal). The call is a
|
|
1473
|
+
* fresh `claude -p` process, so it reads the credential and the settings env the switch just wrote, exactly as the
|
|
1474
|
+
* next real request will. Who answered (the label switched to, the login's email, the model the CLI reports it used)
|
|
1475
|
+
* is appended to ~/.bullseye/auto-switch/switch-proof.jsonl whether it answered or not.
|
|
1476
|
+
* @param {string} home @param {string} label the account or key the switch moved to
|
|
1477
|
+
* @returns {{ ok: boolean, label: string, route: string, account: string, model: string, reply: string, attempt: number }}
|
|
1478
|
+
*/
|
|
1479
|
+
function proveSwitch(home, label) {
|
|
1480
|
+
let proof = proofCall(home, label);
|
|
1481
|
+
for (let attempt = 1; !proof.ok && !proof.unanswered && attempt < TRANSIENT_TRIES && TRANSIENT_PROOF_REPLY.test(proof.reply) && !NO_ROOM_REPLY.test(proof.reply); attempt++) {
|
|
1482
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, TRANSIENT_FIRST_WAIT_MS * 2 ** (attempt - 1));
|
|
1483
|
+
proof = proofCall(home, label, attempt + 1);
|
|
1484
|
+
}
|
|
1485
|
+
return proof;
|
|
1486
|
+
}
|
|
1487
|
+
function proofCall(home, label, attempt = 1) {
|
|
1488
|
+
const bin = process.env.CLAUDE_PROOF_BIN || "claude";
|
|
1489
|
+
const call = ["-p", "Reply with the single word OK", "--output-format", "json", "--max-turns", "1", "--settings", '{"disableAllHooks":true}', "--strict-mcp-config"];
|
|
1490
|
+
const run = bin.endsWith(".js") ? spawnSync(process.execPath, [bin, ...call], { ...PROOF_SPAWN, windowsHide: true }) : spawnSync(bin, call, { ...PROOF_SPAWN, windowsHide: true });
|
|
1491
|
+
let answer;
|
|
1492
|
+
let reply;
|
|
1493
|
+
if (run.error)
|
|
1494
|
+
reply = `the claude CLI could not run: ${run.error.message}`;
|
|
1495
|
+
else {
|
|
1496
|
+
try {
|
|
1497
|
+
answer = JSON.parse(run.stdout);
|
|
1498
|
+
reply = typeof answer.result === "string" ? answer.result : "no result in the reply";
|
|
1499
|
+
}
|
|
1500
|
+
catch (unreadable) {
|
|
1501
|
+
reply = `unreadable reply (exit ${run.status}): ${`${run.stdout || ""} ${run.stderr || ""}`.replace(/\s+/g, " ").trim().slice(0, 300)}`;
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
const model = answer && answer.modelUsage ? Object.keys(answer.modelUsage).join("+") : "";
|
|
1505
|
+
const ok = run.status === 0 && answer !== undefined && answer.is_error !== true && typeof answer.result === "string" && answer.result.trim().length > 0 && model.length > 0;
|
|
1506
|
+
const live = liveRoute(home);
|
|
1507
|
+
const proof = { ok, unanswered: run.error !== undefined, label, route: live.onKey ? "key" : "oauth", account: live.account, model, attempt, reply: reply.replace(/\s+/g, " ").trim().slice(0, 300) };
|
|
1508
|
+
const file = path.join(home, ".bullseye", "auto-switch", "switch-proof.jsonl");
|
|
1509
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
1510
|
+
fs.appendFileSync(file, JSON.stringify({ at: new Date().toISOString(), ...proof, unanswered: undefined }) + "\n");
|
|
1511
|
+
return proof;
|
|
1512
|
+
}
|
|
1513
|
+
function readStdin() {
|
|
1514
|
+
return fs.readFileSync(0, "utf8");
|
|
1515
|
+
}
|
|
1516
|
+
const VSCODE_VARIANTS = ['Code', 'Code - Insiders', 'VSCodium'];
|
|
1517
|
+
const VSCODE_FOOTPRINT = ['settings.json', 'keybindings.json', 'tasks.json', 'mcp.json',
|
|
1518
|
+
'globalStorage', 'workspaceStorage', 'History', 'snippets', 'profiles'];
|
|
1519
|
+
function vscodeDataRoot(platform, env, home) {
|
|
1520
|
+
if (platform === 'darwin')
|
|
1521
|
+
return path.join(home, 'Library', 'Application Support');
|
|
1522
|
+
if (platform === 'win32')
|
|
1523
|
+
return env.APPDATA || path.join(home, 'AppData', 'Roaming');
|
|
1524
|
+
return env.XDG_CONFIG_HOME || path.join(home, '.config');
|
|
1525
|
+
}
|
|
1526
|
+
const SEVERAL_VSCODE_SAID = new Set();
|
|
1527
|
+
function looksLikeVscodeUserDir(dir) {
|
|
1528
|
+
const stat = fs.statSync(dir, { throwIfNoEntry: false });
|
|
1529
|
+
if (stat === undefined || !stat.isDirectory())
|
|
1530
|
+
return false;
|
|
1531
|
+
return VSCODE_FOOTPRINT.some((m) => fs.existsSync(path.join(dir, m)));
|
|
1532
|
+
}
|
|
1533
|
+
/**
|
|
1534
|
+
* @param {string} [who]
|
|
1535
|
+
* @param {new (message: string) => Error} [Failure]
|
|
1536
|
+
*/
|
|
1537
|
+
function vscodeUserDir(platform = process.platform, env = process.env, home = os.homedir(), who = 'claude-provider', Failure = Error) {
|
|
1538
|
+
const override = env.BULLSEYE_VSCODE_USER_DIR;
|
|
1539
|
+
const wanted = env.BULLSEYE_VSCODE_VARIANT || VSCODE_VARIANTS[0];
|
|
1540
|
+
const tried = override ? [override]
|
|
1541
|
+
: [wanted].concat(VSCODE_VARIANTS.filter((v) => v !== wanted))
|
|
1542
|
+
.map((v) => path.join(vscodeDataRoot(platform, env, home), v, 'User'));
|
|
1543
|
+
const found = tried.filter(looksLikeVscodeUserDir);
|
|
1544
|
+
if (found.length === 0) {
|
|
1545
|
+
throw new Failure('no VS Code user settings directory was found: tried ' + tried.join(', ')
|
|
1546
|
+
+ ' — not one of them carries VS Code\'s own data (' + VSCODE_FOOTPRINT.join('/') + '), so a switch '
|
|
1547
|
+
+ 'written there would be a switch VS Code never reads'
|
|
1548
|
+
+ (override
|
|
1549
|
+
? '. BULLSEYE_VSCODE_USER_DIR is set to ' + override + ': point it at the User directory this VS '
|
|
1550
|
+
+ 'Code really uses, or unset it'
|
|
1551
|
+
: '. Launch VS Code once so that it creates its User directory, or name it with '
|
|
1552
|
+
+ 'BULLSEYE_VSCODE_VARIANT / BULLSEYE_VSCODE_USER_DIR'));
|
|
1553
|
+
}
|
|
1554
|
+
if (found.length > 1 && !override && !SEVERAL_VSCODE_SAID.has(found.join('|'))) {
|
|
1555
|
+
SEVERAL_VSCODE_SAID.add(found.join('|'));
|
|
1556
|
+
console.error(who + ': ' + found.length + ' VS Code user directories carry data on this '
|
|
1557
|
+
+ 'machine (' + found.join(', ') + '); routing ' + found[0]
|
|
1558
|
+
+ ' — set BULLSEYE_VSCODE_VARIANT to route another.');
|
|
1559
|
+
}
|
|
1560
|
+
return found[0];
|
|
1561
|
+
}
|
|
1562
|
+
function jsoncToJson(text) {
|
|
1563
|
+
let out = '', inStr = false, esc = false;
|
|
1564
|
+
for (let i = 0; i < text.length; i++) {
|
|
1565
|
+
const ch = text[i];
|
|
1566
|
+
if (inStr) {
|
|
1567
|
+
out += ch;
|
|
1568
|
+
if (esc)
|
|
1569
|
+
esc = false;
|
|
1570
|
+
else if (ch === '\\')
|
|
1571
|
+
esc = true;
|
|
1572
|
+
else if (ch === '"')
|
|
1573
|
+
inStr = false;
|
|
1574
|
+
}
|
|
1575
|
+
else if (ch === '"') {
|
|
1576
|
+
inStr = true;
|
|
1577
|
+
out += ch;
|
|
1578
|
+
}
|
|
1579
|
+
else if (ch === '/' && text[i + 1] === '/') {
|
|
1580
|
+
while (i < text.length && text[i] !== '\n')
|
|
1581
|
+
i++;
|
|
1582
|
+
out += '\n';
|
|
1583
|
+
}
|
|
1584
|
+
else if (ch === '/' && text[i + 1] === '*') {
|
|
1585
|
+
const close = text.indexOf('*/', i + 2);
|
|
1586
|
+
i = close < 0 ? text.length : close + 1;
|
|
1587
|
+
}
|
|
1588
|
+
else if (ch === ',' && /^\s*[\]}]/.test(text.slice(i + 1).replace(/^(\s|\/\/[^\n]*|\/\*[\s\S]*?\*\/)*/, ''))) {
|
|
1589
|
+
continue;
|
|
1590
|
+
}
|
|
1591
|
+
else {
|
|
1592
|
+
out += ch;
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
return out;
|
|
1596
|
+
}
|
|
1597
|
+
const DEEPAGENT_PREFIX = 'deepagent.';
|
|
1598
|
+
const IDENTITY_RECORDS = 'deepagent.identities';
|
|
1599
|
+
/** #3849 — the workspace store: shipped flat beside this file in an extension, in its own folder in BullseyeShared. */
|
|
1600
|
+
const workspaceStore = () => require(__rewriteRelativeImportExtension(fs.existsSync(path.join(__dirname, 'workspaceList.js')) ? path.join(__dirname, 'workspaceList.js') : path.join(__dirname, '..', '..', 'bullseye-webhost', 'workspaceList.js')));
|
|
1601
|
+
function deepagentValues(saved) {
|
|
1602
|
+
const values = { ...saved.settings, ...saved.secrets };
|
|
1603
|
+
if (Object.prototype.hasOwnProperty.call(saved.box, 'deepagent.apiKey'))
|
|
1604
|
+
values['deepagent.apiKey'] = saved.box['deepagent.apiKey'];
|
|
1605
|
+
if (IDENTITY_RECORDS in values) {
|
|
1606
|
+
const logins = boxLogins(saved.box[IDENTITY_RECORDS], saved.file);
|
|
1607
|
+
const keys = identityKeys(saved.box['deepagent.identityKeys'], saved.file);
|
|
1608
|
+
values[IDENTITY_RECORDS] = withThisBoxsLogins(values[IDENTITY_RECORDS], logins, saved.file).map((record) => ({ ...record, ...(keys.get(record.id) || {}) }));
|
|
1609
|
+
}
|
|
1610
|
+
return values;
|
|
1611
|
+
}
|
|
1612
|
+
/**
|
|
1613
|
+
* #3849 — DeepAgent's machine-wide settings, the ONE reader DeepAgent, claude-provider and every pad script share: da.json
|
|
1614
|
+
* under the store's toolHome(), its settings and secrets as one `deepagent.*` map, each identity's login joined back from
|
|
1615
|
+
* this box's own part. No da.json THROWS the store's SettingsUndefined naming the file — an absent read is never "no accounts".
|
|
1616
|
+
* @returns {{ file: string, base: string, values: Record<string, any> }}
|
|
1617
|
+
*/
|
|
1618
|
+
function deepagentSettings() {
|
|
1619
|
+
const store = workspaceStore();
|
|
1620
|
+
for (;;) {
|
|
1621
|
+
const saved = store.readSettings(store.toolHome(), 'da');
|
|
1622
|
+
const values = deepagentValues(saved);
|
|
1623
|
+
const records = saved.secrets[IDENTITY_RECORDS] || saved.settings[IDENTITY_RECORDS];
|
|
1624
|
+
const exposed = Object.prototype.hasOwnProperty.call(saved.secrets, 'deepagent.apiKey') || Object.prototype.hasOwnProperty.call(saved.settings, 'deepagent.apiKey') || Object.prototype.hasOwnProperty.call(saved.secrets, IDENTITY_RECORDS) || (Array.isArray(records) && records.some((record) => ['credential', 'key', 'usageKey'].some((key) => Object.prototype.hasOwnProperty.call(record, key))));
|
|
1625
|
+
if (!exposed)
|
|
1626
|
+
return { file: saved.file, base: saved.base, values };
|
|
1627
|
+
const change = {};
|
|
1628
|
+
if (IDENTITY_RECORDS in values)
|
|
1629
|
+
change[IDENTITY_RECORDS] = values[IDENTITY_RECORDS];
|
|
1630
|
+
if ('deepagent.apiKey' in values)
|
|
1631
|
+
change['deepagent.apiKey'] = values['deepagent.apiKey'];
|
|
1632
|
+
try {
|
|
1633
|
+
store.writeSettings(store.toolHome(), 'da', deepagentParts(change), saved.base);
|
|
1634
|
+
}
|
|
1635
|
+
catch (cause) {
|
|
1636
|
+
if (!(cause instanceof store.SettingsMoved))
|
|
1637
|
+
throw cause;
|
|
1638
|
+
// OWNER: ITER/LOOP — retry the migration only after a concurrent save moved its snapshot.
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
function boxLogins(logins, file) {
|
|
1643
|
+
if (logins === undefined)
|
|
1644
|
+
return new Map();
|
|
1645
|
+
if (logins === null || typeof logins !== 'object' || Array.isArray(logins))
|
|
1646
|
+
throw new UnreadableSettings(IDENTITY_RECORDS + ' in the box part of ' + file + ' is not a map of identity id to login');
|
|
1647
|
+
return new Map(Object.entries(logins));
|
|
1648
|
+
}
|
|
1649
|
+
function identityKeys(value, file) {
|
|
1650
|
+
const entries = boxLogins(value, file);
|
|
1651
|
+
for (const held of entries.values()) {
|
|
1652
|
+
if (held === null || typeof held !== 'object' || Array.isArray(held) || Object.entries(held).some(([key, value]) => !['key', 'usageKey'].includes(key) || typeof value !== 'string')) {
|
|
1653
|
+
throw new UnreadableSettings('deepagent.identityKeys in the box part of ' + file + ' must map identity ids to key and usageKey strings');
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
return entries;
|
|
1657
|
+
}
|
|
1658
|
+
/** @returns {{ settings: Record<string, any>, secrets: Record<string, any>, box?: Record<string, any> }} */
|
|
1659
|
+
function deepagentParts(values) {
|
|
1660
|
+
const parts = { settings: {}, secrets: {} };
|
|
1661
|
+
for (const [key, value] of Object.entries(values)) {
|
|
1662
|
+
if (key === 'deepagent.apiKey') {
|
|
1663
|
+
(parts.box ||= {})[key] = value;
|
|
1664
|
+
parts.settings[key] = null;
|
|
1665
|
+
parts.secrets[key] = null;
|
|
1666
|
+
continue;
|
|
1667
|
+
}
|
|
1668
|
+
if (key !== IDENTITY_RECORDS) {
|
|
1669
|
+
parts.settings[key] = value;
|
|
1670
|
+
continue;
|
|
1671
|
+
}
|
|
1672
|
+
const logins = {}, keys = {};
|
|
1673
|
+
parts.settings[key] = value.map(({ credential, key: apiKey, usageKey, ...record }) => {
|
|
1674
|
+
if (credential !== undefined)
|
|
1675
|
+
logins[record.id] = credential;
|
|
1676
|
+
if (apiKey !== undefined || usageKey !== undefined)
|
|
1677
|
+
keys[record.id] = { ...(apiKey === undefined ? {} : { key: apiKey }), ...(usageKey === undefined ? {} : { usageKey }) };
|
|
1678
|
+
return record;
|
|
1679
|
+
});
|
|
1680
|
+
parts.secrets[key] = null;
|
|
1681
|
+
parts.box = { ...parts.box, [key]: logins, 'deepagent.identityKeys': keys };
|
|
1682
|
+
}
|
|
1683
|
+
return parts;
|
|
1684
|
+
}
|
|
1685
|
+
function saveDeepagentSettings(change, base) {
|
|
1686
|
+
const store = workspaceStore();
|
|
1687
|
+
for (;;) {
|
|
1688
|
+
const root = store.toolHome();
|
|
1689
|
+
const saved = fs.existsSync(store.settingsFile(root, 'da')) ? store.readSettings(root, 'da') : undefined;
|
|
1690
|
+
const legacy = {};
|
|
1691
|
+
if (saved !== undefined) {
|
|
1692
|
+
const values = deepagentValues(saved);
|
|
1693
|
+
if (IDENTITY_RECORDS in saved.secrets || (Array.isArray(saved.settings[IDENTITY_RECORDS]) && saved.settings[IDENTITY_RECORDS].some((record) => ['credential', 'key', 'usageKey'].some((key) => key in record))))
|
|
1694
|
+
legacy[IDENTITY_RECORDS] = values[IDENTITY_RECORDS];
|
|
1695
|
+
if ('deepagent.apiKey' in saved.settings || 'deepagent.apiKey' in saved.secrets)
|
|
1696
|
+
legacy['deepagent.apiKey'] = values['deepagent.apiKey'];
|
|
1697
|
+
}
|
|
1698
|
+
const combined = { ...legacy, ...change };
|
|
1699
|
+
const parts = deepagentParts(Object.fromEntries(Object.entries(combined).filter(([, value]) => value !== null)));
|
|
1700
|
+
for (const key of Object.keys(combined).filter((k) => combined[k] === null)) {
|
|
1701
|
+
parts.settings[key] = null;
|
|
1702
|
+
parts.secrets[key] = null;
|
|
1703
|
+
if (key === IDENTITY_RECORDS)
|
|
1704
|
+
parts.box = { ...parts.box, [key]: null, 'deepagent.identityKeys': null };
|
|
1705
|
+
if (key === 'deepagent.apiKey')
|
|
1706
|
+
(parts.box ||= {})[key] = null;
|
|
1707
|
+
}
|
|
1708
|
+
try {
|
|
1709
|
+
store.writeSettings(root, 'da', parts, base === undefined ? (saved === undefined ? store.settingsBase(root, 'da') : saved.base) : base);
|
|
1710
|
+
return deepagentSettings();
|
|
1711
|
+
}
|
|
1712
|
+
catch (cause) {
|
|
1713
|
+
if (base !== undefined || !(cause instanceof store.SettingsMoved))
|
|
1714
|
+
throw cause;
|
|
1715
|
+
// OWNER: ITER/LOOP — only a write made without an earlier reading is redone from the concurrent writer's fresh snapshot.
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
function settingsTokens(text) {
|
|
1720
|
+
const tokens = [];
|
|
1721
|
+
let depth = 0;
|
|
1722
|
+
for (let i = 0; i < text.length;) {
|
|
1723
|
+
const start = i, ch = text[i];
|
|
1724
|
+
if (/\s/.test(ch)) {
|
|
1725
|
+
i++;
|
|
1726
|
+
continue;
|
|
1727
|
+
}
|
|
1728
|
+
if (text.startsWith('//', i)) {
|
|
1729
|
+
const end = text.indexOf('\n', i + 2);
|
|
1730
|
+
i = end < 0 ? text.length : end + 1;
|
|
1731
|
+
continue;
|
|
1732
|
+
}
|
|
1733
|
+
if (text.startsWith('/*', i)) {
|
|
1734
|
+
const end = text.indexOf('*/', i + 2);
|
|
1735
|
+
if (end < 0)
|
|
1736
|
+
throw new UnreadableSettings('unterminated settings comment');
|
|
1737
|
+
i = end + 2;
|
|
1738
|
+
continue;
|
|
1739
|
+
}
|
|
1740
|
+
if (ch === '"') {
|
|
1741
|
+
i++;
|
|
1742
|
+
while (i < text.length) {
|
|
1743
|
+
if (text[i] === '\\') {
|
|
1744
|
+
i += 2;
|
|
1745
|
+
continue;
|
|
1746
|
+
}
|
|
1747
|
+
if (text[i++] === '"')
|
|
1748
|
+
break;
|
|
1749
|
+
}
|
|
1750
|
+
tokens.push({ start, end: i, depth, text: text.slice(start, i), string: true });
|
|
1751
|
+
continue;
|
|
1752
|
+
}
|
|
1753
|
+
if (ch === '}' || ch === ']')
|
|
1754
|
+
depth--;
|
|
1755
|
+
tokens.push({ start, end: i + 1, depth, text: ch, string: false });
|
|
1756
|
+
if (ch === '{' || ch === '[')
|
|
1757
|
+
depth++;
|
|
1758
|
+
i++;
|
|
1759
|
+
}
|
|
1760
|
+
return tokens;
|
|
1761
|
+
}
|
|
1762
|
+
function canonical(value) {
|
|
1763
|
+
if (Array.isArray(value))
|
|
1764
|
+
return value.map(canonical);
|
|
1765
|
+
if (value === null || typeof value !== 'object')
|
|
1766
|
+
return value;
|
|
1767
|
+
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
|
|
1768
|
+
}
|
|
1769
|
+
const same = (a, b) => JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
|
|
1770
|
+
function identityIds(records, where) {
|
|
1771
|
+
if (!Array.isArray(records))
|
|
1772
|
+
throw new UnreadableSettings(IDENTITY_RECORDS + ' in ' + where + ' is not a list');
|
|
1773
|
+
const ids = records.map((record, i) => {
|
|
1774
|
+
if (record === null || typeof record !== 'object' || typeof record.id !== 'string' || record.id === '') {
|
|
1775
|
+
throw new UnreadableSettings(IDENTITY_RECORDS + '[' + i + '] in ' + where + ' carries no readable id, so its login cannot be told apart from another box\'s');
|
|
1776
|
+
}
|
|
1777
|
+
return record.id;
|
|
1778
|
+
});
|
|
1779
|
+
const shared = ids.find((id, i) => ids.indexOf(id) !== i);
|
|
1780
|
+
if (shared !== undefined)
|
|
1781
|
+
throw new UnreadableSettings('two ' + IDENTITY_RECORDS + ' records in ' + where + ' share the id ' + JSON.stringify(shared) + ' — remove one in DeepAgent');
|
|
1782
|
+
return ids;
|
|
1783
|
+
}
|
|
1784
|
+
function deepagentMirror(settings, file) {
|
|
1785
|
+
const mirrored = {};
|
|
1786
|
+
for (const key of Object.keys(settings).filter((k) => k.startsWith(DEEPAGENT_PREFIX)).sort()) {
|
|
1787
|
+
if (key !== 'deepagent.apiKey')
|
|
1788
|
+
mirrored[key] = settings[key];
|
|
1789
|
+
}
|
|
1790
|
+
if (IDENTITY_RECORDS in mirrored) {
|
|
1791
|
+
identityIds(mirrored[IDENTITY_RECORDS], file);
|
|
1792
|
+
mirrored[IDENTITY_RECORDS] = mirrored[IDENTITY_RECORDS].map(({ credential, key, usageKey, ...record }) => record);
|
|
1793
|
+
}
|
|
1794
|
+
return canonical(mirrored);
|
|
1795
|
+
}
|
|
1796
|
+
/** `records` with each one that carries no credential of its own given this box's login for its id (`logins`, id → login); an identity this box never signed in reads `credential: ''`, DeepAgent's own word for no login. */
|
|
1797
|
+
function withThisBoxsLogins(records, logins, file) {
|
|
1798
|
+
identityIds(records, file);
|
|
1799
|
+
return records.map((record) => ({ ...record, credential: logins.has(record.id) ? logins.get(record.id) : (record.credential === undefined ? '' : record.credential) }));
|
|
1800
|
+
}
|
|
1801
|
+
/** The logins `records` carry, by identity id. */
|
|
1802
|
+
const loginsOf = (records, file) => new Map(records === undefined ? [] : identityIds(records, file).map((id, i) => [id, records[i].credential]).filter(([, credential]) => credential !== undefined));
|
|
1803
|
+
/** #3849 — HP's mirrored DeepAgent settings written into this box's da.json, each identity keeping this box's own login; bytes that moved since they were read refuse the write in the store with nothing written, and the next pass writes it. */
|
|
1804
|
+
function applyDeepagentMirror(mirror) {
|
|
1805
|
+
const store = workspaceStore();
|
|
1806
|
+
const root = store.toolHome();
|
|
1807
|
+
const file = store.settingsFile(root, 'da');
|
|
1808
|
+
const held = fs.existsSync(file) ? deepagentSettings() : { base: store.settingsBase(root, 'da'), values: {} };
|
|
1809
|
+
const settings = held.values;
|
|
1810
|
+
const wanted = deepagentMirror(mirror, file);
|
|
1811
|
+
if (IDENTITY_RECORDS in wanted) {
|
|
1812
|
+
const local = new Map((settings[IDENTITY_RECORDS] || []).map((record) => [record.id, record]));
|
|
1813
|
+
wanted[IDENTITY_RECORDS] = withThisBoxsLogins(wanted[IDENTITY_RECORDS], loginsOf(settings[IDENTITY_RECORDS], file), file).map((record) => {
|
|
1814
|
+
const held = local.get(record.id);
|
|
1815
|
+
return { ...record, ...(held && 'key' in held ? { key: held.key } : {}), ...(held && 'usageKey' in held ? { usageKey: held.usageKey } : {}) };
|
|
1816
|
+
});
|
|
1817
|
+
}
|
|
1818
|
+
const keys = new Set([...Object.keys(settings).filter((k) => k.startsWith(DEEPAGENT_PREFIX) && k !== 'deepagent.apiKey'), ...Object.keys(wanted)]);
|
|
1819
|
+
const changed = [...keys].filter((key) => !same(settings[key], wanted[key])).sort();
|
|
1820
|
+
if (changed.length === 0)
|
|
1821
|
+
return { file, changed, said: [] };
|
|
1822
|
+
saveDeepagentSettings(Object.fromEntries(changed.map((key) => [key, key in wanted ? wanted[key] : null])), held.base);
|
|
1823
|
+
const ids = new Set((wanted[IDENTITY_RECORDS] || []).map((record) => record.id));
|
|
1824
|
+
const said = changed.map((key) => {
|
|
1825
|
+
if (key === IDENTITY_RECORDS)
|
|
1826
|
+
return key + ': ' + identityChanges(settings[key], wanted[key]);
|
|
1827
|
+
if (ids.has(settings[key]) || ids.has(wanted[key]))
|
|
1828
|
+
return key + ': ' + (settings[key] === undefined ? 'unset' : settings[key]) + ' -> ' + (wanted[key] === undefined ? 'unset' : wanted[key]);
|
|
1829
|
+
return key + (key in wanted ? ' changed' : ' removed');
|
|
1830
|
+
});
|
|
1831
|
+
return { file, changed, said };
|
|
1832
|
+
}
|
|
1833
|
+
function identityChanges(before, after) {
|
|
1834
|
+
const was = new Map((Array.isArray(before) ? before : []).map((record) => [record.id, record]));
|
|
1835
|
+
const now = new Map((after || []).map((record) => [record.id, record]));
|
|
1836
|
+
const added = [...now.keys()].filter((id) => !was.has(id));
|
|
1837
|
+
const removed = [...was.keys()].filter((id) => !now.has(id));
|
|
1838
|
+
const moved = [...now.keys()].filter((id) => was.has(id) && !same(was.get(id), now.get(id)));
|
|
1839
|
+
return [['added', added], ['removed', removed], ['changed', moved]].filter(([, ids]) => ids.length > 0)
|
|
1840
|
+
.map(([what, ids]) => what + ' ' + ids.join(', ')).join('; ');
|
|
1841
|
+
}
|
|
1842
|
+
const POLICY_AGENTS = { anthropic: 'Claude', openai: 'Codex', github: 'Copilot' };
|
|
1843
|
+
const POLICY_FIELDS = [[AUTO_BOX, 'switches between its subscriptions by itself'], [BYOK_BOX, 'falls back to a key once every subscription is spent'], ['byokKey', 'the key it falls back to']];
|
|
1844
|
+
function statOrAbsent(file) {
|
|
1845
|
+
const found = unlessErr('ENOENT', () => fs.statSync(file, { bigint: true }));
|
|
1846
|
+
return found === undefined ? ['absent'] : [String(found.mtimeNs), String(found.size)];
|
|
1847
|
+
}
|
|
1848
|
+
function readSwitchPolicy(home) {
|
|
1849
|
+
const text = unlessErr('ENOENT', () => fs.readFileSync(settingsPath(home), 'utf8'));
|
|
1850
|
+
return text === undefined ? undefined : JSON.parse(text);
|
|
1851
|
+
}
|
|
1852
|
+
function deepagentMirrorOf(home) {
|
|
1853
|
+
const { file, values } = deepagentSettings();
|
|
1854
|
+
const policy = readSwitchPolicy(home);
|
|
1855
|
+
return { file, stat: [...statOrAbsent(file), ...statOrAbsent(settingsPath(home))],
|
|
1856
|
+
mirror: deepagentMirror(values, file), switching: policy === undefined ? null : canonical(policy) };
|
|
1857
|
+
}
|
|
1858
|
+
function policyValue(field, value) {
|
|
1859
|
+
if (field === 'byokKey')
|
|
1860
|
+
return value === undefined || value === '' ? 'none picked' : value;
|
|
1861
|
+
return value === true ? 'on' : 'off';
|
|
1862
|
+
}
|
|
1863
|
+
function applySwitchPolicy(home, wanted) {
|
|
1864
|
+
const file = settingsPath(home);
|
|
1865
|
+
const text = unlessErr('ENOENT', () => fs.readFileSync(file, 'utf8'));
|
|
1866
|
+
const held = text === undefined ? {} : JSON.parse(text);
|
|
1867
|
+
if (text !== undefined && same(held, wanted))
|
|
1868
|
+
return { changed: [], said: [] };
|
|
1869
|
+
const said = [];
|
|
1870
|
+
for (const provider of [...new Set([...Object.keys(held), ...Object.keys(wanted)])].sort()) {
|
|
1871
|
+
for (const [field, words] of POLICY_FIELDS) {
|
|
1872
|
+
const was = policyValue(field, (held[provider] || {})[field]), now = policyValue(field, (wanted[provider] || {})[field]);
|
|
1873
|
+
if (was !== now)
|
|
1874
|
+
said.push((POLICY_AGENTS[provider] || provider) + ' ' + words + ': ' + was + ' -> ' + now);
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
if (unlessErr('ENOENT', () => fs.readFileSync(file, 'utf8')) !== text)
|
|
1878
|
+
throw new Error(file + ' changed while HP\'s switching choices were being written into it; nothing was written — the next pass writes them');
|
|
1879
|
+
writeAtomically(file, JSON.stringify(canonical(wanted), null, 2) + '\n');
|
|
1880
|
+
return { changed: [file], said };
|
|
1881
|
+
}
|
|
1882
|
+
function applyDeepagentMirrorOf(home, mirror, switching) {
|
|
1883
|
+
const applied = applyDeepagentMirror(mirror);
|
|
1884
|
+
const switched = switching === undefined ? { changed: [], said: [] } : applySwitchPolicy(home, switching);
|
|
1885
|
+
return { file: applied.file, changed: [...applied.changed, ...switched.changed], said: [...applied.said, ...switched.said], switched: switching !== undefined };
|
|
1886
|
+
}
|
|
1887
|
+
/**
|
|
1888
|
+
* The label of the Claude subscription HP's DeepAgent choice names on this box (`deepagent.subscription.claude` in its
|
|
1889
|
+
* da.json, mirrored from HP), or undefined when HP chose none. No da.json THROWS, naming it.
|
|
1890
|
+
* @returns {string | undefined}
|
|
1891
|
+
*/
|
|
1892
|
+
function chosenSubscriptionOf() {
|
|
1893
|
+
const { file, values: settings } = deepagentSettings();
|
|
1894
|
+
const id = settings['deepagent.subscription.claude'];
|
|
1895
|
+
if (id === undefined || id === '')
|
|
1896
|
+
return undefined;
|
|
1897
|
+
if (typeof id !== 'string')
|
|
1898
|
+
throw new Error(file + ' carries a deepagent.subscription.claude that is not text');
|
|
1899
|
+
const named = claudeSubscriptions(settings[IDENTITY_RECORDS]).find((s) => s.id === id);
|
|
1900
|
+
if (named === undefined)
|
|
1901
|
+
throw new Error(file + ' chooses the Claude subscription ' + id + ', which is none of its deepagent.identities');
|
|
1902
|
+
return named.label;
|
|
1903
|
+
}
|
|
1904
|
+
/**
|
|
1905
|
+
* @param {new (message: string) => Error} [Failure]
|
|
1906
|
+
* @returns {{ id: string, label: string, token: string }[]}
|
|
1907
|
+
*/
|
|
1908
|
+
function claudeSubscriptions(identities, Failure = Error) {
|
|
1909
|
+
if (identities === undefined)
|
|
1910
|
+
return [];
|
|
1911
|
+
if (!Array.isArray(identities))
|
|
1912
|
+
throw new Failure('deepagent.identities is not a list, so it names no Claude subscription');
|
|
1913
|
+
const named = new Map();
|
|
1914
|
+
identities.forEach((row, i) => {
|
|
1915
|
+
if (row === null || typeof row !== 'object' || Array.isArray(row))
|
|
1916
|
+
throw new Failure('deepagent.identities entry ' + i + ' is not an entry object, so it names no Claude subscription');
|
|
1917
|
+
});
|
|
1918
|
+
const text = (row, field) => {
|
|
1919
|
+
if (row[field] === undefined)
|
|
1920
|
+
return '';
|
|
1921
|
+
if (typeof row[field] !== 'string')
|
|
1922
|
+
throw new Failure('the Claude subscription ' + row.id + ' carries a ' + field + ' that is not text');
|
|
1923
|
+
return row[field].trim();
|
|
1924
|
+
};
|
|
1925
|
+
return identities.filter((row) => row.kind === 'subscription' && row.providerType === 'anthropic').map((row) => {
|
|
1926
|
+
const account = text(row, 'account');
|
|
1927
|
+
const label = (account.includes('@') ? account.slice(0, account.indexOf('@')) : String(row.id)).toLowerCase();
|
|
1928
|
+
if (!/^[a-z0-9._-]+$/.test(label))
|
|
1929
|
+
throw new Failure('the Claude subscription ' + row.id + ' names the account ' + JSON.stringify(account) + ', which is no usable account name');
|
|
1930
|
+
if (named.has(label))
|
|
1931
|
+
throw new Failure('the Claude subscriptions ' + named.get(label) + ' and ' + row.id + ' in deepagent.identities are both the account ' + label + ' — remove one in DeepAgent');
|
|
1932
|
+
named.set(label, row.id);
|
|
1933
|
+
return { id: String(row.id), label, token: text(row, 'credential') };
|
|
1934
|
+
});
|
|
1935
|
+
}
|
|
1936
|
+
/**
|
|
1937
|
+
* Every Claude subscription this box's DeepAgent holds (`deepagent.identities` in its da.json). No da.json THROWS the store's
|
|
1938
|
+
* SettingsUndefined naming it; `[]` is a da.json that names no Claude subscription, never a failed read.
|
|
1939
|
+
* @returns {{ id: string, label: string, token: string }[]}
|
|
1940
|
+
*/
|
|
1941
|
+
function boxClaudeSubscriptions() {
|
|
1942
|
+
return claudeSubscriptions(deepagentSettings().values[IDENTITY_RECORDS]);
|
|
1943
|
+
}
|
|
1944
|
+
module.exports = {
|
|
1945
|
+
UnreadableSettings,
|
|
1946
|
+
VSCODE_VARIANTS,
|
|
1947
|
+
vscodeDataRoot,
|
|
1948
|
+
vscodeUserDir,
|
|
1949
|
+
jsoncToJson,
|
|
1950
|
+
claudeSubscriptions,
|
|
1951
|
+
boxClaudeSubscriptions,
|
|
1952
|
+
chosenSubscriptionOf,
|
|
1953
|
+
settingsTokens,
|
|
1954
|
+
deepagentSettings,
|
|
1955
|
+
deepagentParts,
|
|
1956
|
+
saveDeepagentSettings,
|
|
1957
|
+
deepagentMirror,
|
|
1958
|
+
applyDeepagentMirror,
|
|
1959
|
+
deepagentMirrorOf,
|
|
1960
|
+
applyDeepagentMirrorOf,
|
|
1961
|
+
CLI_PROVIDER,
|
|
1962
|
+
ROUTED_EFFORT_LEVEL,
|
|
1963
|
+
WARN_BAND_ROOM_PCT,
|
|
1964
|
+
writeAtomically,
|
|
1965
|
+
settingsPath,
|
|
1966
|
+
readAuto,
|
|
1967
|
+
readByokFallback,
|
|
1968
|
+
writeAuto,
|
|
1969
|
+
writeByokFallback,
|
|
1970
|
+
readByokKey,
|
|
1971
|
+
writeByokKey,
|
|
1972
|
+
OPENCODE_ROUTES,
|
|
1973
|
+
readOpencodeRoute,
|
|
1974
|
+
writeOpencodeRoute,
|
|
1975
|
+
readOpencodeModel,
|
|
1976
|
+
writeOpencodeModel,
|
|
1977
|
+
decide,
|
|
1978
|
+
subscriptionFirst,
|
|
1979
|
+
RoomReadError,
|
|
1980
|
+
runsOnKeys,
|
|
1981
|
+
billsAKey,
|
|
1982
|
+
unreadRooms,
|
|
1983
|
+
autoProvider,
|
|
1984
|
+
readProviderRooms,
|
|
1985
|
+
coverageOf,
|
|
1986
|
+
transientRetried,
|
|
1987
|
+
firstRefillAt,
|
|
1988
|
+
markRefused,
|
|
1989
|
+
readRefusal,
|
|
1990
|
+
clearRefusal,
|
|
1991
|
+
refusalIsFresh,
|
|
1992
|
+
isSubscriptionQuota,
|
|
1993
|
+
readMove,
|
|
1994
|
+
recordMove,
|
|
1995
|
+
forgetMove,
|
|
1996
|
+
roomPath,
|
|
1997
|
+
recordRoom,
|
|
1998
|
+
recordRoomLive,
|
|
1999
|
+
CREDIT_KEY_PROVIDER,
|
|
2000
|
+
keyPlanPath,
|
|
2001
|
+
recordKeyPlan,
|
|
2002
|
+
readKeyPlan,
|
|
2003
|
+
AGENT_CLIS,
|
|
2004
|
+
OPENCODE_PROVIDER,
|
|
2005
|
+
OPENCODE_KEY_KINDS,
|
|
2006
|
+
markKeyRefused,
|
|
2007
|
+
keyRefusalId,
|
|
2008
|
+
opencodeRoute,
|
|
2009
|
+
opencodeStoreEnv,
|
|
2010
|
+
opencodeKeyRoute,
|
|
2011
|
+
OPENCODE_CATALOGUE_UNREADABLE,
|
|
2012
|
+
OPENCODE_FREE_ID,
|
|
2013
|
+
opencodeFreeModelRefusalId,
|
|
2014
|
+
opencodeFreeModels,
|
|
2015
|
+
opencodeFreeState,
|
|
2016
|
+
opencodeFreeFailure,
|
|
2017
|
+
opencodeEventError,
|
|
2018
|
+
opencodeRetryPrompt,
|
|
2019
|
+
OPENCODE_RULES,
|
|
2020
|
+
OPENCODE_KEY_REFUSAL_WORDS,
|
|
2021
|
+
keyFundsRecord,
|
|
2022
|
+
failbackDue,
|
|
2023
|
+
appliedHookWired,
|
|
2024
|
+
expectApplied,
|
|
2025
|
+
reapplySettings,
|
|
2026
|
+
markApplied,
|
|
2027
|
+
whenApplied,
|
|
2028
|
+
failbackCheck,
|
|
2029
|
+
whoDecides,
|
|
2030
|
+
handToDecider,
|
|
2031
|
+
failoverByDecider,
|
|
2032
|
+
proveSwitch,
|
|
2033
|
+
};
|
|
2034
|
+
if (require.main === module) {
|
|
2035
|
+
const home = process.env.HOME || os.homedir();
|
|
2036
|
+
const [op, ...args] = process.argv.slice(2);
|
|
2037
|
+
try {
|
|
2038
|
+
switch (op) {
|
|
2039
|
+
case "route-generation": {
|
|
2040
|
+
const files = ["settings.json", ".credentials.json"].map((name) => path.join(home, ".claude", name));
|
|
2041
|
+
files.push(settingsPath(home));
|
|
2042
|
+
const bytes = files.map((file) => unlessErr("ENOENT", () => fs.readFileSync(file, "utf8")));
|
|
2043
|
+
process.stdout.write(require("crypto").createHash("sha256").update(JSON.stringify(bytes)).digest("hex"));
|
|
2044
|
+
break;
|
|
2045
|
+
}
|
|
2046
|
+
case "lock-alive":
|
|
2047
|
+
process.exitCode = workspaceStore().alive(Number(args[0].split(":")[0])) ? 0 : 1;
|
|
2048
|
+
break;
|
|
2049
|
+
case "agents":
|
|
2050
|
+
process.stdout.write(JSON.stringify({ agents: AGENT_CLIS }));
|
|
2051
|
+
break;
|
|
2052
|
+
case "subscription-tier-kinds":
|
|
2053
|
+
process.stdout.write(SUBSCRIPTION_TIER_KINDS.join("\n") + "\n");
|
|
2054
|
+
break;
|
|
2055
|
+
case "subscription-first": {
|
|
2056
|
+
const chainAsk = JSON.parse(readStdin());
|
|
2057
|
+
process.stdout.write(subscriptionFirst({ ...chainAsk, keyFallback: keyRungOf(chainAsk) !== undefined && readByokFallback(home, "claude") }).join("\n") + "\n");
|
|
2058
|
+
break;
|
|
2059
|
+
}
|
|
2060
|
+
case "deepagent-settings":
|
|
2061
|
+
process.stdout.write(JSON.stringify(deepagentSettings()));
|
|
2062
|
+
break;
|
|
2063
|
+
case "claude-subscriptions":
|
|
2064
|
+
process.stdout.write(JSON.stringify(boxClaudeSubscriptions()));
|
|
2065
|
+
break;
|
|
2066
|
+
case "deepagent-save": {
|
|
2067
|
+
const { change, base } = JSON.parse(readStdin());
|
|
2068
|
+
process.stdout.write(JSON.stringify(saveDeepagentSettings(change, base)));
|
|
2069
|
+
break;
|
|
2070
|
+
}
|
|
2071
|
+
case "deepagent-mirror":
|
|
2072
|
+
process.stdout.write(JSON.stringify(deepagentMirrorOf(args[0] === undefined ? home : args[0])));
|
|
2073
|
+
break;
|
|
2074
|
+
case "deepagent-apply":
|
|
2075
|
+
process.stdout.write(JSON.stringify(applyDeepagentMirrorOf(args[1] === undefined ? home : args[1], JSON.parse(fs.readFileSync(args[0], "utf8")), args[2] === undefined ? undefined : JSON.parse(fs.readFileSync(args[2], "utf8")))));
|
|
2076
|
+
break;
|
|
2077
|
+
case "failback-check":
|
|
2078
|
+
process.exitCode = failbackCheck(home);
|
|
2079
|
+
break;
|
|
2080
|
+
case "failback-run":
|
|
2081
|
+
handToDecider(CLI_PROVIDER, "the fail-back hook saw a subscription due back").then((handed) => {
|
|
2082
|
+
logSwitch(args[0], `fail-back: ${handed.handed ? handed.why : `the pad decides, so its next pass makes this fail-back — ${handed.why}`}`);
|
|
2083
|
+
return 0;
|
|
2084
|
+
}, (cause) => {
|
|
2085
|
+
logSwitch(args[0], `fail-back FAILED: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
2086
|
+
return 1;
|
|
2087
|
+
}).then((code) => { process.exitCode = code; }, (cause) => {
|
|
2088
|
+
console.error("auto-switch: " + (cause instanceof Error ? cause.message : String(cause)));
|
|
2089
|
+
process.exitCode = 1;
|
|
2090
|
+
});
|
|
2091
|
+
break;
|
|
2092
|
+
case "failover-to-decider":
|
|
2093
|
+
failoverByDecider(readStdin()).then((ran) => {
|
|
2094
|
+
if (!ran.handled) {
|
|
2095
|
+
logSwitch(home, `failover: the pad decides, so the hook makes it -- ${ran.why}`);
|
|
2096
|
+
process.exitCode = 3;
|
|
2097
|
+
return;
|
|
2098
|
+
}
|
|
2099
|
+
process.stderr.write(ran.said);
|
|
2100
|
+
process.exitCode = ran.exit;
|
|
2101
|
+
}, (cause) => {
|
|
2102
|
+
console.error("auto-switch: " + (cause instanceof Error ? cause.message : String(cause)));
|
|
2103
|
+
process.exitCode = 1;
|
|
2104
|
+
});
|
|
2105
|
+
break;
|
|
2106
|
+
case "who-decides":
|
|
2107
|
+
whoDecides(args[0]).then((who) => console.log(JSON.stringify(who)), (cause) => {
|
|
2108
|
+
console.error("auto-switch: " + (cause instanceof Error ? cause.message : String(cause)));
|
|
2109
|
+
process.exitCode = 1;
|
|
2110
|
+
});
|
|
2111
|
+
break;
|
|
2112
|
+
case "applied":
|
|
2113
|
+
markApplied(home, JSON.parse(readStdin()));
|
|
2114
|
+
break;
|
|
2115
|
+
case "expect-applied":
|
|
2116
|
+
expectApplied(home, args[0]);
|
|
2117
|
+
break;
|
|
2118
|
+
case "reapply":
|
|
2119
|
+
reapplySettings(home);
|
|
2120
|
+
break;
|
|
2121
|
+
case "when-applied":
|
|
2122
|
+
whenApplied(home, args[0], Number(args[1])).then((outcome) => {
|
|
2123
|
+
if (outcome === "gone")
|
|
2124
|
+
console.error(`auto-switch: session ${args[0]} ended before it applied the change, so there is no session to wake`);
|
|
2125
|
+
}, (cause) => {
|
|
2126
|
+
console.error("auto-switch: " + cause.message);
|
|
2127
|
+
process.exitCode = 1;
|
|
2128
|
+
});
|
|
2129
|
+
break;
|
|
2130
|
+
case "auto":
|
|
2131
|
+
console.log(JSON.stringify(readAuto(home, args[0])));
|
|
2132
|
+
break;
|
|
2133
|
+
case "byok-fallback":
|
|
2134
|
+
console.log(JSON.stringify(readByokFallback(home, args[0])));
|
|
2135
|
+
break;
|
|
2136
|
+
case "byok-key":
|
|
2137
|
+
console.log(JSON.stringify(readByokKey(home, args[0])));
|
|
2138
|
+
break;
|
|
2139
|
+
case "set-byok-key":
|
|
2140
|
+
writeByokKey(home, args[0], args[1] === undefined ? "" : args[1]);
|
|
2141
|
+
break;
|
|
2142
|
+
case "refused":
|
|
2143
|
+
markRefused(home, args[0], args.slice(1).join(" ") || "a prompt was refused");
|
|
2144
|
+
break;
|
|
2145
|
+
case "clear-refused":
|
|
2146
|
+
clearRefusal(home, args[0]);
|
|
2147
|
+
break;
|
|
2148
|
+
case "refusal":
|
|
2149
|
+
console.log(JSON.stringify(readRefusal(home, args[0]) || null));
|
|
2150
|
+
break;
|
|
2151
|
+
case "set-auto":
|
|
2152
|
+
if (args[1] !== "true" && args[1] !== "false")
|
|
2153
|
+
throw new Error(`set-auto <provider> true|false — ${args[1]} is neither`);
|
|
2154
|
+
writeAuto(home, args[0], args[1] === "true");
|
|
2155
|
+
break;
|
|
2156
|
+
case "set-byok-fallback":
|
|
2157
|
+
if (args[1] !== "true" && args[1] !== "false")
|
|
2158
|
+
throw new Error(`set-byok-fallback <provider> true|false — ${args[1]} is neither`);
|
|
2159
|
+
writeByokFallback(home, args[0], args[1] === "true");
|
|
2160
|
+
break;
|
|
2161
|
+
case "prove-switch": {
|
|
2162
|
+
const proof = proveSwitch(home, args[0]);
|
|
2163
|
+
if (!proof.ok) {
|
|
2164
|
+
// #3339 — A ROUTE WITH NO ROOM SAYS SO. A provider that refused the call for its balance or its
|
|
2165
|
+
// quota is the fact the operator acts on; naming a model id that exists beside it sends him to the
|
|
2166
|
+
// wrong place, so the refusal is reported as the room it is.
|
|
2167
|
+
if (NO_ROOM_REPLY.test(proof.reply)) {
|
|
2168
|
+
throw new Error(`the switch to ${proof.label} has NO ROOM on this route: the provider refused the call — ${proof.reply}`);
|
|
2169
|
+
}
|
|
2170
|
+
throw new Error(`the switch to ${proof.label} FAILED its proof call: account ${proof.account || "(none)"}, model ${proof.model || "(none)"}, the provider replied: ${proof.reply}`);
|
|
2171
|
+
}
|
|
2172
|
+
const who = proof.account || (proof.route === "key" ? "(key route)" : "(OAuth route, no account recorded)");
|
|
2173
|
+
console.log(`switch to ${proof.label} proved by a real call: account ${who}, model ${proof.model}, answered "${proof.reply}"`);
|
|
2174
|
+
break;
|
|
2175
|
+
}
|
|
2176
|
+
default:
|
|
2177
|
+
throw new Error(`unknown auto-switch command: ${op}`);
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
catch (cause) {
|
|
2181
|
+
console.error("auto-switch: " + (cause instanceof Error ? cause.message : String(cause)));
|
|
2182
|
+
process.exitCode = 1;
|
|
2183
|
+
}
|
|
2184
|
+
}
|