sideby 0.35.9 → 0.36.1

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 (68) 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 +489 -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 +187 -0
  9. package/dist/src/core/advisor.js +519 -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/claude-settings-file.d.ts +14 -0
  13. package/dist/src/core/claude-settings-file.js +62 -23
  14. package/dist/src/core/cli-commands.js +25 -1
  15. package/dist/src/core/config.d.ts +29 -0
  16. package/dist/src/core/config.js +25 -0
  17. package/dist/src/core/handoff-select.d.ts +13 -2
  18. package/dist/src/core/handoff-select.js +6 -2
  19. package/dist/src/core/launch.d.ts +4 -0
  20. package/dist/src/core/launch.js +7 -0
  21. package/dist/src/core/limit-reset.d.ts +198 -0
  22. package/dist/src/core/limit-reset.js +299 -0
  23. package/dist/src/core/quota-fetch.d.ts +57 -2
  24. package/dist/src/core/quota-fetch.js +291 -13
  25. package/dist/src/core/quota-levels.d.ts +70 -0
  26. package/dist/src/core/quota-levels.js +80 -0
  27. package/dist/src/core/quota-store.d.ts +15 -1
  28. package/dist/src/core/quota-store.js +26 -1
  29. package/dist/src/core/same-login.d.ts +8 -0
  30. package/dist/src/core/same-login.js +39 -2
  31. package/dist/src/core/search-catalog.js +38 -0
  32. package/dist/src/families/claude/index.js +2 -0
  33. package/dist/src/families/codex/index.js +3 -1
  34. package/dist/src/families/codex/quota.d.ts +23 -1
  35. package/dist/src/families/codex/quota.js +122 -21
  36. package/dist/src/families/grok/quota-log.d.ts +1 -0
  37. package/dist/src/menubar/script.js +70 -18
  38. package/dist/src/menubar/snapshot.d.ts +33 -1
  39. package/dist/src/menubar/snapshot.js +79 -11
  40. package/dist/src/menubar/strings.d.ts +16 -0
  41. package/dist/src/menubar/strings.js +16 -0
  42. package/dist/src/panel/handler.d.ts +21 -0
  43. package/dist/src/panel/handler.js +134 -12
  44. package/dist/src/panel/i18n.d.ts +87 -0
  45. package/dist/src/panel/i18n.js +174 -0
  46. package/dist/src/panel/page-logic.d.ts +17 -0
  47. package/dist/src/panel/page-logic.js +23 -0
  48. package/dist/src/panel/page-script.js +442 -19
  49. package/dist/src/panel/page-styles.js +38 -2
  50. package/dist/src/plugins/loader.d.ts +2 -0
  51. package/dist/src/plugins/loader.js +27 -0
  52. package/dist/src/runtime.d.ts +65 -1
  53. package/dist/src/runtime.js +530 -9
  54. package/dist/src/types.d.ts +67 -0
  55. package/package.json +1 -1
  56. package/schemas/advisor.json +332 -0
  57. package/schemas/config.json +22 -0
  58. package/schemas/error.json +4 -0
  59. package/schemas/menubar-reset.json +93 -0
  60. package/schemas/menubar-snapshot.json +70 -2
  61. package/schemas/quota-reset.json +369 -0
  62. package/schemas/quota.json +30 -0
  63. package/schemas/update.json +4 -0
  64. package/skills/sideby/SKILL.md +6 -2
  65. package/skills/sideby/references/ai-tasks.md +1 -1
  66. package/skills/sideby/references/panel.md +14 -0
  67. package/skills/sideby/references/quota.md +27 -0
  68. package/skills/sideby/references/update.md +1 -1
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"id":"20261110T040509-f565d3"}
1
+ {"id":"20261113T091614-584b60"}
@@ -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,250 @@ 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 file = tildify(g.file, home);
1198
+ if (choice) {
1199
+ const to = choice === 'off' ? 'removed' : `"${choice}"`;
1200
+ if (g.state !== choice)
1201
+ io.out(` ${file}: advisorModel ${advisorValue(g)} -> ${to}`);
1202
+ if (plan?.betas.includes(g))
1203
+ io.out(` ${file}: env.${BETAS_VAR} ${g.betasValue} -> removed`);
1204
+ }
1205
+ else {
1206
+ // Only what undo really puts back: a change that kept the model only removed the env entry.
1207
+ if (g.undoModel)
1208
+ io.out(` ${file}: advisorModel ${advisorValue(g)} -> ${g.undoModel}`);
1209
+ if (g.undoBetas)
1210
+ io.out(` ${file}: env.${BETAS_VAR} absent -> ${g.undoBetas}`);
1211
+ }
1212
+ io.out(c.dim(` used by ${g.accounts.join(', ')}`));
1213
+ if (g.apiAccounts?.length && (plan ? plan.betas.includes(g) : g.undoApiBetas))
1214
+ io.out(c.dim(` and by API accounts ${g.apiAccounts.join(', ')}`));
1215
+ }
1216
+ if (plan?.betas.length)
1217
+ 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.`));
1218
+ if (plan?.apiAccounts.length) {
1219
+ const names = plan.apiAccounts.join(', ');
1220
+ if (plan.apiBetas) {
1221
+ io.out(' sideby config: claude.apiBetasOff false -> true');
1222
+ 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.`));
1223
+ }
1224
+ else
1225
+ io.out(c.dim(` ${names} already get ${BETAS_VAR}=1 from sideby (config claude.apiBetasOff), so they keep it.`));
1226
+ }
1227
+ if (apiBack) {
1228
+ io.out(' sideby config: claude.apiBetasOff true -> as before');
1229
+ io.out(c.dim(` The settings file sets ${BETAS_VAR} for the API accounts again.`));
1230
+ }
1231
+ for (const g of plan?.skipped ?? [])
1232
+ io.out(c.dim(` Not changed: ${g.accounts.join(', ')}: ${tilde(g.reason ?? '', home)}`));
1233
+ if (plan?.unlock) {
1234
+ io.out(' sideby config: advisor.unlock false -> true');
1235
+ io.out(c.dim(` Sessions sideby starts for Claude subscription accounts get ${ADVISOR_UNLOCK_VAR}=1, which shows /advisor.`));
1236
+ }
1237
+ io.out(choice === 'off'
1238
+ ? 'Restart sessions that are already running. Undo this with `sideby advisor undo`.'
1239
+ : choice
1240
+ ? `The advisor uses more quota. ${restart} Undo this with \`sideby advisor undo\`.`
1241
+ : 'New sessions go back to the previous setting.');
1242
+ io.out(`Run again with --yes to ${verb}.`);
1243
+ }
1244
+ return 10;
1245
+ }
1246
+ const r = choice
1247
+ ? await rt.advisorSet(choice, accountRef ? { account: accountRef } : {})
1248
+ : await rt.advisorUndo();
1249
+ const results = r.results.map((x) => ({ ...x, file: tildify(x.file, home) }));
1250
+ if (wantJson)
1251
+ out({
1252
+ applied: r.ok,
1253
+ results,
1254
+ ...(choice ? { unlocked: r.unlocked } : {}),
1255
+ unlock: status.unlock || r.unlocked,
1256
+ apiBetasOff: r.apiBetas ?? status.apiBetasOff,
1257
+ message: tilde(r.message, home),
1258
+ });
1259
+ else {
1260
+ for (const x of results)
1261
+ io.out(` ${x.ok ? c.green('ok') : c.red('failed')} ${x.file}: ${x.message}`);
1262
+ if (r.unlocked)
1263
+ io.out(` ${c.green('ok')} sideby config: advisor.unlock true`);
1264
+ if (r.apiBetas !== undefined)
1265
+ io.out(` ${c.green('ok')} sideby config: claude.apiBetasOff ${r.apiBetas ? 'true' : 'back as before'}`);
1266
+ io.out(tilde(r.message, home));
1267
+ }
1268
+ return r.ok ? 0 : 1;
1269
+ }
1024
1270
  const FROM = {
1025
1271
  sideby: 'set by sideby',
1026
1272
  host: 'from the host config',
@@ -1145,7 +1391,13 @@ export async function cmdQuota(a, io) {
1145
1391
  }
1146
1392
  if (sub === 'setup' || sub === 'teardown')
1147
1393
  return cmdQuotaSetup(a, io, sub);
1394
+ if (sub === 'reset')
1395
+ return cmdQuotaReset(a, io);
1396
+ if (a.flags.has('open') || a.flags.has('operation'))
1397
+ throw new UsageError('--open and --operation go with `sideby quota reset <account>`');
1148
1398
  const rt = await createRuntime();
1399
+ // Records of Limit Reset operations that finished a day ago go with the next quota command (spec §3.40).
1400
+ await pruneLimitResetRecords(rt.paths.stateDir, rt.readContext().now).catch(() => { });
1149
1401
  const accounts = !sub
1150
1402
  ? displayOrdered(await rt.accounts(), rt)
1151
1403
  : rt.families.has(sub)
@@ -1169,9 +1421,25 @@ export async function cmdQuota(a, io) {
1169
1421
  return 0;
1170
1422
  }
1171
1423
  const now = new Date();
1424
+ // A reading over an hour old is old only when this computer used the login since (spec §3.31); a Same Login's
1425
+ // sessions count too, read only then.
1426
+ const lastUse = new Map();
1427
+ for (const r of rows) {
1428
+ if (r.quota.status !== 'ok' || !overAnHour(r.quota, now.getTime()))
1429
+ continue;
1430
+ const x = accounts.find((y) => y.ref === r.ref);
1431
+ const peers = await rt.sameLogin(x);
1432
+ const all = peers.length ? (await rt.accounts()).filter((y) => peers.includes(y.ref)) : [];
1433
+ lastUse.set(r.ref, await lastLocalUse(rt, [x, ...all]));
1434
+ }
1435
+ const listed = new Set(rows.map((r) => r.ref));
1172
1436
  io.out(table(rows.map((r) => [
1173
1437
  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)`) : ''}`,
1438
+ // A Same Login's Limit Resets are said once, on the row the reading came from.
1439
+ `${quotaText(r.quota, now, {
1440
+ lastUseAt: lastUse.get(r.ref),
1441
+ resets: !(r.quota.status === 'ok' && r.quota.from && listed.has(r.quota.from)),
1442
+ })}${r.quota.status === 'ok' && r.quota.from ? c.dim(` read from ${r.quota.from} (same login)`) : ''}`,
1175
1443
  usageText(r.usage),
1176
1444
  ]), ['ACCOUNT', 'QUOTA', `USAGE (${USAGE_DAYS}d)`]));
1177
1445
  for (const r of rows) {
@@ -1190,6 +1458,155 @@ export async function cmdQuota(a, io) {
1190
1458
  io.out(c.cyan(`\nTurn on ${s.family} quota with \`sideby quota setup ${s.family}\` (shows the change first).`));
1191
1459
  return 0;
1192
1460
  }
1461
+ /** One window as the Limit Reset plan lists it: its name, used percent and own reset time. */
1462
+ function resetWindowLine(w, now) {
1463
+ const label = w.name ? `${w.name} ${w.label}` : w.label;
1464
+ const passed = Date.parse(w.resetsAt) <= now.getTime();
1465
+ return ` ${label.padEnd(8)} ${String(Math.round(w.usedPercent)).padStart(3)}% used · ${passed ? 'reset time passed' : `resets ${resetWhen(w.resetsAt, now.getTime(), 'en')}`}`;
1466
+ }
1467
+ /**
1468
+ * `sideby quota reset <account> [--yes] [--operation <id>] [--open] [--json]` (spec §3.40, ADR-0072): use a Limit
1469
+ * Reset. Where the Host can spend one (Codex) it shows the plan, read from the Host now, and exits 10; `--yes` spends
1470
+ * one, which cannot be undone. Where only the vendor's page can (Claude Code) it prints the page, and `--open` opens
1471
+ * it. A spend that got no final answer fails with the `operationId` to retry.
1472
+ */
1473
+ export async function cmdQuotaReset(a, io, runtime) {
1474
+ const usage = 'usage: sideby quota reset <account> [--yes] [--operation <id>] [--open] [--json]';
1475
+ const ref = a.positionals[1];
1476
+ if (!ref || a.positionals.length !== 2 || a.rest.length || a.flags.has('refresh'))
1477
+ throw new UsageError(usage);
1478
+ const operation = a.flags.get('operation');
1479
+ const asJson = a.flags.has('json');
1480
+ const rt = runtime ?? (await createRuntime());
1481
+ const now = rt.readContext().now;
1482
+ await pruneLimitResetRecords(rt.paths.stateDir, now).catch(() => { });
1483
+ const account = await rt.resolve(ref);
1484
+ const kind = rt.limitResetKind(account);
1485
+ const f = rt.families.get(account.family);
1486
+ if (kind?.kind === 'page') {
1487
+ if (a.flags.has('yes') || operation !== undefined)
1488
+ 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' });
1489
+ const [quota, st] = await Promise.all([rt.quota(account), rt.status(account)]);
1490
+ const offer = limitResetOffer(quota.status === 'ok' ? quota : null, 'page', now.getTime(), {
1491
+ short: QUOTA_WARN_PERCENT,
1492
+ long: QUOTA_LONG_WARN_PERCENT,
1493
+ });
1494
+ const tight = quota.status === 'ok' ? (offer?.tight ?? []).map((i) => quota.windows[i]) : [];
1495
+ const opened = a.flags.has('open') ? await openVendorPage(rt, account) : undefined;
1496
+ const who = st.identity?.email;
1497
+ 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.`;
1498
+ if (asJson) {
1499
+ json(io, {
1500
+ account: account.ref,
1501
+ outcome: 'open-vendor-page',
1502
+ url: kind.url,
1503
+ opened: Boolean(opened),
1504
+ ...(opened?.profile ? { profile: opened.profile } : {}),
1505
+ ...(who ? { identity: { email: who, ...(st.identity?.org ? { org: st.identity.org } : {}) } } : {}),
1506
+ tight: tight.map((w) => ({
1507
+ label: w.label,
1508
+ ...(w.name ? { name: w.name } : {}),
1509
+ usedPercent: w.usedPercent,
1510
+ resetsAt: w.resetsAt,
1511
+ })),
1512
+ message,
1513
+ });
1514
+ return 0;
1515
+ }
1516
+ io.out(message);
1517
+ io.out(` ${c.bold(kind.url)}`);
1518
+ io.out(who
1519
+ ? `Check that the page is signed in as ${who} (${account.ref}): a reset used there belongs to the login of the page.`
1520
+ : `Check that the page is signed in as the login of ${account.ref}: a reset used there belongs to the login of the page.`);
1521
+ if (tight.length) {
1522
+ io.out('Windows that are tight now:');
1523
+ for (const w of tight)
1524
+ io.out(resetWindowLine(w, now));
1525
+ }
1526
+ io.out(opened
1527
+ ? `${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.`
1528
+ : c.cyan(`Open it with \`sideby quota reset ${account.ref} --open\`.`));
1529
+ return 0;
1530
+ }
1531
+ if (a.flags.has('open')) {
1532
+ if (!f.limitReset?.vendorPage)
1533
+ 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' });
1534
+ // A Family whose Host can use one and that has a vendor page too: `--open` only opens the page, and uses nothing.
1535
+ const opened = await openVendorPage(rt, account);
1536
+ 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}\`.`;
1537
+ if (asJson)
1538
+ json(io, {
1539
+ account: account.ref,
1540
+ outcome: 'open-vendor-page',
1541
+ url: opened.url,
1542
+ opened: true,
1543
+ ...(opened.profile ? { profile: opened.profile } : {}),
1544
+ message,
1545
+ });
1546
+ else
1547
+ io.out(`${c.green('✓')} ${message}`);
1548
+ return 0;
1549
+ }
1550
+ const planLines = (plan) => {
1551
+ const q = plan.quota;
1552
+ const stock = plan.limitResets;
1553
+ return [
1554
+ c.bold(`Use a limit reset for ${plan.account}`),
1555
+ ...(plan.sameLogin.length ? [` Also applies to: ${plan.sameLogin.join(', ')} (same login)`] : []),
1556
+ ...(plan.via !== plan.account ? [` Sent through: ${plan.via}`] : []),
1557
+ ...(q.status === 'ok'
1558
+ ? q.windows.map((w) => resetWindowLine(w, now))
1559
+ : [` quota: ${q.detail ?? q.reason}`]),
1560
+ stock
1561
+ ? ` Limit resets: ${stock.available} available${plan.expectedAfter !== undefined ? ` → ${plan.expectedAfter} expected afterwards` : ''} · ${stock.nextExpiresAt ? `the next one expires ${clock(stock.nextExpiresAt, now)}` : 'expiry unknown'}`
1562
+ : ' Limit resets: unknown',
1563
+ '',
1564
+ plan.message,
1565
+ ];
1566
+ };
1567
+ if (!a.flags.has('yes')) {
1568
+ if (operation !== undefined)
1569
+ throw new UsageError(`--operation goes with --yes; ${usage}`);
1570
+ const plan = await rt.limitResetPlan(account);
1571
+ if (asJson)
1572
+ json(io, { confirmationRequired: plan.canUse, ...plan });
1573
+ else {
1574
+ for (const l of planLines(plan))
1575
+ io.out(l);
1576
+ io.out(plan.canUse
1577
+ ? c.cyan(`\nConfirm with \`sideby quota reset ${account.ref} --yes --operation ${plan.operationId}\`. It cannot be undone.`)
1578
+ : c.yellow(`\nNot possible now: ${plan.blocked}.`));
1579
+ }
1580
+ // 10: the plan is shown and waits for the user's yes (spec §3.9); agents ask before adding --yes.
1581
+ return plan.canUse ? 10 : 1;
1582
+ }
1583
+ let operationId = operation;
1584
+ if (operationId === undefined) {
1585
+ // `--yes` alone: the plan is read first, so a spend never goes out on old numbers. An earlier attempt of this
1586
+ // login that got no final answer is the plan's operation, and is asked again with its own key.
1587
+ const plan = await rt.limitResetPlan(account);
1588
+ if (!asJson)
1589
+ for (const l of planLines(plan))
1590
+ io.out(l);
1591
+ if (!plan.canUse || !plan.operationId)
1592
+ throw new LimitResetError(`${plan.blocked ?? 'this limit reset cannot be used now'}; nothing was sent`, {
1593
+ code: 'cannot-use',
1594
+ });
1595
+ operationId = plan.operationId;
1596
+ if (!asJson)
1597
+ io.out('');
1598
+ }
1599
+ const r = await rt.limitResetUse(account, operationId);
1600
+ const used = r.outcome === 'reset' || r.outcome === 'already-done';
1601
+ if (asJson)
1602
+ json(io, r);
1603
+ else {
1604
+ io.out(`${used ? c.green('✓') : c.yellow('•')} ${r.message}`);
1605
+ if (r.quota)
1606
+ io.out(`${c.bold(r.account)} ${quotaText(r.quota, new Date())}`);
1607
+ }
1608
+ return used ? 0 : 1;
1609
+ }
1193
1610
  async function cmdQuotaSetup(a, io, sub) {
1194
1611
  const familyId = a.positionals[1];
1195
1612
  if (!familyId)
@@ -1873,6 +2290,7 @@ export async function cmdUpdate(a, io) {
1873
2290
  ...(r.refreshedAutostart === undefined ? {} : { refreshedAutostart: r.refreshedAutostart }),
1874
2291
  skill: SKILL_INSTALL,
1875
2292
  ...(r.skillUpdated === undefined ? {} : { skillUpdated: r.skillUpdated }),
2293
+ ...(r.skillMessage === undefined ? {} : { skillMessage: r.skillMessage }),
1876
2294
  ...(r.ok ? {} : { output: r.output }),
1877
2295
  });
1878
2296
  return r.ok ? 0 : 1;
@@ -2789,6 +3207,10 @@ export async function cmdAutostart(a, io) {
2789
3207
  }
2790
3208
  return 0;
2791
3209
  }
3210
+ /** Whether any window of the reading was read over an hour ago (a window may be older than the rest, ADR-0073). */
3211
+ function overAnHour(quota, now) {
3212
+ return !(now - Date.parse(quotaAge(quota, now).observedAt) <= 3600_000);
3213
+ }
2792
3214
  /** The newest session activity among these Accounts, from their Usage; undefined when none can be read. */
2793
3215
  async function lastLocalUse(rt, list) {
2794
3216
  const times = await Promise.all(list.map(async (x) => {
@@ -2827,7 +3249,9 @@ async function menubarFamilies(rt, o = {}) {
2827
3249
  const login = st ? st.login : 'not-needed';
2828
3250
  let refresh;
2829
3251
  if (asks && x.kind === 'subscription' && login !== 'logged-out') {
2830
- const kept = await readQuotaStore(quotaStoreFile(rt.paths.stateDir, x.family, x.name));
3252
+ // A Same Login is asked once, through one of its Accounts (spec §3.26): that answer is this one's.
3253
+ const asked = await rt.quotaAsker(x);
3254
+ const kept = await readQuotaStore(quotaStoreFile(rt.paths.stateDir, asked.family, asked.name));
2831
3255
  const attempted = kept ? Date.parse(kept.attemptedAt) : Number.NaN;
2832
3256
  // The refresh's own snapshot has nothing left waiting: an answer it could not keep counts as failed.
2833
3257
  if (!(attempted >= o.since))
@@ -2836,7 +3260,7 @@ async function menubarFamilies(rt, o = {}) {
2836
3260
  refresh = 'failed';
2837
3261
  }
2838
3262
  // 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;
3263
+ const old = quota.status === 'ok' && overAnHour(quota, now);
2840
3264
  const lastUseAt = old
2841
3265
  ? await lastLocalUse(rt, [x, ...accounts.filter((p) => sameLogin.includes(p.ref))])
2842
3266
  : undefined;
@@ -2857,6 +3281,12 @@ async function menubarFamilies(rt, o = {}) {
2857
3281
  title: f.title,
2858
3282
  logo: f.logo ?? null,
2859
3283
  refreshable: Boolean(f.fetchQuota),
3284
+ ...(f.fetchQuota ? { everyMinutes: f.fetchQuota.everyMinutes } : {}),
3285
+ ...(f.limitReset?.use
3286
+ ? { limitReset: 'use' }
3287
+ : f.limitReset?.vendorPage
3288
+ ? { limitReset: 'page', limitResetSite: new URL(f.limitReset.vendorPage).host }
3289
+ : {}),
2860
3290
  plan,
2861
3291
  accounts: list,
2862
3292
  };
@@ -2875,12 +3305,14 @@ export async function cmdMenubar(a, io) {
2875
3305
  const sinceFlag = a.flags.get('refreshing-since');
2876
3306
  const since = sinceFlag === undefined ? undefined : Date.parse(sinceFlag);
2877
3307
  const cached = a.flags.has('cached');
3308
+ const ask = a.flags.get('ask');
2878
3309
  if (extra !== undefined ||
2879
3310
  (cached && a.flags.has('refresh')) ||
3311
+ (ask !== undefined && (cached || a.flags.has('refresh'))) ||
2880
3312
  (since !== undefined && (!cached || !Number.isFinite(since))) ||
2881
3313
  (reported !== undefined && reported !== 'ok' && reported !== 'taken') ||
2882
3314
  (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]');
3315
+ 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
3316
  const { menubarHotkey, menubarLang, menubarSnapshot } = await import('../menubar/snapshot.js');
2885
3317
  const rt = await createRuntime();
2886
3318
  const hotkey = menubarHotkey(rt.config.menubar?.hotkey);
@@ -2913,6 +3345,13 @@ export async function cmdMenubar(a, io) {
2913
3345
  refreshedSince = Date.now();
2914
3346
  await rt.refreshQuota();
2915
3347
  }
3348
+ // After "Use a reset…" (spec §3.40): that one account is asked once, as its numbers may have changed on the
3349
+ // vendor's page or in the Panel. An account that is gone by now is not an error for the menu.
3350
+ if (ask) {
3351
+ const one = await rt.resolve(ask).catch(() => null);
3352
+ if (one)
3353
+ await rt.refreshQuota([one]).catch(() => { });
3354
+ }
2916
3355
  const families = await menubarFamilies(rt, cached ? { fetch: 'never', since } : { since: refreshedSince, final: true });
2917
3356
  const snap = menubarSnapshot(families, rt.readContext().now, lang, hotkey);
2918
3357
  if (wantJson)
@@ -2971,6 +3410,50 @@ export async function cmdMenubar(a, io) {
2971
3410
  : 'Menu bar shortcut turned off.');
2972
3411
  return 0;
2973
3412
  }
3413
+ if (action === 'reset') {
3414
+ // What "Use a reset…" in the menu runs (spec §3.40, ADR-0072). It only opens a page: the Panel on that account's
3415
+ // confirmation where the Host can use one, the vendor's page where only that can. It never uses one.
3416
+ if (!extra || a.positionals.length > 2)
3417
+ throw new UsageError('usage: sideby menubar reset <account> [--json]');
3418
+ const rt = await createRuntime();
3419
+ const account = await rt.resolve(extra);
3420
+ const kind = rt.limitResetKind(account);
3421
+ if (!kind)
3422
+ 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' });
3423
+ if (kind.kind === 'page') {
3424
+ const r = await openVendorPage(rt, account);
3425
+ if (wantJson)
3426
+ json(io, {
3427
+ account: account.ref,
3428
+ url: r.url,
3429
+ opened: true,
3430
+ ...(r.profile ? { profile: r.profile.name } : {}),
3431
+ });
3432
+ else
3433
+ io.out(`Opened ${r.url} for ${account.ref}${r.profile ? ` in the browser profile ${r.profile.name}` : ''}.`);
3434
+ return 0;
3435
+ }
3436
+ const bg = await import('../panel/background.js');
3437
+ const { openBrowser } = await import('../panel/server.js');
3438
+ const paths = resolvePaths();
3439
+ const panel = await bg.startBackgroundPanel({ paths, env: process.env, entry: cliEntry() });
3440
+ const url = `${panel.url.replace(/#.*$/, '')}#reset=${encodeURIComponent(account.ref)}`;
3441
+ // The browser is started detached and does not keep this process alive, so a short timer waits for its answer;
3442
+ // without one, the page is taken as opened.
3443
+ let timer;
3444
+ const opened = await Promise.race([
3445
+ openBrowser(url),
3446
+ new Promise((done) => {
3447
+ timer = setTimeout(() => done(true), 3000);
3448
+ }),
3449
+ ]);
3450
+ clearTimeout(timer);
3451
+ if (wantJson)
3452
+ json(io, { account: account.ref, url, opened });
3453
+ else
3454
+ io.out(opened ? `Opened the panel on ${account.ref}'s limit reset.` : `Open ${url} in your browser.`);
3455
+ return opened ? 0 : 1;
3456
+ }
2974
3457
  if (action === 'start') {
2975
3458
  if (!extra || a.positionals.length > 2)
2976
3459
  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. */