sideby 0.31.3 → 0.32.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.
- package/README.md +4 -4
- package/dist/build.json +1 -1
- package/dist/src/cli/commands.js +27 -11
- package/dist/src/cli/format.js +3 -2
- package/dist/src/cli/json-schemas.js +25 -5
- package/dist/src/core/ask.js +6 -1
- package/dist/src/core/handoff-rules.js +5 -5
- package/dist/src/core/handoff-select.js +6 -6
- package/dist/src/core/handoff.d.ts +36 -3
- package/dist/src/core/handoff.js +57 -18
- package/dist/src/core/pick-commands.d.ts +19 -4
- package/dist/src/core/pick-commands.js +19 -5
- package/dist/src/core/quota-levels.d.ts +67 -4
- package/dist/src/core/quota-levels.js +82 -6
- package/dist/src/families/claude/index.js +3 -0
- package/dist/src/families/claude/quota-fetch.d.ts +26 -0
- package/dist/src/families/claude/quota-fetch.js +236 -0
- package/dist/src/menubar/script.js +62 -12
- package/dist/src/menubar/snapshot.d.ts +9 -5
- package/dist/src/menubar/snapshot.js +37 -24
- package/dist/src/menubar/strings.d.ts +6 -4
- package/dist/src/menubar/strings.js +6 -4
- package/dist/src/panel/handler.js +7 -3
- package/dist/src/panel/i18n.d.ts +1 -0
- package/dist/src/panel/i18n.js +8 -6
- package/dist/src/panel/page-logic.d.ts +32 -8
- package/dist/src/panel/page-logic.js +43 -16
- package/dist/src/panel/page-script.js +12 -9
- package/dist/src/panel/page.js +3 -1
- package/dist/src/runtime.d.ts +2 -1
- package/dist/src/runtime.js +10 -4
- package/dist/testing/index.d.ts +5 -0
- package/dist/testing/index.js +2 -0
- package/package.json +2 -2
- package/schemas/menubar-snapshot.json +3 -3
- package/schemas/next.json +57 -4
- package/skills/sideby/SKILL.md +2 -2
- package/skills/sideby/references/accounts.md +1 -1
- package/skills/sideby/references/ai-tasks.md +2 -2
- package/skills/sideby/references/diagnose.md +1 -1
- package/skills/sideby/references/handoff.md +12 -8
- package/skills/sideby/references/panel.md +1 -1
- 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
|
|
4
|
-
*
|
|
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.
|
|
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
|
-
|
|
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
|
|
3
|
-
*
|
|
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.
|
|
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
|
-
|
|
33
|
-
|
|
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
|
+
};
|
|
@@ -45,7 +45,7 @@ function run(argv) {
|
|
|
45
45
|
|
|
46
46
|
var out = ObjC.unwrap($.NSTemporaryDirectory()) + 'sideby-menubar-' + $.NSProcessInfo.processInfo.processIdentifier + '.json';
|
|
47
47
|
var snap = null, task = null, handle = null, lastStart = 0, lastOk = 0, failed = false;
|
|
48
|
-
var refs = [], actions = [], footer = null, appearance = '';
|
|
48
|
+
var refs = [], actions = [], footer = null, appearance = '', manual = false;
|
|
49
49
|
// The first words, before any snapshot has said which language to use.
|
|
50
50
|
var zh = /^zh/i.test(lang);
|
|
51
51
|
var CARD_ICON = ${JSON.stringify(FAVICON_SVG)};
|
|
@@ -89,6 +89,7 @@ function run(argv) {
|
|
|
89
89
|
function finishSnapshot() {
|
|
90
90
|
var ok = task.terminationStatus === 0;
|
|
91
91
|
task = null;
|
|
92
|
+
manual = false;
|
|
92
93
|
closeHandle();
|
|
93
94
|
if (ok) {
|
|
94
95
|
try {
|
|
@@ -233,7 +234,7 @@ function run(argv) {
|
|
|
233
234
|
function footerText() {
|
|
234
235
|
if (!snap) return LOADING;
|
|
235
236
|
var l = snap.labels;
|
|
236
|
-
if (task && !lastOk) return l.refreshing;
|
|
237
|
+
if (task && (manual || !lastOk)) return l.refreshing;
|
|
237
238
|
if (failed) return l.refreshFailed;
|
|
238
239
|
var minutes = Math.floor((now() - lastOk) / 60);
|
|
239
240
|
return minutes < 1 ? l.updatedJustNow : l.updatedMinutes.replace('{n}', String(minutes));
|
|
@@ -329,13 +330,18 @@ function run(argv) {
|
|
|
329
330
|
head: $.NSFont.systemFontOfSizeWeight(size - 2, $.NSFontWeightSemibold),
|
|
330
331
|
small: $.NSFont.systemFontOfSize(size - 2),
|
|
331
332
|
};
|
|
332
|
-
|
|
333
|
+
// The reset column names its window ("7d · in 4d 17h"), so it is as wide as its longest entry.
|
|
334
|
+
var nameW = 0, first = false, resetW = width('7d · in 24d 23h', L.font);
|
|
333
335
|
sections.forEach(function (s) {
|
|
334
336
|
nameW = Math.max(nameW, width(s.title, L.head));
|
|
335
337
|
if (s.columns[0]) first = true;
|
|
336
338
|
s.rows.concat(s.more ? s.more.rows : []).forEach(function (r) {
|
|
337
339
|
nameW = Math.max(nameW, width(r.label, L.font));
|
|
338
|
-
(r.
|
|
340
|
+
if (r.reset) resetW = Math.max(resetW, width(r.reset, L.font));
|
|
341
|
+
(r.groups || []).forEach(function (g) {
|
|
342
|
+
nameW = Math.max(nameW, width(GROUP_INDENT + g.label, L.font));
|
|
343
|
+
if (g.reset) resetW = Math.max(resetW, width(g.reset, L.font));
|
|
344
|
+
});
|
|
339
345
|
});
|
|
340
346
|
});
|
|
341
347
|
var pctW = width('100%', L.mono), x = Math.ceil(nameW) + 20, stops = [], at = [];
|
|
@@ -355,7 +361,7 @@ function run(argv) {
|
|
|
355
361
|
L.headPara.tabStops = $(at.concat([x]).map(function (pos) {
|
|
356
362
|
return $.NSTextTab.alloc.initWithTextAlignmentLocationOptions($.NSTextAlignmentLeft, pos, $());
|
|
357
363
|
}));
|
|
358
|
-
L.width = x +
|
|
364
|
+
L.width = x + resetW + 70;
|
|
359
365
|
return L;
|
|
360
366
|
}
|
|
361
367
|
function rowTitle(r, L) {
|
|
@@ -460,10 +466,52 @@ function run(argv) {
|
|
|
460
466
|
if (img) mi.image = img;
|
|
461
467
|
return mi;
|
|
462
468
|
}
|
|
469
|
+
// The last line: when the numbers were checked, and a refresh button. A button in a view keeps the menu open, so
|
|
470
|
+
// a click shows "Refreshing…" and then the new numbers in place, as menu bar apps such as CodexBar do. ⌘R does the
|
|
471
|
+
// same through a hidden item.
|
|
472
|
+
function footerItem(menu, L, refreshTitle) {
|
|
473
|
+
var W = Math.max(280, L ? L.width : 280), H = 24;
|
|
474
|
+
var v = $.NSView.alloc.initWithFrame($.NSMakeRect(0, 0, W, H));
|
|
475
|
+
v.autoresizingMask = $.NSViewWidthSizable;
|
|
476
|
+
var clock = symbol('clock');
|
|
477
|
+
if (clock) {
|
|
478
|
+
var iv = $.NSImageView.imageViewWithImage(clock);
|
|
479
|
+
iv.frame = $.NSMakeRect(HEAD_X, (H - 14) / 2, 14, 14);
|
|
480
|
+
iv.contentTintColor = $.NSColor.secondaryLabelColor;
|
|
481
|
+
v.addSubview(iv);
|
|
482
|
+
}
|
|
483
|
+
footer = $.NSTextField.labelWithString(footerText());
|
|
484
|
+
footer.font = $.NSFont.menuFontOfSize(0);
|
|
485
|
+
footer.textColor = $.NSColor.secondaryLabelColor;
|
|
486
|
+
footer.frame = $.NSMakeRect(HEAD_TEXT_X, (H - 17) / 2, W - HEAD_TEXT_X - 44, 17);
|
|
487
|
+
v.addSubview(footer);
|
|
488
|
+
if (refreshTitle) {
|
|
489
|
+
var b = $.NSButton.alloc.initWithFrame($.NSMakeRect(W - 38, (H - 22) / 2, 26, 22));
|
|
490
|
+
b.autoresizingMask = $.NSViewMinXMargin;
|
|
491
|
+
b.bezelStyle = $.NSBezelStyleRecessed;
|
|
492
|
+
b.showsBorderOnlyWhileMouseInside = true;
|
|
493
|
+
b.image = symbol('arrow.clockwise');
|
|
494
|
+
b.imagePosition = $.NSImageOnly;
|
|
495
|
+
b.toolTip = refreshTitle + ' (⌘R)';
|
|
496
|
+
b.target = target;
|
|
497
|
+
b.action = 'refresh:';
|
|
498
|
+
v.addSubview(b);
|
|
499
|
+
var key = $.NSMenuItem.alloc.initWithTitleActionKeyEquivalent(refreshTitle, 'refresh:', 'r');
|
|
500
|
+
key.target = target;
|
|
501
|
+
key.hidden = true;
|
|
502
|
+
key.allowsKeyEquivalentWhenHidden = true;
|
|
503
|
+
menu.addItem(key);
|
|
504
|
+
}
|
|
505
|
+
var mi = $.NSMenuItem.alloc.init;
|
|
506
|
+
mi.view = v;
|
|
507
|
+
menu.addItem(mi);
|
|
508
|
+
}
|
|
509
|
+
// One menu for the item's life: a rebuild swaps its items, so an open menu shows new numbers in place.
|
|
510
|
+
var menu = $.NSMenu.alloc.init;
|
|
511
|
+
menu.autoenablesItems = false;
|
|
463
512
|
function build() {
|
|
464
513
|
drawTitle();
|
|
465
|
-
|
|
466
|
-
menu.autoenablesItems = false;
|
|
514
|
+
menu.removeAllItems;
|
|
467
515
|
refs = [];
|
|
468
516
|
if (snap) {
|
|
469
517
|
var L = layout(snap.sections);
|
|
@@ -491,15 +539,14 @@ function run(argv) {
|
|
|
491
539
|
}
|
|
492
540
|
});
|
|
493
541
|
menu.addItem($.NSMenuItem.separatorItem);
|
|
494
|
-
|
|
495
|
-
withImage(add(menu, snap.labels.refresh, 'refresh:', 0, 'r'), 'arrow.clockwise');
|
|
542
|
+
footerItem(menu, L, snap.labels.refresh);
|
|
496
543
|
withImage(add(menu, snap.labels.openPanel, 'openPanel:', 0, 'o'), 'macwindow');
|
|
497
544
|
menu.addItem($.NSMenuItem.separatorItem);
|
|
498
545
|
if (hotkeyStatus === 'taken' && hotkeyWant)
|
|
499
546
|
withImage(add(menu, snap.labels.hotkeyTaken.replace('{key}', hotkeyWant.label), 'openPanel:'), 'keyboard');
|
|
500
547
|
withImage(add(menu, snap.labels.hide, 'hide:'), 'eye.slash');
|
|
501
548
|
} else {
|
|
502
|
-
|
|
549
|
+
footerItem(menu, null, null);
|
|
503
550
|
withImage(add(menu, OPEN_PANEL, 'openPanel:', 0, 'o'), 'macwindow');
|
|
504
551
|
}
|
|
505
552
|
closeItem(menu);
|
|
@@ -533,14 +580,16 @@ function run(argv) {
|
|
|
533
580
|
// The bars are pictures in the colours of the moment; redraw them when light or dark mode changes.
|
|
534
581
|
if (ObjC.unwrap(app.effectiveAppearance.name) !== appearance) build();
|
|
535
582
|
else drawTitle();
|
|
536
|
-
if (footer) footer.
|
|
583
|
+
if (footer) footer.stringValue = footerText();
|
|
537
584
|
},
|
|
538
585
|
},
|
|
539
586
|
'refresh:': {
|
|
540
587
|
types: ['void', ['id']],
|
|
541
588
|
implementation: function () {
|
|
542
589
|
// A manual refresh must query the Host, even if an automatic cache read is already running.
|
|
590
|
+
manual = true;
|
|
543
591
|
startSnapshot(true);
|
|
592
|
+
if (footer) footer.stringValue = footerText();
|
|
544
593
|
},
|
|
545
594
|
},
|
|
546
595
|
// A setting changed (the shortcut): read the snapshot again now, after one that is running, with no restart.
|
|
@@ -587,7 +636,8 @@ function run(argv) {
|
|
|
587
636
|
$.NSDistributedNotificationCenter.defaultCenter.addObserverSelectorNameObject(target, 'reload:', $('${MENUBAR_RELOAD}'), $());
|
|
588
637
|
build();
|
|
589
638
|
startSnapshot();
|
|
590
|
-
|
|
639
|
+
// Common modes: the tick also runs while the menu is open, so a refresh started there lands in place.
|
|
640
|
+
$.NSRunLoop.mainRunLoop.addTimerForMode($.NSTimer.timerWithTimeIntervalTargetSelectorUserInfoRepeats(TICK, target, 'tick:', $(), true), $.NSRunLoopCommonModes);
|
|
591
641
|
app.run;
|
|
592
642
|
}
|
|
593
643
|
`;
|