limitcast 0.0.0-stage → 0.6.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/LICENSE +95 -0
- package/README.md +73 -2
- package/bin/limitcast.mjs +256 -0
- package/package.json +14 -4
- package/src/forecast.mjs +89 -0
- package/src/formats.mjs +115 -0
- package/src/guard.mjs +65 -0
- package/src/install.mjs +241 -0
- package/src/license.mjs +71 -0
- package/src/overhead.mjs +101 -0
- package/src/polar.mjs +169 -0
- package/src/report.mjs +111 -0
- package/src/sources.mjs +95 -0
- package/src/startup.mjs +184 -0
- package/src/store.mjs +70 -0
- package/src/trim.mjs +312 -0
- package/src/usage.mjs +233 -0
package/src/guard.mjs
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { forecastAll, oneClaudeSession } from './forecast.mjs';
|
|
3
|
+
import { readCodex } from './sources.mjs';
|
|
4
|
+
import { KEEP_MS, load } from './store.mjs';
|
|
5
|
+
|
|
6
|
+
const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Whose limits a subagent-spawning tool call draws on, or null if the call spawns nothing.
|
|
10
|
+
* Claude Code: Task/Agent. Codex: spawn_agent (reported with a namespace prefix). Grok: spawn_subagent.
|
|
11
|
+
* @param {string} tool
|
|
12
|
+
* @returns {'claude'|'codex'|'grok'|null}
|
|
13
|
+
*/
|
|
14
|
+
export function spawnSource(tool) {
|
|
15
|
+
if (tool === 'Task' || tool === 'Agent') return 'claude';
|
|
16
|
+
if (/spawn_agent$/.test(tool)) return 'codex';
|
|
17
|
+
if (tool === 'spawn_subagent') return 'grok';
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Reason to block a new subagent, or null to allow it.
|
|
23
|
+
* Blocks only when the spawning tool's own window is on pace to run out before it resets within `minutes`.
|
|
24
|
+
* A window already at 100% is left to the tool: with extra usage enabled, work continues past it.
|
|
25
|
+
* Grok keeps no limit readings on disk, so its spawns are never blocked.
|
|
26
|
+
* @param {string} tool
|
|
27
|
+
* @param {ReturnType<typeof import('./forecast.mjs').forecastAll>} forecasts
|
|
28
|
+
* @param {number} now epoch ms
|
|
29
|
+
* @param {number} minutes
|
|
30
|
+
*/
|
|
31
|
+
export function guardDecision(tool, forecasts, now, minutes) {
|
|
32
|
+
const src = spawnSource(tool);
|
|
33
|
+
if (!src) return null;
|
|
34
|
+
for (const f of forecasts) {
|
|
35
|
+
if (f.src !== src) continue;
|
|
36
|
+
if (f.verdict === 'AT_RISK' && f.wall !== null && f.wall - now <= minutes * 60_000) {
|
|
37
|
+
const left = Math.max(0, Math.round((f.wall - now) / 60_000));
|
|
38
|
+
return (
|
|
39
|
+
`limitcast: ${NAMES[src]} ${f.win} limit is ${f.pct}% used and on pace to run out in ~${left} min, before it resets. ` +
|
|
40
|
+
'Finish with the agents already running, or set LIMITCAST_ALLOW=1 to spawn anyway.'
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The PreToolUse hook: load the readings for the spawning tool and decide. Returns the deny reason or null.
|
|
49
|
+
* Claude Code and Codex send snake_case fields; Grok sends camelCase.
|
|
50
|
+
* @param {any} hook parsed hook input
|
|
51
|
+
* @param {number} now epoch ms
|
|
52
|
+
* @param {number} minutes
|
|
53
|
+
*/
|
|
54
|
+
export async function runGuard(hook, now, minutes) {
|
|
55
|
+
const tool = String(hook?.tool_name ?? hook?.toolName ?? hook?.tool ?? '');
|
|
56
|
+
const src = spawnSource(tool);
|
|
57
|
+
// Codex: only the last two hours of rollouts, so the hook stays fast; Grok has no readings to judge by.
|
|
58
|
+
const samples =
|
|
59
|
+
src === 'claude'
|
|
60
|
+
? oneClaudeSession(load(now - KEEP_MS), hook.session_id ?? hook.sessionId)
|
|
61
|
+
: src === 'codex'
|
|
62
|
+
? await readCodex(now - 2 * 3600_000)
|
|
63
|
+
: [];
|
|
64
|
+
return guardDecision(tool, forecastAll(samples, now), now, minutes);
|
|
65
|
+
}
|
package/src/install.mjs
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
|
|
7
|
+
export const settingsPath = () => join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude'), 'settings.json');
|
|
8
|
+
export const codexHooksPath = () => join(process.env.CODEX_HOME ?? join(homedir(), '.codex'), 'hooks.json');
|
|
9
|
+
const MARK = 'limitcast';
|
|
10
|
+
// Codex reports the tool with a namespace prefix (e.g. "collaborationspawn_agent"); match it anywhere.
|
|
11
|
+
const CODEX_MATCHER = '.*spawn_agent.*';
|
|
12
|
+
|
|
13
|
+
/** Shell-quote one argument. @param {string} s */
|
|
14
|
+
const q = (s) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
|
|
15
|
+
|
|
16
|
+
/** The command that runs this copy of limitcast: absolute node + script, so hooks work without PATH. */
|
|
17
|
+
export function selfCommand() {
|
|
18
|
+
const bin = realpathSync(fileURLToPath(new URL('../bin/limitcast.mjs', import.meta.url)));
|
|
19
|
+
return `${q(process.execPath)} ${q(bin)}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Add the status-line recorder (wrapping any existing status line) and, optionally, the subagent guard.
|
|
24
|
+
* Idempotent; backs up settings.json first; remembers the original status line for uninstall.
|
|
25
|
+
* With `guard`, Codex gets the guard too when ~/.codex exists. With `alerts`, a SessionStart hook tells you
|
|
26
|
+
* (never the model) when your starting context grew.
|
|
27
|
+
* @param {{guard:boolean, alerts?:boolean, path?:string, codexPath?:string, self?:string}} opts
|
|
28
|
+
*/
|
|
29
|
+
export function install({ guard, alerts = false, path = settingsPath(), codexPath = codexHooksPath(), self = selfCommand() }) {
|
|
30
|
+
const cfg = readSettings(path);
|
|
31
|
+
backup(path);
|
|
32
|
+
const changes = [];
|
|
33
|
+
const current = cfg.statusLine?.command;
|
|
34
|
+
if (!current?.includes(MARK)) {
|
|
35
|
+
cfg.statusLine = {
|
|
36
|
+
...(cfg.statusLine ?? { type: 'command' }),
|
|
37
|
+
type: 'command',
|
|
38
|
+
command: current ? `${self} statusline -- sh -c ${q(current)}` : `${self} statusline`,
|
|
39
|
+
};
|
|
40
|
+
changes.push(current ? 'wrapped your status line' : 'added a status line');
|
|
41
|
+
} else {
|
|
42
|
+
cfg.statusLine.command = current.replace(/^.*? statusline\b/, `${self} statusline`);
|
|
43
|
+
changes.push('status line already installed (command path refreshed)');
|
|
44
|
+
}
|
|
45
|
+
if (guard) {
|
|
46
|
+
upsertGuard(cfg, { matcher: 'Task|Agent', hooks: [{ type: 'command', command: `${self} guard`, timeout: 10 }] });
|
|
47
|
+
changes.push('added the Claude Code subagent guard');
|
|
48
|
+
}
|
|
49
|
+
if (alerts) {
|
|
50
|
+
cfg.hooks ??= {};
|
|
51
|
+
const list = (cfg.hooks.SessionStart ??= []);
|
|
52
|
+
const entry = { matcher: '', hooks: [{ type: 'command', command: `${self} drift --hook`, timeout: 15 }] };
|
|
53
|
+
const i = list.findIndex(isAlert);
|
|
54
|
+
if (i >= 0) list[i] = entry;
|
|
55
|
+
else list.push(entry);
|
|
56
|
+
changes.push('added the starting-context alert');
|
|
57
|
+
}
|
|
58
|
+
writeSettings(path, cfg);
|
|
59
|
+
if (guard && existsSync(join(codexPath, '..'))) {
|
|
60
|
+
const codex = readSettings(codexPath);
|
|
61
|
+
backup(codexPath);
|
|
62
|
+
upsertGuard(codex, { matcher: CODEX_MATCHER, hooks: [{ type: 'command', command: `${self} guard`, timeout: 10 }] });
|
|
63
|
+
writeSettings(codexPath, codex);
|
|
64
|
+
changes.push('added the Codex subagent guard (Codex runs it after you trust it: start Codex and approve the new hook)');
|
|
65
|
+
}
|
|
66
|
+
return changes;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Put the guard in PreToolUse: update it where it is, else append.
|
|
71
|
+
* Codex trusts hooks by their position, so existing hooks must keep their places.
|
|
72
|
+
* @param {any} cfg
|
|
73
|
+
* @param {any} entry
|
|
74
|
+
*/
|
|
75
|
+
function upsertGuard(cfg, entry) {
|
|
76
|
+
cfg.hooks ??= {};
|
|
77
|
+
const list = (cfg.hooks.PreToolUse ??= []);
|
|
78
|
+
const i = list.findIndex(isGuard);
|
|
79
|
+
if (i >= 0) list[i] = entry;
|
|
80
|
+
else list.push(entry);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Remove everything limitcast added and restore the original status line.
|
|
85
|
+
* @param {{path?:string, codexPath?:string}} [opts]
|
|
86
|
+
*/
|
|
87
|
+
export function uninstall({ path = settingsPath(), codexPath = codexHooksPath() } = {}) {
|
|
88
|
+
const cfg = readSettings(path);
|
|
89
|
+
backup(path);
|
|
90
|
+
const changes = [];
|
|
91
|
+
if (cfg.statusLine?.command?.includes(MARK)) {
|
|
92
|
+
const prev = wrappedCommand(cfg.statusLine.command);
|
|
93
|
+
if (prev) cfg.statusLine.command = prev;
|
|
94
|
+
else delete cfg.statusLine;
|
|
95
|
+
changes.push(prev ? 'restored your original status line' : 'removed the status line');
|
|
96
|
+
}
|
|
97
|
+
const before = cfg.hooks?.PreToolUse?.length ?? 0;
|
|
98
|
+
if (before) {
|
|
99
|
+
cfg.hooks.PreToolUse = cfg.hooks.PreToolUse.filter((/** @type {any} */ h) => !isGuard(h));
|
|
100
|
+
if (cfg.hooks.PreToolUse.length < before) changes.push('removed the Claude Code subagent guard');
|
|
101
|
+
}
|
|
102
|
+
const alertsBefore = cfg.hooks?.SessionStart?.length ?? 0;
|
|
103
|
+
if (alertsBefore) {
|
|
104
|
+
cfg.hooks.SessionStart = cfg.hooks.SessionStart.filter((/** @type {any} */ h) => !isAlert(h));
|
|
105
|
+
if (cfg.hooks.SessionStart.length < alertsBefore) changes.push('removed the starting-context alert');
|
|
106
|
+
}
|
|
107
|
+
writeSettings(path, cfg);
|
|
108
|
+
if (existsSync(codexPath)) {
|
|
109
|
+
const codex = readSettings(codexPath);
|
|
110
|
+
const list = codex.hooks?.PreToolUse ?? [];
|
|
111
|
+
if (list.some(isGuard)) {
|
|
112
|
+
backup(codexPath);
|
|
113
|
+
codex.hooks.PreToolUse = list.filter((/** @type {any} */ h) => !isGuard(h));
|
|
114
|
+
writeSettings(codexPath, codex);
|
|
115
|
+
changes.push('removed the Codex subagent guard');
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return changes;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The status-line command limitcast wraps, recovered from `... statusline -- <cmd>`; null if none.
|
|
123
|
+
* @param {string} command
|
|
124
|
+
*/
|
|
125
|
+
export function wrappedCommand(command) {
|
|
126
|
+
const rest = command.split(' statusline -- ')[1];
|
|
127
|
+
if (!rest) return null;
|
|
128
|
+
const m = rest.match(/^sh -c '((?:[^']|'\\'')*)'$/);
|
|
129
|
+
if (m) return m[1].replace(/'\\''/g, "'");
|
|
130
|
+
const plain = rest.match(/^sh -c (\S+)$/);
|
|
131
|
+
return plain ? plain[1] : rest;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** @param {any} h */
|
|
135
|
+
const isGuard = (h) =>
|
|
136
|
+
(h.hooks ?? []).some((/** @type {any} */ x) => typeof x.command === 'string' && x.command.includes(MARK) && /\bguard\b/.test(x.command));
|
|
137
|
+
/** @param {any} h */
|
|
138
|
+
const isAlert = (h) =>
|
|
139
|
+
(h.hooks ?? []).some((/** @type {any} */ x) => typeof x.command === 'string' && x.command.includes(MARK) && /\bdrift --hook\b/.test(x.command));
|
|
140
|
+
|
|
141
|
+
/** @param {string} path */
|
|
142
|
+
export function readSettings(path) {
|
|
143
|
+
if (!existsSync(path)) return {};
|
|
144
|
+
try {
|
|
145
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
146
|
+
} catch (e) {
|
|
147
|
+
// Refuse to rewrite a file we can't parse: that would destroy the user's settings.
|
|
148
|
+
throw new Error(`${path} is not valid JSON; fix it first (${e instanceof Error ? e.message : e})`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** @param {string} path @param {any} cfg */
|
|
153
|
+
function writeSettings(path, cfg) {
|
|
154
|
+
mkdirSync(join(path, '..'), { recursive: true });
|
|
155
|
+
writeFileSync(path, `${JSON.stringify(cfg, null, 2)}\n`);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** @param {string} path */
|
|
159
|
+
function backup(path) {
|
|
160
|
+
if (existsSync(path)) copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Is the Codex guard installed, and has Codex trusted it? Codex records trust in config.toml per hook position.
|
|
165
|
+
* @param {string} codexPath
|
|
166
|
+
*/
|
|
167
|
+
function codexGuardCheck(codexPath) {
|
|
168
|
+
let list = [];
|
|
169
|
+
try {
|
|
170
|
+
list = readSettings(codexPath).hooks?.PreToolUse ?? [];
|
|
171
|
+
} catch (e) {
|
|
172
|
+
return { ok: false, line: String(e instanceof Error ? e.message : e) };
|
|
173
|
+
}
|
|
174
|
+
const i = list.findIndex(isGuard);
|
|
175
|
+
if (i < 0) return { ok: true, line: 'Codex subagent guard not installed (optional: `limitcast install --guard`)' };
|
|
176
|
+
let toml = '';
|
|
177
|
+
try {
|
|
178
|
+
toml = readFileSync(join(codexPath, '..', 'config.toml'), 'utf8');
|
|
179
|
+
} catch {
|
|
180
|
+
/* no config yet */
|
|
181
|
+
}
|
|
182
|
+
const trusted = toml.includes(`hooks.json:pre_tool_use:${i}:0"]`);
|
|
183
|
+
return trusted
|
|
184
|
+
? { ok: true, line: 'Codex subagent guard installed and trusted' }
|
|
185
|
+
: { ok: false, line: 'Codex subagent guard installed but not trusted yet: start Codex and approve the new hook' };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Health checks: settings wired, the node path in them still exists, data arriving, license state.
|
|
190
|
+
* @param {{path?:string, codexPath?:string, samplesAgeMs:number|null, license:ReturnType<typeof import('./license.mjs').currentLicense>}} info
|
|
191
|
+
* @returns {{ok:boolean, line:string}[]}
|
|
192
|
+
*/
|
|
193
|
+
export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), samplesAgeMs, license }) {
|
|
194
|
+
/** @type {{ok:boolean, line:string}[]} */
|
|
195
|
+
const out = [];
|
|
196
|
+
const major = Number(process.versions.node.split('.')[0]);
|
|
197
|
+
out.push({ ok: major >= 20, line: `Node ${process.versions.node}${major >= 20 ? '' : ' (need 20+)'}` });
|
|
198
|
+
let cfg = {};
|
|
199
|
+
try {
|
|
200
|
+
cfg = readSettings(path);
|
|
201
|
+
} catch (e) {
|
|
202
|
+
out.push({ ok: false, line: String(e instanceof Error ? e.message : e) });
|
|
203
|
+
}
|
|
204
|
+
const sl = /** @type {any} */ (cfg).statusLine?.command ?? '';
|
|
205
|
+
out.push({
|
|
206
|
+
ok: sl.includes(MARK),
|
|
207
|
+
line: sl.includes(MARK) ? 'Status-line recorder installed' : 'Status-line recorder missing: run `limitcast install`',
|
|
208
|
+
});
|
|
209
|
+
const exe = sl.match(/^'([^']+)'|^(\S+)/);
|
|
210
|
+
const exePath = exe?.[1] ?? exe?.[2];
|
|
211
|
+
if (sl.includes(MARK) && exePath?.startsWith('/')) {
|
|
212
|
+
out.push({
|
|
213
|
+
ok: existsSync(exePath),
|
|
214
|
+
line: existsSync(exePath) ? 'Node path in settings exists' : `Node path in settings is gone (${exePath}): run \`limitcast install\` again`,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
const guard = /** @type {any} */ (cfg.hooks?.PreToolUse ?? []).some(isGuard);
|
|
218
|
+
out.push({
|
|
219
|
+
ok: true,
|
|
220
|
+
line: guard ? 'Claude Code subagent guard installed' : 'Claude Code subagent guard not installed (optional: `limitcast install --guard`)',
|
|
221
|
+
});
|
|
222
|
+
if (existsSync(codexPath)) out.push(codexGuardCheck(codexPath));
|
|
223
|
+
out.push(
|
|
224
|
+
samplesAgeMs === null
|
|
225
|
+
? { ok: false, line: 'No Claude limit readings yet: send a message in Claude Code' }
|
|
226
|
+
: { ok: samplesAgeMs < 24 * 3600_000, line: `Last Claude reading ${Math.round(samplesAgeMs / 60_000)} min ago` },
|
|
227
|
+
);
|
|
228
|
+
out.push({
|
|
229
|
+
ok: license?.ok !== false,
|
|
230
|
+
line: license === null ? 'Free tier' : license.ok ? `Pro: ${license.claims.e}${proTerm(license.claims)}` : `License problem: ${license.reason}`,
|
|
231
|
+
});
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** @param {{p:string, i:number, x:number}} c */
|
|
236
|
+
function proTerm(c) {
|
|
237
|
+
const day = (/** @type {number} */ s) => new Date(s * 1000).toISOString().slice(0, 10);
|
|
238
|
+
if (c.x) return `, ${c.p === 'polar' ? 'valid until' : 'renews'} ${day(c.x)}`;
|
|
239
|
+
// A Polar key has no end date for Lifetime or an active subscription; the weekly check is what keeps it honest.
|
|
240
|
+
return c.p === 'polar' ? `, last checked with Polar ${day(c.i)}` : ', lifetime';
|
|
241
|
+
}
|
package/src/license.mjs
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { createPrivateKey, createPublicKey, sign, verify } from 'node:crypto';
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { loadPolar, polarStatus } from './polar.mjs';
|
|
6
|
+
import { stateDir } from './store.mjs';
|
|
7
|
+
|
|
8
|
+
export const UPGRADE_URL = 'https://limitcast.dev/#pricing';
|
|
9
|
+
const PUBLIC_KEY = 'MCowBQYDK2VwAyEAG+4c5uaNB7IAZiAxtcyyXBEmmRkmZfWvlEFyvhmDQvA=';
|
|
10
|
+
const PREFIX = 'LC1';
|
|
11
|
+
|
|
12
|
+
/** @typedef {{e:string, p:string, i:number, x:number}} Claims e: email, p: plan, i: issued, x: expires (epoch s, 0 = never) */
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Offline license check: Ed25519 signature over the claims, plus expiry. No network.
|
|
16
|
+
* @param {string} key
|
|
17
|
+
* @param {number} now epoch ms
|
|
18
|
+
* @param {string} [publicKey] base64 SPKI (tests pass their own)
|
|
19
|
+
* @returns {{ok:true, claims:Claims} | {ok:false, reason:string}}
|
|
20
|
+
*/
|
|
21
|
+
export function checkLicense(key, now, publicKey = PUBLIC_KEY) {
|
|
22
|
+
const [prefix, body, sig] = key.trim().split('.');
|
|
23
|
+
if (prefix !== PREFIX || !body || !sig) return { ok: false, reason: 'not a limitcast license key' };
|
|
24
|
+
const pub = createPublicKey({ key: Buffer.from(publicKey, 'base64'), format: 'der', type: 'spki' });
|
|
25
|
+
if (!verify(null, Buffer.from(`${prefix}.${body}`), pub, Buffer.from(sig, 'base64url'))) return { ok: false, reason: 'signature does not match' };
|
|
26
|
+
/** @type {Claims} */
|
|
27
|
+
let claims;
|
|
28
|
+
try {
|
|
29
|
+
claims = JSON.parse(Buffer.from(body, 'base64url').toString());
|
|
30
|
+
} catch {
|
|
31
|
+
return { ok: false, reason: 'unreadable claims' };
|
|
32
|
+
}
|
|
33
|
+
if (claims.x && claims.x * 1000 < now) return { ok: false, reason: `expired ${new Date(claims.x * 1000).toISOString().slice(0, 10)}` };
|
|
34
|
+
return { ok: true, claims };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Sign a license. Used only by scripts/issue-license.mjs with the private key from the Keychain.
|
|
39
|
+
* @param {Claims} claims
|
|
40
|
+
* @param {string} privatePem
|
|
41
|
+
*/
|
|
42
|
+
export function issueLicense(claims, privatePem) {
|
|
43
|
+
const body = Buffer.from(JSON.stringify(claims)).toString('base64url');
|
|
44
|
+
const sig = sign(null, Buffer.from(`${PREFIX}.${body}`), createPrivateKey(privatePem)).toString('base64url');
|
|
45
|
+
return `${PREFIX}.${body}.${sig}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const licenseFile = () => join(stateDir(), 'license.key');
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The active license: LIMITCAST_LICENSE env var, else an activated signed key, else a Polar activation.
|
|
52
|
+
* Never touches the network (hooks call it on every tool use).
|
|
53
|
+
*/
|
|
54
|
+
export function currentLicense(now = Date.now()) {
|
|
55
|
+
const key = process.env.LIMITCAST_LICENSE ?? (existsSync(licenseFile()) ? readFileSync(licenseFile(), 'utf8') : '');
|
|
56
|
+
if (key) return checkLicense(key, now);
|
|
57
|
+
const polar = loadPolar();
|
|
58
|
+
return polar ? polarStatus(polar, now) : null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** @param {string} key */
|
|
62
|
+
export function activate(key) {
|
|
63
|
+
const res = checkLicense(key, Date.now());
|
|
64
|
+
if (res.ok) {
|
|
65
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
66
|
+
writeFileSync(licenseFile(), `${key.trim()}\n`, { mode: 0o600 });
|
|
67
|
+
}
|
|
68
|
+
return res;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export const isPro = () => currentLicense()?.ok === true;
|
package/src/overhead.mjs
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { stateDir } from './store.mjs';
|
|
5
|
+
|
|
6
|
+
/** @typedef {import('./startup.mjs').Piece} Piece */
|
|
7
|
+
/** @typedef {{at:number, chars:number, items:Record<string, number>}} Snapshot sizes in characters, keyed "group|name" */
|
|
8
|
+
|
|
9
|
+
const ALERT_CHARS = 4000; // ~1k tokens: smaller changes aren't worth interrupting for
|
|
10
|
+
const ITEM_CHARS = 2000; // ~500 tokens: smallest single item worth naming
|
|
11
|
+
|
|
12
|
+
/** @param {{pieces:Piece[], at:number}} b */
|
|
13
|
+
export function snapshot(b) {
|
|
14
|
+
/** @type {Record<string, number>} */
|
|
15
|
+
const items = {};
|
|
16
|
+
for (const p of b.pieces) items[`${p.group}|${p.name}`] = (items[`${p.group}|${p.name}`] ?? 0) + p.chars;
|
|
17
|
+
return { at: b.at, chars: Object.values(items).reduce((a, c) => a + c, 0), items };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* What grew between two snapshots: new or bigger items of at least ~500 tokens, and the total change.
|
|
22
|
+
* @param {Snapshot} prev
|
|
23
|
+
* @param {Snapshot} cur
|
|
24
|
+
*/
|
|
25
|
+
export function drift(prev, cur) {
|
|
26
|
+
const grew = Object.entries(cur.items)
|
|
27
|
+
.map(([key, chars]) => ({ key, chars, delta: chars - (prev.items[key] ?? 0), isNew: !(key in prev.items) }))
|
|
28
|
+
.filter((x) => x.delta >= ITEM_CHARS)
|
|
29
|
+
.sort((a, b) => b.delta - a.delta);
|
|
30
|
+
return { delta: cur.chars - prev.chars, grew, alert: cur.chars - prev.chars >= ALERT_CHARS || grew.length > 0 };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const file = () => join(stateDir(), 'overhead.json');
|
|
34
|
+
|
|
35
|
+
/** @returns {{first:Snapshot, last:Snapshot}|null} */
|
|
36
|
+
export function loadOverhead() {
|
|
37
|
+
try {
|
|
38
|
+
return JSON.parse(readFileSync(file(), 'utf8'));
|
|
39
|
+
} catch {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** @param {{first:Snapshot, last:Snapshot}} s */
|
|
45
|
+
export function saveOverhead(s) {
|
|
46
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
47
|
+
writeFileSync(file(), JSON.stringify(s));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Record `cur` and return what changed since the last recorded session (null the first time).
|
|
52
|
+
* A snapshot of the same session as last time changes nothing.
|
|
53
|
+
* @param {Snapshot} cur
|
|
54
|
+
*/
|
|
55
|
+
export function recordOverhead(cur) {
|
|
56
|
+
const s = existsSync(file()) ? loadOverhead() : null;
|
|
57
|
+
if (!s) {
|
|
58
|
+
saveOverhead({ first: cur, last: cur });
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
if (cur.at === s.last.at) return { delta: 0, grew: [], alert: false };
|
|
62
|
+
const d = drift(s.last, cur);
|
|
63
|
+
saveOverhead({ first: s.first, last: cur });
|
|
64
|
+
return d;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const tok = (/** @type {number} */ chars) => Math.round(chars / 4);
|
|
68
|
+
const label = (/** @type {string} */ key) => key.replace('|', ': ').replace(/\/Users\/[^/]+/, '~');
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* One-line alert for the user (never the model) when starting context grew.
|
|
72
|
+
* @param {ReturnType<typeof drift>} d
|
|
73
|
+
*/
|
|
74
|
+
export function driftMessage(d) {
|
|
75
|
+
const items = d.grew
|
|
76
|
+
.slice(0, 3)
|
|
77
|
+
.map((g) => `${label(g.key)} ${g.isNew ? 'new' : '+'}~${(tok(g.delta) / 1000).toFixed(1)}k`)
|
|
78
|
+
.join(', ');
|
|
79
|
+
return `limitcast: your Claude Code starting context grew ~${(tok(d.delta) / 1000).toFixed(1)}k tokens since your last session${items ? ` (${items})` : ''}. Run \`limitcast trim\` for details.`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* "Tokens saved" since limitcast first measured you: the drop in starting context times the sessions since.
|
|
84
|
+
* Conservative: counts each session's start once, though that context is re-sent every turn.
|
|
85
|
+
* @param {{first:Snapshot, last:Snapshot}} s
|
|
86
|
+
* @param {number} sessions interactive sessions since s.first.at
|
|
87
|
+
*/
|
|
88
|
+
export function savedSummary(s, sessions) {
|
|
89
|
+
const perSession = tok(s.first.chars - s.last.chars);
|
|
90
|
+
const since = new Date(s.first.at).toLocaleDateString();
|
|
91
|
+
if (perSession <= 0) {
|
|
92
|
+
return `Since ${since}, the part of your starting context you control (hooks, MCP servers, skills, agents, instruction files) went from ~${fmtK(tok(s.first.chars))} to ~${fmtK(tok(s.last.chars))} tokens (${perSession === 0 ? 'no change' : `+${fmtK(-perSession)}`}). Run \`limitcast trim\` to find cuts.`;
|
|
93
|
+
}
|
|
94
|
+
return [
|
|
95
|
+
`Since ${since}, the part of your starting context you control (hooks, MCP servers, skills, agents, instruction files) dropped from ~${fmtK(tok(s.first.chars))} to ~${fmtK(tok(s.last.chars))} tokens: ${fmtK(perSession)} less per session.`,
|
|
96
|
+
`Across ${sessions} interactive sessions that's ~${fmtK(perSession * sessions)} tokens not loaded, counting each session's start once (the real figure is higher: that context is re-sent every turn).`,
|
|
97
|
+
].join('\n');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** @param {number} n */
|
|
101
|
+
const fmtK = (n) => (Math.abs(n) >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : Math.abs(n) >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : `${n}`);
|
package/src/polar.mjs
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { hostname } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { stateDir } from './store.mjs';
|
|
6
|
+
|
|
7
|
+
// Polar's customer-portal license endpoints need no secret: they are meant for desktop apps and CLIs.
|
|
8
|
+
export const POLAR_ORG_ID = 'c8fb2062-7f49-4ef0-927b-32d752e2990a';
|
|
9
|
+
const API = 'https://api.polar.sh/v1/customer-portal/license-keys';
|
|
10
|
+
const RECHECK_MS = 7 * 86400_000; // re-check with Polar weekly when online
|
|
11
|
+
const GRACE_MS = 30 * 86400_000; // keep working offline this long after the last successful check
|
|
12
|
+
|
|
13
|
+
/** @typedef {{key:string, activationId:string, email:string, status:string, expiresAt:string|null, checkedAt:number}} PolarLicense */
|
|
14
|
+
|
|
15
|
+
const file = () => join(stateDir(), 'polar-license.json');
|
|
16
|
+
|
|
17
|
+
/** @returns {PolarLicense|null} */
|
|
18
|
+
export function loadPolar() {
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(readFileSync(file(), 'utf8'));
|
|
21
|
+
} catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param {PolarLicense} l */
|
|
27
|
+
function savePolar(l) {
|
|
28
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
29
|
+
writeFileSync(file(), JSON.stringify(l), { mode: 0o600 });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Is a stored Polar license usable right now? No network: hooks call this on every tool use.
|
|
34
|
+
* @param {PolarLicense} l
|
|
35
|
+
* @param {number} now
|
|
36
|
+
* @returns {{ok:true, claims:{e:string, p:string, i:number, x:number}} | {ok:false, reason:string}}
|
|
37
|
+
*/
|
|
38
|
+
export function polarStatus(l, now) {
|
|
39
|
+
if (l.status !== 'granted') return { ok: false, reason: `license ${l.status} at Polar` };
|
|
40
|
+
const exp = l.expiresAt ? Date.parse(l.expiresAt) : 0;
|
|
41
|
+
if (exp && exp < now) return { ok: false, reason: `expired ${new Date(exp).toISOString().slice(0, 10)}` };
|
|
42
|
+
if (now - l.checkedAt > GRACE_MS)
|
|
43
|
+
return { ok: false, reason: 'not checked with Polar for 30 days: connect to the internet and run `limitcast license`' };
|
|
44
|
+
// p 'polar': i is the last successful check, and x is 0 for both Lifetime and an active subscription.
|
|
45
|
+
return { ok: true, claims: { e: l.email, p: 'polar', i: Math.floor(l.checkedAt / 1000), x: exp ? Math.floor(exp / 1000) : 0 } };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Hooks never touch the network, so the status line asks this before starting a detached re-check.
|
|
50
|
+
* True when the weekly re-check is due and no attempt was made in the last hour (offline or rate-limited).
|
|
51
|
+
* @param {number} now
|
|
52
|
+
*/
|
|
53
|
+
export function refreshDue(now) {
|
|
54
|
+
const l = loadPolar();
|
|
55
|
+
if (!l || now - l.checkedAt < RECHECK_MS) return false;
|
|
56
|
+
const mark = join(stateDir(), 'polar-refresh.at');
|
|
57
|
+
let last = 0;
|
|
58
|
+
try {
|
|
59
|
+
last = Number(readFileSync(mark, 'utf8')) || 0;
|
|
60
|
+
} catch {
|
|
61
|
+
/* never attempted */
|
|
62
|
+
}
|
|
63
|
+
if (Math.abs(now - last) < 3600_000) return false;
|
|
64
|
+
writeFileSync(mark, String(now));
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* @param {string} path
|
|
70
|
+
* @param {object} body
|
|
71
|
+
* @param {typeof fetch} fetchImpl
|
|
72
|
+
*/
|
|
73
|
+
async function post(path, body, fetchImpl) {
|
|
74
|
+
const res = await fetchImpl(`${API}/${path}`, {
|
|
75
|
+
method: 'POST',
|
|
76
|
+
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
|
77
|
+
body: JSON.stringify(body),
|
|
78
|
+
});
|
|
79
|
+
let data = null;
|
|
80
|
+
try {
|
|
81
|
+
data = await res.json();
|
|
82
|
+
} catch {
|
|
83
|
+
/* empty body */
|
|
84
|
+
}
|
|
85
|
+
return { status: res.status, data };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** @param {any} data */
|
|
89
|
+
const detail = (data) => (typeof data?.detail === 'string' ? data.detail : '');
|
|
90
|
+
const BUSY = 'Polar is rate-limiting requests: wait a minute and try again';
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Register this machine with Polar and store the result for offline use.
|
|
94
|
+
* @param {string} key
|
|
95
|
+
* @param {{fetchImpl?:typeof fetch, now?:number, label?:string}} [opts]
|
|
96
|
+
* @returns {Promise<{ok:true, claims:{e:string}} | {ok:false, reason:string}>}
|
|
97
|
+
*/
|
|
98
|
+
export async function activatePolar(key, { fetchImpl = fetch, now = Date.now(), label = hostname() } = {}) {
|
|
99
|
+
let r;
|
|
100
|
+
try {
|
|
101
|
+
r = await post('activate', { key: key.trim(), organization_id: POLAR_ORG_ID, label }, fetchImpl);
|
|
102
|
+
} catch (e) {
|
|
103
|
+
return { ok: false, reason: `could not reach Polar (${e instanceof Error ? e.message : e}); activation needs the internet once` };
|
|
104
|
+
}
|
|
105
|
+
if (r.status === 404) return { ok: false, reason: 'Polar does not know this license key' };
|
|
106
|
+
if (r.status === 429) return { ok: false, reason: BUSY };
|
|
107
|
+
if (r.status === 403)
|
|
108
|
+
return {
|
|
109
|
+
ok: false,
|
|
110
|
+
reason: detail(r.data) || 'Polar refused activation (limit reached, revoked or expired). Free a device with `limitcast deactivate` on it.',
|
|
111
|
+
};
|
|
112
|
+
if (r.status !== 200 || !r.data?.id) return { ok: false, reason: `Polar returned ${r.status}${detail(r.data) ? `: ${detail(r.data)}` : ''}` };
|
|
113
|
+
const lk = r.data.license_key ?? {};
|
|
114
|
+
const l = {
|
|
115
|
+
key: key.trim(),
|
|
116
|
+
activationId: r.data.id,
|
|
117
|
+
email: lk.customer?.email ?? '',
|
|
118
|
+
status: lk.status ?? 'granted',
|
|
119
|
+
expiresAt: lk.expires_at ?? null,
|
|
120
|
+
checkedAt: now,
|
|
121
|
+
};
|
|
122
|
+
savePolar(l);
|
|
123
|
+
return { ok: true, claims: { e: l.email } };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Re-check a stored Polar license if it's due. Offline or Polar down: keep the stored state (grace period).
|
|
128
|
+
* Only a definite answer from Polar (not found, or a non-granted status) turns it off.
|
|
129
|
+
* @param {{fetchImpl?:typeof fetch, now?:number, force?:boolean}} [opts]
|
|
130
|
+
*/
|
|
131
|
+
export async function refreshPolar({ fetchImpl = fetch, now = Date.now(), force = false } = {}) {
|
|
132
|
+
const l = loadPolar();
|
|
133
|
+
if (!l || (!force && now - l.checkedAt < RECHECK_MS)) return l;
|
|
134
|
+
let r;
|
|
135
|
+
try {
|
|
136
|
+
r = await post('validate', { key: l.key, organization_id: POLAR_ORG_ID, activation_id: l.activationId }, fetchImpl);
|
|
137
|
+
} catch {
|
|
138
|
+
return l;
|
|
139
|
+
}
|
|
140
|
+
if (r.status === 404) l.status = 'not found';
|
|
141
|
+
else if (r.status === 200 && r.data) {
|
|
142
|
+
l.status = r.data.status ?? l.status;
|
|
143
|
+
l.expiresAt = r.data.expires_at ?? null;
|
|
144
|
+
l.email = r.data.customer?.email ?? l.email;
|
|
145
|
+
l.checkedAt = now;
|
|
146
|
+
} else return l;
|
|
147
|
+
savePolar(l);
|
|
148
|
+
return l;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Free this machine's activation at Polar so the key can be used elsewhere, then forget it locally.
|
|
153
|
+
* @param {{fetchImpl?:typeof fetch}} [opts]
|
|
154
|
+
*/
|
|
155
|
+
export async function deactivatePolar({ fetchImpl = fetch } = {}) {
|
|
156
|
+
const l = loadPolar();
|
|
157
|
+
if (!l) return { ok: false, reason: 'no Polar license is active on this machine' };
|
|
158
|
+
let r;
|
|
159
|
+
try {
|
|
160
|
+
r = await post('deactivate', { key: l.key, organization_id: POLAR_ORG_ID, activation_id: l.activationId }, fetchImpl);
|
|
161
|
+
} catch (e) {
|
|
162
|
+
return { ok: false, reason: `could not reach Polar (${e instanceof Error ? e.message : e})` };
|
|
163
|
+
}
|
|
164
|
+
if (r.status === 429) return { ok: false, reason: BUSY };
|
|
165
|
+
if (r.status !== 204 && r.status !== 200 && r.status !== 404)
|
|
166
|
+
return { ok: false, reason: `Polar returned ${r.status}${detail(r.data) ? `: ${detail(r.data)}` : ''}` };
|
|
167
|
+
if (existsSync(file())) rmSync(file());
|
|
168
|
+
return { ok: true };
|
|
169
|
+
}
|