sideby 0.31.3 → 0.32.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 (43) hide show
  1. package/README.md +4 -4
  2. package/dist/build.json +1 -1
  3. package/dist/src/cli/commands.js +27 -11
  4. package/dist/src/cli/format.js +3 -2
  5. package/dist/src/cli/json-schemas.js +25 -5
  6. package/dist/src/core/ask.js +6 -1
  7. package/dist/src/core/handoff-rules.js +5 -5
  8. package/dist/src/core/handoff-select.js +6 -6
  9. package/dist/src/core/handoff.d.ts +36 -3
  10. package/dist/src/core/handoff.js +57 -18
  11. package/dist/src/core/pick-commands.d.ts +19 -4
  12. package/dist/src/core/pick-commands.js +19 -5
  13. package/dist/src/core/quota-levels.d.ts +67 -4
  14. package/dist/src/core/quota-levels.js +82 -6
  15. package/dist/src/families/claude/index.js +3 -0
  16. package/dist/src/families/claude/quota-fetch.d.ts +26 -0
  17. package/dist/src/families/claude/quota-fetch.js +236 -0
  18. package/dist/src/menubar/script.js +8 -3
  19. package/dist/src/menubar/snapshot.d.ts +9 -5
  20. package/dist/src/menubar/snapshot.js +37 -24
  21. package/dist/src/menubar/strings.d.ts +6 -4
  22. package/dist/src/menubar/strings.js +6 -4
  23. package/dist/src/panel/handler.js +7 -3
  24. package/dist/src/panel/i18n.d.ts +1 -0
  25. package/dist/src/panel/i18n.js +8 -6
  26. package/dist/src/panel/page-logic.d.ts +32 -8
  27. package/dist/src/panel/page-logic.js +43 -16
  28. package/dist/src/panel/page-script.js +12 -9
  29. package/dist/src/panel/page.js +3 -1
  30. package/dist/src/runtime.d.ts +2 -1
  31. package/dist/src/runtime.js +10 -4
  32. package/dist/testing/index.d.ts +5 -0
  33. package/dist/testing/index.js +2 -0
  34. package/package.json +2 -2
  35. package/schemas/menubar-snapshot.json +3 -3
  36. package/schemas/next.json +57 -4
  37. package/skills/sideby/SKILL.md +2 -2
  38. package/skills/sideby/references/accounts.md +1 -1
  39. package/skills/sideby/references/ai-tasks.md +2 -2
  40. package/skills/sideby/references/diagnose.md +1 -1
  41. package/skills/sideby/references/handoff.md +12 -8
  42. package/skills/sideby/references/panel.md +1 -1
  43. package/skills/sideby/references/quota.md +9 -3
@@ -1,4 +1,4 @@
1
- import { openWindows, quotaIsStale, quotaLevel } from '../core/quota-levels.js';
1
+ import { bindingWindow, openWindows, quotaIsStale, windowLevel, worseLevel, } from '../core/quota-levels.js';
2
2
  import { fill, MENUBAR_STRINGS } from './strings.js';
3
3
  export const DEFAULT_MENUBAR_HOTKEY = 'opt+x';
4
4
  // macOS virtual key codes of the ANSI letters and digits (HIToolbox Events.h, kVK_ANSI_*).
@@ -98,8 +98,9 @@ function groupLabel(name) {
98
98
  }
99
99
  /**
100
100
  * What a Quota whose windows cover every model draws: two bar columns (the shortest window, then the fullest of the
101
- * others, so a third window that is used up still shows; a single window fills the second), the time until the fullest
102
- * resets, and one hover line per window with its use and reset.
101
+ * others, so a third window that is used up still shows; a single window fills the second), each colored by its own
102
+ * levels (a weekly window warns later, spec §3.26), which window runs out first and when it resets, and one hover line
103
+ * per window with its use and reset.
103
104
  */
104
105
  function drawn(quota, now, s) {
105
106
  const open = openWindows(quota, now) ?? [];
@@ -109,7 +110,7 @@ function drawn(quota, now, s) {
109
110
  const openOf = (w) => open.find((o) => o.label === w.label);
110
111
  const bar = (w) => {
111
112
  const percent = Math.round(openOf(w)?.usedPercent ?? 0);
112
- return { label: w.label, percent, level: quotaLevel(percent) };
113
+ return { label: w.label, percent, level: windowLevel({ ...w, usedPercent: percent }) };
113
114
  };
114
115
  const longer = windows
115
116
  .slice(1)
@@ -120,8 +121,11 @@ function drawn(quota, now, s) {
120
121
  : longer
121
122
  ? [bar(windows[0]), longer]
122
123
  : [null, bar(windows[0])];
123
- const fullest = open.reduce((best, w) => (!best || w.usedPercent > best.usedPercent ? w : best), null);
124
- const reset = fullest && fullest.usedPercent > 0 ? untilText(fullest.resetsAt, now, s) : '';
124
+ // The window that runs out first relative to its own kind: a weekly 87% before a 5-hour 60%.
125
+ const fullest = bindingWindow(open) ?? null;
126
+ const level = open.reduce((l, w) => worseLevel(l, windowLevel(w)), 'ok');
127
+ const resetTime = fullest && fullest.usedPercent > 0 ? untilText(fullest.resetsAt, now, s) : '';
128
+ const reset = resetTime ? fill(s.resetIn, { label: fullest.label, time: resetTime }) : '';
125
129
  const lines = windows.map((w) => {
126
130
  const o = openOf(w);
127
131
  const p = bar(w).percent;
@@ -132,7 +136,9 @@ function drawn(quota, now, s) {
132
136
  return {
133
137
  bars,
134
138
  fullest,
139
+ level,
135
140
  reset,
141
+ resetTime,
136
142
  parts: windows.map((w) => fill(s.window, { label: w.label, p: bar(w).percent })),
137
143
  lines,
138
144
  };
@@ -183,9 +189,6 @@ function row(a, plan, now, s, refreshable) {
183
189
  if (groups) {
184
190
  // One line per model group under the account, each with its own 5h and 7d bars (spec §3.31).
185
191
  const drawnGroups = groups.map((g) => ({ name: g.name, d: drawn(g.quota, now, s) }));
186
- const fullest = drawnGroups
187
- .map((g) => g.d.fullest)
188
- .reduce((best, w) => (w && (!best || w.usedPercent > best.usedPercent) ? w : best), null);
189
192
  const groupTip = (g) => [g.name, ...g.d.lines.map((l) => ` ${l}`)];
190
193
  return {
191
194
  ...base,
@@ -195,7 +198,7 @@ function row(a, plan, now, s, refreshable) {
195
198
  ...drawnGroups.map((g) => `${groupLabel(g.name)} ${g.d.parts.join(' ')}`),
196
199
  ...(stale ? [s.olderReading] : []),
197
200
  ].join(s.sep),
198
- level: quotaLevel(fullest?.usedPercent ?? 0),
201
+ level: drawnGroups.reduce((l, g) => worseLevel(l, g.d.level), 'ok'),
199
202
  tip: [...head, '', ...drawnGroups.flatMap(groupTip), '', startTip].join('\n'),
200
203
  groups: drawnGroups.map((g) => ({
201
204
  label: groupLabel(g.name),
@@ -210,8 +213,8 @@ function row(a, plan, now, s, refreshable) {
210
213
  return noted(s.noData);
211
214
  const d = drawn(quota, now, s);
212
215
  const parts = [...d.parts];
213
- if (d.reset)
214
- parts.push(fill(s.resets, { time: d.reset }));
216
+ if (d.resetTime)
217
+ parts.push(fill(s.resets, { label: d.fullest.label, time: d.resetTime }));
215
218
  if (stale)
216
219
  parts.push(s.olderReading);
217
220
  return {
@@ -219,7 +222,7 @@ function row(a, plan, now, s, refreshable) {
219
222
  observedAt: quota.observedAt,
220
223
  stale,
221
224
  detail: parts.join(s.sep),
222
- level: quotaLevel(d.fullest?.usedPercent ?? 0),
225
+ level: d.level,
223
226
  tip: [...head, '', ...d.lines, '', startTip].join('\n'),
224
227
  bars: d.bars,
225
228
  reset: d.reset,
@@ -293,9 +296,10 @@ function section(f, now, s) {
293
296
  return { ...head, columns: columns(rows), rows, more: { title, rows: rest.map((x) => x.r) } };
294
297
  }
295
298
  /**
296
- * Each Family's number is the Quota Pressure of the account `sideby next` would pick, or, when every account is past
297
- * the fail level, the lowest of theirs; the title shows the highest of these, so it turns red when some tool has
298
- * nothing left to hand over to.
299
+ * Each Family's number is the account `sideby next` would pick, or, when every account is full, the one with the lowest
300
+ * Limit Use: the used percent of its window closest to its own limit, colored by that account's windows at their own
301
+ * levels (spec §3.26). The title shows the tightest of these by Limit Use, so it turns red when some tool has nothing
302
+ * left to hand over to, and a weekly window at 87% stays quiet.
299
303
  */
300
304
  export function menubarSnapshot(families, now, lang, hotkey = null) {
301
305
  const s = MENUBAR_STRINGS[lang];
@@ -312,16 +316,25 @@ export function menubarSnapshot(families, now, lang, hotkey = null) {
312
316
  const best = f.plan.pick
313
317
  ? f.plan.accounts.find((e) => e.ref === f.plan.pick)
314
318
  : f.plan.accounts
315
- .filter((e) => e.state === 'full' && e.pressure !== null)
316
- .sort((x, y) => x.pressure - y.pressure)[0];
317
- const value = best?.pressure ?? null;
318
- if (best && value !== null && (!worst || value > worst.value))
319
- worst = { value, ref: best.ref, tool: f.title };
319
+ .filter((e) => e.state === 'full' && e.limitUse !== null)
320
+ .sort((x, y) => x.limitUse - y.limitUse)[0];
321
+ const use = best?.limitUse ?? null;
322
+ if (best && use !== null && (!worst || use > worst.use)) {
323
+ const quota = f.accounts.find((a) => a.ref === best.ref)?.quota;
324
+ const level = (openWindows(quota, now) ?? []).reduce((l, w) => worseLevel(l, windowLevel(w)), 'ok');
325
+ worst = {
326
+ use,
327
+ value: best.window?.usedPercent ?? best.pressure ?? 0,
328
+ level,
329
+ ref: best.ref,
330
+ tool: f.title,
331
+ };
332
+ }
320
333
  }
321
334
  const values = worst
322
335
  ? { account: worst.ref, tool: worst.tool, p: Math.round(worst.value) }
323
336
  : {};
324
- const low = worst !== null && quotaLevel(worst.value) !== 'ok';
337
+ const low = worst !== null && worst.level !== 'ok';
325
338
  const old = sections.some((s) => s.rows.some((r) => r.stale));
326
339
  // "Refresh" brings new numbers only for a Family that can be asked; otherwise a session in that account must run.
327
340
  const oldSays = old &&
@@ -332,7 +345,7 @@ export function menubarSnapshot(families, now, lang, hotkey = null) {
332
345
  return {
333
346
  schemaVersion: 1,
334
347
  title: low ? fill(s.title, values) : '',
335
- level: worst && !old ? quotaLevel(worst.value) : 'none',
348
+ level: worst && !old ? worst.level : 'none',
336
349
  tooltip: [
337
350
  old
338
351
  ? `${s.statusOld} · ${oldSays}`
@@ -347,7 +360,7 @@ export function menubarSnapshot(families, now, lang, hotkey = null) {
347
360
  ? {
348
361
  status: old ? s.statusOld : fill(low ? s.statusLow : s.statusOk, values),
349
362
  detail: old ? oldSays : fill(low ? s.detailLow : s.detailOk, values),
350
- level: old ? 'none' : quotaLevel(worst.value),
363
+ level: old ? 'none' : worst.level,
351
364
  }
352
365
  : null,
353
366
  updatedAt: now.toISOString(),
@@ -31,7 +31,8 @@ export declare const MENUBAR_STRINGS: {
31
31
  readonly windowTip: '{label}: {p}% used';
32
32
  readonly windowResetsTip: '{label}: {p}% used · resets in {time}';
33
33
  readonly window: '{label} {p}%';
34
- readonly resets: 'resets in {time}';
34
+ readonly resets: '{label} resets in {time}';
35
+ readonly resetIn: '{label} · in {time}';
35
36
  readonly moreApi: 'API keys ({n})';
36
37
  readonly moreSignedOut: '{n} signed out';
37
38
  readonly moreMixed: '{n} more';
@@ -89,7 +90,8 @@ export declare const MENUBAR_STRINGS: {
89
90
  readonly windowTip: '{label}:已用 {p}%';
90
91
  readonly windowResetsTip: '{label}:已用 {p}% · {time}后重置';
91
92
  readonly window: '{label} {p}%';
92
- readonly resets: '{time}后重置';
93
+ readonly resets: '{label} {time}后重置';
94
+ readonly resetIn: '{label} · {time}后';
93
95
  readonly moreApi: '{n} 个 API 密钥账号';
94
96
  readonly moreSignedOut: '{n} 个未登录账号';
95
97
  readonly moreMixed: '另外 {n} 个账号';
@@ -97,8 +99,8 @@ export declare const MENUBAR_STRINGS: {
97
99
  readonly sameLoginTip: '与 {names} 同一登录,共用这份额度';
98
100
  readonly sep: ' · ';
99
101
  readonly minutes: '{m}分';
100
- readonly hoursMinutes: '{h}小时 {m}分';
101
- readonly daysHours: '{d}天 {h}小时';
102
+ readonly hoursMinutes: '{h}小时{m}分';
103
+ readonly daysHours: '{d}天{h}小时';
102
104
  readonly startTip: '在终端里启动 {account}';
103
105
  readonly empty: '还没有账号';
104
106
  readonly loading: '正在读取额度…';
@@ -31,7 +31,8 @@ export const MENUBAR_STRINGS = {
31
31
  windowTip: '{label}: {p}% used',
32
32
  windowResetsTip: '{label}: {p}% used · resets in {time}',
33
33
  window: '{label} {p}%',
34
- resets: 'resets in {time}',
34
+ resets: '{label} resets in {time}',
35
+ resetIn: '{label} · in {time}',
35
36
  moreApi: 'API keys ({n})',
36
37
  moreSignedOut: '{n} signed out',
37
38
  moreMixed: '{n} more',
@@ -89,7 +90,8 @@ export const MENUBAR_STRINGS = {
89
90
  windowTip: '{label}:已用 {p}%',
90
91
  windowResetsTip: '{label}:已用 {p}% · {time}后重置',
91
92
  window: '{label} {p}%',
92
- resets: '{time}后重置',
93
+ resets: '{label} {time}后重置',
94
+ resetIn: '{label} · {time}后',
93
95
  moreApi: '{n} 个 API 密钥账号',
94
96
  moreSignedOut: '{n} 个未登录账号',
95
97
  moreMixed: '另外 {n} 个账号',
@@ -97,8 +99,8 @@ export const MENUBAR_STRINGS = {
97
99
  sameLoginTip: '与 {names} 同一登录,共用这份额度',
98
100
  sep: ' · ',
99
101
  minutes: '{m}分',
100
- hoursMinutes: '{h}小时 {m}分',
101
- daysHours: '{d}天 {h}小时',
102
+ hoursMinutes: '{h}小时{m}分',
103
+ daysHours: '{d}天{h}小时',
102
104
  startTip: '在终端里启动 {account}',
103
105
  empty: '还没有账号',
104
106
  loading: '正在读取额度…',
@@ -22,6 +22,7 @@ import { listMessages, sendMessage } from '../core/messages.js';
22
22
  import { accountModel, setAccountModel } from '../core/model-choice.js';
23
23
  import { GUARDED_FAMILIES, setNetwork } from '../core/network.js';
24
24
  import { tildify } from '../core/paths.js';
25
+ import { takeoverLimits } from '../core/quota-levels.js';
25
26
  import { remoteControlTodo } from '../core/remote-control.js';
26
27
  import { openRunBoard, withRuns } from '../core/run-link.js';
27
28
  import { SECRET_VAR_NAME, secretVarFor, setSecret } from '../core/secret-file.js';
@@ -260,7 +261,9 @@ export function handoffByFamily(rt, accounts, now) {
260
261
  kind: a.kind,
261
262
  login: a.login ?? 'unknown',
262
263
  quota: a.quota ?? { status: 'unavailable', reason: 'unrecognized' },
263
- })), now);
264
+ })), now,
265
+ // The same plan as `sideby next`: the same Takeover Limits, and past them the least used Account (a Last Resort).
266
+ { limits: takeoverLimits(rt.handoffSettings().threshold), lastResort: true });
264
267
  if (plan.pick && plan.hasQuota)
265
268
  out[id] = plan.pick;
266
269
  }
@@ -1272,7 +1275,7 @@ export function createPanelHandler(opts) {
1272
1275
  const { family, choice } = await rt.pickChoice(name);
1273
1276
  if (choice.ref === null)
1274
1277
  throw new UserError(choice.earliestReset
1275
- ? `Every ${family} account is at its limit; ${choice.earliestReset.ref} is back first.`
1278
+ ? `Every signed-in ${family} account has used up its quota; ${choice.earliestReset.ref} is back first.`
1276
1279
  : `No ${family} account can be used now; sign one in first.`, { code: 'none-usable' });
1277
1280
  // The terminal runs the Pick Command itself, so it picks again as it starts and prints which and why.
1278
1281
  const r = opened(await openPickInTerminal(rt, name));
@@ -1282,7 +1285,8 @@ export function createPanelHandler(opts) {
1282
1285
  family,
1283
1286
  picked: choice.ref,
1284
1287
  reason: choice.reason,
1285
- ...('pressure' in choice ? { pressure: choice.pressure } : {}),
1288
+ ...('pressure' in choice ? { pressure: choice.pressure, window: choice.window } : {}),
1289
+ ...('limit' in choice ? { limit: choice.limit, longLimit: choice.longLimit } : {}),
1286
1290
  };
1287
1291
  },
1288
1292
  },
@@ -628,6 +628,7 @@ declare const en: {
628
628
  'pk.namePh': string;
629
629
  'pk.started': string;
630
630
  'pk.why.room': string;
631
+ 'pk.why.tight': string;
631
632
  'pk.why.noData': string;
632
633
  'login.opened': string;
633
634
  'login.failed': string;
@@ -629,7 +629,8 @@ const en = {
629
629
  'pk.offerNoNameShort': 'Add short command',
630
630
  'pk.namePh': 'e.g. cc',
631
631
  'pk.started': 'Opened {ref} in {terminal} ({why}).',
632
- 'pk.why.room': '{n}% used, most quota left',
632
+ 'pk.why.room': '{w}{n}% used, most quota left',
633
+ 'pk.why.tight': 'every account is past its limit ({limit}% of a 5-hour window, {longLimit}% of a weekly one); this one has the most left, {w}{n}% used',
633
634
  'pk.why.noData': 'no quota data yet',
634
635
  'login.opened': 'Opened {terminal}: sign in to {ref} there.',
635
636
  'login.failed': 'Could not open a terminal. Copied: paste it into your terminal and press Return.',
@@ -885,8 +886,8 @@ const en = {
885
886
  'hp.rulesNote': 'These rules decide when an account hands over and which account takes over. Each change applies at once and can be undone.',
886
887
  'hp.rule.whenAdaptive': 'The AI writes a handoff note at {prepare}% used. Handoff starts at {p}% used until sideby learns how fast this session spends quota, then between {prepare}% and {max}%, earlier if recent turns used a lot.',
887
888
  'hp.rule.when': 'The AI writes a handoff note at {prepare}% used. Handoff starts at {p}% used.',
888
- 'hp.rule.windows': 'Every quota window counts (5 hours, weekly, a billing period): the fullest one decides. No AI has a daily quota.',
889
- 'hp.rule.takeover': 'Accounts already over {limit}% used will not take over, so the next account has room to work. This stays 10 points below the handoff level ({p}%).',
889
+ 'hp.rule.windows': 'Every quota window counts (5 hours, weekly, a billing period): the session hands over when its fullest window reaches the level above. No AI has a daily quota.',
890
+ 'hp.rule.takeover': 'An account will not take over once a 5-hour window is {limit}% used or a weekly window is {long}% used, so the next account has room to work. A 5-hour window costs only about a fifth of a week, so the weekly line sits higher: at the handoff level ({p}%), the 5-hour line 10 points below it. The account furthest from these lines goes first.',
890
891
  'hp.rule.wait': 'If the quota comes back within {w} minutes and the session carries on by itself at that point (Claude Code), it waits instead of switching. Codex and Grok switch right away.',
891
892
  'hp.rule.noWait': 'It never waits for quota to come back; it switches right away.',
892
893
  'hp.rule.sameOn': 'Other accounts of the same AI can take over first (for example cc001 to cc002). The account with the most quota left goes first.',
@@ -2218,7 +2219,8 @@ const zh = {
2218
2219
  'pk.offerNoNameShort': '添加短命令',
2219
2220
  'pk.namePh': '例如 cc',
2220
2221
  'pk.started': '已在 {terminal} 启动 {ref}({why})。',
2221
- 'pk.why.room': '已用 {n}%,剩余额度最多',
2222
+ 'pk.why.room': '{w}已用 {n}%,剩余额度最多',
2223
+ 'pk.why.tight': '所有账号都已到上限(5 小时窗口 {limit}%,每周窗口 {longLimit}%);这个剩得最多,{w}已用 {n}%',
2222
2224
  'pk.why.noData': '还没有额度数据',
2223
2225
  'login.opened': '已打开 {terminal},请在那里登录 {ref}。',
2224
2226
  'login.failed': '终端没打开,命令已复制:粘贴到你的终端,按回车。',
@@ -2474,8 +2476,8 @@ const zh = {
2474
2476
  'hp.rulesNote': '这些规则决定什么时候接力、交给哪个账号。每项改动立即生效,可以撤销。',
2475
2477
  'hp.rule.whenAdaptive': '用量到 {prepare}% 时,AI 会写好接力笔记。sideby 了解本次会话的消耗速度前,会在用量到 {p}% 时接力;之后会在 {prepare}% 到 {max}% 之间接力,最近几轮用得多就更早接力。',
2476
2478
  'hp.rule.when': '用量到 {prepare}% 时,AI 会写好接力笔记;用量到 {p}% 时接力。',
2477
- 'hp.rule.windows': '每个额度窗口都算(5 小时、每周、计费周期),以用得最多的那个为准。目前没有 AI 设日额度。',
2478
- 'hp.rule.takeover': '用量超过 {limit}% 的账号不会接手,确保下一个账号有足够额度干活。这条线始终比接力用量({p}%)低 10 个百分点。',
2479
+ 'hp.rule.windows': '每个额度窗口都算(5 小时、每周、计费周期):会话用得最多的窗口到上面的用量就接力。目前没有 AI 设日额度。',
2480
+ 'hp.rule.takeover': '5 小时窗口用到 {limit}%、或每周窗口用到 {long}% 的账号不会接手,确保下一个账号有足够额度干活。一个 5 小时窗口只占一周额度的五分之一左右,所以每周的线更高:等于接力用量({p}%),5 小时的线比它低 10 个百分点。离这两条线最远的账号先接手。',
2479
2481
  'hp.rule.wait': '如果 {w} 分钟内额度就恢复,而且会话到时会自己继续(Claude Code),就原地等,不换号。Codex 和 Grok 直接换号。',
2480
2482
  'hp.rule.noWait': '不等额度恢复,直接换号。',
2481
2483
  'hp.rule.sameOn': '同一个 AI 的其他账号优先接手(例如 cc001 到 cc002),剩余额度最多的优先。',
@@ -52,11 +52,27 @@ export interface LogicUsage {
52
52
  }
53
53
  /** A short countdown such as `2h 05m`, `3d 4h` or `12m` (`2小时05分` in Chinese); fixed shape so it does not jump. */
54
54
  export declare function formatDuration(ms: number, lang: string): string;
55
- /** One Quota window as the page draws it: percent used (0 after a reset passed) and its warning level. */
55
+ /**
56
+ * A Long Window: longer than one day (weekly, a billing period), from `windowMinutes` or else a label such as `7d`.
57
+ * The page's copy of `isLongWindow` in core/quota-levels.ts; a test keeps the two equal.
58
+ */
59
+ export declare function longWindow(w: {
60
+ label?: string;
61
+ windowMinutes?: number;
62
+ }): boolean;
63
+ /**
64
+ * One Quota window as the page draws it: percent used (0 after a reset passed) and its warning level. `warn` and
65
+ * `fail` are a Short Window's levels; `long`, when given, a Long Window's (spec §3.26: a weekly window warns later).
66
+ */
56
67
  export declare function windowState(w: {
57
68
  usedPercent: number;
58
69
  resetsAt: string;
59
- }, now: number, warn: number, fail: number): {
70
+ label?: string;
71
+ windowMinutes?: number;
72
+ }, now: number, warn: number, fail: number, long?: {
73
+ warn: number;
74
+ fail: number;
75
+ }): {
60
76
  pct: number;
61
77
  passed: boolean;
62
78
  level: string;
@@ -68,7 +84,12 @@ export declare function windowState(w: {
68
84
  export declare function bindingWindow<W extends {
69
85
  usedPercent: number;
70
86
  resetsAt: string;
71
- }>(list: W[], now: number, warn: number, fail: number): W | undefined;
87
+ label?: string;
88
+ windowMinutes?: number;
89
+ }>(list: W[], now: number, warn: number, fail: number, long?: {
90
+ warn: number;
91
+ fail: number;
92
+ }): W | undefined;
72
93
  /**
73
94
  * A window whose reset time has passed: the numbers on record are from before the reset and nothing newer came
74
95
  * in. `since` is when they were last seen (the Quota's observation time, or the reset itself when that is
@@ -89,12 +110,15 @@ export declare function quotaPressure(a: LogicAccount, now: number): number;
89
110
  export declare function attentionReasons(a: LogicAccount, health: {
90
111
  fail: number;
91
112
  warn: number;
92
- } | null, now: number, warn: number): string[];
113
+ } | null, now: number, warn: number,
114
+ /** A Long Window's warning level (spec §3.26); without it every window uses `warn`. */
115
+ longWarn?: number): string[];
93
116
  /**
94
- * How serious an Account's `quota-high` is: `fail` once its fullest live window reaches `fail` (the bar turns red),
95
- * else `warn`, so a running-low label takes the same color as the bar it speaks about.
117
+ * How serious an Account's `quota-high` is: `fail` once a live window reaches its red level (`fail`, or `longFail` for
118
+ * a Long Window: the bar turns red), else `warn`, so a running-low label takes the same color as the bar it speaks
119
+ * about.
96
120
  */
97
- export declare function quotaHighLevel(a: LogicAccount, now: number, fail: number): 'warn' | 'fail';
121
+ export declare function quotaHighLevel(a: LogicAccount, now: number, fail: number, longFail?: number): 'warn' | 'fail';
98
122
  /**
99
123
  * The one status badge an account row shows after its name (spec §3.27), most important first: `health-fail`
100
124
  * (needs fixing), `quota-high` (running low), the other attention labels (`signed-out`, `not-installed`,
@@ -112,7 +136,7 @@ export declare function rowBadge(reasons: string[], opts: {
112
136
  export declare function attentionWhy(a: LogicAccount, health: {
113
137
  fail: number;
114
138
  warn: number;
115
- } | null, now: number, warn: number): {
139
+ } | null, now: number, warn: number, longWarn?: number): {
116
140
  key: string;
117
141
  vars: Record<string, string | number>;
118
142
  } | null;
@@ -18,23 +18,42 @@ export function formatDuration(ms, lang) {
18
18
  return zh ? `${h}小时${mm}分` : `${h}h ${mm}m`;
19
19
  return zh ? `${m}分钟` : `${m}m`;
20
20
  }
21
- /** One Quota window as the page draws it: percent used (0 after a reset passed) and its warning level. */
22
- export function windowState(w, now, warn, fail) {
21
+ /**
22
+ * A Long Window: longer than one day (weekly, a billing period), from `windowMinutes` or else a label such as `7d`.
23
+ * The page's copy of `isLongWindow` in core/quota-levels.ts; a test keeps the two equal.
24
+ */
25
+ export function longWindow(w) {
26
+ let minutes = Number(w.windowMinutes);
27
+ if (!(Number.isFinite(minutes) && minutes > 0)) {
28
+ const m = /^(\d+(?:\.\d+)?)\s*([mhdw])$/i.exec(String(w.label ?? '').trim());
29
+ const units = { m: 1, h: 60, d: 1440, w: 10080 };
30
+ minutes = m ? Number(m[1]) * units[m[2].toLowerCase()] : 0;
31
+ }
32
+ return minutes > 1440;
33
+ }
34
+ /**
35
+ * One Quota window as the page draws it: percent used (0 after a reset passed) and its warning level. `warn` and
36
+ * `fail` are a Short Window's levels; `long`, when given, a Long Window's (spec §3.26: a weekly window warns later).
37
+ */
38
+ export function windowState(w, now, warn, fail, long) {
23
39
  const reset = Date.parse(w.resetsAt);
24
40
  const passed = Number.isFinite(reset) && reset <= now;
25
41
  const raw = Math.max(0, Math.min(100, Math.round(Number(w.usedPercent) || 0)));
26
42
  const pct = passed ? 0 : raw;
27
- const level = passed ? 'reset' : pct >= fail ? 'fail' : pct >= warn ? 'warn' : 'ok';
43
+ const lv = long && longWindow(w) ? long : { warn, fail };
44
+ const level = passed ? 'reset' : pct >= lv.fail ? 'fail' : pct >= lv.warn ? 'warn' : 'ok';
28
45
  return { pct, passed, level };
29
46
  }
30
47
  /**
31
48
  * The window that binds first among those sharing one column (a model group with a 5-hour and a weekly limit, as
32
49
  * Antigravity CLI reports): the most used as the page draws it, the first on a tie. Undefined for none.
33
50
  */
34
- export function bindingWindow(list, now, warn, fail) {
51
+ export function bindingWindow(list, now, warn, fail, long) {
52
+ // Closest to its own red level: a weekly 87% of 95 binds before a 5-hour 80% of 85.
53
+ const share = (w) => windowState(w, now, warn, fail).pct / (long && longWindow(w) ? long.fail : fail);
35
54
  let best;
36
55
  for (const w of list)
37
- if (!best || windowState(w, now, warn, fail).pct > windowState(best, now, warn, fail).pct)
56
+ if (!best || share(w) > share(best))
38
57
  best = w;
39
58
  return best;
40
59
  }
@@ -71,7 +90,9 @@ export function quotaPressure(a, now) {
71
90
  * `quota-high` (a live window at or over the warning level), `health-warn`. Empty when all is well. A Quota read from
72
91
  * another Account of the same login (`quota.from`, spec §3.21) is that Account's warning, so it counts once per group.
73
92
  */
74
- export function attentionReasons(a, health, now, warn) {
93
+ export function attentionReasons(a, health, now, warn,
94
+ /** A Long Window's warning level (spec §3.26); without it every window uses `warn`. */
95
+ longWarn = warn) {
75
96
  const out = [];
76
97
  if (a.error)
77
98
  out.push('error');
@@ -89,7 +110,7 @@ export function attentionReasons(a, health, now, warn) {
89
110
  const reset = Date.parse(w.resetsAt);
90
111
  if (Number.isFinite(reset) && reset <= now)
91
112
  continue;
92
- if ((Number(w.usedPercent) || 0) >= warn) {
113
+ if ((Number(w.usedPercent) || 0) >= (longWindow(w) ? longWarn : warn)) {
93
114
  out.push('quota-high');
94
115
  break;
95
116
  }
@@ -99,10 +120,11 @@ export function attentionReasons(a, health, now, warn) {
99
120
  return out;
100
121
  }
101
122
  /**
102
- * How serious an Account's `quota-high` is: `fail` once its fullest live window reaches `fail` (the bar turns red),
103
- * else `warn`, so a running-low label takes the same color as the bar it speaks about.
123
+ * How serious an Account's `quota-high` is: `fail` once a live window reaches its red level (`fail`, or `longFail` for
124
+ * a Long Window: the bar turns red), else `warn`, so a running-low label takes the same color as the bar it speaks
125
+ * about.
104
126
  */
105
- export function quotaHighLevel(a, now, fail) {
127
+ export function quotaHighLevel(a, now, fail, longFail = fail) {
106
128
  const q = a.quota;
107
129
  if (!q || q.status !== 'ok' || !q.windows || q.from)
108
130
  return 'warn';
@@ -112,7 +134,7 @@ export function quotaHighLevel(a, now, fail) {
112
134
  const reset = Date.parse(w.resetsAt);
113
135
  if (Number.isFinite(reset) && reset <= now)
114
136
  continue;
115
- if ((Number(w.usedPercent) || 0) >= fail)
137
+ if ((Number(w.usedPercent) || 0) >= (longWindow(w) ? longFail : fail))
116
138
  return 'fail';
117
139
  }
118
140
  return 'warn';
@@ -137,12 +159,13 @@ export function rowBadge(reasons, opts) {
137
159
  * attention count is: `why.<reason>`; for `quota-high` the fullest live window at or over `warn`, with its label and
138
160
  * rounded percentage. Null when all is well.
139
161
  */
140
- export function attentionWhy(a, health, now, warn) {
141
- const reason = attentionReasons(a, health, now, warn)[0];
162
+ export function attentionWhy(a, health, now, warn, longWarn = warn) {
163
+ const reason = attentionReasons(a, health, now, warn, longWarn)[0];
142
164
  if (!reason)
143
165
  return null;
144
166
  if (reason !== 'quota-high')
145
167
  return { key: `why.${reason}`, vars: {} };
168
+ // The window furthest past its own warning level: a weekly window warns at `longWarn` (spec §3.26).
146
169
  let top = null;
147
170
  for (const w of a.quota?.windows ?? []) {
148
171
  if (w.name)
@@ -151,10 +174,14 @@ export function attentionWhy(a, health, now, warn) {
151
174
  if (Number.isFinite(reset) && reset <= now)
152
175
  continue;
153
176
  const pct = Number(w.usedPercent) || 0;
154
- if (pct >= warn && (!top || pct > top.pct))
155
- top = { label: w.label, pct };
177
+ const at = longWindow(w) ? longWarn : warn;
178
+ if (pct >= at && (!top || pct / at > top.pct / top.at))
179
+ top = { label: w.label, pct, at };
156
180
  }
157
- return { key: 'why.quota-high', vars: { label: top?.label ?? '', pct: Math.round(top?.pct ?? 0), warn } };
181
+ return {
182
+ key: 'why.quota-high',
183
+ vars: { label: top?.label ?? '', pct: Math.round(top?.pct ?? 0), warn: top?.at ?? warn },
184
+ };
158
185
  }
159
186
  /**
160
187
  * `items` in Display Order (spec §3.25): those whose key is in `order` first, in that order; the others after, in the
@@ -5,7 +5,7 @@ import { groupsToAccept } from '../core/inbound.js';
5
5
  import { quotaIsStale } from '../core/quota-levels.js';
6
6
  import { remoteControlTodo } from '../core/remote-control.js';
7
7
  import { catalogMatchLevel, catalogNorm, searchCatalog } from '../core/search-catalog.js';
8
- import { aiTaskAccounts, aliasArgsOf, aliasIssue, askBridge, askBridged, askCopy, attentionReasons, attentionWhy, autostartNote, bindingWindow, cacheHitRate, canLeaveLocal, categoryOrder, codeSwapOutcome, dotsKeepKeyboard, enableOutcome, fileSize, fixPrompt, foldSkips, foldToolCalls, formatDuration, handoffChangeOf, handoffHintAccount, handoffTaskFacts, hiddenIn, highlightParts, histFilters, historyEmpty, historyWhen, hotkeyFromKey, hotkeyPressKind, inDisplayOrder, loginClusters, loginKey, maskEmail, matchesQuery, mdBlocks, mdInline, menuPlacement, mergeDaily, mergeUsage, messageChip, messageNews, networkTaskFacts, newAccountDir, nextReset, panelFixes, panelHint, panelLang, panelMigration, panelPrefs, passedWindow, pinnedIn, quotaAskable, quotaHighLevel, quotaPressure, radioStep, reloadForBuild, remoteControlSummary, reorder, rowBadge, runCodeSwap, saveHandoffChange, sendBlock, sendFileProblem, sendResultView, sessionAge, sessionLabelParts, shortCwd, shortSessionLabel, sortAccounts, sortSessions, steadyOrder, stripSecrets, suggestAlias, suggestName, switchFailure, tailInView, taskFindings, uaDayRuns, uaGroupPending, uaOnChoices, uaParseClock, uaPickTime, uaSameSlot, uaShouldRead, uaSlotNight, uaStatusParts, uaStepClock, uaToggleDay, uaWaitingCount, uaWhen, updatedAge, widthFollower, widthTier, windowState, withPinned, } from './page-logic.js';
8
+ import { aiTaskAccounts, aliasArgsOf, aliasIssue, askBridge, askBridged, askCopy, attentionReasons, attentionWhy, autostartNote, bindingWindow, cacheHitRate, canLeaveLocal, categoryOrder, codeSwapOutcome, dotsKeepKeyboard, enableOutcome, fileSize, fixPrompt, foldSkips, foldToolCalls, formatDuration, handoffChangeOf, handoffHintAccount, handoffTaskFacts, hiddenIn, highlightParts, histFilters, historyEmpty, historyWhen, hotkeyFromKey, hotkeyPressKind, inDisplayOrder, loginClusters, loginKey, longWindow, maskEmail, matchesQuery, mdBlocks, mdInline, menuPlacement, mergeDaily, mergeUsage, messageChip, messageNews, networkTaskFacts, newAccountDir, nextReset, panelFixes, panelHint, panelLang, panelMigration, panelPrefs, passedWindow, pinnedIn, quotaAskable, quotaHighLevel, quotaPressure, radioStep, reloadForBuild, remoteControlSummary, reorder, rowBadge, runCodeSwap, saveHandoffChange, sendBlock, sendFileProblem, sendResultView, sessionAge, sessionLabelParts, shortCwd, shortSessionLabel, sortAccounts, sortSessions, steadyOrder, stripSecrets, suggestAlias, suggestName, switchFailure, tailInView, taskFindings, uaDayRuns, uaGroupPending, uaOnChoices, uaParseClock, uaPickTime, uaSameSlot, uaShouldRead, uaSlotNight, uaStatusParts, uaStepClock, uaToggleDay, uaWaitingCount, uaWhen, updatedAge, widthFollower, widthTier, windowState, withPinned, } from './page-logic.js';
9
9
  const LOGIC = [
10
10
  quotaIsStale,
11
11
  catalogNorm,
@@ -54,6 +54,7 @@ const LOGIC = [
54
54
  mergeUsage,
55
55
  messageChip,
56
56
  messageNews,
57
+ longWindow,
57
58
  newAccountDir,
58
59
  nextReset,
59
60
  canLeaveLocal,
@@ -119,6 +120,8 @@ const MAIN = String.raw `
119
120
  const MESSAGES = JSON.parse(document.getElementById('sideby-i18n').textContent)
120
121
  const WARN = BOOT.warn
121
122
  const FAIL = BOOT.fail
123
+ // A Long Window's levels (weekly, a billing period): it warns later than a 5-hour one (spec §3.26).
124
+ const LONG = { warn: BOOT.longWarn, fail: BOOT.longFail }
122
125
  // Quota data older than this is greyed and marked with its age.
123
126
  // Findings listed before the rest fold behind a button.
124
127
  const FINDINGS_SHOWN = 5
@@ -1126,10 +1129,10 @@ const MAIN = String.raw `
1126
1129
  for (const f of e.findings) { if (f.level === 'fail') fail++; else if (f.level === 'warn') warn++ }
1127
1130
  return { fail, warn }
1128
1131
  }
1129
- function reasonsOf(a, now) { return attentionReasons(a, healthOf(a.ref), now, WARN) }
1132
+ function reasonsOf(a, now) { return attentionReasons(a, healthOf(a.ref), now, WARN, LONG.warn) }
1130
1133
  // One line on why an Account needs a look, such as "7d at 62% (warns from 60%)".
1131
1134
  function whyOf(a, now) {
1132
- const m = attentionWhy(a, healthOf(a.ref), now, WARN)
1135
+ const m = attentionWhy(a, healthOf(a.ref), now, WARN, LONG.warn)
1133
1136
  if (m && m.key === 'why.not-installed' && family(a.family).brokenBin) return t('why.broken')
1134
1137
  return m ? t(m.key, m.vars && m.vars.label ? Object.assign({}, m.vars, { label: winTitle(m.vars.label) }) : m.vars) : ''
1135
1138
  }
@@ -1345,7 +1348,7 @@ const MAIN = String.raw `
1345
1348
  // A window's cell: percent and countdown on one line, the bar under them. The label shows where no column
1346
1349
  // header does (cards, narrow screens).
1347
1350
  function meter(w, now, stale, observedAt, withLength) {
1348
- const st = windowState(w, now, WARN, FAIL)
1351
+ const st = windowState(w, now, WARN, FAIL, LONG)
1349
1352
  const passed = passedWindow(w, observedAt, now)
1350
1353
  const left = prefs.quota === 'left'
1351
1354
  const shown = left ? 100 - st.pct : st.pct
@@ -1420,7 +1423,7 @@ const MAIN = String.raw `
1420
1423
  wins.length ? cols.map((c) => {
1421
1424
  // A model group with several limits (Antigravity's 5-hour and weekly) shows the one that binds first.
1422
1425
  const same = wins.filter((x) => winKey(x) === c)
1423
- const w = bindingWindow(same, now, WARN, FAIL)
1426
+ const w = bindingWindow(same, now, WARN, FAIL, LONG)
1424
1427
  return w ? meter(w, now, stale, q.observedAt, same.length > 1) : noMeter(winTitle(c), winShort(c))
1425
1428
  }) : h('div', { class: 'q-note' }, t('quota.noWindows')),
1426
1429
  // Old numbers keep their colours and say their age once, under the bars.
@@ -1480,7 +1483,7 @@ const MAIN = String.raw `
1480
1483
  }
1481
1484
  // A word, not only a colour (spec §3.8): what kind of look the account needs; the reason is on hover.
1482
1485
  function attentionWord(subject, reason) {
1483
- const lvl = reason === 'health-fail' ? 'fail' : reason === 'quota-high' ? quotaHighLevel(subject, Date.now(), FAIL) : 'warn'
1486
+ const lvl = reason === 'health-fail' ? 'fail' : reason === 'quota-high' ? quotaHighLevel(subject, Date.now(), FAIL, LONG.fail) : 'warn'
1484
1487
  const why = whyOf(subject, Date.now())
1485
1488
  const word = reason === 'health-fail' ? t('att.fix') : reason === 'quota-high' ? t('att.quota') : t('att.check')
1486
1489
  const dot = h('span', { class: 'dot dot-' + lvl, 'aria-hidden': 'true' })
@@ -2032,7 +2035,7 @@ const MAIN = String.raw `
2032
2035
  // with more, the count, each one's reason on hover, and a click shows only them (as the summary card does).
2033
2036
  function attentionTag(needing, now) {
2034
2037
  // Red when one of them needs a fix or has a red quota bar, so the tag matches what the rows show.
2035
- const lvl = needing.some((a) => reasonsOf(a, now).includes('health-fail') || quotaHighLevel(a, now, FAIL) === 'fail') ? 'fail' : 'warn'
2038
+ const lvl = needing.some((a) => reasonsOf(a, now).includes('health-fail') || quotaHighLevel(a, now, FAIL, LONG.fail) === 'fail') ? 'fail' : 'warn'
2036
2039
  if (needing.length === 1) {
2037
2040
  const a = needing[0]
2038
2041
  const label = a.name + ' · ' + whyOf(a, now)
@@ -5544,7 +5547,7 @@ const MAIN = String.raw `
5544
5547
  switch (r.id) {
5545
5548
  case 'when': return p.adaptive ? t('hp.rule.whenAdaptive', { prepare: p.prepareAt, p: p.threshold, max: p.max }) : t('hp.rule.when', { prepare: p.prepareAt, p: p.threshold })
5546
5549
  case 'windows': return t('hp.rule.windows')
5547
- case 'takeover': return t('hp.rule.takeover', { limit: p.limit, p: thr })
5550
+ case 'takeover': return t('hp.rule.takeover', { limit: p.limit, long: p.longLimit ?? thr, p: thr })
5548
5551
  case 'wait': return p.minutes > 0 ? t('hp.rule.wait', { w: p.minutes }) : t('hp.rule.noWait')
5549
5552
  case 'sameFamily': return t(p.on ? 'hp.rule.sameOn' : 'hp.rule.sameOff')
5550
5553
  case 'otherFamilies': return p.on ? t('hp.rule.otherOn') : t('hp.rule.otherOff')
@@ -8040,7 +8043,7 @@ const MAIN = String.raw `
8040
8043
  if (BOOT.readOnly) { copyText(name, name); return }
8041
8044
  try {
8042
8045
  const r = await api('/api/pick/start', { name })
8043
- const why = r.reason === 'most-room' ? t('pk.why.room', { n: String(r.pressure) }) : t(r.reason === 'others-full' ? 'pk.why.othersFull' : 'pk.why.noData')
8046
+ const why = r.reason === 'most-room' ? t('pk.why.room', { n: String(r.pressure), w: r.window ? winTitle(r.window) + ' ' : '' }) : r.reason === 'tight' ? t('pk.why.tight', { n: String(r.pressure), w: r.window ? winTitle(r.window) + ' ' : '', limit: String(r.limit), longLimit: String(r.longLimit) }) : t(r.reason === 'others-full' ? 'pk.why.othersFull' : 'pk.why.noData')
8044
8047
  if (r.opened) { toast(t('pk.started', { terminal: TERM_NAMES[r.terminal] || r.terminal, ref: r.picked, why })); return }
8045
8048
  await copyText(name, name)
8046
8049
  toast(r.automation ? t('login.automation', { terminal: TERM_NAMES[r.terminal] || r.terminal }) : t('login.failed'), { kind: 'info' })
@@ -5,7 +5,7 @@ import { createHash } from 'node:crypto';
5
5
  import { FAVICON_SVG, MARK_SVG } from '../core/brand-mark.js';
6
6
  import { commandListForPage } from '../core/cli-commands.js';
7
7
  import { ALIAS_NAME, RESERVED_ALIASES } from '../core/config.js';
8
- import { QUOTA_FAIL_PERCENT, QUOTA_WARN_PERCENT, USAGE_DAYS } from '../core/quota-levels.js';
8
+ import { QUOTA_FAIL_PERCENT, QUOTA_LONG_FAIL_PERCENT, QUOTA_LONG_WARN_PERCENT, QUOTA_WARN_PERCENT, USAGE_DAYS, } from '../core/quota-levels.js';
9
9
  import { COMMON_ENTRIES, SEARCH_CATALOG } from '../core/search-catalog.js';
10
10
  import { REPO_URL, SKILL_INSTALL } from '../core/skill-check.js';
11
11
  import { MESSAGES } from './i18n.js';
@@ -59,6 +59,8 @@ export function renderPage(opts) {
59
59
  },
60
60
  warn: QUOTA_WARN_PERCENT,
61
61
  fail: QUOTA_FAIL_PERCENT,
62
+ longWarn: QUOTA_LONG_WARN_PERCENT,
63
+ longFail: QUOTA_LONG_FAIL_PERCENT,
62
64
  usageDays: USAGE_DAYS,
63
65
  // The alias rules of the config, so the new-account dialog checks a short command as sideby will.
64
66
  aliasPattern: ALIAS_NAME.source,
@@ -357,7 +357,8 @@ export interface Runtime {
357
357
  /** Puts back what `remoteControlOff` or `remoteControlOn` replaced, only where the key still holds what it wrote. */
358
358
  remoteControlUndo(): Promise<RemoteControlChange>;
359
359
  /**
360
- * Which Account of a Family to move on to (spec §3.13). Throws a UserError with code `no-quota-source`
360
+ * Which Account of a Family to move on to (spec §3.13), for a start the user asks for: past the Takeover Limit it
361
+ * falls back to the least used Account under 100% (`tight`). Throws a UserError with code `no-quota-source`
361
362
  * when the Family cannot tell, `no-accounts` when it has none.
362
363
  */
363
364
  handoff(familyId: string, opts?: {