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.
Files changed (66) hide show
  1. package/dist/build.json +1 -1
  2. package/dist/src/cli/commands.d.ts +12 -0
  3. package/dist/src/cli/commands.js +480 -6
  4. package/dist/src/cli/format.d.ts +12 -1
  5. package/dist/src/cli/format.js +23 -3
  6. package/dist/src/cli/json-schemas.js +166 -1
  7. package/dist/src/cli/main.js +18 -4
  8. package/dist/src/core/advisor.d.ts +176 -0
  9. package/dist/src/core/advisor.js +472 -0
  10. package/dist/src/core/browser-profiles.d.ts +16 -0
  11. package/dist/src/core/browser-profiles.js +45 -0
  12. package/dist/src/core/cli-commands.js +25 -1
  13. package/dist/src/core/config.d.ts +29 -0
  14. package/dist/src/core/config.js +25 -0
  15. package/dist/src/core/handoff-select.d.ts +13 -2
  16. package/dist/src/core/handoff-select.js +6 -2
  17. package/dist/src/core/launch.d.ts +4 -0
  18. package/dist/src/core/launch.js +7 -0
  19. package/dist/src/core/limit-reset.d.ts +198 -0
  20. package/dist/src/core/limit-reset.js +299 -0
  21. package/dist/src/core/quota-fetch.d.ts +57 -2
  22. package/dist/src/core/quota-fetch.js +291 -13
  23. package/dist/src/core/quota-levels.d.ts +70 -0
  24. package/dist/src/core/quota-levels.js +80 -0
  25. package/dist/src/core/quota-store.d.ts +15 -1
  26. package/dist/src/core/quota-store.js +26 -1
  27. package/dist/src/core/same-login.d.ts +8 -0
  28. package/dist/src/core/same-login.js +39 -2
  29. package/dist/src/core/search-catalog.js +38 -0
  30. package/dist/src/families/claude/index.js +2 -0
  31. package/dist/src/families/codex/index.js +3 -1
  32. package/dist/src/families/codex/quota.d.ts +23 -1
  33. package/dist/src/families/codex/quota.js +122 -21
  34. package/dist/src/families/grok/quota-log.d.ts +1 -0
  35. package/dist/src/menubar/script.js +70 -18
  36. package/dist/src/menubar/snapshot.d.ts +33 -1
  37. package/dist/src/menubar/snapshot.js +79 -11
  38. package/dist/src/menubar/strings.d.ts +16 -0
  39. package/dist/src/menubar/strings.js +16 -0
  40. package/dist/src/panel/handler.d.ts +21 -0
  41. package/dist/src/panel/handler.js +111 -9
  42. package/dist/src/panel/i18n.d.ts +87 -0
  43. package/dist/src/panel/i18n.js +174 -0
  44. package/dist/src/panel/page-logic.d.ts +17 -0
  45. package/dist/src/panel/page-logic.js +23 -0
  46. package/dist/src/panel/page-script.js +440 -19
  47. package/dist/src/panel/page-styles.js +38 -2
  48. package/dist/src/plugins/loader.d.ts +2 -0
  49. package/dist/src/plugins/loader.js +27 -0
  50. package/dist/src/runtime.d.ts +63 -1
  51. package/dist/src/runtime.js +529 -9
  52. package/dist/src/types.d.ts +67 -0
  53. package/package.json +1 -1
  54. package/schemas/advisor.json +332 -0
  55. package/schemas/config.json +22 -0
  56. package/schemas/error.json +4 -0
  57. package/schemas/menubar-reset.json +93 -0
  58. package/schemas/menubar-snapshot.json +70 -2
  59. package/schemas/quota-reset.json +369 -0
  60. package/schemas/quota.json +30 -0
  61. package/schemas/update.json +4 -0
  62. package/skills/sideby/SKILL.md +6 -2
  63. package/skills/sideby/references/ai-tasks.md +1 -1
  64. package/skills/sideby/references/panel.md +14 -0
  65. package/skills/sideby/references/quota.md +27 -0
  66. package/skills/sideby/references/update.md +1 -1
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"id":"20261110T040509-f565d3"}
1
+ {"id":"20261113T031219-d21513"}
@@ -80,6 +80,11 @@ export declare function cmdDoctor(a: ParsedArgs, io: Io): Promise<number>;
80
80
  * claude.ai by themselves, and turning that on or off for every Account (a preview with exit 10 until --yes).
81
81
  */
82
82
  export declare function cmdRemoteControl(a: ParsedArgs, io: Io, runtime?: Runtime): Promise<number>;
83
+ /**
84
+ * `sideby advisor` (spec §3.41, ADR-0074): which model Claude Code's advisor asks in each Claude settings file, and
85
+ * whether sideby unlocks it at launch; `<model>|off`, `undo` and `unlock on|off` show the change (exit 10) until --yes.
86
+ */
87
+ export declare function cmdAdvisor(a: ParsedArgs, io: Io, runtime?: Runtime): Promise<number>;
83
88
  /**
84
89
  * `sideby model <account> [<model>|default] [--effort <level>|default] [--yes]` (spec §3.19, ADR-0014): shows the
85
90
  * Account's model and effort; with a change, shows it (exit 10) and writes it with --yes.
@@ -88,6 +93,13 @@ export declare function cmdModel(a: ParsedArgs, io: Io): Promise<number>;
88
93
  /** `sideby tune [account|family]`: estimated Compaction Threshold per model (spec §3.18). */
89
94
  export declare function cmdTune(a: ParsedArgs, io: Io): Promise<number>;
90
95
  export declare function cmdQuota(a: ParsedArgs, io: Io): Promise<number>;
96
+ /**
97
+ * `sideby quota reset <account> [--yes] [--operation <id>] [--open] [--json]` (spec §3.40, ADR-0072): use a Limit
98
+ * Reset. Where the Host can spend one (Codex) it shows the plan, read from the Host now, and exits 10; `--yes` spends
99
+ * one, which cannot be undone. Where only the vendor's page can (Claude Code) it prints the page, and `--open` opens
100
+ * it. A spend that got no final answer fails with the `operationId` to retry.
101
+ */
102
+ export declare function cmdQuotaReset(a: ParsedArgs, io: Io, runtime?: Runtime): Promise<number>;
91
103
  /** `sideby handoff ready|setup|teardown` (spec §3.17). */
92
104
  export declare function cmdHandoff(a: ParsedArgs, io: Io): Promise<number>;
93
105
  export declare function cmdPlugins(a: ParsedArgs, io: Io): Promise<number>;
@@ -3,8 +3,9 @@ import { basename, join, resolve } from 'node:path';
3
3
  import { StringDecoder } from 'node:string_decoder';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { aliasesByAccount } from '../core/accounts.js';
6
+ import { ADVISOR_UNLOCK_VAR, advisorGroupsToUndo, advisorNothingToDo, advisorPlan, advisorScope, BETAS_VAR, checkAdvisorAccount, isAdvisorChoice, } from '../core/advisor.js';
6
7
  import { listAppProfiles, openAppProfile, parseProfileRef, removeAppProfile } from '../core/app-profiles.js';
7
- import { browserReport, openInBrowser, setBrowserChoice, setBrowserSignIns, } from '../core/browser-profiles.js';
8
+ import { browserReport, openInBrowser, openVendorPage, setBrowserChoice, setBrowserSignIns, } from '../core/browser-profiles.js';
8
9
  import { CLI_COMMANDS, COMMAND_GROUPS, commonCommands } from '../core/cli-commands.js';
9
10
  import { aiTaskPermissions, aliasAccount, aliasArgs, aliasRefs, EDITORS, editConfigAskPermissions, editConfigUpdate, loadConfig, } from '../core/config.js';
10
11
  import { openDesktopApp, withDesktopApps } from '../core/desktop-app.js';
@@ -16,11 +17,12 @@ import { handoffRulesView } from '../core/handoff-rules.js';
16
17
  import { explain, readyDecision, runWithHandoff } from '../core/handoff-run.js';
17
18
  import { checkHandoffRefs, configureHandoff, handoffHint, handoffRefs, handoffStatus, } from '../core/handoff-status.js';
18
19
  import { installHint, runHost } from '../core/launch.js';
20
+ import { LimitResetError, pruneLimitResetRecords } from '../core/limit-reset.js';
19
21
  import { loginAfterLine, loginBeforeLine } from '../core/login-check.js';
20
22
  import { accountModel, setAccountModel } from '../core/model-choice.js';
21
23
  import { resolvePaths, tildify } from '../core/paths.js';
22
24
  import { quotaCheckOff } from '../core/quota-fetch.js';
23
- import { takeoverLimits, USAGE_DAYS } from '../core/quota-levels.js';
25
+ import { limitResetOffer, QUOTA_LONG_WARN_PERCENT, QUOTA_WARN_PERCENT, quotaAge, takeoverLimits, USAGE_DAYS, } from '../core/quota-levels.js';
24
26
  import { quotaStoreFile, readQuotaStore } from '../core/quota-store.js';
25
27
  import { groupsToUndo, remoteControlNothingToDo, remoteControlTodo, } from '../core/remote-control.js';
26
28
  import { SEARCH_CATALOG, searchCatalog } from '../core/search-catalog.js';
@@ -1021,6 +1023,241 @@ export async function cmdRemoteControl(a, io, runtime) {
1021
1023
  }
1022
1024
  return r.ok ? 0 : 1;
1023
1025
  }
1026
+ const ADVISOR_STATE = {
1027
+ fable: 'Fable',
1028
+ opus: 'Opus',
1029
+ sonnet: 'Sonnet',
1030
+ other: 'other',
1031
+ off: 'off',
1032
+ missing: 'no file',
1033
+ blocked: 'cannot change',
1034
+ };
1035
+ /** The value a group's `advisorModel` holds, as a preview shows it. */
1036
+ function advisorValue(g) {
1037
+ if (g.state === 'off')
1038
+ return 'not set';
1039
+ if (g.state === 'other')
1040
+ return g.model ? `"${g.model}"` : 'another value';
1041
+ return `"${g.state}"`;
1042
+ }
1043
+ function advisorGroupLine(g, home) {
1044
+ const label = g.state === 'other' && g.model ? g.model : ADVISOR_STATE[g.state];
1045
+ const paint = g.state === 'off' ? (x) => x : g.state === 'missing' || g.state === 'blocked' ? c.dim : c.green;
1046
+ const where = g.reason ? tilde(g.reason, home) : tildify(g.file, home);
1047
+ return ` ${paint(label.padEnd(13))} ${c.bold(g.accounts.join(', '))} ${c.dim(where)}`;
1048
+ }
1049
+ const ADVISOR_USAGE = 'usage: sideby advisor [fable|opus|sonnet|off] [--account <account>] [--yes] [--json]\n sideby advisor undo [--yes] [--json]\n sideby advisor unlock on|off [--yes] [--json]';
1050
+ /**
1051
+ * `sideby advisor` (spec §3.41, ADR-0074): which model Claude Code's advisor asks in each Claude settings file, and
1052
+ * whether sideby unlocks it at launch; `<model>|off`, `undo` and `unlock on|off` show the change (exit 10) until --yes.
1053
+ */
1054
+ export async function cmdAdvisor(a, io, runtime) {
1055
+ const [action, arg, extra] = a.positionals;
1056
+ const accountFlag = a.flags.get('account');
1057
+ const choice = isAdvisorChoice(action) ? action : undefined;
1058
+ const bad = extra !== undefined ||
1059
+ accountFlag === true ||
1060
+ (action !== undefined && !choice && action !== 'undo' && action !== 'unlock') ||
1061
+ (action === 'unlock' ? arg !== 'on' && arg !== 'off' : arg !== undefined) ||
1062
+ (accountFlag !== undefined && !choice);
1063
+ if (bad)
1064
+ throw new UsageError(ADVISOR_USAGE);
1065
+ const wantJson = a.flags.has('json');
1066
+ const yes = a.flags.has('yes');
1067
+ const rt = runtime ?? (await createRuntime());
1068
+ const home = rt.paths.home;
1069
+ const show = (gs) => gs.map((g) => ({
1070
+ ...g,
1071
+ file: tildify(g.file, home),
1072
+ ...(g.reason ? { reason: tilde(g.reason, home) } : {}),
1073
+ }));
1074
+ const out = (data) => json(io, { action: choice ? 'set' : (action ?? 'status'), ...(choice ? { to: choice } : {}), ...data });
1075
+ const status = await rt.advisor();
1076
+ const restart = 'Restart sessions that are already running; sessions started with plain `claude` get it only where Anthropic has turned the advisor on.';
1077
+ const apiBetasLine = (on) => on
1078
+ ? ` API accounts get ${BETAS_VAR} from sideby: yes (config claude.apiBetasOff; \`sideby config set claude.apiBetasOff false\` stops it)`
1079
+ : ` API accounts get ${BETAS_VAR} from sideby: no`;
1080
+ if (!action) {
1081
+ if (wantJson) {
1082
+ out({
1083
+ groups: show(status.groups),
1084
+ unlock: status.unlock,
1085
+ apiBetasOff: status.apiBetasOff,
1086
+ ...(status.envOff ? { envOff: status.envOff } : {}),
1087
+ });
1088
+ return 0;
1089
+ }
1090
+ if (!status.groups.length) {
1091
+ io.out('No Claude subscription accounts found. The advisor needs a Claude login; API accounts cannot use it.');
1092
+ return 0;
1093
+ }
1094
+ io.out('Advisor: Claude asks a stronger model for advice at key moments (this uses more quota)');
1095
+ for (const g of status.groups) {
1096
+ io.out(advisorGroupLine(g, home));
1097
+ if (g.betasOff)
1098
+ io.out(c.yellow(` env.${BETAS_VAR} is set here: it turns off Claude Code's experimental features, the advisor too. \`sideby advisor <model>\` offers to remove it.`));
1099
+ if (g.apiAccounts?.length)
1100
+ io.out(c.dim(` Also used by API accounts ${g.apiAccounts.join(', ')}${g.betasOff ? `; if sideby removes the variable here, it gives it to them when it starts them` : ''}`));
1101
+ }
1102
+ io.out(status.unlock
1103
+ ? ` Unlocked when sideby starts Claude: yes (${ADVISOR_UNLOCK_VAR}=1)`
1104
+ : ' Unlocked when sideby starts Claude: no (Claude Code shows /advisor only where Anthropic has turned it on)');
1105
+ if (status.apiBetasOff || status.groups.some((g) => g.apiAccounts?.length))
1106
+ io.out(apiBetasLine(status.apiBetasOff));
1107
+ if (status.envOff)
1108
+ io.out(c.yellow(` Your shell sets ${status.envOff}, so Claude Code hides the advisor in every session, also the ones sideby starts. sideby does not change your shell; remove it from your shell profile to use the advisor.`));
1109
+ io.out(c.cyan('\nRun `sideby advisor opus` (or fable, sonnet, off) to choose; it shows the change first. If a session says "Advisor unavailable", Anthropic has not enabled it for that account.'));
1110
+ return 0;
1111
+ }
1112
+ if (action === 'unlock') {
1113
+ const on = arg === 'on';
1114
+ if (status.unlock === on) {
1115
+ const message = on
1116
+ ? 'sideby already unlocks /advisor at launch (nothing changed).'
1117
+ : 'sideby already leaves /advisor to Claude Code (nothing changed).';
1118
+ if (wantJson)
1119
+ out({ to: arg, applied: false, unlock: status.unlock, message });
1120
+ else
1121
+ io.out(message);
1122
+ return 1;
1123
+ }
1124
+ if (!yes) {
1125
+ if (wantJson)
1126
+ out({
1127
+ to: arg,
1128
+ applied: false,
1129
+ unlock: status.unlock,
1130
+ message: `Run again with --yes to turn it ${arg}.`,
1131
+ });
1132
+ else {
1133
+ io.out(on ? 'Unlock /advisor in the Claude sessions sideby starts?' : 'Stop unlocking /advisor at launch?');
1134
+ io.out(` sideby config: advisor.unlock ${status.unlock} -> ${on}`);
1135
+ io.out(c.dim(on
1136
+ ? ` Sessions sideby starts for Claude subscription accounts get ${ADVISOR_UNLOCK_VAR}=1. ${restart}`
1137
+ : ' Claude Code then shows /advisor only where Anthropic has turned it on. Restart sessions that are already running.'));
1138
+ io.out(`Run again with --yes to turn it ${arg}.`);
1139
+ }
1140
+ return 10;
1141
+ }
1142
+ const r = await rt.advisorUnlock(on);
1143
+ if (wantJson)
1144
+ out({ to: arg, applied: r.ok, unlock: r.unlock, message: r.message });
1145
+ else
1146
+ io.out(r.message);
1147
+ return r.ok ? 0 : 1;
1148
+ }
1149
+ let scope = status.groups;
1150
+ let accountRef;
1151
+ if (typeof accountFlag === 'string') {
1152
+ accountRef = checkAdvisorAccount(await rt.resolve(accountFlag)).ref;
1153
+ scope = advisorScope(status.groups, accountRef);
1154
+ }
1155
+ const plan = choice ? advisorPlan(scope, choice, status) : null;
1156
+ const todo = plan ? plan.todo : advisorGroupsToUndo(status.groups);
1157
+ if (!todo.length && !plan?.unlock) {
1158
+ // Only what was read: writing here would act on a file the user never saw in a preview.
1159
+ const r = advisorNothingToDo(choice ?? 'undo', scope);
1160
+ if (wantJson)
1161
+ out({
1162
+ applied: false,
1163
+ groups: show(scope),
1164
+ unlock: status.unlock,
1165
+ apiBetasOff: status.apiBetasOff,
1166
+ message: r.message,
1167
+ });
1168
+ else
1169
+ io.out(tilde(r.message, home));
1170
+ return 1;
1171
+ }
1172
+ const name = choice && choice !== 'off' ? choice[0].toUpperCase() + choice.slice(1) : '';
1173
+ const verb = choice === 'off' ? 'turn it off' : choice ? `use ${name}` : 'undo';
1174
+ // Undo turns config claude.apiBetasOff back only while it is on and every file it was turned on for comes back.
1175
+ const apiBack = !plan && status.apiBetasOff && todo.some((g) => g.undoApiBetas);
1176
+ if (!yes) {
1177
+ if (wantJson)
1178
+ out({
1179
+ applied: false,
1180
+ groups: show(todo),
1181
+ ...(plan?.skipped.length ? { skipped: show(plan.skipped) } : {}),
1182
+ ...(plan ? { unlocks: plan.unlock } : {}),
1183
+ ...(plan?.betas.length ? { removesBetas: true } : {}),
1184
+ ...(plan?.apiAccounts.length ? { apiAccounts: plan.apiAccounts, apiBetasOn: plan.apiBetas } : {}),
1185
+ ...(apiBack ? { apiBetasBack: true } : {}),
1186
+ unlock: status.unlock,
1187
+ apiBetasOff: status.apiBetasOff,
1188
+ message: `Run again with --yes to ${verb}.`,
1189
+ });
1190
+ else {
1191
+ io.out(choice === 'off'
1192
+ ? 'Turn off the advisor?'
1193
+ : choice
1194
+ ? `Use ${name} as the advisor?`
1195
+ : 'Put back the advisor setting sideby replaced?');
1196
+ for (const g of todo) {
1197
+ const to = choice === 'off' ? 'removed' : choice ? `"${choice}"` : 'what it was before';
1198
+ const file = tildify(g.file, home);
1199
+ if (g.state !== choice)
1200
+ io.out(` ${file}: advisorModel ${advisorValue(g)} -> ${to}`);
1201
+ if (plan?.betas.includes(g))
1202
+ io.out(` ${file}: env.${BETAS_VAR} ${g.betasValue} -> removed`);
1203
+ io.out(c.dim(` used by ${g.accounts.join(', ')}`));
1204
+ if (g.apiAccounts?.length && (plan ? plan.betas.includes(g) : g.undoApiBetas))
1205
+ io.out(c.dim(` and by API accounts ${g.apiAccounts.join(', ')}`));
1206
+ }
1207
+ if (plan?.betas.length)
1208
+ io.out(c.yellow(` ${BETAS_VAR} turns off Claude Code's experimental features, the advisor among them; removing it also turns the others back on for subscription accounts.`));
1209
+ if (plan?.apiAccounts.length) {
1210
+ const names = plan.apiAccounts.join(', ');
1211
+ if (plan.apiBetas) {
1212
+ io.out(' sideby config: claude.apiBetasOff false -> true');
1213
+ io.out(c.dim(` sideby gives ${BETAS_VAR}=1 to ${names} when it starts them, so a gateway that rejects experimental headers keeps working. A value in their proxy.env still wins.`));
1214
+ }
1215
+ else
1216
+ io.out(c.dim(` ${names} already get ${BETAS_VAR}=1 from sideby (config claude.apiBetasOff), so they keep it.`));
1217
+ }
1218
+ if (apiBack) {
1219
+ io.out(' sideby config: claude.apiBetasOff true -> as before');
1220
+ io.out(c.dim(` The settings file sets ${BETAS_VAR} for the API accounts again.`));
1221
+ }
1222
+ for (const g of plan?.skipped ?? [])
1223
+ io.out(c.dim(` Not changed: ${g.accounts.join(', ')}: ${tilde(g.reason ?? '', home)}`));
1224
+ if (plan?.unlock) {
1225
+ io.out(' sideby config: advisor.unlock false -> true');
1226
+ io.out(c.dim(` Sessions sideby starts for Claude subscription accounts get ${ADVISOR_UNLOCK_VAR}=1, which shows /advisor.`));
1227
+ }
1228
+ io.out(choice === 'off'
1229
+ ? 'Restart sessions that are already running. Undo this with `sideby advisor undo`.'
1230
+ : choice
1231
+ ? `The advisor uses more quota. ${restart} Undo this with \`sideby advisor undo\`.`
1232
+ : 'New sessions go back to the previous setting.');
1233
+ io.out(`Run again with --yes to ${verb}.`);
1234
+ }
1235
+ return 10;
1236
+ }
1237
+ const r = choice
1238
+ ? await rt.advisorSet(choice, accountRef ? { account: accountRef } : {})
1239
+ : await rt.advisorUndo();
1240
+ const results = r.results.map((x) => ({ ...x, file: tildify(x.file, home) }));
1241
+ if (wantJson)
1242
+ out({
1243
+ applied: r.ok,
1244
+ results,
1245
+ ...(choice ? { unlocked: r.unlocked } : {}),
1246
+ unlock: status.unlock || r.unlocked,
1247
+ apiBetasOff: r.apiBetas ?? status.apiBetasOff,
1248
+ message: tilde(r.message, home),
1249
+ });
1250
+ else {
1251
+ for (const x of results)
1252
+ io.out(` ${x.ok ? c.green('ok') : c.red('failed')} ${x.file}: ${x.message}`);
1253
+ if (r.unlocked)
1254
+ io.out(` ${c.green('ok')} sideby config: advisor.unlock true`);
1255
+ if (r.apiBetas !== undefined)
1256
+ io.out(` ${c.green('ok')} sideby config: claude.apiBetasOff ${r.apiBetas ? 'true' : 'back as before'}`);
1257
+ io.out(tilde(r.message, home));
1258
+ }
1259
+ return r.ok ? 0 : 1;
1260
+ }
1024
1261
  const FROM = {
1025
1262
  sideby: 'set by sideby',
1026
1263
  host: 'from the host config',
@@ -1145,7 +1382,13 @@ export async function cmdQuota(a, io) {
1145
1382
  }
1146
1383
  if (sub === 'setup' || sub === 'teardown')
1147
1384
  return cmdQuotaSetup(a, io, sub);
1385
+ if (sub === 'reset')
1386
+ return cmdQuotaReset(a, io);
1387
+ if (a.flags.has('open') || a.flags.has('operation'))
1388
+ throw new UsageError('--open and --operation go with `sideby quota reset <account>`');
1148
1389
  const rt = await createRuntime();
1390
+ // Records of Limit Reset operations that finished a day ago go with the next quota command (spec §3.40).
1391
+ await pruneLimitResetRecords(rt.paths.stateDir, rt.readContext().now).catch(() => { });
1149
1392
  const accounts = !sub
1150
1393
  ? displayOrdered(await rt.accounts(), rt)
1151
1394
  : rt.families.has(sub)
@@ -1169,9 +1412,25 @@ export async function cmdQuota(a, io) {
1169
1412
  return 0;
1170
1413
  }
1171
1414
  const now = new Date();
1415
+ // A reading over an hour old is old only when this computer used the login since (spec §3.31); a Same Login's
1416
+ // sessions count too, read only then.
1417
+ const lastUse = new Map();
1418
+ for (const r of rows) {
1419
+ if (r.quota.status !== 'ok' || !overAnHour(r.quota, now.getTime()))
1420
+ continue;
1421
+ const x = accounts.find((y) => y.ref === r.ref);
1422
+ const peers = await rt.sameLogin(x);
1423
+ const all = peers.length ? (await rt.accounts()).filter((y) => peers.includes(y.ref)) : [];
1424
+ lastUse.set(r.ref, await lastLocalUse(rt, [x, ...all]));
1425
+ }
1426
+ const listed = new Set(rows.map((r) => r.ref));
1172
1427
  io.out(table(rows.map((r) => [
1173
1428
  c.bold(r.ref),
1174
- `${quotaText(r.quota, now)}${r.quota.status === 'ok' && r.quota.from ? c.dim(` read from ${r.quota.from} (same login)`) : ''}`,
1429
+ // A Same Login's Limit Resets are said once, on the row the reading came from.
1430
+ `${quotaText(r.quota, now, {
1431
+ lastUseAt: lastUse.get(r.ref),
1432
+ resets: !(r.quota.status === 'ok' && r.quota.from && listed.has(r.quota.from)),
1433
+ })}${r.quota.status === 'ok' && r.quota.from ? c.dim(` read from ${r.quota.from} (same login)`) : ''}`,
1175
1434
  usageText(r.usage),
1176
1435
  ]), ['ACCOUNT', 'QUOTA', `USAGE (${USAGE_DAYS}d)`]));
1177
1436
  for (const r of rows) {
@@ -1190,6 +1449,155 @@ export async function cmdQuota(a, io) {
1190
1449
  io.out(c.cyan(`\nTurn on ${s.family} quota with \`sideby quota setup ${s.family}\` (shows the change first).`));
1191
1450
  return 0;
1192
1451
  }
1452
+ /** One window as the Limit Reset plan lists it: its name, used percent and own reset time. */
1453
+ function resetWindowLine(w, now) {
1454
+ const label = w.name ? `${w.name} ${w.label}` : w.label;
1455
+ const passed = Date.parse(w.resetsAt) <= now.getTime();
1456
+ return ` ${label.padEnd(8)} ${String(Math.round(w.usedPercent)).padStart(3)}% used · ${passed ? 'reset time passed' : `resets ${resetWhen(w.resetsAt, now.getTime(), 'en')}`}`;
1457
+ }
1458
+ /**
1459
+ * `sideby quota reset <account> [--yes] [--operation <id>] [--open] [--json]` (spec §3.40, ADR-0072): use a Limit
1460
+ * Reset. Where the Host can spend one (Codex) it shows the plan, read from the Host now, and exits 10; `--yes` spends
1461
+ * one, which cannot be undone. Where only the vendor's page can (Claude Code) it prints the page, and `--open` opens
1462
+ * it. A spend that got no final answer fails with the `operationId` to retry.
1463
+ */
1464
+ export async function cmdQuotaReset(a, io, runtime) {
1465
+ const usage = 'usage: sideby quota reset <account> [--yes] [--operation <id>] [--open] [--json]';
1466
+ const ref = a.positionals[1];
1467
+ if (!ref || a.positionals.length !== 2 || a.rest.length || a.flags.has('refresh'))
1468
+ throw new UsageError(usage);
1469
+ const operation = a.flags.get('operation');
1470
+ const asJson = a.flags.has('json');
1471
+ const rt = runtime ?? (await createRuntime());
1472
+ const now = rt.readContext().now;
1473
+ await pruneLimitResetRecords(rt.paths.stateDir, now).catch(() => { });
1474
+ const account = await rt.resolve(ref);
1475
+ const kind = rt.limitResetKind(account);
1476
+ const f = rt.families.get(account.family);
1477
+ if (kind?.kind === 'page') {
1478
+ if (a.flags.has('yes') || operation !== undefined)
1479
+ throw new UserError(`${f.title} cannot use a limit reset from the command line, so there is nothing to confirm; it is used on ${kind.url} (open it with \`sideby quota reset ${account.ref} --open\`)`, { code: 'no-limit-reset' });
1480
+ const [quota, st] = await Promise.all([rt.quota(account), rt.status(account)]);
1481
+ const offer = limitResetOffer(quota.status === 'ok' ? quota : null, 'page', now.getTime(), {
1482
+ short: QUOTA_WARN_PERCENT,
1483
+ long: QUOTA_LONG_WARN_PERCENT,
1484
+ });
1485
+ const tight = quota.status === 'ok' ? (offer?.tight ?? []).map((i) => quota.windows[i]) : [];
1486
+ const opened = a.flags.has('open') ? await openVendorPage(rt, account) : undefined;
1487
+ const who = st.identity?.email;
1488
+ const message = `${f.title} cannot use a limit reset from the command line: it is used on the vendor's page, and then applies to ${f.title} too. sideby cannot see whether ${account.ref} holds one.`;
1489
+ if (asJson) {
1490
+ json(io, {
1491
+ account: account.ref,
1492
+ outcome: 'open-vendor-page',
1493
+ url: kind.url,
1494
+ opened: Boolean(opened),
1495
+ ...(opened?.profile ? { profile: opened.profile } : {}),
1496
+ ...(who ? { identity: { email: who, ...(st.identity?.org ? { org: st.identity.org } : {}) } } : {}),
1497
+ tight: tight.map((w) => ({
1498
+ label: w.label,
1499
+ ...(w.name ? { name: w.name } : {}),
1500
+ usedPercent: w.usedPercent,
1501
+ resetsAt: w.resetsAt,
1502
+ })),
1503
+ message,
1504
+ });
1505
+ return 0;
1506
+ }
1507
+ io.out(message);
1508
+ io.out(` ${c.bold(kind.url)}`);
1509
+ io.out(who
1510
+ ? `Check that the page is signed in as ${who} (${account.ref}): a reset used there belongs to the login of the page.`
1511
+ : `Check that the page is signed in as the login of ${account.ref}: a reset used there belongs to the login of the page.`);
1512
+ if (tight.length) {
1513
+ io.out('Windows that are tight now:');
1514
+ for (const w of tight)
1515
+ io.out(resetWindowLine(w, now));
1516
+ }
1517
+ io.out(opened
1518
+ ? `${c.green('✓')} Opened it${opened.profile ? ` in the browser user ${opened.profile.name}` : ' in your browser'}. Run \`sideby quota ${account.ref} --refresh\` after using one.`
1519
+ : c.cyan(`Open it with \`sideby quota reset ${account.ref} --open\`.`));
1520
+ return 0;
1521
+ }
1522
+ if (a.flags.has('open')) {
1523
+ if (!f.limitReset?.vendorPage)
1524
+ throw new UserError(`--open is for an account whose limit reset is used on the vendor's page (Claude Code); for ${account.ref} run \`sideby quota reset ${account.ref}\``, { code: 'no-vendor-page' });
1525
+ // A Family whose Host can use one and that has a vendor page too: `--open` only opens the page, and uses nothing.
1526
+ const opened = await openVendorPage(rt, account);
1527
+ const message = `Opened ${opened.url}${opened.profile ? ` in the browser user ${opened.profile.name}` : ' in your browser'}: the vendor's page for the limit resets of ${account.ref}. Nothing was used from here; to use one through ${f.title} itself, run \`sideby quota reset ${account.ref}\`.`;
1528
+ if (asJson)
1529
+ json(io, {
1530
+ account: account.ref,
1531
+ outcome: 'open-vendor-page',
1532
+ url: opened.url,
1533
+ opened: true,
1534
+ ...(opened.profile ? { profile: opened.profile } : {}),
1535
+ message,
1536
+ });
1537
+ else
1538
+ io.out(`${c.green('✓')} ${message}`);
1539
+ return 0;
1540
+ }
1541
+ const planLines = (plan) => {
1542
+ const q = plan.quota;
1543
+ const stock = plan.limitResets;
1544
+ return [
1545
+ c.bold(`Use a limit reset for ${plan.account}`),
1546
+ ...(plan.sameLogin.length ? [` Also applies to: ${plan.sameLogin.join(', ')} (same login)`] : []),
1547
+ ...(plan.via !== plan.account ? [` Sent through: ${plan.via}`] : []),
1548
+ ...(q.status === 'ok'
1549
+ ? q.windows.map((w) => resetWindowLine(w, now))
1550
+ : [` quota: ${q.detail ?? q.reason}`]),
1551
+ stock
1552
+ ? ` Limit resets: ${stock.available} available${plan.expectedAfter !== undefined ? ` → ${plan.expectedAfter} expected afterwards` : ''} · ${stock.nextExpiresAt ? `the next one expires ${clock(stock.nextExpiresAt, now)}` : 'expiry unknown'}`
1553
+ : ' Limit resets: unknown',
1554
+ '',
1555
+ plan.message,
1556
+ ];
1557
+ };
1558
+ if (!a.flags.has('yes')) {
1559
+ if (operation !== undefined)
1560
+ throw new UsageError(`--operation goes with --yes; ${usage}`);
1561
+ const plan = await rt.limitResetPlan(account);
1562
+ if (asJson)
1563
+ json(io, { confirmationRequired: plan.canUse, ...plan });
1564
+ else {
1565
+ for (const l of planLines(plan))
1566
+ io.out(l);
1567
+ io.out(plan.canUse
1568
+ ? c.cyan(`\nConfirm with \`sideby quota reset ${account.ref} --yes --operation ${plan.operationId}\`. It cannot be undone.`)
1569
+ : c.yellow(`\nNot possible now: ${plan.blocked}.`));
1570
+ }
1571
+ // 10: the plan is shown and waits for the user's yes (spec §3.9); agents ask before adding --yes.
1572
+ return plan.canUse ? 10 : 1;
1573
+ }
1574
+ let operationId = operation;
1575
+ if (operationId === undefined) {
1576
+ // `--yes` alone: the plan is read first, so a spend never goes out on old numbers. An earlier attempt of this
1577
+ // login that got no final answer is the plan's operation, and is asked again with its own key.
1578
+ const plan = await rt.limitResetPlan(account);
1579
+ if (!asJson)
1580
+ for (const l of planLines(plan))
1581
+ io.out(l);
1582
+ if (!plan.canUse || !plan.operationId)
1583
+ throw new LimitResetError(`${plan.blocked ?? 'this limit reset cannot be used now'}; nothing was sent`, {
1584
+ code: 'cannot-use',
1585
+ });
1586
+ operationId = plan.operationId;
1587
+ if (!asJson)
1588
+ io.out('');
1589
+ }
1590
+ const r = await rt.limitResetUse(account, operationId);
1591
+ const used = r.outcome === 'reset' || r.outcome === 'already-done';
1592
+ if (asJson)
1593
+ json(io, r);
1594
+ else {
1595
+ io.out(`${used ? c.green('✓') : c.yellow('•')} ${r.message}`);
1596
+ if (r.quota)
1597
+ io.out(`${c.bold(r.account)} ${quotaText(r.quota, new Date())}`);
1598
+ }
1599
+ return used ? 0 : 1;
1600
+ }
1193
1601
  async function cmdQuotaSetup(a, io, sub) {
1194
1602
  const familyId = a.positionals[1];
1195
1603
  if (!familyId)
@@ -1873,6 +2281,7 @@ export async function cmdUpdate(a, io) {
1873
2281
  ...(r.refreshedAutostart === undefined ? {} : { refreshedAutostart: r.refreshedAutostart }),
1874
2282
  skill: SKILL_INSTALL,
1875
2283
  ...(r.skillUpdated === undefined ? {} : { skillUpdated: r.skillUpdated }),
2284
+ ...(r.skillMessage === undefined ? {} : { skillMessage: r.skillMessage }),
1876
2285
  ...(r.ok ? {} : { output: r.output }),
1877
2286
  });
1878
2287
  return r.ok ? 0 : 1;
@@ -2789,6 +3198,10 @@ export async function cmdAutostart(a, io) {
2789
3198
  }
2790
3199
  return 0;
2791
3200
  }
3201
+ /** Whether any window of the reading was read over an hour ago (a window may be older than the rest, ADR-0073). */
3202
+ function overAnHour(quota, now) {
3203
+ return !(now - Date.parse(quotaAge(quota, now).observedAt) <= 3600_000);
3204
+ }
2792
3205
  /** The newest session activity among these Accounts, from their Usage; undefined when none can be read. */
2793
3206
  async function lastLocalUse(rt, list) {
2794
3207
  const times = await Promise.all(list.map(async (x) => {
@@ -2827,7 +3240,9 @@ async function menubarFamilies(rt, o = {}) {
2827
3240
  const login = st ? st.login : 'not-needed';
2828
3241
  let refresh;
2829
3242
  if (asks && x.kind === 'subscription' && login !== 'logged-out') {
2830
- const kept = await readQuotaStore(quotaStoreFile(rt.paths.stateDir, x.family, x.name));
3243
+ // A Same Login is asked once, through one of its Accounts (spec §3.26): that answer is this one's.
3244
+ const asked = await rt.quotaAsker(x);
3245
+ const kept = await readQuotaStore(quotaStoreFile(rt.paths.stateDir, asked.family, asked.name));
2831
3246
  const attempted = kept ? Date.parse(kept.attemptedAt) : Number.NaN;
2832
3247
  // The refresh's own snapshot has nothing left waiting: an answer it could not keep counts as failed.
2833
3248
  if (!(attempted >= o.since))
@@ -2836,7 +3251,7 @@ async function menubarFamilies(rt, o = {}) {
2836
3251
  refresh = 'failed';
2837
3252
  }
2838
3253
  // Usage is read only for a reading over an hour old, to tell whether this computer used the login since.
2839
- const old = quota.status === 'ok' && now - Date.parse(quota.observedAt) > 3600_000;
3254
+ const old = quota.status === 'ok' && overAnHour(quota, now);
2840
3255
  const lastUseAt = old
2841
3256
  ? await lastLocalUse(rt, [x, ...accounts.filter((p) => sameLogin.includes(p.ref))])
2842
3257
  : undefined;
@@ -2857,6 +3272,12 @@ async function menubarFamilies(rt, o = {}) {
2857
3272
  title: f.title,
2858
3273
  logo: f.logo ?? null,
2859
3274
  refreshable: Boolean(f.fetchQuota),
3275
+ ...(f.fetchQuota ? { everyMinutes: f.fetchQuota.everyMinutes } : {}),
3276
+ ...(f.limitReset?.use
3277
+ ? { limitReset: 'use' }
3278
+ : f.limitReset?.vendorPage
3279
+ ? { limitReset: 'page', limitResetSite: new URL(f.limitReset.vendorPage).host }
3280
+ : {}),
2860
3281
  plan,
2861
3282
  accounts: list,
2862
3283
  };
@@ -2875,12 +3296,14 @@ export async function cmdMenubar(a, io) {
2875
3296
  const sinceFlag = a.flags.get('refreshing-since');
2876
3297
  const since = sinceFlag === undefined ? undefined : Date.parse(sinceFlag);
2877
3298
  const cached = a.flags.has('cached');
3299
+ const ask = a.flags.get('ask');
2878
3300
  if (extra !== undefined ||
2879
3301
  (cached && a.flags.has('refresh')) ||
3302
+ (ask !== undefined && (cached || a.flags.has('refresh'))) ||
2880
3303
  (since !== undefined && (!cached || !Number.isFinite(since))) ||
2881
3304
  (reported !== undefined && reported !== 'ok' && reported !== 'taken') ||
2882
3305
  (icon !== undefined && icon !== 'visible' && icon !== 'hidden'))
2883
- throw new UsageError('usage: sideby menubar snapshot [--refresh | --cached [--refreshing-since <ISO time>]] [--lang en|zh] [--hotkey ok|taken [--hotkey-label <label>]] [--icon visible|hidden] [--json]');
3306
+ throw new UsageError('usage: sideby menubar snapshot [--refresh | --ask <account> | --cached [--refreshing-since <ISO time>]] [--lang en|zh] [--hotkey ok|taken [--hotkey-label <label>]] [--icon visible|hidden] [--json]');
2884
3307
  const { menubarHotkey, menubarLang, menubarSnapshot } = await import('../menubar/snapshot.js');
2885
3308
  const rt = await createRuntime();
2886
3309
  const hotkey = menubarHotkey(rt.config.menubar?.hotkey);
@@ -2913,6 +3336,13 @@ export async function cmdMenubar(a, io) {
2913
3336
  refreshedSince = Date.now();
2914
3337
  await rt.refreshQuota();
2915
3338
  }
3339
+ // After "Use a reset…" (spec §3.40): that one account is asked once, as its numbers may have changed on the
3340
+ // vendor's page or in the Panel. An account that is gone by now is not an error for the menu.
3341
+ if (ask) {
3342
+ const one = await rt.resolve(ask).catch(() => null);
3343
+ if (one)
3344
+ await rt.refreshQuota([one]).catch(() => { });
3345
+ }
2916
3346
  const families = await menubarFamilies(rt, cached ? { fetch: 'never', since } : { since: refreshedSince, final: true });
2917
3347
  const snap = menubarSnapshot(families, rt.readContext().now, lang, hotkey);
2918
3348
  if (wantJson)
@@ -2971,6 +3401,50 @@ export async function cmdMenubar(a, io) {
2971
3401
  : 'Menu bar shortcut turned off.');
2972
3402
  return 0;
2973
3403
  }
3404
+ if (action === 'reset') {
3405
+ // What "Use a reset…" in the menu runs (spec §3.40, ADR-0072). It only opens a page: the Panel on that account's
3406
+ // confirmation where the Host can use one, the vendor's page where only that can. It never uses one.
3407
+ if (!extra || a.positionals.length > 2)
3408
+ throw new UsageError('usage: sideby menubar reset <account> [--json]');
3409
+ const rt = await createRuntime();
3410
+ const account = await rt.resolve(extra);
3411
+ const kind = rt.limitResetKind(account);
3412
+ if (!kind)
3413
+ throw new UserError(`${rt.families.get(account.family).title} offers no way to use a limit reset; its quota comes back when its window resets (see \`sideby quota ${account.ref}\`)`, { code: 'no-limit-reset' });
3414
+ if (kind.kind === 'page') {
3415
+ const r = await openVendorPage(rt, account);
3416
+ if (wantJson)
3417
+ json(io, {
3418
+ account: account.ref,
3419
+ url: r.url,
3420
+ opened: true,
3421
+ ...(r.profile ? { profile: r.profile.name } : {}),
3422
+ });
3423
+ else
3424
+ io.out(`Opened ${r.url} for ${account.ref}${r.profile ? ` in the browser profile ${r.profile.name}` : ''}.`);
3425
+ return 0;
3426
+ }
3427
+ const bg = await import('../panel/background.js');
3428
+ const { openBrowser } = await import('../panel/server.js');
3429
+ const paths = resolvePaths();
3430
+ const panel = await bg.startBackgroundPanel({ paths, env: process.env, entry: cliEntry() });
3431
+ const url = `${panel.url.replace(/#.*$/, '')}#reset=${encodeURIComponent(account.ref)}`;
3432
+ // The browser is started detached and does not keep this process alive, so a short timer waits for its answer;
3433
+ // without one, the page is taken as opened.
3434
+ let timer;
3435
+ const opened = await Promise.race([
3436
+ openBrowser(url),
3437
+ new Promise((done) => {
3438
+ timer = setTimeout(() => done(true), 3000);
3439
+ }),
3440
+ ]);
3441
+ clearTimeout(timer);
3442
+ if (wantJson)
3443
+ json(io, { account: account.ref, url, opened });
3444
+ else
3445
+ io.out(opened ? `Opened the panel on ${account.ref}'s limit reset.` : `Open ${url} in your browser.`);
3446
+ return opened ? 0 : 1;
3447
+ }
2974
3448
  if (action === 'start') {
2975
3449
  if (!extra || a.positionals.length > 2)
2976
3450
  throw new UsageError('usage: sideby menubar start <account> [--json]');
@@ -15,7 +15,18 @@ export declare function table(rows: string[][], header: string[]): string;
15
15
  export declare function ago(iso: string, now: Date): string;
16
16
  export declare function clock(iso: string, now: Date): string;
17
17
  export declare const QUOTA_REASON: Record<string, string>;
18
- export declare function quotaText(q: QuotaResult, now: Date): string;
18
+ /** `1 reset available`, with when the next one expires where the Host told (ADR-0072); empty for none. */
19
+ export declare function limitResetsText(q: QuotaResult, now: Date): string;
20
+ /**
21
+ * One Account's Quota as a line. A window read at another time than the rest says so after its numbers, and numbers
22
+ * that count as old by the shared rule (`quotaAge`, ADR-0073) say so after the read time. `lastUseAt` is the newest
23
+ * use of the login on this computer; `resets: false` leaves the Limit Resets out (another row of the same login
24
+ * says them).
25
+ */
26
+ export declare function quotaText(q: QuotaResult, now: Date, o?: {
27
+ lastUseAt?: string | null;
28
+ resets?: boolean;
29
+ }): string;
19
30
  export declare function compactNumber(n: number): string;
20
31
  export declare function usageText(u: UsageResult): string;
21
32
  /** One line per model of a tuning result, or the reason there is none. */