sideby 0.35.9 → 0.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build.json +1 -1
- package/dist/src/cli/commands.d.ts +12 -0
- package/dist/src/cli/commands.js +480 -6
- package/dist/src/cli/format.d.ts +12 -1
- package/dist/src/cli/format.js +23 -3
- package/dist/src/cli/json-schemas.js +166 -1
- package/dist/src/cli/main.js +18 -4
- package/dist/src/core/advisor.d.ts +176 -0
- package/dist/src/core/advisor.js +472 -0
- package/dist/src/core/browser-profiles.d.ts +16 -0
- package/dist/src/core/browser-profiles.js +45 -0
- package/dist/src/core/cli-commands.js +25 -1
- package/dist/src/core/config.d.ts +29 -0
- package/dist/src/core/config.js +25 -0
- package/dist/src/core/handoff-select.d.ts +13 -2
- package/dist/src/core/handoff-select.js +6 -2
- package/dist/src/core/launch.d.ts +4 -0
- package/dist/src/core/launch.js +7 -0
- package/dist/src/core/limit-reset.d.ts +198 -0
- package/dist/src/core/limit-reset.js +299 -0
- package/dist/src/core/quota-fetch.d.ts +57 -2
- package/dist/src/core/quota-fetch.js +291 -13
- package/dist/src/core/quota-levels.d.ts +70 -0
- package/dist/src/core/quota-levels.js +80 -0
- package/dist/src/core/quota-store.d.ts +15 -1
- package/dist/src/core/quota-store.js +26 -1
- package/dist/src/core/same-login.d.ts +8 -0
- package/dist/src/core/same-login.js +39 -2
- package/dist/src/core/search-catalog.js +38 -0
- package/dist/src/families/claude/index.js +2 -0
- package/dist/src/families/codex/index.js +3 -1
- package/dist/src/families/codex/quota.d.ts +23 -1
- package/dist/src/families/codex/quota.js +122 -21
- package/dist/src/families/grok/quota-log.d.ts +1 -0
- package/dist/src/menubar/script.js +70 -18
- package/dist/src/menubar/snapshot.d.ts +33 -1
- package/dist/src/menubar/snapshot.js +79 -11
- package/dist/src/menubar/strings.d.ts +16 -0
- package/dist/src/menubar/strings.js +16 -0
- package/dist/src/panel/handler.d.ts +21 -0
- package/dist/src/panel/handler.js +111 -9
- package/dist/src/panel/i18n.d.ts +87 -0
- package/dist/src/panel/i18n.js +174 -0
- package/dist/src/panel/page-logic.d.ts +17 -0
- package/dist/src/panel/page-logic.js +23 -0
- package/dist/src/panel/page-script.js +440 -19
- package/dist/src/panel/page-styles.js +38 -2
- package/dist/src/plugins/loader.d.ts +2 -0
- package/dist/src/plugins/loader.js +27 -0
- package/dist/src/runtime.d.ts +63 -1
- package/dist/src/runtime.js +529 -9
- package/dist/src/types.d.ts +67 -0
- package/package.json +1 -1
- package/schemas/advisor.json +332 -0
- package/schemas/config.json +22 -0
- package/schemas/error.json +4 -0
- package/schemas/menubar-reset.json +93 -0
- package/schemas/menubar-snapshot.json +70 -2
- package/schemas/quota-reset.json +369 -0
- package/schemas/quota.json +30 -0
- package/schemas/update.json +4 -0
- package/skills/sideby/SKILL.md +6 -2
- package/skills/sideby/references/ai-tasks.md +1 -1
- package/skills/sideby/references/panel.md +14 -0
- package/skills/sideby/references/quota.md +27 -0
- package/skills/sideby/references/update.md +1 -1
package/dist/src/runtime.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// The one service layer the CLI and the Panel share. Frozen contract for v0.1 (plan: 审核修订).
|
|
2
2
|
import { aliasesByAccount, discoverAccounts, resolveRef, startArgsOf, } from './core/accounts.js';
|
|
3
|
+
import { advisorStatus, checkAdvisorAccount, setAdvisor, setAdvisorUnlock, undoAdvisor, } from './core/advisor.js';
|
|
3
4
|
import { addConfigAlias, addConfigPickCommand, aiTaskPermissions, aliasAccount, aliasArgs, aliasProblem, aliasRefs, editConfigDisplay, editConfigQuotaCheck, handoffSettings, loadConfig, removeConfigAlias, removeConfigPickCommand, } from './core/config.js';
|
|
4
5
|
import { createAccount } from './core/create.js';
|
|
5
6
|
import { bindDesktopDeps, checkAppData } from './core/desktop-app.js';
|
|
@@ -13,18 +14,19 @@ import { identityOf } from './core/identity.js';
|
|
|
13
14
|
import { inboundFindings } from './core/inbound.js';
|
|
14
15
|
import { mergeDoctorHistory, readDoctorHistory, writeDoctorHistory, } from './core/last-doctor.js';
|
|
15
16
|
import { accountEnv, beforeDashes, brokenOnPath, launchCommand, prepareLaunch, which, } from './core/launch.js';
|
|
17
|
+
import { confirmedSpends, isOutcome, LimitResetError, limitResetFile, loginUnchanged, newLimitResetRecord, outcomeMessage, planExpired, pruneLimitResetRecords, readLimitResetRecord, sameAccounts, scanLimitResetRecords, spent, takeLimitResetLock, unreadableRecordsMessage, unresolvedFor, writeLimitResetRecord, } from './core/limit-reset.js';
|
|
16
18
|
import { loginMarkFile, readLoginMark, writeLoginMark } from './core/login-mark.js';
|
|
17
19
|
import { memoStore } from './core/memo-store.js';
|
|
18
20
|
import { codexNetworkTrustLine, guardLaunch, guardOn, ipChangedLine, networkHookPart, networkOverview, networkSettingsLine, } from './core/network.js';
|
|
19
21
|
import { resolvePaths } from './core/paths.js';
|
|
20
22
|
import { choosePick, suggestPickName } from './core/pick-commands.js';
|
|
21
23
|
import { categoryReader } from './core/project-categories.js';
|
|
22
|
-
import { fetchedQuota, loginProblemOf, quotaCheckOff, shownQuota, } from './core/quota-fetch.js';
|
|
24
|
+
import { FETCH_TIMEOUT_MS, fetchedQuota, loginProblemOf, quotaCheckOff, shownQuota, } from './core/quota-fetch.js';
|
|
23
25
|
import { takeoverLimits } from './core/quota-levels.js';
|
|
24
26
|
import { quotaStoreFile, readQuotaStore } from './core/quota-store.js';
|
|
25
27
|
import { remoteControlGroups, turnRemoteControlOff, turnRemoteControlOn, undoRemoteControlOff, } from './core/remote-control.js';
|
|
26
28
|
import { findResumeRoute } from './core/resume.js';
|
|
27
|
-
import { SAME_LOGIN_FAMILIES, sameLoginGroups, sharedQuota } from './core/same-login.js';
|
|
29
|
+
import { loginComparisonKey, SAME_LOGIN_FAMILIES, sameLoginGroups, sharedQuota, } from './core/same-login.js';
|
|
28
30
|
import { sessionHookArgs } from './core/session-hooks.js';
|
|
29
31
|
import { shareMeaning } from './core/share-meaning.js';
|
|
30
32
|
import { SHELLS, shellInitGeneration, shellInitScript, shellInitStampFile, writeShellInitFile, writeShellInitStamp, } from './core/shell-init.js';
|
|
@@ -32,6 +34,7 @@ import { groupSuggestion, MAX_COMPACT_WINDOW, MIN_COMPACT_WINDOW, } from './core
|
|
|
32
34
|
import { applyTune, planTuneApply, readTuneSettings, settingsFileOf, tuneUndoInfo, undoTune, } from './core/tuning-apply.js';
|
|
33
35
|
import { codexUnattendedTrustLine, UNATTENDED_FAMILIES, unattendedFamilyLine, unattendedHookPart, unattendedSettingsLine, unattendedStatus, } from './core/unattended.js';
|
|
34
36
|
import { UNATTENDED_ENV } from './core/unattended-state.js';
|
|
37
|
+
import { inCi } from './core/update.js';
|
|
35
38
|
import { packageVersion } from './core/version.js';
|
|
36
39
|
import { withClaudeMod } from './families/claude/mod.js';
|
|
37
40
|
import { BUILTIN_PLUGINS } from './families/index.js';
|
|
@@ -226,12 +229,78 @@ export async function createRuntime(opts = {}) {
|
|
|
226
229
|
const peers = (await groupsOf(list)).get(account.ref) ?? [];
|
|
227
230
|
return list.filter((a) => peers.includes(a.ref));
|
|
228
231
|
};
|
|
232
|
+
/** A Same Login's Accounts in the order its row names them: the Display Order, the Main Account, then by name. */
|
|
233
|
+
const loginOrder = (list) => {
|
|
234
|
+
const at = (a) => {
|
|
235
|
+
const i = (config.display?.accounts?.[a.family] ?? []).indexOf(a.name);
|
|
236
|
+
return i < 0 ? Number.POSITIVE_INFINITY : i;
|
|
237
|
+
};
|
|
238
|
+
return [...list].sort((x, y) => at(x) - at(y) ||
|
|
239
|
+
Number(y.isMain) - Number(x.isMain) ||
|
|
240
|
+
x.name.localeCompare(y.name, undefined, { numeric: true }));
|
|
241
|
+
};
|
|
242
|
+
/**
|
|
243
|
+
* Who is asked for each Account's Quota (spec §3.26, ADR-0073): a Same Login is one vendor Quota, so only its first
|
|
244
|
+
* Account in `loginOrder` that is signed in and has no Expired Login asks its Host, and the others show that
|
|
245
|
+
* answer. Ref → the ref asked; an Account left out asks for itself (one with an Expired Login does, so its own
|
|
246
|
+
* answer can tell that the login works again).
|
|
247
|
+
*/
|
|
248
|
+
const askersOf = async (list, groups) => {
|
|
249
|
+
const out = new Map();
|
|
250
|
+
for (const a of list) {
|
|
251
|
+
const peers = groups.get(a.ref);
|
|
252
|
+
if (!peers?.length || out.has(a.ref) || !families.get(a.family)?.fetchQuota)
|
|
253
|
+
continue;
|
|
254
|
+
const members = loginOrder(list.filter((x) => x.ref === a.ref || peers.includes(x.ref)));
|
|
255
|
+
const able = [];
|
|
256
|
+
for (const m of members) {
|
|
257
|
+
const login = await loginOf(m);
|
|
258
|
+
if (login === 'logged-out' || (await loginProblemFor(m, login)))
|
|
259
|
+
continue;
|
|
260
|
+
able.push(m);
|
|
261
|
+
}
|
|
262
|
+
for (const m of able)
|
|
263
|
+
out.set(m.ref, able[0].ref);
|
|
264
|
+
}
|
|
265
|
+
return out;
|
|
266
|
+
};
|
|
267
|
+
/** What decides how early `account` is asked among those due at once (spec §3.26). */
|
|
268
|
+
const askHint = (account, peers = []) => {
|
|
269
|
+
const d = config.display ?? {};
|
|
270
|
+
const names = [account.name, ...peers.map((r) => r.slice(r.indexOf(':') + 1))];
|
|
271
|
+
const any = (list) => names.some((n) => list?.includes(n));
|
|
272
|
+
return {
|
|
273
|
+
pinned: any(d.pinned?.[account.family]),
|
|
274
|
+
hidden: Boolean(d.hiddenFamilies?.includes(account.family)) || any(d.hidden?.[account.family]),
|
|
275
|
+
// A Same Login is one vendor Quota: what its other Accounts keep tells which reset instants had their ask.
|
|
276
|
+
...(peers.length
|
|
277
|
+
? {
|
|
278
|
+
peers: () => Promise.all(peers.map((r) => readQuotaStore(quotaStoreFile(paths.stateDir, account.family, r.slice(r.indexOf(':') + 1))))),
|
|
279
|
+
}
|
|
280
|
+
: {}),
|
|
281
|
+
// An answer asked for before a Limit Reset was used for this Account's login is not kept after it (ADR-0072).
|
|
282
|
+
...(families.get(account.family)?.limitReset?.use
|
|
283
|
+
? {
|
|
284
|
+
changedAt: async () => {
|
|
285
|
+
const at = (await scanLimitResetRecords(paths.stateDir)).records
|
|
286
|
+
.filter((r) => spent(r.state) && r.accounts.includes(account.ref))
|
|
287
|
+
.map((r) => Date.parse(r.finishedAt ?? ''))
|
|
288
|
+
.filter(Number.isFinite);
|
|
289
|
+
return at.length ? Math.max(...at) : undefined;
|
|
290
|
+
},
|
|
291
|
+
}
|
|
292
|
+
: {}),
|
|
293
|
+
};
|
|
294
|
+
};
|
|
229
295
|
/** Every Account's Quota as shown (shared within a Same Login), reading each Account's own cache once. */
|
|
230
296
|
const quotasOf = async (list, mode = 'wait') => {
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
297
|
+
const groups = await groupsOf(list);
|
|
298
|
+
const askers = mode === 'never' ? new Map() : await askersOf(list, groups);
|
|
299
|
+
const own = new Map(await Promise.all(list.map(async (a) => {
|
|
300
|
+
// Another Account of its Same Login asks for the group; this one reads what is kept.
|
|
301
|
+
const asked = (askers.get(a.ref) ?? a.ref) === a.ref;
|
|
302
|
+
return [a.ref, await ownQuota(a, asked ? mode : 'never', askHint(a, groups.get(a.ref)))];
|
|
303
|
+
})));
|
|
235
304
|
return new Map(list.map((a) => [
|
|
236
305
|
a.ref,
|
|
237
306
|
sharedQuota(a.ref, own, groups.get(a.ref) ?? [], families.get(a.family)?.fetchQuota?.localFallbackOnly),
|
|
@@ -244,7 +313,7 @@ export async function createRuntime(opts = {}) {
|
|
|
244
313
|
const { from: _from, fetched: _fetched, fetchError: _error, ...own } = q;
|
|
245
314
|
return own;
|
|
246
315
|
};
|
|
247
|
-
const ownQuota = async (account, mode = 'wait') => {
|
|
316
|
+
const ownQuota = async (account, mode = 'wait', hint = askHint(account)) => {
|
|
248
317
|
if (account.kind === 'api')
|
|
249
318
|
return { status: 'unavailable', reason: 'api-account' };
|
|
250
319
|
const f = familyOf(account.family);
|
|
@@ -265,13 +334,158 @@ export async function createRuntime(opts = {}) {
|
|
|
265
334
|
const off = quotaCheckOff(f.id, config, env);
|
|
266
335
|
// A signed-out Account has nothing to ask about; its kept answer still shows.
|
|
267
336
|
const ask = off || mode === 'never' || (await loginOf(account)) === 'logged-out' ? 'never' : mode;
|
|
268
|
-
|
|
337
|
+
// The local reading's time stands for the last use on this computer: the Hosts write it while a session runs.
|
|
338
|
+
const usedAt = local?.status === 'ok' ? Date.parse(local.observedAt) : Number.NaN;
|
|
339
|
+
const kept = await fetchedQuota(f.fetchQuota, account, readContext(), accountEnv(f, account, env), ask, {
|
|
340
|
+
...hint,
|
|
341
|
+
...(Number.isFinite(usedAt) ? { usedAt } : {}),
|
|
342
|
+
local,
|
|
343
|
+
});
|
|
269
344
|
return shownQuota(local, kept, off, f.fetchQuota.localFallbackOnly);
|
|
270
345
|
}
|
|
271
346
|
finally {
|
|
272
347
|
memos.saveSoon();
|
|
273
348
|
}
|
|
274
349
|
};
|
|
350
|
+
/** The Account asked for `account`'s Quota (`Runtime.quotaAsker`). */
|
|
351
|
+
const askerOf = async (account) => {
|
|
352
|
+
const peers = await peersOf(account);
|
|
353
|
+
if (!peers.length)
|
|
354
|
+
return account;
|
|
355
|
+
const list = [account, ...peers];
|
|
356
|
+
const ref = (await askersOf(list, await groupsOf(list))).get(account.ref);
|
|
357
|
+
return list.find((a) => a.ref === ref) ?? account;
|
|
358
|
+
};
|
|
359
|
+
/**
|
|
360
|
+
* Asks `asker`'s Host for its Quota now, outside `everyMinutes`, and says whether a new answer was kept. With
|
|
361
|
+
* `notBefore` (real ms) an answer another reader took before that moment does not count.
|
|
362
|
+
*/
|
|
363
|
+
const askQuotaNow = async (asker, notBefore) => {
|
|
364
|
+
const file = quotaStoreFile(paths.stateDir, asker.family, asker.name);
|
|
365
|
+
const before = (await readQuotaStore(file))?.attemptedAt;
|
|
366
|
+
await ownQuota(asker, 'force', {
|
|
367
|
+
...askHint(asker),
|
|
368
|
+
...(notBefore !== undefined ? { notBefore } : {}),
|
|
369
|
+
}).catch(() => undefined);
|
|
370
|
+
const after = await readQuotaStore(file);
|
|
371
|
+
// An answer whose ask began before `notBefore` may hold the numbers from before the change, whenever it was kept.
|
|
372
|
+
const seen = notBefore === undefined || Date.parse(after?.startedAt ?? '') >= notBefore;
|
|
373
|
+
return Boolean(after?.quota && !after.error && after.attemptedAt !== before && seen);
|
|
374
|
+
};
|
|
375
|
+
/**
|
|
376
|
+
* Whether `asker`'s kept Quota is from after `sinceMs` (real ms), the moment a Limit Reset was spent (ADR-0072): its
|
|
377
|
+
* ask began at or after that moment, or one made now did. Only a read; false when neither is so, and the numbers
|
|
378
|
+
* kept are then still the ones from before.
|
|
379
|
+
*/
|
|
380
|
+
const quotaSince = async (asker, sinceMs) => {
|
|
381
|
+
const kept = await readQuotaStore(quotaStoreFile(paths.stateDir, asker.family, asker.name));
|
|
382
|
+
// After a failed ask `startedAt` is that ask's, and the numbers are older than it.
|
|
383
|
+
if (kept?.quota && !kept.error && Date.parse(kept.startedAt ?? '') >= sinceMs)
|
|
384
|
+
return true;
|
|
385
|
+
return askQuotaNow(asker, sinceMs);
|
|
386
|
+
};
|
|
387
|
+
/** The Family of an Account whose Host can spend a Limit Reset, or a `LimitResetError` saying what to do. */
|
|
388
|
+
const limitResetFamily = (account) => {
|
|
389
|
+
const f = familyOf(account.family);
|
|
390
|
+
if (account.kind !== 'api' && f.limitReset?.use)
|
|
391
|
+
return f;
|
|
392
|
+
const page = account.kind !== 'api' ? f.limitReset?.vendorPage : undefined;
|
|
393
|
+
throw new LimitResetError(page
|
|
394
|
+
? `${f.title} cannot use a limit reset from the command line; it is used on ${page} (open it with \`sideby quota reset ${account.ref} --open\`)`
|
|
395
|
+
: account.kind === 'api'
|
|
396
|
+
? `${account.ref} is an API account, which has no limit resets; they belong to subscription accounts`
|
|
397
|
+
: `${f.title} has no limit reset sideby can use; check the vendor's own usage page`, { code: 'no-limit-reset' });
|
|
398
|
+
};
|
|
399
|
+
/** Why a spend is refused whoever asks (ADR-0072), or null: in CI, and from a session under Unattended Mode. */
|
|
400
|
+
const limitResetRefused = async (account) => {
|
|
401
|
+
if (inCi(env))
|
|
402
|
+
return { why: 'Using a limit reset is off in CI', code: 'ci' };
|
|
403
|
+
if (env.SIDEBY_ACCOUNT) {
|
|
404
|
+
const st = await unattendedStatus({
|
|
405
|
+
paths,
|
|
406
|
+
families: [...families.keys()],
|
|
407
|
+
env,
|
|
408
|
+
now: now(),
|
|
409
|
+
readOnly: true,
|
|
410
|
+
}).catch(() => null);
|
|
411
|
+
if (st?.on)
|
|
412
|
+
return {
|
|
413
|
+
why: `Unattended Mode is on, and using a limit reset cannot be undone, so it waits for the user: they can run \`sideby quota reset ${account.ref}\` themselves or use the Panel`,
|
|
414
|
+
code: 'unattended',
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
return null;
|
|
418
|
+
};
|
|
419
|
+
/**
|
|
420
|
+
* The comparison key of the login `account` is signed in as right now (`loginComparisonKey`), read from the Host's
|
|
421
|
+
* files each time; undefined when it cannot be told (signed out, an unreadable sign-in, a Family without an
|
|
422
|
+
* Identity). It holds the Login Key and the Identity, so it stays in the Runtime: a Limit Reset record keeps only a
|
|
423
|
+
* salted digest of it, to tell that the login of an operation is unchanged (ADR-0072).
|
|
424
|
+
*/
|
|
425
|
+
const loginKeyNow = async (account) => {
|
|
426
|
+
const f = families.get(account.family);
|
|
427
|
+
if (!f || account.kind !== 'subscription')
|
|
428
|
+
return undefined;
|
|
429
|
+
const [identity, loginKey] = await Promise.all([readIdentity(f, account), readLoginKey(account)]);
|
|
430
|
+
return loginComparisonKey({
|
|
431
|
+
family: account.family,
|
|
432
|
+
kind: account.kind,
|
|
433
|
+
...(identity ? { identity } : {}),
|
|
434
|
+
...(loginKey ? { loginKey } : {}),
|
|
435
|
+
});
|
|
436
|
+
};
|
|
437
|
+
/**
|
|
438
|
+
* Why an unresolved operation is not sent from `asker`: sideby cannot show that `asker` is still signed in as the
|
|
439
|
+
* login the operation was sent for. The operation stays unresolved; only that login may ask about it again.
|
|
440
|
+
* `refs` are the Accounts of `account`'s login now: an Account the operation names beside them may still be
|
|
441
|
+
* signed in as its login, and can ask from there.
|
|
442
|
+
*/
|
|
443
|
+
const otherLogin = (rec, account, asker, known, refs) => {
|
|
444
|
+
const elsewhere = rec.accounts.filter((r) => !refs.includes(r));
|
|
445
|
+
const retry = (ref) => `\`sideby quota reset ${ref} --yes --operation ${rec.operationId}\``;
|
|
446
|
+
return `${known
|
|
447
|
+
? `${asker.ref} is now signed in as a different login than the one operation ${rec.operationId} was sent for`
|
|
448
|
+
: `sideby cannot read which login ${asker.ref} is signed in as now, so it cannot tell that it is the one operation ${rec.operationId} was sent for`}, and sideby will not retry that operation from this account: it would use a limit reset of the wrong login. Nothing was sent. Whether that earlier attempt used one is still unknown. ${elsewhere.length
|
|
449
|
+
? `If ${elsewhere.join(' or ')} is still signed in as the original login, run ${retry(elsewhere[0])}. Otherwise sign`
|
|
450
|
+
: 'Sign'} in as the original login (\`sideby login ${asker.ref}\`), then run ${retry(account.ref)}; if you no longer use that login, check its count on the vendor's own usage page, then move ${limitResetFile(paths.stateDir, rec.operationId)} away`;
|
|
451
|
+
};
|
|
452
|
+
/** Stops a spend while an operation file is there but cannot be read: it may be an unresolved one (ADR-0072). */
|
|
453
|
+
const readableRecords = async () => {
|
|
454
|
+
const scan = await scanLimitResetRecords(paths.stateDir);
|
|
455
|
+
if (scan.unreadable.length)
|
|
456
|
+
throw new LimitResetError(`${unreadableRecordsMessage(paths.stateDir, scan.unreadable)}. Nothing was sent`, { code: 'records-unreadable' });
|
|
457
|
+
return scan.records;
|
|
458
|
+
};
|
|
459
|
+
/** `account` and the other Accounts of its Same Login, with their refs sorted. */
|
|
460
|
+
const loginGroup = async (account) => {
|
|
461
|
+
const peers = await peersOf(account);
|
|
462
|
+
return { peers, group: [account, ...peers], refs: [account.ref, ...peers.map((a) => a.ref)].sort() };
|
|
463
|
+
};
|
|
464
|
+
/** One request to spend a Limit Reset, ended after `FETCH_TIMEOUT_MS` whatever the Family does. */
|
|
465
|
+
const sendLimitReset = async (f, asker, idempotencyKey) => {
|
|
466
|
+
const ac = new AbortController();
|
|
467
|
+
const timer = setTimeout(() => ac.abort(), opts.limitReset?.timeoutMs ?? FETCH_TIMEOUT_MS);
|
|
468
|
+
const aborted = new Promise((_, reject) => {
|
|
469
|
+
ac.signal.addEventListener('abort', () => reject(new Error('no answer in time')), { once: true });
|
|
470
|
+
});
|
|
471
|
+
aborted.catch(() => { });
|
|
472
|
+
try {
|
|
473
|
+
return await Promise.race([
|
|
474
|
+
f.limitReset.use(asker, {
|
|
475
|
+
...readContext(),
|
|
476
|
+
signal: ac.signal,
|
|
477
|
+
hostEnv: accountEnv(f, asker, env),
|
|
478
|
+
idempotencyKey,
|
|
479
|
+
}),
|
|
480
|
+
aborted,
|
|
481
|
+
]);
|
|
482
|
+
}
|
|
483
|
+
finally {
|
|
484
|
+
clearTimeout(timer);
|
|
485
|
+
if (!ac.signal.aborted)
|
|
486
|
+
ac.abort();
|
|
487
|
+
}
|
|
488
|
+
};
|
|
275
489
|
const loginOf = async (a) => {
|
|
276
490
|
if (a.kind === 'api')
|
|
277
491
|
return 'not-needed';
|
|
@@ -345,6 +559,19 @@ export async function createRuntime(opts = {}) {
|
|
|
345
559
|
stateDir: paths.stateDir,
|
|
346
560
|
env,
|
|
347
561
|
});
|
|
562
|
+
/** The two config switches the Advisor reads and may change (spec §3.41). */
|
|
563
|
+
const advisorConfig = () => ({
|
|
564
|
+
unlock: config.advisor?.unlock === true,
|
|
565
|
+
apiBetasOff: config.claude?.apiBetasOff === true,
|
|
566
|
+
});
|
|
567
|
+
/** After an Advisor change wrote the config file, this Runtime reads those two switches again. */
|
|
568
|
+
const reloadAdvisorConfig = async () => {
|
|
569
|
+
const fresh = await loadConfig(paths.configFile).catch(() => null);
|
|
570
|
+
if (fresh) {
|
|
571
|
+
config.advisor = fresh.advisor;
|
|
572
|
+
config.claude = fresh.claude;
|
|
573
|
+
}
|
|
574
|
+
};
|
|
348
575
|
/** The config value of the alias `name`, from own keys only (`constructor` is not an alias unless configured). */
|
|
349
576
|
const ownAlias = (name) => config.aliases && Object.hasOwn(config.aliases, name) ? config.aliases[name] : undefined;
|
|
350
577
|
/** The config value of `ref` when it names an alias (no colon), as `resolveRef` reads it. */
|
|
@@ -774,11 +1001,17 @@ export async function createRuntime(opts = {}) {
|
|
|
774
1001
|
config.accounts = fresh.accounts;
|
|
775
1002
|
config.unattended = fresh.unattended;
|
|
776
1003
|
config.ask = fresh.ask;
|
|
1004
|
+
config.advisor = fresh.advisor;
|
|
1005
|
+
config.claude = fresh.claude;
|
|
777
1006
|
}
|
|
778
1007
|
const all = await accounts();
|
|
779
1008
|
const inputs = launchInputs(ref, all, userArgs, command);
|
|
780
1009
|
const p = await prepareLaunch({
|
|
781
1010
|
...inputs,
|
|
1011
|
+
// Claude Code's advisor (spec §3.41, ADR-0074): unlocked in Claude subscription sessions while config says so.
|
|
1012
|
+
...(config.advisor?.unlock === true ? { advisorUnlock: true } : {}),
|
|
1013
|
+
// Claude API Accounts get the variable that turns experimental betas off, moved here from a shared settings file.
|
|
1014
|
+
...(config.claude?.apiBetasOff === true ? { apiBetasOff: true } : {}),
|
|
782
1015
|
// Config `ask.permissions: account` (ADR-0070): the AI Task keeps the Account's own arguments, as `run` does.
|
|
783
1016
|
...(opts.aiTask && aiTaskPermissions(config) === 'checked' ? { aiTask: true } : {}),
|
|
784
1017
|
label: launchLabel(ref, inputs.account, all),
|
|
@@ -883,7 +1116,256 @@ export async function createRuntime(opts = {}) {
|
|
|
883
1116
|
},
|
|
884
1117
|
async refreshQuota(only) {
|
|
885
1118
|
const list = (only ?? (await accounts())).filter((a) => a.kind === 'subscription' && families.get(a.family)?.fetchQuota);
|
|
886
|
-
|
|
1119
|
+
// A Same Login among them is asked once (spec §3.26); an Account named alone is asked itself.
|
|
1120
|
+
const groups = await groupsOf(list);
|
|
1121
|
+
const askers = await askersOf(list, groups);
|
|
1122
|
+
await Promise.all(list
|
|
1123
|
+
.filter((a) => (askers.get(a.ref) ?? a.ref) === a.ref)
|
|
1124
|
+
.map((a) => ownQuota(a, 'force', askHint(a, groups.get(a.ref)))));
|
|
1125
|
+
},
|
|
1126
|
+
quotaAsker: (account) => askerOf(account),
|
|
1127
|
+
limitResetKind(account) {
|
|
1128
|
+
const r = account.kind === 'api' ? undefined : families.get(account.family)?.limitReset;
|
|
1129
|
+
if (r?.use)
|
|
1130
|
+
return { kind: 'use' };
|
|
1131
|
+
return r?.vendorPage ? { kind: 'page', url: r.vendorPage } : null;
|
|
1132
|
+
},
|
|
1133
|
+
async limitResetPlan(account) {
|
|
1134
|
+
const f = limitResetFamily(account);
|
|
1135
|
+
const { peers, group, refs } = await loginGroup(account);
|
|
1136
|
+
const asker = await askerOf(account);
|
|
1137
|
+
await pruneLimitResetRecords(paths.stateDir, now()).catch(() => { });
|
|
1138
|
+
// A file that is there but cannot be read may be an unresolved spend: the plan still shows, and says so.
|
|
1139
|
+
const scan = await scanLimitResetRecords(paths.stateDir);
|
|
1140
|
+
const refused = await limitResetRefused(account);
|
|
1141
|
+
const off = quotaCheckOff(f.id, config, env);
|
|
1142
|
+
const login = await loginOf(asker);
|
|
1143
|
+
const signedOut = login === 'logged-out' || Boolean(await loginProblemFor(asker, login));
|
|
1144
|
+
// The login is read before and after the numbers: a plan is for one login, and the record keeps its digest.
|
|
1145
|
+
const keyBefore = await loginKeyNow(asker);
|
|
1146
|
+
// The count and the Quota, read from the Host now: a plan is never made of old numbers.
|
|
1147
|
+
const fresh = !off && !signedOut && !refused ? await askQuotaNow(asker) : false;
|
|
1148
|
+
const quota = (await quotasOf(group, 'never')).get(account.ref);
|
|
1149
|
+
const stock = quota.status === 'ok' ? quota.limitResets : undefined;
|
|
1150
|
+
const why = quota.status === 'ok' ? quota.fetchError : (quota.detail ?? quota.reason);
|
|
1151
|
+
const key = await loginKeyNow(asker);
|
|
1152
|
+
// An attempt of this login with no final answer, also one made before this Account signed in as the login: no
|
|
1153
|
+
// new operation, and so no new key, is made beside it.
|
|
1154
|
+
const open = unresolvedFor(scan.records, refs, key);
|
|
1155
|
+
const blocked = refused
|
|
1156
|
+
? refused.why
|
|
1157
|
+
: signedOut
|
|
1158
|
+
? `${asker.ref} is signed out; run \`sideby login ${asker.ref}\` first`
|
|
1159
|
+
: scan.unreadable.length
|
|
1160
|
+
? unreadableRecordsMessage(paths.stateDir, scan.unreadable)
|
|
1161
|
+
: open && !loginUnchanged(open, key)
|
|
1162
|
+
? otherLogin(open, account, asker, key !== undefined, refs)
|
|
1163
|
+
: open
|
|
1164
|
+
? undefined
|
|
1165
|
+
: !key
|
|
1166
|
+
? f.identity
|
|
1167
|
+
? `sideby cannot read which login ${asker.ref} is signed in as, so it cannot make sure a limit reset goes to the login you confirm it for; sign in again with \`sideby login ${asker.ref}\`, then try again`
|
|
1168
|
+
: `${f.title} does not tell sideby which login an account is signed in as, so sideby cannot make sure a limit reset goes to the login you confirm it for; use it in ${f.title} itself`
|
|
1169
|
+
: key !== keyBefore
|
|
1170
|
+
? `${asker.ref} signed in as another login while this plan was read; run \`sideby quota reset ${account.ref}\` again`
|
|
1171
|
+
: off
|
|
1172
|
+
? `${off}, so sideby cannot read how many limit resets ${account.ref} holds`
|
|
1173
|
+
: !fresh
|
|
1174
|
+
? `sideby could not read ${account.ref}'s quota just now${why ? ` (${why})` : ''}, and it does not use a limit reset on old numbers; try again in a moment`
|
|
1175
|
+
: !stock
|
|
1176
|
+
? `${f.title} did not say whether ${account.ref} holds a limit reset; update ${f.title}, then try again`
|
|
1177
|
+
: stock.available < 1
|
|
1178
|
+
? `${account.ref} holds no limit reset`
|
|
1179
|
+
: undefined;
|
|
1180
|
+
let operationId = open?.operationId;
|
|
1181
|
+
if (!blocked && !operationId && key) {
|
|
1182
|
+
const record = newLimitResetRecord(refs, now(), key);
|
|
1183
|
+
await writeLimitResetRecord(paths.stateDir, record);
|
|
1184
|
+
operationId = record.operationId;
|
|
1185
|
+
}
|
|
1186
|
+
const all = peers.length
|
|
1187
|
+
? ` and every account of the same login (${peers.map((a) => a.ref).join(', ')})`
|
|
1188
|
+
: '';
|
|
1189
|
+
return {
|
|
1190
|
+
account: account.ref,
|
|
1191
|
+
via: asker.ref,
|
|
1192
|
+
sameLogin: peers.map((a) => a.ref),
|
|
1193
|
+
...(!blocked && operationId ? { operationId } : {}),
|
|
1194
|
+
...(open ? { unresolved: true } : {}),
|
|
1195
|
+
quota,
|
|
1196
|
+
...(stock ? { limitResets: stock } : {}),
|
|
1197
|
+
...(stock && stock.available > 0 ? { expectedAfter: stock.available - 1 } : {}),
|
|
1198
|
+
canUse: !blocked,
|
|
1199
|
+
...(blocked ? { blocked } : {}),
|
|
1200
|
+
message: open
|
|
1201
|
+
? `An earlier attempt to use a limit reset for ${account.ref} got no final answer. Confirming asks ${f.title} again with the same request: it uses nothing more if that attempt already went through, and it cannot be undone if it did not.`
|
|
1202
|
+
: `Using a limit reset restores quota for ${account.ref}${all} before its windows reset by themselves. It cannot be undone, and ${f.title} does not say beforehand which windows it restores.`,
|
|
1203
|
+
};
|
|
1204
|
+
},
|
|
1205
|
+
async limitResetUse(account, operationId) {
|
|
1206
|
+
const f = limitResetFamily(account);
|
|
1207
|
+
const refused = await limitResetRefused(account);
|
|
1208
|
+
if (refused)
|
|
1209
|
+
throw new LimitResetError(`${refused.why}. Nothing was sent.`, { code: refused.code });
|
|
1210
|
+
// Before anything is made or changed under the folder: every operation file in it must be readable.
|
|
1211
|
+
const before = await readableRecords();
|
|
1212
|
+
const { peers, group, refs } = await loginGroup(account);
|
|
1213
|
+
const again = `sideby quota reset ${account.ref}`;
|
|
1214
|
+
/**
|
|
1215
|
+
* Refuses unless the login that would send `rec` now is the one it was made for (ADR-0072). Equal Account refs
|
|
1216
|
+
* do not show that: an Account can sign in as another login and keep its name. A confirmed plan is out of date
|
|
1217
|
+
* then; an unresolved operation stays unresolved, for its own login to ask again.
|
|
1218
|
+
*/
|
|
1219
|
+
const sameLoginOrThrow = async (rec, asker) => {
|
|
1220
|
+
const key = await loginKeyNow(asker);
|
|
1221
|
+
if (loginUnchanged(rec, key))
|
|
1222
|
+
return;
|
|
1223
|
+
if (rec.state === 'pending')
|
|
1224
|
+
throw new LimitResetError(otherLogin(rec, account, asker, key !== undefined, refs), {
|
|
1225
|
+
code: 'login-changed',
|
|
1226
|
+
operationId: rec.operationId,
|
|
1227
|
+
});
|
|
1228
|
+
throw new LimitResetError(`${key === undefined ? `sideby cannot read which login ${asker.ref} is signed in as now` : `${asker.ref} is signed in as a different login than when this plan was shown`}, so nothing was sent; run \`${again}\` to see a new plan, and confirm that one`, { code: 'plan-outdated' });
|
|
1229
|
+
};
|
|
1230
|
+
// When the plan is confirmed: the operation this confirmation would send, checked before waiting for the lock.
|
|
1231
|
+
const firstAsker = await askerOf(account);
|
|
1232
|
+
const first = unresolvedFor(before, refs, await loginKeyNow(firstAsker)) ??
|
|
1233
|
+
before.find((r) => r.operationId === operationId && r.state === 'planned' && sameAccounts(r, refs));
|
|
1234
|
+
if (first)
|
|
1235
|
+
await sameLoginOrThrow(first, firstAsker);
|
|
1236
|
+
// An unresolved operation is also locked for the Accounts it names, so everyone who may resume it takes turns.
|
|
1237
|
+
const release = await takeLimitResetLock(paths.stateDir, [...refs, ...(first?.state === 'pending' ? first.accounts : [])], FETCH_TIMEOUT_MS + 15_000);
|
|
1238
|
+
if (!release)
|
|
1239
|
+
throw new LimitResetError(`another sideby is using a limit reset for this login right now, so nothing was sent; wait a moment, then run \`sideby quota reset ${account.ref}\` again`, { code: 'busy' });
|
|
1240
|
+
const save = (r) => writeLimitResetRecord(paths.stateDir, r);
|
|
1241
|
+
// Notes on a spent operation that the Quota read after it is kept. False when the record cannot be written:
|
|
1242
|
+
// the spend stands either way, and only Auto Handoff's early return to the Account (ADR-0060) waits.
|
|
1243
|
+
const noteQuotaRead = (r) => save({ ...r, quotaReadAt: now().toISOString() }).then(() => true, () => false);
|
|
1244
|
+
const shown = async () => (await quotasOf(group, 'never')).get(account.ref);
|
|
1245
|
+
const base = { account: account.ref, sameLogin: peers.map((a) => a.ref) };
|
|
1246
|
+
const oldNumbers = ' The quota could not be read yet, so the numbers on show are still the old ones; they update with the next check.';
|
|
1247
|
+
try {
|
|
1248
|
+
const records = await readableRecords();
|
|
1249
|
+
const asker = await askerOf(account);
|
|
1250
|
+
// The unresolved operation of this login goes first, with its own key, whichever Accounts it names: an Account
|
|
1251
|
+
// that left the login or joined it since never ends it, because its request may already have used one.
|
|
1252
|
+
let rec = unresolvedFor(records, refs, await loginKeyNow(asker));
|
|
1253
|
+
const resumed = Boolean(rec);
|
|
1254
|
+
if (rec)
|
|
1255
|
+
await sameLoginOrThrow(rec, asker);
|
|
1256
|
+
if (!rec) {
|
|
1257
|
+
const given = await readLimitResetRecord(paths.stateDir, operationId);
|
|
1258
|
+
if (!given?.accounts.includes(account.ref))
|
|
1259
|
+
throw new LimitResetError(`there is no plan ${operationId} for ${account.ref} (a plan is kept for a day); run \`${again}\` for a new one. Nothing was sent`, { code: 'unknown-operation' });
|
|
1260
|
+
if (isOutcome(given.state)) {
|
|
1261
|
+
// Already answered: say it again, and send no second request. After a spend the numbers are shown as
|
|
1262
|
+
// current only when the read kept for the Account asked now began after it: the read that followed may
|
|
1263
|
+
// have failed, or been kept for an Account that has left this login since, and what is kept here is then
|
|
1264
|
+
// from before. `quotaReadAt` does not prove it, so it is looked at each time; a missing read is made now
|
|
1265
|
+
// (a read, never a spend), and noted once it is kept.
|
|
1266
|
+
let current = !spent(given.state);
|
|
1267
|
+
if (!current) {
|
|
1268
|
+
const finished = Date.parse(given.finishedAt ?? '');
|
|
1269
|
+
current = await quotaSince(asker, Number.isFinite(finished) ? finished : Date.now());
|
|
1270
|
+
if (current && !given.quotaReadAt)
|
|
1271
|
+
await noteQuotaRead(given);
|
|
1272
|
+
}
|
|
1273
|
+
return {
|
|
1274
|
+
...base,
|
|
1275
|
+
via: asker.ref,
|
|
1276
|
+
operationId: given.operationId,
|
|
1277
|
+
outcome: given.state,
|
|
1278
|
+
replayed: true,
|
|
1279
|
+
...(current ? { quota: await shown() } : { quotaPending: true }),
|
|
1280
|
+
message: `${outcomeMessage(given.state, account.ref)}${current ? '' : oldNumbers}`,
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
if (given.state !== 'planned')
|
|
1284
|
+
throw new LimitResetError(`operation ${given.operationId} ended without an answer from ${f.title}${given.state === 'not-sent' ? ' (nothing was sent, so nothing was spent)' : ''}; run \`${again}\` for a new plan`, { code: 'operation-ended', operationId: given.operationId });
|
|
1285
|
+
if (!sameAccounts(given, refs))
|
|
1286
|
+
throw new LimitResetError(`the accounts signed in as this login changed since this plan was shown, so nothing was sent; run \`${again}\` to see the plan as it is now`, { code: 'plan-outdated' });
|
|
1287
|
+
// Its numbers are a day old, and pruning may remove it: it is refused here, under the lock pruning takes.
|
|
1288
|
+
if (planExpired(given, now()))
|
|
1289
|
+
throw new LimitResetError(`this plan was shown more than a day ago, so its numbers are out of date and nothing was sent; run \`${again}\` to see them now`, { code: 'plan-outdated' });
|
|
1290
|
+
const later = records.find((r) => spent(r.state) &&
|
|
1291
|
+
r.accounts.some((a) => refs.includes(a)) &&
|
|
1292
|
+
Date.parse(r.finishedAt ?? '') >= Date.parse(given.createdAt));
|
|
1293
|
+
if (later)
|
|
1294
|
+
throw new LimitResetError(`a limit reset was already used for this login after this plan was shown (operation ${later.operationId}), so its numbers are out of date and nothing was sent; run \`${again}\` to see them now`, { code: 'plan-outdated', operationId: later.operationId });
|
|
1295
|
+
rec = given;
|
|
1296
|
+
}
|
|
1297
|
+
// Under the lock, right before the request: the login is read once more, for a plan and for a retry alike.
|
|
1298
|
+
await sameLoginOrThrow(rec, asker);
|
|
1299
|
+
// The key is on disk before the request leaves, so a retry from any process sends the same one. While it is
|
|
1300
|
+
// unresolved the record names every Account it was made for or resumed from, so each of them finds it.
|
|
1301
|
+
rec = {
|
|
1302
|
+
...rec,
|
|
1303
|
+
accounts: [...new Set([...rec.accounts, ...refs])].sort(),
|
|
1304
|
+
state: 'pending',
|
|
1305
|
+
attempts: [...rec.attempts, now().toISOString()],
|
|
1306
|
+
};
|
|
1307
|
+
const file = limitResetFile(paths.stateDir, rec.operationId);
|
|
1308
|
+
const retryWith = `\`${again} --yes --operation ${rec.operationId}\` (or "Check again" in the Panel)`;
|
|
1309
|
+
const retry = `Check again with ${retryWith}: it repeats the same request, which cannot use a second one`;
|
|
1310
|
+
try {
|
|
1311
|
+
await save(rec);
|
|
1312
|
+
}
|
|
1313
|
+
catch (err) {
|
|
1314
|
+
// Not on disk, not sent. A plan stays a plan; an earlier attempt stays as unanswered as it was.
|
|
1315
|
+
const why = `sideby could not write ${file} (${err?.message || String(err)}), and it sends nothing before the request is on disk`;
|
|
1316
|
+
throw resumed
|
|
1317
|
+
? new LimitResetError(`${why}. Nothing was sent now, and sideby still cannot tell whether the earlier attempt used a limit reset for ${account.ref}. Once that file can be written: ${retry}`, { code: 'outcome-unknown', operationId: rec.operationId })
|
|
1318
|
+
: new LimitResetError(`${why}. Nothing was sent, so nothing was spent. Once that file can be written, run \`${again}\` again`, { code: 'not-sent', operationId: rec.operationId });
|
|
1319
|
+
}
|
|
1320
|
+
let outcome;
|
|
1321
|
+
try {
|
|
1322
|
+
outcome = await sendLimitReset(f, asker, rec.idempotencyKey);
|
|
1323
|
+
if (!isOutcome(outcome))
|
|
1324
|
+
throw new Error(`${f.title} gave an answer sideby does not know`);
|
|
1325
|
+
}
|
|
1326
|
+
catch (err) {
|
|
1327
|
+
const why = err?.message || String(err);
|
|
1328
|
+
// Only a first attempt that never left this computer is known to have spent nothing.
|
|
1329
|
+
if (err?.sent === false && rec.attempts.length === 1) {
|
|
1330
|
+
// Left as `pending` when this cannot be saved: a later confirmation then sends the same key, which is safe.
|
|
1331
|
+
await save({ ...rec, state: 'not-sent', finishedAt: now().toISOString() }).catch(() => { });
|
|
1332
|
+
throw new LimitResetError(`${why}. Nothing was sent, so nothing was spent`, {
|
|
1333
|
+
code: 'not-sent',
|
|
1334
|
+
operationId: rec.operationId,
|
|
1335
|
+
});
|
|
1336
|
+
}
|
|
1337
|
+
throw new LimitResetError(`${why}, so sideby cannot tell whether a limit reset was used for ${account.ref}. ${retry}`, { code: 'outcome-unknown', operationId: rec.operationId });
|
|
1338
|
+
}
|
|
1339
|
+
// The Host answered: the outcome is for the Accounts of this login as they are now.
|
|
1340
|
+
rec = { ...rec, accounts: refs, state: outcome, finishedAt: now().toISOString() };
|
|
1341
|
+
try {
|
|
1342
|
+
await save(rec);
|
|
1343
|
+
}
|
|
1344
|
+
catch (err) {
|
|
1345
|
+
// The answer is known but not on disk, where the operation still reads as unanswered. Say what the Host
|
|
1346
|
+
// answered, and that only its own key may ask again: the retry cannot use a second one.
|
|
1347
|
+
if (spent(outcome))
|
|
1348
|
+
await askQuotaNow(asker, Date.now());
|
|
1349
|
+
throw new LimitResetError(`${outcomeMessage(outcome, account.ref)} That is what ${f.title} answered, but sideby could not write ${file} to record it (${err?.message || String(err)}), so it still lists this operation as unanswered. Once that file can be written, check again with ${retryWith}: it repeats the same request, ${spent(outcome) ? 'which cannot use a second one' : 'so it uses at most the one limit reset you confirmed'}`, { code: 'outcome-not-saved', operationId: rec.operationId });
|
|
1350
|
+
}
|
|
1351
|
+
// The answer holds no Quota: ask at once, outside `everyMinutes`, and show what the Host says. The count and
|
|
1352
|
+
// the bars are never changed by sideby itself.
|
|
1353
|
+
const read = await askQuotaNow(asker, Date.now());
|
|
1354
|
+
// A note that cannot be saved does not undo the spend: it is reported as it went.
|
|
1355
|
+
const noted = !read || !spent(outcome) || (await noteQuotaRead(rec));
|
|
1356
|
+
return {
|
|
1357
|
+
...base,
|
|
1358
|
+
via: asker.ref,
|
|
1359
|
+
operationId: rec.operationId,
|
|
1360
|
+
outcome,
|
|
1361
|
+
...(resumed ? { resumed: true } : {}),
|
|
1362
|
+
...(read ? { quota: await shown() } : spent(outcome) ? { quotaPending: true } : {}),
|
|
1363
|
+
message: `${outcomeMessage(outcome, account.ref)}${spent(outcome) && !read ? oldNumbers : ''}${noted ? '' : ` sideby could not note in ${file} that the quota was read afterwards, so Auto Handoff comes back to this account at its window's own reset time, not before.`}`,
|
|
1364
|
+
};
|
|
1365
|
+
}
|
|
1366
|
+
finally {
|
|
1367
|
+
await release();
|
|
1368
|
+
}
|
|
887
1369
|
},
|
|
888
1370
|
quotaChecks() {
|
|
889
1371
|
const ci = quotaCheckOff('', {}, env);
|
|
@@ -1014,6 +1496,32 @@ export async function createRuntime(opts = {}) {
|
|
|
1014
1496
|
async remoteControlUndo() {
|
|
1015
1497
|
return undoRemoteControlOff(await accounts(), readContext());
|
|
1016
1498
|
},
|
|
1499
|
+
async advisor() {
|
|
1500
|
+
return advisorStatus(await accounts(), readContext(), advisorConfig());
|
|
1501
|
+
},
|
|
1502
|
+
async advisorSet(to, opts = {}) {
|
|
1503
|
+
const account = opts.account ? checkAdvisorAccount(await rt.resolve(opts.account)).ref : undefined;
|
|
1504
|
+
const r = await setAdvisor(await accounts(), readContext(), to, {
|
|
1505
|
+
configFile: paths.configFile,
|
|
1506
|
+
...advisorConfig(),
|
|
1507
|
+
...(account ? { account } : {}),
|
|
1508
|
+
});
|
|
1509
|
+
await reloadAdvisorConfig();
|
|
1510
|
+
return r;
|
|
1511
|
+
},
|
|
1512
|
+
async advisorUndo() {
|
|
1513
|
+
const r = await undoAdvisor(await accounts(), readContext(), {
|
|
1514
|
+
configFile: paths.configFile,
|
|
1515
|
+
...advisorConfig(),
|
|
1516
|
+
});
|
|
1517
|
+
await reloadAdvisorConfig();
|
|
1518
|
+
return r;
|
|
1519
|
+
},
|
|
1520
|
+
async advisorUnlock(on) {
|
|
1521
|
+
const r = await setAdvisorUnlock(paths.configFile, on);
|
|
1522
|
+
await reloadAdvisorConfig();
|
|
1523
|
+
return r;
|
|
1524
|
+
},
|
|
1017
1525
|
async tuneUndoInfo(account) {
|
|
1018
1526
|
return account.family === 'claude' ? tuneUndoInfo(account, readContext()) : null;
|
|
1019
1527
|
},
|
|
@@ -1073,6 +1581,18 @@ export async function createRuntime(opts = {}) {
|
|
|
1073
1581
|
},
|
|
1074
1582
|
handoffSettings: () => handoffSettings(config),
|
|
1075
1583
|
async handoffDecision(origin, used, opts = {}) {
|
|
1584
|
+
// An Account left for a full window comes back early when a Limit Reset the user confirmed was spent for it
|
|
1585
|
+
// since, and the Quota read after that spend is kept (ADR-0072, amending ADR-0060); `selectNext` then takes
|
|
1586
|
+
// it only when that Quota shows it under the Takeover Limit.
|
|
1587
|
+
const spends = await confirmedSpends(paths.stateDir).catch(() => []);
|
|
1588
|
+
if (spends.length)
|
|
1589
|
+
used = used.map((u) => {
|
|
1590
|
+
if (typeof u === 'string' || !u.window)
|
|
1591
|
+
return u;
|
|
1592
|
+
const since = Date.parse(u.startedAt ?? '');
|
|
1593
|
+
const hit = spends.some((sp) => sp.accounts.includes(u.ref) && (!Number.isFinite(since) || Date.parse(sp.quotaReadAt) > since));
|
|
1594
|
+
return hit ? { ...u, resetUsed: true } : u;
|
|
1595
|
+
});
|
|
1076
1596
|
const all = await accounts();
|
|
1077
1597
|
const [quotas, groups] = await Promise.all([quotasOf(all), groupsOf(all)]);
|
|
1078
1598
|
const candidates = await Promise.all(all.map(async (a) => {
|