limitcast 0.11.5 → 0.12.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 +10 -5
- package/bin/limitcast.mjs +170 -35
- package/package.json +1 -1
- package/src/grok.mjs +585 -0
- package/src/guard.mjs +15 -5
- package/src/install.mjs +17 -4
- package/src/report.mjs +15 -8
- package/src/subagents.mjs +27 -0
- package/src/toolcheck.mjs +83 -0
- package/src/where.mjs +445 -0
package/src/install.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, writeF
|
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { grokDoctor, grokHome, grokPresent, installGrok, uninstallGrok } from './grok.mjs';
|
|
6
7
|
import { stateDir } from './store.mjs';
|
|
7
8
|
|
|
8
9
|
export const settingsPath = () => join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude'), 'settings.json');
|
|
@@ -77,9 +78,9 @@ export function launcherTargets(path) {
|
|
|
77
78
|
* Idempotent; backs up settings.json first; remembers the original status line for uninstall.
|
|
78
79
|
* With `guard`, Codex gets the guard too when ~/.codex exists. With `alerts`, a SessionStart hook tells you
|
|
79
80
|
* (never the model) when your starting context grew.
|
|
80
|
-
* @param {{guard:boolean, alerts?:boolean, path?:string, codexPath?:string, self?:string}} opts
|
|
81
|
+
* @param {{guard:boolean, alerts?:boolean, path?:string, codexPath?:string, grokDir?:string, self?:string}} opts
|
|
81
82
|
*/
|
|
82
|
-
export function install({ guard, alerts = false, path = settingsPath(), codexPath = codexHooksPath(), self = selfCommand() }) {
|
|
83
|
+
export function install({ guard, alerts = false, path = settingsPath(), codexPath = codexHooksPath(), grokDir = grokHome(), self = selfCommand() }) {
|
|
83
84
|
const cfg = readSettings(path);
|
|
84
85
|
backup(path);
|
|
85
86
|
const changes = [];
|
|
@@ -104,6 +105,13 @@ export function install({ guard, alerts = false, path = settingsPath(), codexPat
|
|
|
104
105
|
if (alerts) {
|
|
105
106
|
upsertHook(cfg, 'SessionStart', { matcher: '', hooks: [{ type: 'command', command: `${self} drift --hook`, timeout: 15 }] }, isAlert);
|
|
106
107
|
changes.push('added the starting-context alert');
|
|
108
|
+
upsertHook(
|
|
109
|
+
cfg,
|
|
110
|
+
'PostToolUse',
|
|
111
|
+
{ matcher: 'Bash|Read|Grep|WebFetch|mcp__.*', hooks: [{ type: 'command', command: `${self} tool-check`, timeout: 10 }] },
|
|
112
|
+
isToolCheck,
|
|
113
|
+
);
|
|
114
|
+
changes.push('added the large tool-output notice');
|
|
107
115
|
}
|
|
108
116
|
writeSettings(path, cfg);
|
|
109
117
|
if (guard && existsSync(join(codexPath, '..'))) {
|
|
@@ -113,6 +121,7 @@ export function install({ guard, alerts = false, path = settingsPath(), codexPat
|
|
|
113
121
|
writeSettings(codexPath, codex);
|
|
114
122
|
changes.push('added the Codex subagent guard (Codex runs it after you trust it: start Codex and approve the new hook)');
|
|
115
123
|
}
|
|
124
|
+
if (grokPresent(grokDir)) changes.push(...installGrok({ guard, self, home: grokDir }));
|
|
116
125
|
return changes;
|
|
117
126
|
}
|
|
118
127
|
|
|
@@ -143,9 +152,9 @@ function upsertHook(cfg, event, entry, mine) {
|
|
|
143
152
|
|
|
144
153
|
/**
|
|
145
154
|
* Remove everything limitcast added and restore the original status line.
|
|
146
|
-
* @param {{path?:string, codexPath?:string}} [opts]
|
|
155
|
+
* @param {{path?:string, codexPath?:string, grokDir?:string}} [opts]
|
|
147
156
|
*/
|
|
148
|
-
export function uninstall({ path = settingsPath(), codexPath = codexHooksPath() } = {}) {
|
|
157
|
+
export function uninstall({ path = settingsPath(), codexPath = codexHooksPath(), grokDir = grokHome() } = {}) {
|
|
149
158
|
const cfg = readSettings(path);
|
|
150
159
|
backup(path);
|
|
151
160
|
const changes = [];
|
|
@@ -164,6 +173,7 @@ export function uninstall({ path = settingsPath(), codexPath = codexHooksPath()
|
|
|
164
173
|
['SessionStart', isAlert, 'the starting-context alert'],
|
|
165
174
|
['UserPromptSubmit', isPromptCheck, 'the cold-cache warning'],
|
|
166
175
|
['SubagentStop', isReceipt, 'subagent receipts'],
|
|
176
|
+
['PostToolUse', isToolCheck, 'the large tool-output notice'],
|
|
167
177
|
])) {
|
|
168
178
|
const n = cfg.hooks?.[event]?.length ?? 0;
|
|
169
179
|
if (!n) continue;
|
|
@@ -181,6 +191,7 @@ export function uninstall({ path = settingsPath(), codexPath = codexHooksPath()
|
|
|
181
191
|
changes.push('removed the Codex subagent guard');
|
|
182
192
|
}
|
|
183
193
|
}
|
|
194
|
+
changes.push(...uninstallGrok({ home: grokDir }));
|
|
184
195
|
return changes;
|
|
185
196
|
}
|
|
186
197
|
|
|
@@ -219,6 +230,7 @@ const runs = (re) => (h) =>
|
|
|
219
230
|
const isAlert = runs(/\bdrift --hook\b/);
|
|
220
231
|
const isPromptCheck = runs(/\bprompt-check\b/);
|
|
221
232
|
const isReceipt = runs(/\bsubagent-receipt\b/);
|
|
233
|
+
const isToolCheck = runs(/\btool-check\b/);
|
|
222
234
|
|
|
223
235
|
/** @param {string} path */
|
|
224
236
|
export function readSettings(path) {
|
|
@@ -324,6 +336,7 @@ export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), sa
|
|
|
324
336
|
line: 'Cold-cache warning and subagent receipts not installed yet: run `limitcast doctor --fix`',
|
|
325
337
|
});
|
|
326
338
|
if (existsSync(codexPath)) out.push(codexGuardCheck(codexPath));
|
|
339
|
+
out.push(...grokDoctor());
|
|
327
340
|
out.push(
|
|
328
341
|
samplesAgeMs === null
|
|
329
342
|
? { ok: false, line: 'No Claude limit readings yet: send a message in Claude Code' }
|
package/src/report.mjs
CHANGED
|
@@ -37,32 +37,38 @@ export function burnReport(usage, { since, now }) {
|
|
|
37
37
|
all,
|
|
38
38
|
false,
|
|
39
39
|
);
|
|
40
|
+
// Ranked by new tokens (input, cache writes, output): cached reads barely count against the limit.
|
|
41
|
+
const fresh = (/** @type {Usage[]} */ xs) => xs.reduce((a, u) => a + u.input + u.cacheWrite + u.output, 0);
|
|
42
|
+
const allFresh = fresh(usage);
|
|
40
43
|
table(
|
|
41
44
|
lines,
|
|
42
45
|
'Top projects',
|
|
43
46
|
group(usage, (u) => short(u.project) || '(unknown)'),
|
|
44
|
-
|
|
45
|
-
|
|
47
|
+
fresh,
|
|
48
|
+
allFresh,
|
|
46
49
|
true,
|
|
47
50
|
8,
|
|
51
|
+
'new tokens',
|
|
48
52
|
);
|
|
49
53
|
table(
|
|
50
54
|
lines,
|
|
51
55
|
'By model',
|
|
52
56
|
group(usage, (u) => u.model || '(unknown)'),
|
|
53
|
-
|
|
54
|
-
|
|
57
|
+
fresh,
|
|
58
|
+
allFresh,
|
|
55
59
|
true,
|
|
56
60
|
6,
|
|
61
|
+
'new tokens',
|
|
57
62
|
);
|
|
58
63
|
table(
|
|
59
64
|
lines,
|
|
60
65
|
'Heaviest sessions',
|
|
61
66
|
group(usage, (u) => `${u.src} ${u.session.slice(0, 8)} · ${short(u.project)}`),
|
|
62
|
-
|
|
63
|
-
|
|
67
|
+
fresh,
|
|
68
|
+
allFresh,
|
|
64
69
|
true,
|
|
65
70
|
5,
|
|
71
|
+
'new tokens',
|
|
66
72
|
);
|
|
67
73
|
lines.push('', `_Generated by limitcast. Token counts come from your local Claude Code and Codex logs._`);
|
|
68
74
|
return lines.join('\n');
|
|
@@ -76,11 +82,12 @@ export function burnReport(usage, { since, now }) {
|
|
|
76
82
|
* @param {number} all
|
|
77
83
|
* @param {boolean} sortBySize
|
|
78
84
|
* @param {number} [limit]
|
|
85
|
+
* @param {string} [col] header of the token column
|
|
79
86
|
*/
|
|
80
|
-
function table(lines, title, groups, sum, all, sortBySize, limit = Infinity) {
|
|
87
|
+
function table(lines, title, groups, sum, all, sortBySize, limit = Infinity, col = 'tokens') {
|
|
81
88
|
let rows = [...groups].map(([k, xs]) => /** @type {[string, number]} */ ([k, sum(xs)]));
|
|
82
89
|
rows = sortBySize ? rows.sort((a, b) => b[1] - a[1]) : rows.sort((a, b) => a[0].localeCompare(b[0]));
|
|
83
|
-
lines.push('', `## ${title}`, '',
|
|
90
|
+
lines.push('', `## ${title}`, '', `| | ${col} | share |`, '|---|---:|---:|');
|
|
84
91
|
for (const [k, n] of rows.slice(0, limit)) lines.push(`| ${k} | ${fmt(n)} | ${pct(n, all)} |`);
|
|
85
92
|
}
|
|
86
93
|
|
package/src/subagents.mjs
CHANGED
|
@@ -54,6 +54,33 @@ export function receiptMessage(type, u, pct) {
|
|
|
54
54
|
}
|
|
55
55
|
|
|
56
56
|
const k = (/** @type {number} */ n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : `${Math.round(n / 1000)}k`);
|
|
57
|
+
const pct1 = (/** @type {number} */ p) => (p < 1 ? p.toFixed(2) : p.toFixed(1));
|
|
58
|
+
|
|
59
|
+
const NOTICE_MIN_RUNS = 3;
|
|
60
|
+
const NOTICE_MIN_PCT = 1; // a typical run under 1% of a window is not worth a message
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Before a subagent starts: what that kind has cost you so far, from the receipts ledger.
|
|
64
|
+
* "limitcast: Explore subagents have cost you a median ≈1.2% (max ≈3.6%) of a 5-hour window over 7 runs; this window is 38% used."
|
|
65
|
+
* Uses the same type when it has at least 3 priced runs, else every subagent. Null with too little history, or when
|
|
66
|
+
* the typical run is under 1% of a window and the window is not NEAR.
|
|
67
|
+
* @param {SubagentEntry[]} entries
|
|
68
|
+
* @param {unknown} type the subagent type about to start
|
|
69
|
+
* @param {{pct:number, verdict:string}|undefined} win the current 5-hour window
|
|
70
|
+
*/
|
|
71
|
+
export function spawnNotice(entries, type, win) {
|
|
72
|
+
const priced = entries.filter((e) => typeof e.pct === 'number');
|
|
73
|
+
const same = typeof type === 'string' && type ? priced.filter((e) => e.type === type) : [];
|
|
74
|
+
const runs = same.length >= NOTICE_MIN_RUNS ? same : priced;
|
|
75
|
+
if (runs.length < NOTICE_MIN_RUNS) return null;
|
|
76
|
+
const sorted = runs.map((e) => /** @type {number} */ (e.pct)).sort((a, b) => a - b);
|
|
77
|
+
const mid = sorted.length >> 1;
|
|
78
|
+
const median = sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
|
|
79
|
+
if (median < NOTICE_MIN_PCT && win?.verdict !== 'NEAR') return null;
|
|
80
|
+
const who = runs === same ? `${type} subagents have` : 'Your subagents have';
|
|
81
|
+
const used = win ? `; this window is ${Math.round(win.pct)}% used` : '';
|
|
82
|
+
return `limitcast: ${who} cost you a median ≈${pct1(median)}% (max ≈${pct1(sorted.at(-1) ?? 0)}%) of a 5-hour window over ${runs.length} runs${used}.`;
|
|
83
|
+
}
|
|
57
84
|
|
|
58
85
|
/** @param {SubagentEntry} e */
|
|
59
86
|
export function logSubagent(e) {
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { stateDir } from './store.mjs';
|
|
5
|
+
|
|
6
|
+
// Large tool-output notice (Pro, PostToolUse hook, installed with --alerts). A tool result enters the context once as
|
|
7
|
+
// new tokens and is then re-read on every later call, so a very large one is worth knowing about. The notice goes to
|
|
8
|
+
// the user (systemMessage), never the model, once per tool per session, with what to ask for next time.
|
|
9
|
+
|
|
10
|
+
export const BIG_RESULT = 20_000; // estimated tokens of one result worth a notice
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The name a tool goes by in reports: MCP tools by server ("mcp:claude_ai_HubSpot"), the rest as they are.
|
|
14
|
+
* @param {string} name
|
|
15
|
+
*/
|
|
16
|
+
export const toolKey = (name) => (name.startsWith('mcp__') ? `mcp:${name.split('__')[1]}` : name);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* What to ask for next time, or null when there is nothing to suggest (a Skill loads whole).
|
|
20
|
+
* @param {string} key a toolKey
|
|
21
|
+
*/
|
|
22
|
+
export function tipFor(key) {
|
|
23
|
+
if (key.startsWith('mcp:')) return 'ask for fewer fields and a smaller limit';
|
|
24
|
+
return (
|
|
25
|
+
/** @type {Record<string, string>} */ ({
|
|
26
|
+
Read: 'ask for a line range (offset and limit) instead of the whole file',
|
|
27
|
+
Bash: 'pipe long output through head, tail or grep',
|
|
28
|
+
Grep: 'narrow the pattern, or add a path or glob',
|
|
29
|
+
WebFetch: 'ask for one section of the page, not all of it',
|
|
30
|
+
})[key] ?? null
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Tokens in a tool result, estimated from its size (about 4 characters each). Works on any result shape.
|
|
36
|
+
* @param {unknown} response
|
|
37
|
+
*/
|
|
38
|
+
export function resultTokens(response) {
|
|
39
|
+
const text = typeof response === 'string' ? response : (JSON.stringify(response) ?? '');
|
|
40
|
+
return Math.round(text.length / 4);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* "limitcast: that HubSpot get_crm_objects result was ≈25k tokens (≈0.17% of a 5-hour window to write, then re-read on
|
|
45
|
+
* every later call). Next time: ask for fewer fields and a smaller limit." Null under the threshold.
|
|
46
|
+
* @param {string} toolName
|
|
47
|
+
* @param {unknown} response
|
|
48
|
+
* @param {{fresh:number}|null|undefined} calib % of the 5-hour window per million new tokens
|
|
49
|
+
* @param {number} [threshold]
|
|
50
|
+
*/
|
|
51
|
+
export function toolNotice(toolName, response, calib, threshold = BIG_RESULT) {
|
|
52
|
+
const tokens = resultTokens(response);
|
|
53
|
+
if (tokens < threshold) return null;
|
|
54
|
+
const [, server, ...rest] = toolName.startsWith('mcp__') ? toolName.split('__') : ['', toolName];
|
|
55
|
+
const label = toolName.startsWith('mcp__') ? `${server.replace(/^claude_ai_/, '')} ${rest.join('__')}` : toolName;
|
|
56
|
+
const pct = calib ? ` (≈${((tokens / 1e6) * calib.fresh).toFixed(2)}% of a 5-hour window to write, then re-read on every later call)` : '';
|
|
57
|
+
const tip = tipFor(toolKey(toolName));
|
|
58
|
+
return `limitcast: that ${label} result was ≈${Math.round(tokens / 1000)}k tokens${pct}.${tip ? ` Next time: ${tip}.` : ''}`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const stateFile = () => join(stateDir(), 'tool-check.json');
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* True the first time a tool is flagged in a session, false after that.
|
|
65
|
+
* @param {string} sid
|
|
66
|
+
* @param {string} tool
|
|
67
|
+
*/
|
|
68
|
+
export function firstFlag(sid, tool) {
|
|
69
|
+
/** @type {Record<string, string[]>} */
|
|
70
|
+
let seen = {};
|
|
71
|
+
try {
|
|
72
|
+
seen = JSON.parse(readFileSync(stateFile(), 'utf8'));
|
|
73
|
+
} catch {
|
|
74
|
+
/* first flag */
|
|
75
|
+
}
|
|
76
|
+
if (seen[sid]?.includes(tool)) return false;
|
|
77
|
+
const keep = Object.entries(seen)
|
|
78
|
+
.filter(([k]) => k !== sid)
|
|
79
|
+
.slice(-49); // the 49 most recent other sessions
|
|
80
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
81
|
+
writeFileSync(stateFile(), JSON.stringify(Object.fromEntries([...keep, [sid, [...(seen[sid] ?? []), tool]]])));
|
|
82
|
+
return true;
|
|
83
|
+
}
|