sideby 0.31.2 → 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.
- package/README.md +4 -4
- package/dist/build.json +1 -1
- package/dist/src/cli/commands.d.ts +0 -4
- package/dist/src/cli/commands.js +76 -14
- package/dist/src/cli/format.js +3 -2
- package/dist/src/cli/json-schemas.js +45 -5
- package/dist/src/cli/main.js +19 -159
- package/dist/src/core/ask.js +6 -1
- package/dist/src/core/cli-commands.d.ts +56 -0
- package/dist/src/core/cli-commands.js +842 -0
- package/dist/src/core/handoff-chain.d.ts +9 -3
- package/dist/src/core/handoff-chain.js +3 -2
- package/dist/src/core/handoff-rules.js +5 -5
- package/dist/src/core/handoff-run.js +19 -2
- package/dist/src/core/handoff-select.d.ts +15 -5
- package/dist/src/core/handoff-select.js +34 -22
- 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/core/search-catalog.js +20 -0
- 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/handoff/hook.js +5 -0
- package/dist/src/menubar/script.js +8 -3
- 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 +15 -0
- package/dist/src/panel/i18n.js +36 -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 +129 -17
- package/dist/src/panel/page-styles.js +18 -0
- package/dist/src/panel/page.js +6 -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/commands-list.json +165 -0
- package/schemas/menubar-snapshot.json +3 -3
- package/schemas/next.json +57 -4
- package/skills/sideby/SKILL.md +3 -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 +13 -9
- package/skills/sideby/references/panel.md +11 -1
- package/skills/sideby/references/quota.md +9 -3
|
@@ -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);
|
|
@@ -312,6 +312,26 @@ const ENTRIES = [
|
|
|
312
312
|
target: { action: 'ask', write: true },
|
|
313
313
|
cliCommand: 'sideby ask',
|
|
314
314
|
},
|
|
315
|
+
{
|
|
316
|
+
id: 'action.commands',
|
|
317
|
+
kind: 'action',
|
|
318
|
+
title: { en: 'Commands', zh: '命令' },
|
|
319
|
+
synonyms: [
|
|
320
|
+
'command list',
|
|
321
|
+
'commands',
|
|
322
|
+
'cli',
|
|
323
|
+
'terminal',
|
|
324
|
+
'help',
|
|
325
|
+
'shortcuts',
|
|
326
|
+
'命令列表',
|
|
327
|
+
'指令',
|
|
328
|
+
'终端命令',
|
|
329
|
+
'帮助',
|
|
330
|
+
],
|
|
331
|
+
panel: at(HEADER, { en: 'Commands', zh: '命令' }),
|
|
332
|
+
target: { action: 'commands', write: false },
|
|
333
|
+
cliCommand: 'sideby commands',
|
|
334
|
+
},
|
|
315
335
|
{
|
|
316
336
|
id: 'action.health-check',
|
|
317
337
|
kind: 'action',
|
|
@@ -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
|
+
};
|
package/dist/src/handoff/hook.js
CHANGED
|
@@ -121,6 +121,11 @@ export async function decide(opts) {
|
|
|
121
121
|
const reason = field(input, 'reason');
|
|
122
122
|
if (reason && reason !== 'end_turn')
|
|
123
123
|
return {};
|
|
124
|
+
// A finished turn means a Host kept at its limit has continued: a later `handoff ready` waits for the turn again.
|
|
125
|
+
const waitingFile = join(dir, FILES.waiting);
|
|
126
|
+
const held = await readJsonFile(waitingFile);
|
|
127
|
+
if (held && held.runId === runId && held.trigger === 'limit')
|
|
128
|
+
await rm(waitingFile, { force: true });
|
|
124
129
|
const request = await readJsonFile(join(dir, FILES.request));
|
|
125
130
|
if (request && request.runId === runId) {
|
|
126
131
|
await ready({ ...request, trigger: 'manual' });
|
|
@@ -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
|
-
|
|
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.
|
|
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 +
|
|
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
|
-
/**
|
|
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
|
|
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
|
|
141
|
-
*
|
|
142
|
-
*
|
|
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. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { openWindows, quotaIsStale,
|
|
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),
|
|
102
|
-
*
|
|
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:
|
|
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
|
-
|
|
124
|
-
const
|
|
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:
|
|
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.
|
|
214
|
-
parts.push(fill(s.resets, { time: d.
|
|
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:
|
|
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
|
|
297
|
-
*
|
|
298
|
-
*
|
|
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.
|
|
316
|
-
.sort((x, y) => x.
|
|
317
|
-
const
|
|
318
|
-
if (best &&
|
|
319
|
-
|
|
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 &&
|
|
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 ?
|
|
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' :
|
|
363
|
+
level: old ? 'none' : worst.level,
|
|
351
364
|
}
|
|
352
365
|
: null,
|
|
353
366
|
updatedAt: now.toISOString(),
|