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
@@ -1,4 +1,4 @@
1
- import { bindingWindow, openWindows, quotaIsStale, windowLevel, worseLevel, } from '../core/quota-levels.js';
1
+ import { bindingWindow, limitResetOffer, openWindows, QUOTA_LONG_WARN_PERCENT, QUOTA_WARN_PERCENT, quotaAge, windowLevel, worseLevel, } from '../core/quota-levels.js';
2
2
  import { resetDate, resetWhen } from '../panel/page-logic.js';
3
3
  import { fill, MENUBAR_STRINGS } from './strings.js';
4
4
  export const DEFAULT_MENUBAR_HOTKEY = 'opt+x';
@@ -194,8 +194,8 @@ function observedText(observedAt, now, s) {
194
194
  return s.observedJustNow;
195
195
  return fill(s.observedAgo, { time: durationText(minutes, s) });
196
196
  }
197
- function row(a, plan, now, s, refreshable, lang) {
198
- const r = quotaRow(a, plan, now, s, refreshable, lang);
197
+ function row(a, plan, now, s, refreshable, lang, everyMinutes, limitReset) {
198
+ const r = quotaRow(a, plan, now, s, refreshable, lang, everyMinutes, limitReset);
199
199
  if (!a.refresh)
200
200
  return r;
201
201
  // A manual refresh in progress (spec §3.31): the old bars stay, and the reset cell says where the refresh stands.
@@ -212,7 +212,7 @@ function row(a, plan, now, s, refreshable, lang) {
212
212
  detail: [r.detail, says].filter(Boolean).join(s.sep),
213
213
  };
214
214
  }
215
- function quotaRow(a, plan, now, s, refreshable, lang) {
215
+ function quotaRow(a, plan, now, s, refreshable, lang, everyMinutes, limitReset) {
216
216
  const recommended = Boolean(plan?.hasQuota && plan.pick === a.ref);
217
217
  const startTip = fill(s.startTip, { account: a.ref });
218
218
  const base = {
@@ -238,9 +238,12 @@ function quotaRow(a, plan, now, s, refreshable, lang) {
238
238
  const quota = a.quota;
239
239
  if (quota.status !== 'ok')
240
240
  return noted(s.noData);
241
- const stale = quotaIsStale(quota, now.getTime(), a.lastUseAt);
241
+ // Each window by its own read time (ADR-0073): a model group kept under a newer plan reading may be older.
242
+ const ageOf = (windows) => quotaAge({ ...quota, windows }, now.getTime(), a.lastUseAt, everyMinutes);
243
+ const age = ageOf(quota.windows);
244
+ const stale = age.stale;
242
245
  // Over an hour old but unused here since: the numbers stand, and the hover text says what it cannot see.
243
- const quiet = !stale && now.getTime() - Date.parse(quota.observedAt) > 3600_000;
246
+ const quiet = !stale && age.quiet;
244
247
  // The head of the hover text: when the numbers were read, and why they may be old.
245
248
  const head = [
246
249
  observedText(quota.observedAt, now, s),
@@ -248,27 +251,80 @@ function quotaRow(a, plan, now, s, refreshable, lang) {
248
251
  ...(quiet ? [s.quietTip] : []),
249
252
  ...(quota.fetchError ? [fill(s.fetchFailed, { error: quota.fetchError })] : []),
250
253
  ];
254
+ // The Limit Resets the Host tells (ADR-0072): a quiet note on the row, with the next expiry in the hover text.
255
+ const stock = quota.limitResets && quota.limitResets.available > 0 ? quota.limitResets : null;
256
+ const resetsNote = stock
257
+ ? stock.available === 1
258
+ ? s.limitResetsOne
259
+ : fill(s.limitResetsMany, { n: stock.available })
260
+ : '';
261
+ const resetsTip = stock
262
+ ? [
263
+ '',
264
+ fill(s.limitResetsTip, { n: stock.available }),
265
+ ...(stock.nextExpiresAt
266
+ ? [fill(s.limitResetsExpiry, { date: resetDate(stock.nextExpiresAt, now.getTime(), lang) })]
267
+ : []),
268
+ ]
269
+ : [];
270
+ const minutesOld = Math.floor((now.getTime() - Date.parse(age.observedAt)) / 60000);
271
+ const ageNote = age.showAge && Number.isFinite(minutesOld) && minutesOld >= 1
272
+ ? fill(s.readAgo, { time: durationText(minutesOld, s) })
273
+ : '';
274
+ // The line that leads to using one: where the Host can, whenever the Account holds one; where only the vendor's
275
+ // page can, once a window is at its warning level, as sideby cannot see the count.
276
+ const offered = limitReset?.kind === 'use'
277
+ ? stock !== null
278
+ : limitReset?.kind === 'page' &&
279
+ limitResetOffer(quota, 'page', now.getTime(), {
280
+ short: QUOTA_WARN_PERCENT,
281
+ long: QUOTA_LONG_WARN_PERCENT,
282
+ }) !== null;
283
+ const extra = {
284
+ ...(offered
285
+ ? {
286
+ useReset: {
287
+ title: s.useReset,
288
+ tip: limitReset.kind === 'use'
289
+ ? s.useResetTip
290
+ : fill(s.useResetPageTip, { site: limitReset.site ?? '' }),
291
+ },
292
+ }
293
+ : {}),
294
+ ...(resetsNote ? { limitResets: resetsNote } : {}),
295
+ ...(ageNote ? { age: ageNote } : {}),
296
+ };
251
297
  // Every window is past its reset: Refresh asks now, where the Family can be asked.
252
298
  const due = (d) => (d.allPassed && refreshable ? [s.resetDueTip] : []);
253
299
  const groups = quotaGroups(quota);
254
300
  if (groups) {
255
301
  // One line per model group under the account, each with its own 5h and 7d bars (spec §3.31). Windows that cover
256
302
  // every model (Cursor's plan total) keep their bars on the account's own line.
257
- const drawnGroups = groups.map((g) => ({ name: g.name, d: drawn(g.quota, now, s, lang) }));
303
+ const drawnGroups = groups.map((g) => ({
304
+ name: g.name,
305
+ d: drawn(g.quota, now, s, lang),
306
+ age: ageOf(g.quota.windows),
307
+ }));
258
308
  const groupTip = (g) => [
259
309
  g.name,
260
310
  ...g.d.lines.map((l) => ` ${l}`),
311
+ // A group read at another time than the rest says when.
312
+ ...(g.age.observedAt !== quota.observedAt ? [` ${observedText(g.age.observedAt, now, s)}`] : []),
261
313
  ...due(g.d).map((l) => ` ${l}`),
262
314
  ];
263
315
  const all = openWindows(quota, now) ? drawn(quota, now, s, lang) : null;
316
+ const ownStale = all ? ageOf(quota.windows.filter((w) => !w.name)).stale : stale;
264
317
  return {
265
318
  ...base,
319
+ ...extra,
266
320
  observedAt: quota.observedAt,
267
321
  stale,
322
+ ...(ownStale !== stale ? { barsStale: ownStale } : {}),
268
323
  detail: [
269
324
  ...(all ? [all.parts.join(' ')] : []),
270
325
  ...drawnGroups.map((g) => `${groupLabel(g.name)} ${g.d.parts.join(' ')}`),
271
326
  ...(stale ? [s.olderReading] : []),
327
+ ...(resetsNote ? [resetsNote] : []),
272
328
  ].join(s.sep),
273
329
  level: drawnGroups.reduce((l, g) => worseLevel(l, g.d.level), all?.level ?? 'ok'),
274
330
  tip: [
@@ -276,6 +332,7 @@ function quotaRow(a, plan, now, s, refreshable, lang) {
276
332
  '',
277
333
  ...(all ? [...all.lines, ...due(all), ''] : []),
278
334
  ...drawnGroups.flatMap(groupTip),
335
+ ...resetsTip,
279
336
  '',
280
337
  startTip,
281
338
  ].join('\n'),
@@ -294,8 +351,9 @@ function quotaRow(a, plan, now, s, refreshable, lang) {
294
351
  resetLabel: g.d.resetLabel,
295
352
  resetTime: g.d.resetTime,
296
353
  tip: [...head, '', ...groupTip(g), '', startTip].join('\n'),
354
+ ...(g.age.stale !== stale ? { stale: g.age.stale } : {}),
297
355
  })),
298
- note: stale ? s.olderReading : '',
356
+ note: ownStale ? s.olderReading : '',
299
357
  };
300
358
  }
301
359
  if (openWindows(quota, now) === null)
@@ -308,13 +366,16 @@ function quotaRow(a, plan, now, s, refreshable, lang) {
308
366
  parts.push(s.resetDue);
309
367
  if (stale)
310
368
  parts.push(s.olderReading);
369
+ if (resetsNote)
370
+ parts.push(resetsNote);
311
371
  return {
312
372
  ...base,
373
+ ...extra,
313
374
  observedAt: quota.observedAt,
314
375
  stale,
315
376
  detail: parts.join(s.sep),
316
377
  level: d.level,
317
- tip: [...head, '', ...d.lines, ...due(d), '', startTip].join('\n'),
378
+ tip: [...head, '', ...d.lines, ...due(d), ...resetsTip, '', startTip].join('\n'),
318
379
  bars: d.bars,
319
380
  reset: d.reset,
320
381
  resetLabel: d.resetLabel,
@@ -339,7 +400,12 @@ function section(f, now, s, lang) {
339
400
  ...(f.logo.gradients?.length ? { gradients: f.logo.gradients } : {}),
340
401
  }
341
402
  : null;
342
- const all = f.accounts.map((a) => ({ a, r: row(a, f.plan, now, s, f.refreshable !== false, lang) }));
403
+ const all = f.accounts.map((a) => ({
404
+ a,
405
+ r: row(a, f.plan, now, s, f.refreshable !== false, lang, f.everyMinutes, f.limitReset
406
+ ? { kind: f.limitReset, ...(f.limitResetSite ? { site: f.limitResetSite } : {}) }
407
+ : undefined),
408
+ }));
343
409
  const aside = (a) => a.kind === 'api' || a.login === 'logged-out';
344
410
  // A Same Login is one quota, so one row, named like the Panel's: after the directory first in Display Order (the
345
411
  // Panel's "Set as shown name" moves one there). It is recommended when any of its directories is. The other
@@ -370,10 +436,12 @@ function section(f, now, s, lang) {
370
436
  : lead);
371
437
  for (const y of others) {
372
438
  const note = y.a.loginExpired ? s.loginExpired : fill(s.sameLoginNote, { name: lead.a.name });
439
+ // The shared Quota, its Limit Resets and its age are said once, on the row that leads the login.
440
+ const { limitResets: _resets, age: _age, useReset: _use, ...rest } = y.r;
373
441
  same.push({
374
442
  ...y,
375
443
  r: {
376
- ...y.r,
444
+ ...rest,
377
445
  bars: null,
378
446
  reset: '',
379
447
  resetLabel: '',
@@ -30,6 +30,14 @@ export declare const MENUBAR_STRINGS: {
30
30
  readonly olderReadingSessionTip: 'These numbers may be old · they update when a session runs in this account';
31
31
  readonly quietTip: 'Not used on this computer since · use on the web or other computers is not included';
32
32
  readonly fetchFailed: 'The last check failed: {error}';
33
+ readonly readAgo: 'read {time} ago';
34
+ readonly limitResetsOne: '1 reset available';
35
+ readonly limitResetsMany: '{n} resets available';
36
+ readonly limitResetsTip: 'Limit resets: {n} available · using one restores quota before a window resets by itself';
37
+ readonly limitResetsExpiry: 'The next one expires {date}';
38
+ readonly useReset: 'Use a reset…';
39
+ readonly useResetTip: 'Opens the Panel, which shows what a reset would do and asks before using one';
40
+ readonly useResetPageTip: 'Opens {site}, where a reset is used · sideby cannot see whether this account holds one';
33
41
  readonly windowTip: '{label}: {p}% used';
34
42
  readonly windowResetsTip: '{label}: {p}% used · resets {date} (in {left})';
35
43
  readonly windowPassedTip: '{label}: reset at {date} · new numbers come with the next check';
@@ -99,6 +107,14 @@ export declare const MENUBAR_STRINGS: {
99
107
  readonly olderReadingSessionTip: '这些数字可能已经过时 · 在这个账号开一次会话就会更新';
100
108
  readonly quietTip: '之后这台电脑没用过这个账号 · 网页或其他电脑上的用量不在内';
101
109
  readonly fetchFailed: '上次检查没成功:{error}';
110
+ readonly readAgo: '{time}前读取';
111
+ readonly limitResetsOne: '可用重置 1 次';
112
+ readonly limitResetsMany: '可用重置 {n} 次';
113
+ readonly limitResetsTip: '重置次数:可用 {n} 次 · 用一次能在窗口自己重置之前恢复额度';
114
+ readonly limitResetsExpiry: '最近一次 {date} 到期';
115
+ readonly useReset: '使用重置…';
116
+ readonly useResetTip: '打开面板:先看这次重置会带来什么,确认后才使用';
117
+ readonly useResetPageTip: '打开 {site},在那里使用重置 · sideby 看不到这个账号有没有可用的重置';
102
118
  readonly windowTip: '{label}:已用 {p}%';
103
119
  readonly windowResetsTip: '{label}:已用 {p}% · {date} 重置({left}后)';
104
120
  readonly windowPassedTip: '{label}:已于 {date} 重置 · 下次检查时更新';
@@ -30,6 +30,14 @@ export const MENUBAR_STRINGS = {
30
30
  olderReadingSessionTip: 'These numbers may be old · they update when a session runs in this account',
31
31
  quietTip: 'Not used on this computer since · use on the web or other computers is not included',
32
32
  fetchFailed: 'The last check failed: {error}',
33
+ readAgo: 'read {time} ago',
34
+ limitResetsOne: '1 reset available',
35
+ limitResetsMany: '{n} resets available',
36
+ limitResetsTip: 'Limit resets: {n} available · using one restores quota before a window resets by itself',
37
+ limitResetsExpiry: 'The next one expires {date}',
38
+ useReset: 'Use a reset…',
39
+ useResetTip: 'Opens the Panel, which shows what a reset would do and asks before using one',
40
+ useResetPageTip: 'Opens {site}, where a reset is used · sideby cannot see whether this account holds one',
33
41
  windowTip: '{label}: {p}% used',
34
42
  windowResetsTip: '{label}: {p}% used · resets {date} (in {left})',
35
43
  windowPassedTip: '{label}: reset at {date} · new numbers come with the next check',
@@ -99,6 +107,14 @@ export const MENUBAR_STRINGS = {
99
107
  olderReadingSessionTip: '这些数字可能已经过时 · 在这个账号开一次会话就会更新',
100
108
  quietTip: '之后这台电脑没用过这个账号 · 网页或其他电脑上的用量不在内',
101
109
  fetchFailed: '上次检查没成功:{error}',
110
+ readAgo: '{time}前读取',
111
+ limitResetsOne: '可用重置 1 次',
112
+ limitResetsMany: '可用重置 {n} 次',
113
+ limitResetsTip: '重置次数:可用 {n} 次 · 用一次能在窗口自己重置之前恢复额度',
114
+ limitResetsExpiry: '最近一次 {date} 到期',
115
+ useReset: '使用重置…',
116
+ useResetTip: '打开面板:先看这次重置会带来什么,确认后才使用',
117
+ useResetPageTip: '打开 {site},在那里使用重置 · sideby 看不到这个账号有没有可用的重置',
102
118
  windowTip: '{label}:已用 {p}%',
103
119
  windowResetsTip: '{label}:已用 {p}% · {date} 重置({left}后)',
104
120
  windowPassedTip: '{label}:已于 {date} 重置 · 下次检查时更新',
@@ -1,4 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { type AdvisorStatus } from '../core/advisor.ts';
2
3
  import { type AppProfileStatus } from '../core/app-profiles.ts';
3
4
  import { type AutostartContext, type AutostartStatus } from '../core/autostart.ts';
4
5
  import { type BrowserReport } from '../core/browser-profiles.ts';
@@ -168,6 +169,15 @@ export type PanelFamily = FamilyInfo & {
168
169
  aiTaskSafe?: true;
169
170
  /** "Refresh" can ask the Host for its Quota (`fetchQuota`); without it old numbers wait for a session (spec §3.31). */
170
171
  quotaRefresh?: true;
172
+ /** How often sideby asks this Host for Quota, in minutes: a number older than this says its age (ADR-0073). */
173
+ quotaEvery?: number;
174
+ /**
175
+ * How a Limit Reset of its Subscription Accounts is spent (ADR-0072): `use` through the Host after a confirmation,
176
+ * `page` only on the vendor's page (`limitResetPage`). Absent when the Family offers neither.
177
+ */
178
+ limitReset?: 'use' | 'page';
179
+ /** The vendor's page where a Limit Reset is spent, when the Family names one. */
180
+ limitResetPage?: string;
171
181
  };
172
182
  /** What the Panel shows about updates (spec §3.23); absent when the handler was created with `updates: false`. */
173
183
  export interface PanelUpdate {
@@ -216,6 +226,11 @@ export interface PanelState {
216
226
  /** Config `ask.permissions` when it is `account` (ADR-0070): AI Tasks start with the Account's own arguments. */
217
227
  aiTaskPermissions?: 'account';
218
228
  accounts: PanelAccount[];
229
+ /**
230
+ * The Accounts whose Host is being asked for Quota right now, behind the kept answer on show (spec §3.26); the page
231
+ * reads the state again soon, so each row takes its new numbers as they land. Left out when none is.
232
+ */
233
+ quotaAsking?: string[];
219
234
  pluginErrors: {
220
235
  where: string;
221
236
  message: string;
@@ -262,6 +277,11 @@ export interface PanelState {
262
277
  };
263
278
  /** Claude settings files grouped as `sideby remote-control` shows them (spec §3.22); absent without Claude Accounts. */
264
279
  remoteControl?: RemoteControlView[];
280
+ /**
281
+ * Claude Code's advisor as `sideby advisor --json` shows it (spec §3.41): the settings files of Claude subscription
282
+ * Accounts and whether sideby unlocks it at launch; absent without such Accounts.
283
+ */
284
+ advisor?: AdvisorView;
265
285
  /** Grok Bot windows (ADR-0019), data folders shown as `~/…`; absent when there are none to show. */
266
286
  appProfiles?: AppProfileStatus[];
267
287
  /** Update Check result and Auto Update setting (spec §3.23); absent with `updates: false`. */
@@ -340,6 +360,7 @@ export declare function handoffByFamily(rt: Runtime, accounts: readonly PanelAcc
340
360
  export type RemoteControlView = Omit<RemoteControlGroup, 'file'> & {
341
361
  file: string;
342
362
  };
363
+ export type AdvisorView = AdvisorStatus;
343
364
  /**
344
365
  * How long one state waits for an Account's reads. A slower Account (a plugin reader that hangs, a Host that answers
345
366
  * late) is sent as pending, so it does not hold up every other row; its reads go on and the next state picks up the
@@ -2,12 +2,13 @@
2
2
  import { randomBytes, timingSafeEqual } from 'node:crypto';
3
3
  import { realpath } from 'node:fs/promises';
4
4
  import { aliasesByAccount, startArgsOf } from '../core/accounts.js';
5
+ import { advisorPlan, advisorScope, checkAdvisorAccount, isAdvisorChoice, } from '../core/advisor.js';
5
6
  import { listAppProfiles, openAppProfile, removeAppProfile, } from '../core/app-profiles.js';
6
7
  import { openLoginInTerminal, openPickInTerminal, pickTaskAccount, previewAttachments, promptForTask, setCustomTerminal, setPreferredTerminal, startAiTask, taskContext, terminals, tryAccount, } from '../core/ask.js';
7
8
  import { ATTACHMENT_LIMITS, MAX_ATTACHMENTS, MAX_UPLOAD_BYTES, removeStaged, stagedAttachments, stageUpload, } from '../core/attachments.js';
8
9
  import { applyAutostart, autostartStatus, PANEL_AGENT, planAutostart, } from '../core/autostart.js';
9
10
  import { FAVICON_SVG, ICON_SVG } from '../core/brand-mark.js';
10
- import { browserReport, openInBrowser, setBrowserChoice, setBrowserSignIns, } from '../core/browser-profiles.js';
11
+ import { browserReport, openInBrowser, openVendorPage, setBrowserChoice, setBrowserSignIns, } from '../core/browser-profiles.js';
11
12
  import { aiTaskPermissions, aliasArgs, aliasRefs, EDITORS, editConfigPanel, editConfigPath, editConfigTerminal, editConfigUpdate, loadConfig, } from '../core/config.js';
12
13
  import { openDesktopApp, withDesktopApps } from '../core/desktop-app.js';
13
14
  import { editSettings, isEditor } from '../core/edit-settings.js';
@@ -18,11 +19,13 @@ import { handoffOverview } from '../core/handoff-overview.js';
18
19
  import { apiUndecided, handoffRulesView } from '../core/handoff-rules.js';
19
20
  import { configureHandoff, handoffStatus } from '../core/handoff-status.js';
20
21
  import { acceptInbound, groupsToAccept, inboundGroups, undoInbound, waitingFiles, } from '../core/inbound.js';
22
+ import { LimitResetError } from '../core/limit-reset.js';
21
23
  import { accountLabels, listLiveSessions, liveKey, referenceText, resumeCommandFor, sessionCopyText, } from '../core/live-sessions.js';
22
24
  import { listMessages, sendMessage } from '../core/messages.js';
23
25
  import { accountModel, setAccountModel } from '../core/model-choice.js';
24
26
  import { GUARDED_FAMILIES, setNetwork } from '../core/network.js';
25
27
  import { tildify } from '../core/paths.js';
28
+ import { quotaAsking } from '../core/quota-fetch.js';
26
29
  import { takeoverLimits } from '../core/quota-levels.js';
27
30
  import { remoteControlTodo } from '../core/remote-control.js';
28
31
  import { openRunBoard, withRuns } from '../core/run-link.js';
@@ -102,7 +105,13 @@ function keyFacts(def, permissions) {
102
105
  ...(def.secretFileMeansApi === false ? { keyAlways: true } : {}),
103
106
  ...(def.probe ? { tryCommand: [def.bin, ...def.probe.args] } : {}),
104
107
  ...(def.aiTaskArgs && permissions === 'checked' ? { aiTaskSafe: true } : {}),
105
- ...(def.fetchQuota ? { quotaRefresh: true } : {}),
108
+ ...(def.fetchQuota ? { quotaRefresh: true, quotaEvery: def.fetchQuota.everyMinutes } : {}),
109
+ ...(def.limitReset?.use
110
+ ? { limitReset: 'use' }
111
+ : def.limitReset?.vendorPage
112
+ ? { limitReset: 'page' }
113
+ : {}),
114
+ ...(def.limitReset?.vendorPage ? { limitResetPage: def.limitReset.vendorPage } : {}),
106
115
  };
107
116
  }
108
117
  let autostartOverride = {};
@@ -485,9 +494,26 @@ async function accountState(rt, account, families) {
485
494
  ...(errors.length ? { error: errors.join('; ') } : {}),
486
495
  };
487
496
  }
497
+ /** The model an advisor request asks for, and the Account it is limited to (a ref), checked. */
498
+ async function advisorBody(rt, body) {
499
+ if (!isAdvisorChoice(body.to))
500
+ throw new HttpError(400, '"to" must be "fable", "opus", "sonnet" or "off"');
501
+ const ref = optString(body, 'account');
502
+ return ref ? { to: body.to, account: checkAdvisorAccount(await rt.resolve(ref)).ref } : { to: body.to };
503
+ }
488
504
  function rcView(groups, home) {
489
505
  return groups.map((g) => ({ ...g, file: tildify(g.file, home) }));
490
506
  }
507
+ function advisorView(st, home) {
508
+ return {
509
+ ...st,
510
+ groups: st.groups.map((g) => ({
511
+ ...g,
512
+ file: tildify(g.file, home),
513
+ ...(g.reason ? { reason: g.reason.split(home).join('~') } : {}),
514
+ })),
515
+ };
516
+ }
491
517
  /**
492
518
  * How long one state waits for an Account's reads. A slower Account (a plugin reader that hangs, a Host that answers
493
519
  * late) is sent as pending, so it does not hold up every other row; its reads go on and the next state picks up the
@@ -557,12 +583,13 @@ async function timedAccountState(rt, account, families, mine) {
557
583
  }
558
584
  async function buildState(rt, opts) {
559
585
  const ctx = rt.readContext();
560
- const [families, accounts, history, quotaSetups, remoteControl, upd] = await Promise.all([
586
+ const [families, accounts, history, quotaSetups, remoteControl, advisor, upd] = await Promise.all([
561
587
  rt.familyInfo(),
562
588
  rt.accounts(),
563
589
  rt.doctorHistory(),
564
590
  rt.quotaSetups(),
565
591
  rt.remoteControl(),
592
+ rt.advisor(),
566
593
  opts.updates ? updateState(rt, opts.readOnly).catch(() => undefined) : Promise.resolve(undefined),
567
594
  ]);
568
595
  const health = healthByAccount(history);
@@ -574,11 +601,19 @@ async function buildState(rt, opts) {
574
601
  if (!accounts.some((a) => a.ref === ref))
575
602
  opts.readings.delete(ref);
576
603
  const aliases = aliasesByAccount(aliasRefs(rt.config.aliases), accounts);
604
+ // Asks in flight before the reads start: one that ends while they run may have left a row with the older numbers.
605
+ const askingOf = () => accounts.filter((a) => quotaAsking(rt.paths.stateDir, a.family, a.name)).map((a) => a.ref);
606
+ const askingBefore = askingOf();
577
607
  // Desktop Apps (spec §3.20): one process listing for every Account, run alongside the per-Account reads.
578
608
  const [states, appProfiles] = await Promise.all([
579
609
  withDesktopApps(rt, accounts, Promise.all(accounts.map((a) => timedAccountState(rt, a, families, opts.readings)))),
580
610
  listAppProfiles(rt),
581
611
  ]);
612
+ // A Same Login is asked through one of its Accounts, so every Account of it is waiting for that answer.
613
+ const askingNow = new Set([...askingBefore, ...askingOf()]);
614
+ const asking = states
615
+ .filter((st) => askingNow.has(st.ref) || (st.sameLogin ?? []).some((r) => askingNow.has(r)))
616
+ .map((st) => st.ref);
582
617
  const list = states.map((st) => {
583
618
  const h = health.get(st.ref);
584
619
  const names = aliases.get(st.ref);
@@ -638,6 +673,7 @@ async function buildState(rt, opts) {
638
673
  shellSetup: { ...shellSt, rc: tildify(shellSt.rc, ctx.home), block: setupBlock(shellSt.shell) },
639
674
  ...(Object.keys(handoff).length ? { handoff } : {}),
640
675
  ...(remoteControl.length ? { remoteControl: rcView(remoteControl, ctx.home) } : {}),
676
+ ...(advisor.groups.length ? { advisor: advisorView(advisor, ctx.home) } : {}),
641
677
  ...(appProfiles.length
642
678
  ? {
643
679
  appProfiles: appProfiles.map((p) => p.appData ? { ...p, appData: tildify(p.appData, rt.paths.home) } : p),
@@ -653,6 +689,7 @@ async function buildState(rt, opts) {
653
689
  ...(upd ? { update: upd } : {}),
654
690
  ...(showBrowser ? { browser } : {}),
655
691
  display: rt.displayOrder(),
692
+ ...(asking.length ? { quotaAsking: asking } : {}),
656
693
  ...(rt.quotaChecks().length ? { quotaChecks: rt.quotaChecks() } : {}),
657
694
  ...(rt.config.panel && Object.keys(rt.config.panel).length ? { panel: rt.config.panel } : {}),
658
695
  ...(network ? { network } : {}),
@@ -1044,24 +1081,41 @@ export function createPanelHandler(opts) {
1044
1081
  * A change of one key in Claude's settings files that the page showed file by file before the user confirmed
1045
1082
  * (Remote Control, spec §3.22; receiving Messages, ADR-0045). Without `confirm` it writes nothing and names the
1046
1083
  * files; with it, `files` must be exactly the files the page showed, or nothing is written and `changedSince` says
1047
- * so, because a file the user never saw in the preview must not change. Undo passes no `todo`: it only puts back
1048
- * what sideby wrote, and its toast runs before the page has read the new state.
1084
+ * so, because a file the user never saw in the preview must not change. Where what a file holds decides what the
1085
+ * write does (Advisor: whether `env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` goes too), `shown` names that part of a
1086
+ * group: the page sends the groups it showed as `groups`, and a file whose part differs now refuses the same way.
1087
+ * Remote Control and receiving Messages need none: they write one fixed value, whatever the file held. Undo passes
1088
+ * no `todo`: it only puts back what sideby wrote, only while the file still holds that (spec §3.22), and its toast
1089
+ * runs before the page has read the new state.
1049
1090
  */
1050
1091
  const previewedChange = (change) => ({
1051
1092
  writes: (body) => body.confirm === true,
1052
1093
  async run(body) {
1053
1094
  const rt = await getRuntime();
1054
1095
  const home = rt.paths.home;
1055
- const files = change.todo ? (await change.todo(rt)).map((g) => tildify(g.file, home)) : undefined;
1096
+ const raw = change.todo ? await change.todo(rt, body) : undefined;
1097
+ const todo = raw?.map((g) => ({ ...g, file: tildify(g.file, home) }));
1098
+ const files = todo?.map((g) => g.file);
1056
1099
  if (!optBool(body, 'confirm'))
1057
1100
  return { applied: false, ...(files ? { files } : {}) };
1058
- if (files) {
1101
+ if (todo && files) {
1059
1102
  const saw = body.files;
1060
1103
  const same = Array.isArray(saw) && saw.length === files.length && files.every((f) => saw.includes(f));
1061
1104
  if (!same)
1062
1105
  return { applied: false, changedSince: true, files };
1106
+ const shown = change.shown;
1107
+ if (shown) {
1108
+ const seen = (Array.isArray(body.groups) ? body.groups : []).filter((x) => typeof x === 'object' && x !== null && !Array.isArray(x));
1109
+ const key = (g) => JSON.stringify(shown(g) ?? null);
1110
+ const alike = todo.every((g) => {
1111
+ const s = seen.find((x) => x.file === g.file);
1112
+ return s !== undefined && key(s) === key(g);
1113
+ });
1114
+ if (!alike)
1115
+ return { applied: false, changedSince: true, files };
1116
+ }
1063
1117
  }
1064
- const r = await change.apply(rt);
1118
+ const r = await change.apply(rt, body, raw);
1065
1119
  return { ...r, applied: true, results: r.results.map((x) => ({ ...x, file: tildify(x.file, home) })) };
1066
1120
  },
1067
1121
  });
@@ -1430,6 +1484,33 @@ export function createPanelHandler(opts) {
1430
1484
  apply: (rt) => rt.remoteControlOn(),
1431
1485
  }),
1432
1486
  '/api/remote-control/undo': previewedChange({ apply: (rt) => rt.remoteControlUndo() }),
1487
+ // Claude Code's advisor (spec §3.41, ADR-0074): the same change as `sideby advisor <model>|off [--account]`. It
1488
+ // writes `advisorModel` only into the files the page showed (`previewedChange`); a model also turns config
1489
+ // `advisor.unlock` on, and config `claude.apiBetasOff` where the variable leaves a file API Accounts share, both
1490
+ // of which the page shows from the state it read.
1491
+ '/api/advisor/set': previewedChange({
1492
+ async todo(rt, body) {
1493
+ const { to, account } = await advisorBody(rt, body);
1494
+ const st = await rt.advisor();
1495
+ return advisorPlan(advisorScope(st.groups, account), to, st).todo;
1496
+ },
1497
+ // What decides the write besides the model the body names: the env entry it removes, and who shares the file.
1498
+ shown: (g) => [g.state ?? null, g.model ?? null, g.betasValue ?? null, g.apiAccounts ?? []],
1499
+ // The files as the page showed them, checked again under each file's lock right before the write.
1500
+ async apply(rt, body, checked) {
1501
+ const { to, account } = await advisorBody(rt, body);
1502
+ return rt.advisorSet(to, { ...(account ? { account } : {}), ...(checked ? { seen: checked } : {}) });
1503
+ },
1504
+ }),
1505
+ '/api/advisor/undo': previewedChange({ apply: (rt) => rt.advisorUndo() }),
1506
+ // Config `advisor.unlock` only: sideby's own setting, so the switch writes at once and the toast offers the way back.
1507
+ '/api/advisor/unlock': {
1508
+ async run(body) {
1509
+ if (typeof body.on !== 'boolean')
1510
+ throw new HttpError(400, '"on" must be true or false');
1511
+ return (await getRuntime()).advisorUnlock(body.on);
1512
+ },
1513
+ },
1433
1514
  // Sessions (spec §3.32, ADR-0039): what every Account is running now, read only, with the texts its copy buttons
1434
1515
  // copy in the Panel's language. Polled every few seconds, so it runs beside the write queue.
1435
1516
  '/api/sessions': {
@@ -2096,6 +2177,7 @@ export function createPanelHandler(opts) {
2096
2177
  restartedPanel: r.restartedPanel,
2097
2178
  refreshedApp: r.refreshedApp,
2098
2179
  ...(r.skillUpdated === undefined ? {} : { skillUpdated: r.skillUpdated }),
2180
+ ...(r.skillMessage === undefined ? {} : { skillMessage: r.skillMessage }),
2099
2181
  ...(r.skillSyncStarted === undefined ? {} : { skillSyncStarted: r.skillSyncStarted }),
2100
2182
  };
2101
2183
  },
@@ -2162,14 +2244,48 @@ export function createPanelHandler(opts) {
2162
2244
  return { display: await rt.setDisplayOrder(display) };
2163
2245
  },
2164
2246
  },
2165
- // Asks every Family that fetches Quota again now, and waits (spec §3.26); the page reloads its state after.
2247
+ // Asks every Family that fetches Quota again now, and waits (spec §3.26); the page reloads its state after. With
2248
+ // `account`, only that Account (its Same Login is asked once): the one ask after a jump to the vendor's page.
2166
2249
  '/api/quota/refresh': {
2167
- async run() {
2250
+ async run(body) {
2168
2251
  const rt = await getRuntime();
2169
- await rt.refreshQuota();
2252
+ const account = optString(body, 'account');
2253
+ await rt.refreshQuota(account ? [await rt.resolve(account)] : undefined);
2170
2254
  return { ok: true };
2171
2255
  },
2172
2256
  },
2257
+ // Using a Limit Reset (spec §3.40, ADR-0072). Without `confirm`: the plan, read from the Host now, and the
2258
+ // operation to confirm; nothing is spent. With `confirm` and that `operationId`: one spend, which cannot be
2259
+ // undone, then the Quota read again. Beside the write queue: the Runtime's own lock makes spends take turns, and
2260
+ // a Host that is slow to answer must not hold other changes back.
2261
+ '/api/quota/reset': {
2262
+ queued: false,
2263
+ async run(body) {
2264
+ const ref = optString(body, 'account');
2265
+ if (!ref)
2266
+ throw new HttpError(400, '"account" is required');
2267
+ const rt = await getRuntime();
2268
+ const account = await rt.resolve(ref);
2269
+ if (!optBool(body, 'confirm'))
2270
+ return { plan: await rt.limitResetPlan(account) };
2271
+ const operationId = optString(body, 'operationId');
2272
+ if (!operationId)
2273
+ throw new HttpError(400, '"operationId" is required to confirm');
2274
+ return { result: await rt.limitResetUse(account, operationId) };
2275
+ },
2276
+ },
2277
+ // Opens the vendor's page where a Limit Reset is spent (Claude Code, ADR-0072), in the Account's Browser Profile
2278
+ // when one is known, else the default browser. It starts a program, so a read-only Panel refuses it.
2279
+ '/api/quota/reset/open': {
2280
+ async run(body) {
2281
+ const ref = optString(body, 'account');
2282
+ if (!ref)
2283
+ throw new HttpError(400, '"account" is required');
2284
+ const rt = await getRuntime();
2285
+ const r = await openVendorPage(rt, await rt.resolve(ref));
2286
+ return { ref: r.ref, url: r.url, ...(r.profile ? { profile: r.profile } : {}) };
2287
+ },
2288
+ },
2173
2289
  // A Family's Quota check on or off: config `quota.check.<family>` (spec §3.26).
2174
2290
  '/api/quota/check': {
2175
2291
  async run(body) {
@@ -2464,7 +2580,13 @@ export function createPanelHandler(opts) {
2464
2580
  req.resume();
2465
2581
  }
2466
2582
  else if (err instanceof UserError) {
2467
- send(res, 400, err.code ? { error: err.message, code: err.code } : { error: err.message });
2583
+ // A Limit Reset that got no final answer names its operation, so the page retries that one (ADR-0072).
2584
+ const operationId = err instanceof LimitResetError ? err.operationId : undefined;
2585
+ send(res, 400, {
2586
+ error: err.message,
2587
+ ...(err.code ? { code: err.code } : {}),
2588
+ ...(operationId ? { operationId } : {}),
2589
+ });
2468
2590
  }
2469
2591
  else {
2470
2592
  send(res, 500, { error: err?.message || 'internal error' });