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,16 +1,51 @@
1
1
  import type { QuotaResult, QuotaWindow } from '../types.ts';
2
2
  /**
3
- * How full a Quota window must be before the CLI and the Panel warn about it, and the Usage window both
4
- * report. One rule for both surfaces: the Panel interpolates these numbers into its inline script.
3
+ * How full a Quota window must be before the CLI, the Panel and the menu bar warn about it (yellow) and show it as
4
+ * nearly used up (red). A Short Window (5 hours) uses the first pair, a Long Window (weekly, a billing period) the
5
+ * second: one full 5-hour window costs only about a fifth of a weekly one, so 87% of a week still leaves several
6
+ * 5-hour windows of work (spec §3.26, ADR-0062). The Panel interpolates these numbers into its inline script.
5
7
  */
6
8
  export declare const QUOTA_FAIL_PERCENT = 85;
7
9
  export declare const QUOTA_WARN_PERCENT = 60;
10
+ export declare const QUOTA_LONG_FAIL_PERCENT = 95;
11
+ export declare const QUOTA_LONG_WARN_PERCENT = 85;
12
+ /** A window longer than this many minutes (one day) is a Long Window. No Host has a daily Quota. */
13
+ export declare const LONG_WINDOW_MINUTES = 1440;
8
14
  /**
9
15
  * Takeover Limit (spec §3.17 "接力规则"): an Account more used than this does not take over a Handoff, so the next
10
- * Account starts with room to work. It sits this many points below the Handoff Threshold and moves with it.
16
+ * Account starts with room to work. For a Short Window it sits this many points below the Handoff Threshold and moves
17
+ * with it; a Long Window's limit is the Handoff Threshold itself (`takeoverLimits`).
11
18
  */
12
19
  export declare const TAKEOVER_GAP = 10;
13
20
  export declare function takeoverLimit(threshold: number): number;
21
+ /** The Takeover Limit of each kind of window: at or above it, that window makes an Account full. */
22
+ export interface TakeoverLimits {
23
+ /** Short Windows (5 hours): the Handoff Threshold − 10, 85 by default. */
24
+ short: number;
25
+ /** Long Windows (weekly, a billing period): the Handoff Threshold, 95 by default. */
26
+ long: number;
27
+ }
28
+ export declare function takeoverLimits(threshold: number): TakeoverLimits;
29
+ /** The limits at the default Handoff Threshold (95): 85 for Short Windows, 95 for Long ones. */
30
+ export declare const DEFAULT_TAKEOVER_LIMITS: TakeoverLimits;
31
+ /**
32
+ * A window's length in minutes: `windowMinutes`, or read from a label such as `5h`, `7d` or `90m` when that is
33
+ * missing; 0 when neither tells. The Panel keeps its own copy in `longWindow` (page-logic.ts); a test keeps them equal.
34
+ */
35
+ export declare function windowLength(w: {
36
+ label?: string;
37
+ windowMinutes?: number;
38
+ }): number;
39
+ /** A Long Window: longer than one day (weekly, a billing period). Every other window is a Short Window. */
40
+ export declare function isLongWindow(w: {
41
+ label?: string;
42
+ windowMinutes?: number;
43
+ }): boolean;
44
+ /** The window's own Takeover Limit. */
45
+ export declare function limitOf(w: {
46
+ label?: string;
47
+ windowMinutes?: number;
48
+ }, limits: TakeoverLimits): number;
14
49
  /** Days of Usage every Family reports. */
15
50
  export declare const USAGE_DAYS = 7;
16
51
  export type QuotaLevel = 'ok' | 'warn' | 'fail';
@@ -24,7 +59,35 @@ export declare function quotaIsStale(quota: {
24
59
  observedAt: string;
25
60
  fetchError?: string;
26
61
  }, now: number, lastUseAt?: string | null): boolean;
27
- export declare function quotaLevel(usedPercent: number): QuotaLevel;
62
+ /** The warning level of a used percent; `long` for a Long Window, which warns later (spec §3.26). */
63
+ export declare function quotaLevel(usedPercent: number, long?: boolean): QuotaLevel;
64
+ /** One window's warning level by its own kind: a Short Window warns at 60/85, a Long Window at 85/95. */
65
+ export declare function windowLevel(w: {
66
+ label?: string;
67
+ windowMinutes?: number;
68
+ usedPercent: number;
69
+ }): QuotaLevel;
70
+ /** The more serious of two levels. */
71
+ export declare function worseLevel(a: QuotaLevel, b: QuotaLevel): QuotaLevel;
72
+ /**
73
+ * The window that runs out first relative to its own kind: the highest used percent over that window's red level
74
+ * (85 for a Short Window, 95 for a Long one), the first on a tie. What the menu bar's reset column and title speak
75
+ * about. Undefined without windows.
76
+ */
77
+ export declare function bindingWindow<W extends {
78
+ label?: string;
79
+ windowMinutes?: number;
80
+ usedPercent: number;
81
+ }>(windows: readonly W[]): W | undefined;
82
+ /**
83
+ * Limit Use: how close an Account is to being full, as the percent of its own Takeover Limit that its closest window
84
+ * has used (a weekly window at 87% under a limit of 95 is 91.6; a 5-hour window at 43% under 85 is 50.6), with that
85
+ * window. Null when the Account has no Quota. A Handoff ranks ready Accounts by it, lowest first (spec §3.13).
86
+ */
87
+ export declare function limitUse(quota: QuotaResult | undefined, now: Date, limits: TakeoverLimits): {
88
+ percent: number;
89
+ window: QuotaWindow | null;
90
+ } | null;
28
91
  /** True once a window's reset time has passed; an unreadable time never counts as reset. */
29
92
  export declare function windowReset(resetsAt: string, now: Date): boolean;
30
93
  /**
@@ -1,17 +1,49 @@
1
1
  /**
2
- * How full a Quota window must be before the CLI and the Panel warn about it, and the Usage window both
3
- * report. One rule for both surfaces: the Panel interpolates these numbers into its inline script.
2
+ * How full a Quota window must be before the CLI, the Panel and the menu bar warn about it (yellow) and show it as
3
+ * nearly used up (red). A Short Window (5 hours) uses the first pair, a Long Window (weekly, a billing period) the
4
+ * second: one full 5-hour window costs only about a fifth of a weekly one, so 87% of a week still leaves several
5
+ * 5-hour windows of work (spec §3.26, ADR-0062). The Panel interpolates these numbers into its inline script.
4
6
  */
5
7
  export const QUOTA_FAIL_PERCENT = 85;
6
8
  export const QUOTA_WARN_PERCENT = 60;
9
+ export const QUOTA_LONG_FAIL_PERCENT = 95;
10
+ export const QUOTA_LONG_WARN_PERCENT = 85;
11
+ /** A window longer than this many minutes (one day) is a Long Window. No Host has a daily Quota. */
12
+ export const LONG_WINDOW_MINUTES = 1440;
7
13
  /**
8
14
  * Takeover Limit (spec §3.17 "接力规则"): an Account more used than this does not take over a Handoff, so the next
9
- * Account starts with room to work. It sits this many points below the Handoff Threshold and moves with it.
15
+ * Account starts with room to work. For a Short Window it sits this many points below the Handoff Threshold and moves
16
+ * with it; a Long Window's limit is the Handoff Threshold itself (`takeoverLimits`).
10
17
  */
11
18
  export const TAKEOVER_GAP = 10;
12
19
  export function takeoverLimit(threshold) {
13
20
  return Math.max(1, threshold - TAKEOVER_GAP);
14
21
  }
22
+ export function takeoverLimits(threshold) {
23
+ return { short: takeoverLimit(threshold), long: Math.max(1, Math.min(100, threshold)) };
24
+ }
25
+ /** The limits at the default Handoff Threshold (95): 85 for Short Windows, 95 for Long ones. */
26
+ export const DEFAULT_TAKEOVER_LIMITS = takeoverLimits(95);
27
+ const UNIT_MINUTES = { m: 1, h: 60, d: 1440, w: 10080 };
28
+ /**
29
+ * A window's length in minutes: `windowMinutes`, or read from a label such as `5h`, `7d` or `90m` when that is
30
+ * missing; 0 when neither tells. The Panel keeps its own copy in `longWindow` (page-logic.ts); a test keeps them equal.
31
+ */
32
+ export function windowLength(w) {
33
+ const minutes = Number(w.windowMinutes);
34
+ if (Number.isFinite(minutes) && minutes > 0)
35
+ return minutes;
36
+ const m = /^(\d+(?:\.\d+)?)\s*([mhdw])$/i.exec(String(w.label ?? '').trim());
37
+ return m ? Number(m[1]) * UNIT_MINUTES[m[2].toLowerCase()] : 0;
38
+ }
39
+ /** A Long Window: longer than one day (weekly, a billing period). Every other window is a Short Window. */
40
+ export function isLongWindow(w) {
41
+ return windowLength(w) > LONG_WINDOW_MINUTES;
42
+ }
43
+ /** The window's own Takeover Limit. */
44
+ export function limitOf(w, limits) {
45
+ return isLongWindow(w) ? limits.long : limits.short;
46
+ }
15
47
  /** Days of Usage every Family reports. */
16
48
  export const USAGE_DAYS = 7;
17
49
  /**
@@ -29,13 +61,57 @@ export function quotaIsStale(quota, now, lastUseAt) {
29
61
  const used = lastUseAt ? Date.parse(lastUseAt) : Number.NaN;
30
62
  return !(Number.isFinite(used) && used - at <= 600_000);
31
63
  }
32
- export function quotaLevel(usedPercent) {
33
- if (usedPercent >= QUOTA_FAIL_PERCENT)
64
+ /** The warning level of a used percent; `long` for a Long Window, which warns later (spec §3.26). */
65
+ export function quotaLevel(usedPercent, long = false) {
66
+ if (usedPercent >= (long ? QUOTA_LONG_FAIL_PERCENT : QUOTA_FAIL_PERCENT))
34
67
  return 'fail';
35
- if (usedPercent >= QUOTA_WARN_PERCENT)
68
+ if (usedPercent >= (long ? QUOTA_LONG_WARN_PERCENT : QUOTA_WARN_PERCENT))
36
69
  return 'warn';
37
70
  return 'ok';
38
71
  }
72
+ /** One window's warning level by its own kind: a Short Window warns at 60/85, a Long Window at 85/95. */
73
+ export function windowLevel(w) {
74
+ return quotaLevel(w.usedPercent, isLongWindow(w));
75
+ }
76
+ const LEVEL_RANK = { ok: 0, warn: 1, fail: 2 };
77
+ /** The more serious of two levels. */
78
+ export function worseLevel(a, b) {
79
+ return LEVEL_RANK[b] > LEVEL_RANK[a] ? b : a;
80
+ }
81
+ /**
82
+ * The window that runs out first relative to its own kind: the highest used percent over that window's red level
83
+ * (85 for a Short Window, 95 for a Long one), the first on a tie. What the menu bar's reset column and title speak
84
+ * about. Undefined without windows.
85
+ */
86
+ export function bindingWindow(windows) {
87
+ let best;
88
+ let bestShare = -1;
89
+ for (const w of windows) {
90
+ const share = w.usedPercent / (isLongWindow(w) ? QUOTA_LONG_FAIL_PERCENT : QUOTA_FAIL_PERCENT);
91
+ if (share > bestShare) {
92
+ best = w;
93
+ bestShare = share;
94
+ }
95
+ }
96
+ return best;
97
+ }
98
+ /**
99
+ * Limit Use: how close an Account is to being full, as the percent of its own Takeover Limit that its closest window
100
+ * has used (a weekly window at 87% under a limit of 95 is 91.6; a 5-hour window at 43% under 85 is 50.6), with that
101
+ * window. Null when the Account has no Quota. A Handoff ranks ready Accounts by it, lowest first (spec §3.13).
102
+ */
103
+ export function limitUse(quota, now, limits) {
104
+ const windows = openWindows(quota, now);
105
+ if (windows === null)
106
+ return null;
107
+ let best = { percent: 0, window: null };
108
+ for (const w of windows) {
109
+ const percent = Math.round((w.usedPercent / limitOf(w, limits)) * 1000) / 10;
110
+ if (best.window === null || percent > best.percent)
111
+ best = { percent, window: w };
112
+ }
113
+ return best;
114
+ }
39
115
  /** True once a window's reset time has passed; an unreadable time never counts as reset. */
40
116
  export function windowReset(resetsAt, now) {
41
117
  const t = Date.parse(resetsAt);
@@ -11,6 +11,7 @@ import { claudeHandoff } from './handoff.js';
11
11
  import { CLAUDE_LAYOUT } from './layout.js';
12
12
  import { claudeModelChoice } from './model.js';
13
13
  import { readClaudeQuota } from './quota.js';
14
+ import { claudeQuotaFetch } from './quota-fetch.js';
14
15
  import { readClaudeTuning } from './tuning.js';
15
16
  import { readClaudeUsage } from './usage.js';
16
17
  const LINKED = [
@@ -127,6 +128,8 @@ export const claudeFamily = {
127
128
  modelChoice: claudeModelChoice,
128
129
  identity: claudeIdentity,
129
130
  readQuota: readClaudeQuota,
131
+ // Newer of the two shows: the status line's reading while a session runs, else the `/usage` answer (ADR-0063).
132
+ fetchQuota: claudeQuotaFetch,
130
133
  readUsage: readClaudeUsage,
131
134
  readTuning: readClaudeTuning,
132
135
  quotaSetup: claudeStatusline,
@@ -0,0 +1,26 @@
1
+ import type { Account, QuotaFetch, QuotaFetchContext, QuotaResult, QuotaWindow } from '../../types.ts';
2
+ /**
3
+ * Hooks off and no MCP servers: a quota check is no session, so the user's hooks (notifications, loggers) must not
4
+ * run for it and no MCP server needs starting. `/usage` itself needs neither.
5
+ */
6
+ export declare const CLAUDE_QUOTA_ARGS: readonly ['-p', '/usage', '--no-session-persistence', '--output-format', 'json', '--settings', '{"disableAllHooks":true}', '--strict-mcp-config'];
7
+ export declare const QUOTA_FETCH_SOURCE = "claude /usage";
8
+ /**
9
+ * The instant "resets Nov 2 at 4am (Asia/Singapore)" names: the first such time after now (a few minutes of slack)
10
+ * within `minutes`, since Claude Code writes no year. A time without a date is today's or a later day's. Null when the
11
+ * text does not parse, the time zone is unknown, or no such time falls in the window.
12
+ */
13
+ export declare function resetInstant(text: string, now: number, minutes: number): number | null;
14
+ /**
15
+ * The Quota in the text of Claude Code's `/usage` answer, or null when any `Current …` line does not parse (no
16
+ * partial guess). `Current session` is the 5-hour window, `Current week (all models)` the weekly one, and a week for
17
+ * one model (`Current week (Fable)`) a window named after it, which never counts toward Quota Pressure.
18
+ */
19
+ export declare function usageQuota(text: string, now: number): QuotaWindow[] | null;
20
+ /**
21
+ * The Quota in Claude Code's JSON answer, or why there is none. Claude Code's own words are only matched, never
22
+ * repeated: the text holds this computer's sessions, skills and MCP servers.
23
+ */
24
+ export declare function claudeUsageAnswer(answer: unknown, account: Account, now: number): QuotaResult;
25
+ export declare function fetchClaudeQuota(account: Account, ctx: QuotaFetchContext): Promise<QuotaResult>;
26
+ export declare const claudeQuotaFetch: QuotaFetch;
@@ -0,0 +1,236 @@
1
+ // Asks Claude Code for a subscription Account's Quota (spec §3.26, ADR-0063): `claude -p /usage
2
+ // --no-session-persistence --output-format json` runs the local `/usage` command with the Account's own sign-in and
3
+ // starts no model turn (`num_turns` 0, `total_cost_usd` 0, `local_command` "usage"; tried with Claude Code 2.1.314
4
+ // on 2026-10-30). sideby never reads the sign-in and sends no request of its own. Of the answer's text only the
5
+ // `Current session:` and `Current week (...)` lines are read; everything else in it (request counts, sessions,
6
+ // skills, subagents, MCP servers) is never kept, logged or returned.
7
+ import { spawn } from 'node:child_process';
8
+ import { join } from 'node:path';
9
+ import { ownedFolder } from '../../core/fs-safe.js';
10
+ /**
11
+ * Hooks off and no MCP servers: a quota check is no session, so the user's hooks (notifications, loggers) must not
12
+ * run for it and no MCP server needs starting. `/usage` itself needs neither.
13
+ */
14
+ export const CLAUDE_QUOTA_ARGS = [
15
+ '-p',
16
+ '/usage',
17
+ '--no-session-persistence',
18
+ '--output-format',
19
+ 'json',
20
+ '--settings',
21
+ '{"disableAllHooks":true}',
22
+ '--strict-mcp-config',
23
+ ];
24
+ /** Claude Code answers in about 4 s with a few KB; anything far larger is not its answer. */
25
+ const MAX_OUTPUT = 512 * 1024;
26
+ export const QUOTA_FETCH_SOURCE = 'claude /usage';
27
+ const failed = (detail) => ({ status: 'unavailable', reason: 'fetch-failed', detail });
28
+ const UNRECOGNISED = 'Claude Code answered /usage in a form sideby does not recognise; update sideby';
29
+ const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
30
+ const SESSION = { label: '5h', minutes: 300 };
31
+ const WEEK = { label: '7d', minutes: 7 * 24 * 60 };
32
+ /** A reset a little in the past still counts: the answer is a few seconds old when read. */
33
+ const PAST_SLACK_MS = 5 * 60_000;
34
+ /** The offset (ms) of `timeZone` from UTC at the instant `utc`. */
35
+ function zoneOffset(utc, timeZone) {
36
+ const parts = new Intl.DateTimeFormat('en-US', {
37
+ timeZone,
38
+ hourCycle: 'h23',
39
+ year: 'numeric',
40
+ month: 'numeric',
41
+ day: 'numeric',
42
+ hour: 'numeric',
43
+ minute: 'numeric',
44
+ second: 'numeric',
45
+ }).formatToParts(new Date(utc));
46
+ const n = (t) => Number(parts.find((p) => p.type === t)?.value);
47
+ const wall = Date.UTC(n('year'), n('month') - 1, n('day'), n('hour') % 24, n('minute'), n('second'));
48
+ return wall - Math.floor(utc / 1000) * 1000;
49
+ }
50
+ /** The instant a wall-clock time in `timeZone` names. */
51
+ function zonedInstant(y, mo, d, h, mi, timeZone) {
52
+ const wall = Date.UTC(y, mo, d, h, mi);
53
+ let utc = wall - zoneOffset(wall, timeZone);
54
+ utc = wall - zoneOffset(utc, timeZone);
55
+ return utc;
56
+ }
57
+ /** The calendar date of `now` in `timeZone`. */
58
+ function zonedDate(now, timeZone) {
59
+ const local = new Date(now + zoneOffset(now, timeZone));
60
+ return { y: local.getUTCFullYear(), mo: local.getUTCMonth(), d: local.getUTCDate() };
61
+ }
62
+ const RESET = /^resets (?:([A-Za-z]{3,9})\.? (\d{1,2})(?:,? (\d{4}))? at )?(\d{1,2})(?::(\d{2}))?\s?(am|pm) \(([A-Za-z0-9_+\-/]+)\)$/i;
63
+ /**
64
+ * The instant "resets Nov 2 at 4am (Asia/Singapore)" names: the first such time after now (a few minutes of slack)
65
+ * within `minutes`, since Claude Code writes no year. A time without a date is today's or a later day's. Null when the
66
+ * text does not parse, the time zone is unknown, or no such time falls in the window.
67
+ */
68
+ export function resetInstant(text, now, minutes) {
69
+ const m = RESET.exec(text.trim());
70
+ if (!m)
71
+ return null;
72
+ const [, mon, day, year, hour = '', minute, ampm = '', timeZone = ''] = m;
73
+ try {
74
+ new Intl.DateTimeFormat('en-US', { timeZone });
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ const h12 = Number(hour);
80
+ const mi = minute === undefined ? 0 : Number(minute);
81
+ if (h12 < 1 || h12 > 12 || mi > 59)
82
+ return null;
83
+ const h = (h12 % 12) + (ampm.toLowerCase() === 'pm' ? 12 : 0);
84
+ const fits = (t) => t >= now - PAST_SLACK_MS && t <= now + minutes * 60_000 + PAST_SLACK_MS;
85
+ const today = zonedDate(now, timeZone);
86
+ const candidates = [];
87
+ if (mon !== undefined) {
88
+ const mo = MONTHS.indexOf(mon.slice(0, 3).toLowerCase());
89
+ const d = Number(day);
90
+ if (mo < 0 || d < 1 || d > 31)
91
+ return null;
92
+ for (const y of year ? [Number(year)] : [today.y - 1, today.y, today.y + 1]) {
93
+ // A day the month does not have (Feb 30) rolls over in Date.UTC; such a time is not the one named.
94
+ if (new Date(Date.UTC(y, mo, d)).getUTCDate() !== d)
95
+ continue;
96
+ candidates.push(zonedInstant(y, mo, d, h, mi, timeZone));
97
+ }
98
+ }
99
+ else {
100
+ for (let i = -1; i <= Math.ceil(minutes / 1440) + 1; i++)
101
+ candidates.push(zonedInstant(today.y, today.mo, today.d + i, h, mi, timeZone));
102
+ }
103
+ const ok = candidates.filter(fits).sort((a, b) => a - b);
104
+ return ok[0] ?? null;
105
+ }
106
+ const LINE = /^Current (session|week \(([^)\n]{1,60})\)):\s*(\d{1,3}(?:\.\d+)?)% used(?:\s*·\s*(.+))?$/;
107
+ /**
108
+ * The Quota in the text of Claude Code's `/usage` answer, or null when any `Current …` line does not parse (no
109
+ * partial guess). `Current session` is the 5-hour window, `Current week (all models)` the weekly one, and a week for
110
+ * one model (`Current week (Fable)`) a window named after it, which never counts toward Quota Pressure.
111
+ */
112
+ export function usageQuota(text, now) {
113
+ const windows = [];
114
+ for (const raw of text.split('\n')) {
115
+ const line = raw.trim();
116
+ if (!line.startsWith('Current '))
117
+ continue;
118
+ const m = LINE.exec(line);
119
+ if (!m)
120
+ return null;
121
+ const [, kind, model = '', pct, reset] = m;
122
+ const used = Number(pct);
123
+ if (!Number.isFinite(used) || used > 100)
124
+ return null;
125
+ const all = kind === 'session' || model === 'all models';
126
+ const w = kind === 'session' ? SESSION : WEEK;
127
+ if (!all && !/^[\w .\-+]+$/.test(model))
128
+ return null;
129
+ if (reset === undefined) {
130
+ // A window nothing has used yet has no reset; there is nothing to show for it.
131
+ if (used === 0)
132
+ continue;
133
+ return null;
134
+ }
135
+ const at = resetInstant(reset, now, w.minutes);
136
+ if (at === null)
137
+ return null;
138
+ windows.push({
139
+ label: w.label,
140
+ ...(all ? {} : { name: model.trim() }),
141
+ windowMinutes: w.minutes,
142
+ usedPercent: Math.round(used),
143
+ resetsAt: new Date(at).toISOString(),
144
+ });
145
+ }
146
+ return windows.some((w) => !w.name) ? windows : null;
147
+ }
148
+ /**
149
+ * The Quota in Claude Code's JSON answer, or why there is none. Claude Code's own words are only matched, never
150
+ * repeated: the text holds this computer's sessions, skills and MCP servers.
151
+ */
152
+ export function claudeUsageAnswer(answer, account, now) {
153
+ if (typeof answer !== 'object' || answer === null)
154
+ return failed(UNRECOGNISED);
155
+ const a = answer;
156
+ const text = typeof a.result === 'string' ? a.result : '';
157
+ const local = a.local_command === 'usage' &&
158
+ a.is_error !== true &&
159
+ !(typeof a.num_turns === 'number' && a.num_turns > 0);
160
+ const windows = local ? usageQuota(text, now) : null;
161
+ if (windows)
162
+ return { status: 'ok', windows, observedAt: new Date(now).toISOString(), source: QUOTA_FETCH_SOURCE };
163
+ if (/not logged in|please (?:run )?\/login|please log ?in/i.test(text))
164
+ return failed(`Claude Code is not signed in; run \`sideby login ${account.ref}\`, then refresh`);
165
+ if (/using your API key|API usage billing/i.test(text))
166
+ return failed('this account uses an API key, which has no subscription quota');
167
+ if (!local)
168
+ return failed('this Claude Code version cannot report quota through /usage; update Claude Code, then refresh');
169
+ return failed(UNRECOGNISED);
170
+ }
171
+ export async function fetchClaudeQuota(account, ctx) {
172
+ if (ctx.signal.aborted)
173
+ return failed('the quota check was stopped; refresh to try again');
174
+ if (account.kind === 'api')
175
+ return failed('an API account has no subscription quota');
176
+ // A folder of sideby's own, so Claude Code never starts in (or records) one of the user's projects.
177
+ let cwd;
178
+ try {
179
+ cwd = await ownedFolder(ctx.stateDir, ['quota', 'claude-run'], { create: true });
180
+ }
181
+ catch {
182
+ cwd = null;
183
+ }
184
+ if (!cwd)
185
+ return failed(`sideby's folder ${join(ctx.stateDir, 'quota')} is not safe to use; check its owner and mode`);
186
+ const child = spawn('claude', [...CLAUDE_QUOTA_ARGS], {
187
+ cwd,
188
+ env: ctx.hostEnv,
189
+ // stderr may name this computer's paths or settings: never read.
190
+ stdio: ['ignore', 'pipe', 'ignore'],
191
+ });
192
+ // Only this short-lived query process is ended, never a running Claude Code session.
193
+ const stop = () => {
194
+ if (child.exitCode === null && child.signalCode === null)
195
+ child.kill('SIGTERM');
196
+ };
197
+ ctx.signal.addEventListener('abort', stop, { once: true });
198
+ try {
199
+ return await new Promise((resolve) => {
200
+ const chunks = [];
201
+ let size = 0;
202
+ child.stdout.on('data', (b) => {
203
+ size += b.length;
204
+ if (size > MAX_OUTPUT)
205
+ return stop();
206
+ chunks.push(b);
207
+ });
208
+ child.on('error', (err) => resolve(failed(err.code === 'ENOENT'
209
+ ? 'Claude Code is not installed or not on PATH; install it, then refresh'
210
+ : `could not start Claude Code (${err.code ?? 'error'})`)));
211
+ child.on('close', () => {
212
+ if (ctx.signal.aborted)
213
+ return resolve(failed('the quota check was stopped; refresh to try again'));
214
+ if (size > MAX_OUTPUT)
215
+ return resolve(failed(UNRECOGNISED));
216
+ let answer;
217
+ try {
218
+ answer = JSON.parse(Buffer.concat(chunks).toString('utf8'));
219
+ }
220
+ catch {
221
+ return resolve(failed('Claude Code exited without answering; sideby asks again later'));
222
+ }
223
+ resolve(claudeUsageAnswer(answer, account, ctx.now.getTime()));
224
+ });
225
+ });
226
+ }
227
+ finally {
228
+ ctx.signal.removeEventListener('abort', stop);
229
+ stop();
230
+ }
231
+ }
232
+ export const claudeQuotaFetch = {
233
+ everyMinutes: 15,
234
+ summary: 'Ask Claude Code for each account’s quota (its /usage command, no model turn) every 15 minutes',
235
+ fetch: fetchClaudeQuota,
236
+ };
@@ -329,13 +329,18 @@ function run(argv) {
329
329
  head: $.NSFont.systemFontOfSizeWeight(size - 2, $.NSFontWeightSemibold),
330
330
  small: $.NSFont.systemFontOfSize(size - 2),
331
331
  };
332
- var nameW = 0, first = false;
332
+ // The reset column names its window ("7d · in 4d 17h"), so it is as wide as its longest entry.
333
+ var nameW = 0, first = false, resetW = width('7d · in 24d 23h', L.font);
333
334
  sections.forEach(function (s) {
334
335
  nameW = Math.max(nameW, width(s.title, L.head));
335
336
  if (s.columns[0]) first = true;
336
337
  s.rows.concat(s.more ? s.more.rows : []).forEach(function (r) {
337
338
  nameW = Math.max(nameW, width(r.label, L.font));
338
- (r.groups || []).forEach(function (g) { nameW = Math.max(nameW, width(GROUP_INDENT + g.label, L.font)); });
339
+ if (r.reset) resetW = Math.max(resetW, width(r.reset, L.font));
340
+ (r.groups || []).forEach(function (g) {
341
+ nameW = Math.max(nameW, width(GROUP_INDENT + g.label, L.font));
342
+ if (g.reset) resetW = Math.max(resetW, width(g.reset, L.font));
343
+ });
339
344
  });
340
345
  });
341
346
  var pctW = width('100%', L.mono), x = Math.ceil(nameW) + 20, stops = [], at = [];
@@ -355,7 +360,7 @@ function run(argv) {
355
360
  L.headPara.tabStops = $(at.concat([x]).map(function (pos) {
356
361
  return $.NSTextTab.alloc.initWithTextAlignmentLocationOptions($.NSTextAlignmentLeft, pos, $());
357
362
  }));
358
- L.width = x + width('24d 23h', L.font) + 70;
363
+ L.width = x + resetW + 70;
359
364
  return L;
360
365
  }
361
366
  function rowTitle(r, L) {
@@ -37,7 +37,10 @@ export interface MenubarRow {
37
37
  reset: string;
38
38
  tip: string;
39
39
  }[] | null;
40
- /** How long until the fullest window resets, such as `4d 17h`; empty when nothing is used. */
40
+ /**
41
+ * Which window resets and how long until it does, such as `7d · in 4d 17h`: the window closest to its own red level
42
+ * (85% for 5 hours, 95% for a week), so the one that runs out first. Empty when nothing is used.
43
+ */
41
44
  reset: string;
42
45
  /** A no-quota explanation, or an old-reading warning beside the bars. */
43
46
  note: string;
@@ -91,7 +94,7 @@ export interface MenubarFamilyInput {
91
94
  title: string;
92
95
  logo?: FamilyLogo | null;
93
96
  /**
94
- * Whether "Refresh" asks the Host for new numbers (the Family has `fetchQuota`). False for Claude Code, whose Quota
97
+ * Whether "Refresh" asks the Host for new numbers (the Family has `fetchQuota`). False for a Family whose Quota
95
98
  * changes only when a session runs in the account; old readings then say so. Default true.
96
99
  */
97
100
  refreshable?: boolean;
@@ -137,9 +140,10 @@ export declare function quotaGroups(quota: QuotaResult): {
137
140
  };
138
141
  }[] | null;
139
142
  /**
140
- * Each Family's number is the Quota Pressure of the account `sideby next` would pick, or, when every account is past
141
- * the fail level, the lowest of theirs; the title shows the highest of these, so it turns red when some tool has
142
- * nothing left to hand over to.
143
+ * Each Family's number is the account `sideby next` would pick, or, when every account is full, the one with the lowest
144
+ * Limit Use: the used percent of its window closest to its own limit, colored by that account's windows at their own
145
+ * levels (spec §3.26). The title shows the tightest of these by Limit Use, so it turns red when some tool has nothing
146
+ * left to hand over to, and a weekly window at 87% stays quiet.
143
147
  */
144
148
  export declare function menubarSnapshot(families: readonly MenubarFamilyInput[], now: Date, lang: MenubarLang, hotkey?: MenubarHotkey | null): MenubarSnapshot;
145
149
  /** The language of the menu: config `panel.language`, else the system language the script passes, else English. */