limitcast 0.17.3 → 0.18.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 +147 -84
- package/bin/limitcast.mjs +225 -45
- package/package.json +2 -2
- package/src/apply.mjs +26 -0
- package/src/codex.mjs +21 -8
- package/src/cold.mjs +47 -10
- package/src/grok.mjs +21 -8
- package/src/guard.mjs +14 -3
- package/src/inflight.mjs +99 -0
- package/src/install.mjs +9 -0
- package/src/results.mjs +21 -1
- package/src/startup.mjs +28 -0
- package/src/toollimit.mjs +137 -0
- package/src/trim.mjs +40 -14
- package/src/value.mjs +17 -3
- package/src/where.mjs +53 -3
package/bin/limitcast.mjs
CHANGED
|
@@ -5,8 +5,11 @@ import { existsSync, mkdirSync, openSync, readFileSync, writeFileSync } from 'no
|
|
|
5
5
|
import { join } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import {
|
|
8
|
+
APPLY_BLOCKED,
|
|
9
|
+
applyBlocked,
|
|
8
10
|
applyTrim,
|
|
9
11
|
claudeJsonPath,
|
|
12
|
+
ensureDefaultKeep,
|
|
10
13
|
getKeep,
|
|
11
14
|
installedPlugins,
|
|
12
15
|
isKept,
|
|
@@ -21,7 +24,7 @@ import {
|
|
|
21
24
|
} from '../src/apply.mjs';
|
|
22
25
|
import { calibrate, limitChange, limitChangeMessage, windowPct } from '../src/calibrate.mjs';
|
|
23
26
|
import { applyCodexTrim, codexConfigPath, codexServers, codexStartup, codexTrimReport, codexUsedServers, undoCodexTrim } from '../src/codex.mjs';
|
|
24
|
-
import { coldCost, coldMessage, firstWarning } from '../src/cold.mjs';
|
|
27
|
+
import { coldCost, coldMessage, coldNotice, firstNotice, firstWarning } from '../src/cold.mjs';
|
|
25
28
|
import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
|
|
26
29
|
import { formatChecks } from '../src/formats.mjs';
|
|
27
30
|
import {
|
|
@@ -49,6 +52,16 @@ import {
|
|
|
49
52
|
import { runGuard } from '../src/guard.mjs';
|
|
50
53
|
import { accountForecasts, bindingLine, compactHint, headroom, lastCall, lastCallTokens } from '../src/hints.mjs';
|
|
51
54
|
import { htmlPage } from '../src/html.mjs';
|
|
55
|
+
import {
|
|
56
|
+
duplicateReason,
|
|
57
|
+
findDuplicate,
|
|
58
|
+
forgetInflight,
|
|
59
|
+
loadInflight,
|
|
60
|
+
pruneInflight,
|
|
61
|
+
rememberInflight,
|
|
62
|
+
saveInflight,
|
|
63
|
+
spawnIdentity,
|
|
64
|
+
} from '../src/inflight.mjs';
|
|
52
65
|
import { insightsReport, insightsShare, periodInsights } from '../src/insights.mjs';
|
|
53
66
|
import { doctor, install, installedFeatures, readSettings, settingsPath, uninstall } from '../src/install.mjs';
|
|
54
67
|
import { memoryCheck, memoryDir, memoryReport, scanMemory } from '../src/memory.mjs';
|
|
@@ -79,6 +92,7 @@ import {
|
|
|
79
92
|
} from '../src/subagents.mjs';
|
|
80
93
|
import { forTerminal } from '../src/term.mjs';
|
|
81
94
|
import { firstFlag, toolKey, toolNotice } from '../src/toolcheck.mjs';
|
|
95
|
+
import { loadToolStats, saveToolStats, toolLimitDecision, toolStats } from '../src/toollimit.mjs';
|
|
82
96
|
import { baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
|
|
83
97
|
import { claudeRoot, grokRoot, readUsage } from '../src/usage.mjs';
|
|
84
98
|
import { dailyDue, foldEvents, loadValue, saveValue, scanSessions, valuePeriod, valueSection, valueTotals } from '../src/value.mjs';
|
|
@@ -104,16 +118,21 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
104
118
|
All features are free (MIT License)
|
|
105
119
|
limitcast trim [--days N] [--share] names what to cut and what each costs
|
|
106
120
|
(--share: totals only, no names, safe to post)
|
|
107
|
-
limitcast trim --apply / --undo
|
|
108
|
-
|
|
109
|
-
|
|
121
|
+
limitcast trim --apply [--yes] / --undo hide unused skills and turn off MCP servers quiet for 30 days
|
|
122
|
+
(backed up, reversible). Refuses while the keep-list is empty
|
|
123
|
+
unless you pass --yes. install, doctor --fix, and trim
|
|
124
|
+
seed ego-browser when that list was never set.
|
|
125
|
+
limitcast trim --codex --apply [--yes] / --undo the same for Codex MCP servers (enabled = false; reversible)
|
|
126
|
+
limitcast trim --grok --apply [--yes] / --undo the same for Grok MCP servers (enabled = false; reversible)
|
|
110
127
|
limitcast trim keep <name>[,<name>…] never hide or turn off these (any --apply); --remove <name> drops one, no name lists them
|
|
111
128
|
limitcast saved tokens saved since limitcast first measured you
|
|
112
129
|
limitcast install --guard block new subagents when a window is on pace to run out, and run
|
|
113
130
|
them on Sonnet while a window is tight (NEAR or AT_RISK); show what
|
|
114
131
|
each finished subagent cost, and what that kind has cost before a new
|
|
115
|
-
one starts; hold
|
|
116
|
-
|
|
132
|
+
one starts; hold a second spawn of the same type and prompt
|
|
133
|
+
while the first is still running; announce a message after the
|
|
134
|
+
cheap cache expires (idle over 5 min, LIMITCAST_CACHE_NOTICE_MINUTES)
|
|
135
|
+
and hold the first one after 60 min (LIMITCAST_CACHE_MINUTES)
|
|
117
136
|
limitcast budget subagents <percent>|off hold new subagents once they used that much of the 5-hour window
|
|
118
137
|
limitcast subagent-model <type> <model>|off run new subagents of that type on sonnet, opus, haiku, grok-… or a model id
|
|
119
138
|
limitcast plan [--days N] does your Claude plan fit your use? Hit-limit and headroom evidence, and the monthly price difference
|
|
@@ -122,8 +141,9 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
122
141
|
needs this cap to block spawn_subagent). Optional: budget grok 7d <usd>
|
|
123
142
|
limitcast budget today on|off hold new subagents once today's share of a weekly window is used up, until
|
|
124
143
|
midnight (off: you only get a notification at 80% of the share; notify on)
|
|
125
|
-
limitcast install --alerts tell you when your starting context grows, plus a weekly summary,
|
|
126
|
-
when one tool result is very large (about 20k tokens),
|
|
144
|
+
limitcast install --alerts tell you when your starting context grows, plus a weekly summary,
|
|
145
|
+
when one tool result is very large (about 20k tokens), and, before it
|
|
146
|
+
runs, when a tool report --why has shown to be fat sets no limit
|
|
127
147
|
limitcast notify on|off|test desktop notification when a window turns NEAR, AT_RISK or HIT, or resets,
|
|
128
148
|
and when your Claude limit itself changes
|
|
129
149
|
limitcast notify ntfy <topic|url>|off also send them to your phone (ntfy.sh)
|
|
@@ -133,13 +153,15 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
133
153
|
limitcast results --html [--out FILE] results, current windows and the burn report as one page
|
|
134
154
|
limitcast report [--days N] [--out FILE] tokens by tool, day, project, model and session
|
|
135
155
|
limitcast report --why [--days N] where the new tokens went: subagents, session starts, cache rebuilds, tool results
|
|
136
|
-
limitcast report --jobs [--days N] the scheduled (headless) jobs that spend the most tokens just starting
|
|
156
|
+
limitcast report --jobs [--days N] the scheduled (headless) jobs that spend the most tokens just starting,
|
|
157
|
+
and which startup piece changed between two runs of the same job
|
|
137
158
|
(status line: points to another account with room, and suggests /compact past ~150k tokens a call)
|
|
138
159
|
|
|
139
160
|
Used by Claude Code, Codex and Grok (set up by install)
|
|
140
161
|
limitcast statusline [-- <cmd...>] record limit readings, then run your status-line command
|
|
141
162
|
limitcast guard PreToolUse hook
|
|
142
|
-
limitcast prompt-check UserPromptSubmit hook: the cold-cache
|
|
163
|
+
limitcast prompt-check UserPromptSubmit hook: the cold-cache notice and hold
|
|
164
|
+
limitcast tool-limit PreToolUse hook: a fat tool call that sets no limit
|
|
143
165
|
limitcast subagent-receipt SubagentStop hook: what the subagent cost
|
|
144
166
|
limitcast drift [--hook] SessionStart hook: compare starting context with the last session
|
|
145
167
|
`;
|
|
@@ -252,24 +274,53 @@ if (cmd === 'status') {
|
|
|
252
274
|
// The installed guard protects all users; LIMITCAST_ALLOW=1 remains the explicit override.
|
|
253
275
|
if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
|
|
254
276
|
try {
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
277
|
+
const hook = JSON.parse(readStdin());
|
|
278
|
+
const id = spawnIdentity(hook);
|
|
279
|
+
const live = pruneInflight(loadInflight(), now);
|
|
280
|
+
const dup = id ? findDuplicate(live, id) : null;
|
|
281
|
+
if (id && dup) {
|
|
282
|
+
saveInflight(live);
|
|
283
|
+
logBlock({
|
|
284
|
+
t: now,
|
|
285
|
+
kind: 'duplicate',
|
|
286
|
+
src: id.src,
|
|
287
|
+
win: '5h',
|
|
288
|
+
pct: 0,
|
|
289
|
+
wall: now,
|
|
290
|
+
reset: now,
|
|
291
|
+
type: id.type,
|
|
292
|
+
sid: id.sid,
|
|
293
|
+
...(typeof hook?.tool_use_id === 'string' ? { operation: hook.tool_use_id } : {}),
|
|
294
|
+
});
|
|
263
295
|
console.log(
|
|
264
296
|
JSON.stringify({
|
|
265
|
-
hookSpecificOutput: {
|
|
266
|
-
hookEventName: 'PreToolUse',
|
|
267
|
-
permissionDecision: 'allow',
|
|
268
|
-
permissionDecisionReason: d.reason,
|
|
269
|
-
updatedInput: d.updatedInput,
|
|
270
|
-
},
|
|
297
|
+
hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: duplicateReason(id) },
|
|
271
298
|
}),
|
|
272
299
|
);
|
|
300
|
+
} else {
|
|
301
|
+
const d = await runGuard(hook, now, Number(process.env.LIMITCAST_GUARD_MINUTES ?? 30), { preview: false });
|
|
302
|
+
if (typeof d === 'string') {
|
|
303
|
+
saveInflight(live);
|
|
304
|
+
console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: d } }));
|
|
305
|
+
} else {
|
|
306
|
+
if (id) saveInflight(rememberInflight(live, id, now));
|
|
307
|
+
if (d && 'notice' in d) {
|
|
308
|
+
// Allowed as is, with what this kind of subagent has cost so far (shown to the user, never the model).
|
|
309
|
+
console.log(JSON.stringify({ systemMessage: d.notice }));
|
|
310
|
+
} else if (d) {
|
|
311
|
+
// Model switch: allow the spawn with the same input and model "sonnet" (updatedInput replaces the whole input).
|
|
312
|
+
console.log(
|
|
313
|
+
JSON.stringify({
|
|
314
|
+
hookSpecificOutput: {
|
|
315
|
+
hookEventName: 'PreToolUse',
|
|
316
|
+
permissionDecision: 'allow',
|
|
317
|
+
permissionDecisionReason: d.reason,
|
|
318
|
+
updatedInput: d.updatedInput,
|
|
319
|
+
},
|
|
320
|
+
}),
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
273
324
|
}
|
|
274
325
|
} catch (e) {
|
|
275
326
|
// Fail open: a broken governor must not stop the agent.
|
|
@@ -282,9 +333,13 @@ if (cmd === 'status') {
|
|
|
282
333
|
const hook = JSON.parse(readStdin());
|
|
283
334
|
const path = hook?.transcript_path;
|
|
284
335
|
const last = process.env.LIMITCAST_ALLOW !== '1' && typeof path === 'string' && existsSync(path) ? lastCall(path) : null;
|
|
285
|
-
const c = coldCost(hook?.prompt, last, now, {
|
|
286
|
-
|
|
287
|
-
|
|
336
|
+
const c = coldCost(hook?.prompt, last, now, {
|
|
337
|
+
minutes: Number(process.env.LIMITCAST_CACHE_MINUTES ?? 60),
|
|
338
|
+
noticeMinutes: Number(process.env.LIMITCAST_CACHE_NOTICE_MINUTES ?? 5),
|
|
339
|
+
calib: loadValue().calib,
|
|
340
|
+
});
|
|
341
|
+
const sid = String(hook.session_id ?? '');
|
|
342
|
+
if (c && last && c.hold && firstWarning(sid, last.t)) {
|
|
288
343
|
logBlock({
|
|
289
344
|
t: now,
|
|
290
345
|
kind: 'cold',
|
|
@@ -295,13 +350,74 @@ if (cmd === 'status') {
|
|
|
295
350
|
reset: now,
|
|
296
351
|
tokens: c.tokens,
|
|
297
352
|
sid: hook.session_id,
|
|
298
|
-
...(pro ? {} : { shadow: true }),
|
|
299
353
|
});
|
|
300
|
-
|
|
354
|
+
console.log(JSON.stringify({ decision: 'block', reason: coldMessage(c) }));
|
|
355
|
+
} else if (c && last && !c.hold && firstNotice(sid, last.t)) {
|
|
356
|
+
logBlock({
|
|
357
|
+
t: now,
|
|
358
|
+
kind: 'cold-notice',
|
|
359
|
+
src: 'claude',
|
|
360
|
+
win: '5h',
|
|
361
|
+
pct: c.pct ?? 0,
|
|
362
|
+
wall: now,
|
|
363
|
+
reset: now,
|
|
364
|
+
tokens: c.tokens,
|
|
365
|
+
sid: hook.session_id,
|
|
366
|
+
});
|
|
367
|
+
console.log(JSON.stringify({ systemMessage: coldNotice(c) }));
|
|
301
368
|
}
|
|
302
369
|
} catch {
|
|
303
370
|
/* a hook must never stop a prompt by failing */
|
|
304
371
|
}
|
|
372
|
+
} else if (cmd === 'tool-limit') {
|
|
373
|
+
// PreToolUse hook (installed with --alerts). A fat tool with no limit is denied so the model can retry smaller.
|
|
374
|
+
// A limit that is only too large is lowered. Fail open, and LIMITCAST_ALLOW=1 skips it.
|
|
375
|
+
if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
|
|
376
|
+
try {
|
|
377
|
+
const hook = JSON.parse(readStdin());
|
|
378
|
+
const name = String(hook?.tool_name ?? hook?.toolName ?? '');
|
|
379
|
+
const d = name ? toolLimitDecision(name, hook?.tool_input ?? hook?.toolInput, loadToolStats()) : null;
|
|
380
|
+
if (d && 'deny' in d) {
|
|
381
|
+
logBlock({
|
|
382
|
+
t: now,
|
|
383
|
+
kind: 'tool-limit',
|
|
384
|
+
src: 'claude',
|
|
385
|
+
win: '5h',
|
|
386
|
+
pct: 0,
|
|
387
|
+
wall: now,
|
|
388
|
+
reset: now,
|
|
389
|
+
sid: hook.session_id,
|
|
390
|
+
...(typeof hook?.tool_use_id === 'string' ? { operation: hook.tool_use_id } : {}),
|
|
391
|
+
});
|
|
392
|
+
console.log(
|
|
393
|
+
JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: d.deny } }),
|
|
394
|
+
);
|
|
395
|
+
} else if (d) {
|
|
396
|
+
logBlock({
|
|
397
|
+
t: now,
|
|
398
|
+
kind: 'tool-cap',
|
|
399
|
+
src: 'claude',
|
|
400
|
+
win: '5h',
|
|
401
|
+
pct: 0,
|
|
402
|
+
wall: now,
|
|
403
|
+
reset: now,
|
|
404
|
+
sid: hook.session_id,
|
|
405
|
+
...(typeof hook?.tool_use_id === 'string' ? { operation: hook.tool_use_id } : {}),
|
|
406
|
+
});
|
|
407
|
+
console.log(
|
|
408
|
+
JSON.stringify({
|
|
409
|
+
hookSpecificOutput: {
|
|
410
|
+
hookEventName: 'PreToolUse',
|
|
411
|
+
permissionDecision: 'allow',
|
|
412
|
+
permissionDecisionReason: d.reason,
|
|
413
|
+
updatedInput: d.updatedInput,
|
|
414
|
+
},
|
|
415
|
+
}),
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
} catch {
|
|
419
|
+
/* a hook must never break the session */
|
|
420
|
+
}
|
|
305
421
|
} else if (cmd === 'tool-check') {
|
|
306
422
|
// PostToolUse hook (installed with --alerts): tell the user, once per tool per session, about a very large tool
|
|
307
423
|
// result and what to ask for next time. Never reaches the model.
|
|
@@ -320,6 +436,7 @@ if (cmd === 'status') {
|
|
|
320
436
|
// Pro shows the receipt to the user (systemMessage, never the model). Internal agents (empty type) are skipped.
|
|
321
437
|
try {
|
|
322
438
|
const hook = JSON.parse(readStdin());
|
|
439
|
+
saveInflight(forgetInflight(loadInflight(), String(hook?.session_id ?? ''), String(hook?.agent_type ?? ''), now));
|
|
323
440
|
const path = hook?.agent_transcript_path;
|
|
324
441
|
if (hook?.agent_type && typeof path === 'string') {
|
|
325
442
|
const u = subagentUsage(path);
|
|
@@ -473,6 +590,7 @@ if (cmd === 'status') {
|
|
|
473
590
|
const wantGuard = args.includes('--guard');
|
|
474
591
|
const wantAlerts = args.includes('--alerts');
|
|
475
592
|
for (const c of install({ guard: wantGuard, alerts: wantAlerts })) console.log(`✓ ${c}`);
|
|
593
|
+
if (ensureDefaultKeep().seeded) console.log('Kept ego-browser: trim --apply will not turn it off. Add more with limitcast trim keep <name>.');
|
|
476
594
|
console.log('Restart Claude Code, Codex and Grok to load it. Then: limitcast doctor');
|
|
477
595
|
if (wantGuard && grokPresent() && !getGrokBudget())
|
|
478
596
|
console.log('Grok stores spend, not a % used. Set a 5-hour dollar cap so the guard can block: limitcast budget grok <usd>');
|
|
@@ -533,6 +651,7 @@ if (cmd === 'status') {
|
|
|
533
651
|
if (!f.statusLine) console.log('limitcast is not installed. Run `limitcast install` first.');
|
|
534
652
|
else {
|
|
535
653
|
for (const c of install({ guard: f.guard, alerts: f.alerts })) console.log(`✓ ${c}`);
|
|
654
|
+
ensureDefaultKeep();
|
|
536
655
|
console.log('Restart Claude Code, Codex and Grok to load it. Codex asks you to approve the guard again: start Codex and accept it.');
|
|
537
656
|
}
|
|
538
657
|
}
|
|
@@ -576,6 +695,16 @@ if (cmd === 'status') {
|
|
|
576
695
|
} else if (cmd === 'report' || cmd === 'trim') {
|
|
577
696
|
const pro = true;
|
|
578
697
|
const since = now - days() * 86400_000;
|
|
698
|
+
if (cmd === 'trim' && args.includes('--share') && (args[0] === 'keep' || args.includes('--apply') || args.includes('--undo'))) {
|
|
699
|
+
console.error('--share is read-only; run keep, --apply, or --undo separately.');
|
|
700
|
+
process.exit(1);
|
|
701
|
+
}
|
|
702
|
+
if (cmd === 'trim' && args[0] !== 'keep' && !args.includes('--undo') && !args.includes('--share')) ensureDefaultKeep();
|
|
703
|
+
if (cmd === 'trim' && args.includes('--apply') && applyBlocked(getKeep(), args.includes('--yes'))) {
|
|
704
|
+
console.log(APPLY_BLOCKED);
|
|
705
|
+
process.exit(1);
|
|
706
|
+
}
|
|
707
|
+
const monthSince = now - 30 * 86400_000;
|
|
579
708
|
if (cmd === 'trim' && args[0] === 'keep') {
|
|
580
709
|
// The keep-list: servers and skills `trim --apply` never touches (Claude, Codex and Grok). Free to manage; apply is Pro.
|
|
581
710
|
const drop = args[1] === '--remove';
|
|
@@ -600,11 +729,25 @@ if (cmd === 'status') {
|
|
|
600
729
|
process.exit(0);
|
|
601
730
|
}
|
|
602
731
|
if (!existsSync(codexConfigPath())) {
|
|
603
|
-
console.log(
|
|
732
|
+
console.log(
|
|
733
|
+
args.includes('--share')
|
|
734
|
+
? 'Codex context summary: unavailable (no setup found).'
|
|
735
|
+
: `No Codex setup found (${codexConfigPath()}). Set CODEX_HOME if Codex keeps it elsewhere.`,
|
|
736
|
+
);
|
|
604
737
|
process.exit(0);
|
|
605
738
|
}
|
|
606
739
|
const servers = codexServers(readFileSync(codexConfigPath(), 'utf8'));
|
|
607
|
-
const
|
|
740
|
+
const usedCodex = await codexUsedServers(since);
|
|
741
|
+
const usedCodexMonth = days() >= 30 ? null : await codexUsedServers(monthSince);
|
|
742
|
+
const r = codexTrimReport({
|
|
743
|
+
servers,
|
|
744
|
+
used: usedCodex,
|
|
745
|
+
usedMonth: usedCodexMonth,
|
|
746
|
+
startup: await codexStartup(),
|
|
747
|
+
days: days(),
|
|
748
|
+
pro,
|
|
749
|
+
keep: getKeep(),
|
|
750
|
+
});
|
|
608
751
|
if (args.includes('--apply')) {
|
|
609
752
|
const changed = applyCodexTrim(r.unused);
|
|
610
753
|
console.log(
|
|
@@ -612,7 +755,12 @@ if (cmd === 'status') {
|
|
|
612
755
|
? `✓ Turned off ${changed.length} Codex MCP servers (enabled = false in ${codexConfigPath()}): ${changed.map((s) => s.name).join(', ')}\nTakes effect in your next Codex session. Undo: limitcast trim --codex --undo`
|
|
613
756
|
: 'Nothing to turn off: every server that is on was used or is on your keep-list.') + keptNote(r.kept),
|
|
614
757
|
);
|
|
615
|
-
} else
|
|
758
|
+
} else
|
|
759
|
+
console.log(
|
|
760
|
+
args.includes('--share')
|
|
761
|
+
? `Codex trim: ${r.unused.length} unused MCP servers, ${r.kept.length} kept.${r.standing.length ? ` ${r.standing.length} used in the last 30 days and left on.` : ''} Totals only; no names or paths. https://limitcast.dev`
|
|
762
|
+
: forTerminal(r.text),
|
|
763
|
+
);
|
|
616
764
|
process.exit(0);
|
|
617
765
|
}
|
|
618
766
|
if (cmd === 'trim' && args.includes('--grok')) {
|
|
@@ -624,12 +772,17 @@ if (cmd === 'status') {
|
|
|
624
772
|
process.exit(0);
|
|
625
773
|
}
|
|
626
774
|
if (!existsSync(grokConfigPath())) {
|
|
627
|
-
console.log(
|
|
775
|
+
console.log(
|
|
776
|
+
args.includes('--share')
|
|
777
|
+
? 'Grok context summary: unavailable (no setup found).'
|
|
778
|
+
: `No Grok setup found (${grokConfigPath()}). Set GROK_HOME if Grok keeps it elsewhere.`,
|
|
779
|
+
);
|
|
628
780
|
process.exit(0);
|
|
629
781
|
}
|
|
630
782
|
const r = grokTrimReport({
|
|
631
783
|
servers: grokServers(),
|
|
632
784
|
used: grokUsedServers(since),
|
|
785
|
+
usedMonth: days() >= 30 ? null : grokUsedServers(monthSince),
|
|
633
786
|
startup: grokStartup(),
|
|
634
787
|
days: days(),
|
|
635
788
|
pro,
|
|
@@ -642,7 +795,12 @@ if (cmd === 'status') {
|
|
|
642
795
|
? `✓ Turned off ${changed.length} Grok MCP servers (enabled = false in ${grokConfigPath()}): ${changed.map((s) => s.name).join(', ')}\nTakes effect in your next Grok session. Undo: limitcast trim --grok --undo`
|
|
643
796
|
: 'Nothing to turn off: every server that is on was used or is on your keep-list.') + keptNote(r.kept),
|
|
644
797
|
);
|
|
645
|
-
} else
|
|
798
|
+
} else
|
|
799
|
+
console.log(
|
|
800
|
+
args.includes('--share')
|
|
801
|
+
? `Grok trim: ${r.unused.length} unused MCP servers, ${r.kept.length} kept.${r.standing.length ? ` ${r.standing.length} used in the last 30 days and left on.` : ''} Totals only; no names or paths. https://limitcast.dev`
|
|
802
|
+
: forTerminal(r.text),
|
|
803
|
+
);
|
|
646
804
|
process.exit(0);
|
|
647
805
|
}
|
|
648
806
|
/** @type {import('../src/trim.mjs').Activity} */
|
|
@@ -650,9 +808,16 @@ if (cmd === 'status') {
|
|
|
650
808
|
const jobs = cmd === 'report' && args.includes('--jobs');
|
|
651
809
|
const why = cmd === 'report' && args.includes('--why');
|
|
652
810
|
const usage = why || jobs ? [] : await readUsage(since, {}, cmd === 'trim' ? used : undefined);
|
|
811
|
+
/** @type {import('../src/trim.mjs').Activity|null} */
|
|
812
|
+
let usedMonth = null;
|
|
813
|
+
if (cmd === 'trim' && days() < 30) {
|
|
814
|
+
usedMonth = { skills: new Set(), mcp: new Set() };
|
|
815
|
+
await readUsage(monthSince, {}, usedMonth);
|
|
816
|
+
}
|
|
653
817
|
let text;
|
|
654
818
|
if (why || jobs) {
|
|
655
819
|
const r = attribute(await whySessions(claudeRoot(), since), since);
|
|
820
|
+
saveToolStats(toolStats(r.tools));
|
|
656
821
|
text = jobs ? jobsReport(r, { since, now }) : whyReport(r, { since, now, calib: loadValue().calib });
|
|
657
822
|
} else if (cmd === 'report') text = burnReport(usage, { since, now });
|
|
658
823
|
else {
|
|
@@ -661,25 +826,28 @@ if (cmd === 'status') {
|
|
|
661
826
|
if (latest) recordOverhead(snapshot(latest));
|
|
662
827
|
// The share view omits private names; the local view includes actionable detail.
|
|
663
828
|
if (args.includes('--apply') || args.includes('--undo')) {
|
|
664
|
-
console.log(args.includes('--undo') ? undoMessage(undoTrim()) : applyMessage(latest, used));
|
|
829
|
+
console.log(args.includes('--undo') ? undoMessage(undoTrim()) : applyMessage(latest, used, usedMonth));
|
|
665
830
|
process.exit(0);
|
|
666
831
|
}
|
|
667
832
|
const keep = getKeep();
|
|
668
|
-
if (latest && args.includes('--share')) text = shareSummary(baseline(usage), latest, used, days(), keep);
|
|
669
|
-
else
|
|
833
|
+
if (latest && args.includes('--share')) text = shareSummary(baseline(usage), latest, used, days(), keep, usedMonth);
|
|
834
|
+
else
|
|
835
|
+
text = latest
|
|
836
|
+
? startupReport(baseline(usage), latest, used, days(), keep, usedMonth)
|
|
837
|
+
: trimReport(baseline(usage), contributors(), used, days(), args.includes('--share'));
|
|
670
838
|
if (latest && !args.includes('--share')) {
|
|
671
839
|
const still = stillLoading(latest);
|
|
672
840
|
text += still.length
|
|
673
841
|
? `\n\nStill loading after \`trim --apply\`: ${still.join(', ')}. A Claude Code session that was running may have rewritten ~/.claude.json; quit Claude Code and run \`limitcast trim --apply\` again.`
|
|
674
|
-
: measuredSavings(latest.pieces, used, keep).tokens > 0
|
|
675
|
-
? '\n\nApply these cuts: `limitcast trim --apply` (backed up; `limitcast trim --undo` reverses it).'
|
|
842
|
+
: measuredSavings(latest.pieces, used, keep, usedMonth).tokens > 0
|
|
843
|
+
? '\n\nApply these cuts: `limitcast trim --apply` turns off MCP servers quiet for 30 days and hides unused skills (backed up; `limitcast trim --undo` reverses it).'
|
|
676
844
|
: '';
|
|
677
845
|
}
|
|
678
846
|
}
|
|
679
847
|
const out = flag('--out');
|
|
680
848
|
if (out) {
|
|
681
849
|
writeFileSync(out, `${text}\n`);
|
|
682
|
-
console.log(`Wrote ${out}`);
|
|
850
|
+
console.log(cmd === 'trim' && args.includes('--share') ? 'Wrote shared summary.' : `Wrote ${out}`);
|
|
683
851
|
} else console.log(forTerminal(text));
|
|
684
852
|
} else if (cmd === 'drift') {
|
|
685
853
|
// SessionStart hook: tells the user (systemMessage, never the model's context) when starting context grew.
|
|
@@ -726,10 +894,13 @@ if (cmd === 'status') {
|
|
|
726
894
|
const since = now - days() * 86400_000;
|
|
727
895
|
let saved = '';
|
|
728
896
|
let perSession = null;
|
|
897
|
+
/** @type {{first:number, last:number}|null} */
|
|
898
|
+
let start = null;
|
|
729
899
|
if (pro) {
|
|
730
900
|
const latest = await latestInteractiveTranscript(claudeRoot());
|
|
731
901
|
if (latest) recordOverhead(snapshot(latest));
|
|
732
902
|
const s = loadOverhead();
|
|
903
|
+
start = s ? { first: s.first.chars, last: s.last.chars } : null;
|
|
733
904
|
perSession = s ? savedPerSession(s) : null;
|
|
734
905
|
saved =
|
|
735
906
|
s && !args.includes('--share')
|
|
@@ -758,7 +929,16 @@ if (cmd === 'status') {
|
|
|
758
929
|
const burn = burnReport(await readUsage(since, {}), { since, now }).replace(/^(#{1,2}) /gm, '#$1 ');
|
|
759
930
|
const md = [
|
|
760
931
|
insightsReport(insight, pro),
|
|
761
|
-
resultsReport({
|
|
932
|
+
resultsReport({
|
|
933
|
+
now,
|
|
934
|
+
days: days(),
|
|
935
|
+
samples,
|
|
936
|
+
blocks,
|
|
937
|
+
pro,
|
|
938
|
+
saved,
|
|
939
|
+
value: valueSection(totals, { now, pro, start }),
|
|
940
|
+
subagents: loadSubagents(since),
|
|
941
|
+
}),
|
|
762
942
|
'## Right now',
|
|
763
943
|
'```',
|
|
764
944
|
rows.length ? table(rows) : 'No readings yet.',
|
|
@@ -785,7 +965,7 @@ if (cmd === 'status') {
|
|
|
785
965
|
blocks,
|
|
786
966
|
pro,
|
|
787
967
|
saved,
|
|
788
|
-
value: valueSection(totals, { now, pro }),
|
|
968
|
+
value: valueSection(totals, { now, pro, start }),
|
|
789
969
|
subagents: loadSubagents(since),
|
|
790
970
|
}),
|
|
791
971
|
].join('\n\n'),
|
|
@@ -965,13 +1145,13 @@ async function refreshValue() {
|
|
|
965
1145
|
* @param {Awaited<ReturnType<typeof latestInteractiveTranscript>>} latest
|
|
966
1146
|
* @param {import('../src/trim.mjs').Activity} used
|
|
967
1147
|
*/
|
|
968
|
-
function applyMessage(latest, used) {
|
|
1148
|
+
function applyMessage(latest, used, usedMonth) {
|
|
969
1149
|
if (!latest) return '`limitcast trim --apply` needs one Claude Code session first.';
|
|
970
|
-
const s = measuredSavings(latest.pieces, used);
|
|
1150
|
+
const s = measuredSavings(latest.pieces, used, getKeep(), usedMonth);
|
|
971
1151
|
const cwd = transcriptCwd(latest.file) ?? process.cwd();
|
|
972
1152
|
const plan = planTrim({
|
|
973
1153
|
skills: s.unusedSkills.map((k) => k.name),
|
|
974
|
-
mcp: s.
|
|
1154
|
+
mcp: s.staleMcp.map((m) => m.name),
|
|
975
1155
|
cwd,
|
|
976
1156
|
settings: readSettings(settingsPath()),
|
|
977
1157
|
claudeJson: readSettings(claudeJsonPath()),
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "limitcast",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.18.1",
|
|
4
|
+
"description": "Claude Code usage limits: forecast Codex and Grok too.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"limitcast": "bin/limitcast.mjs"
|
package/src/apply.mjs
CHANGED
|
@@ -32,6 +32,13 @@ const ledgerPath = () => join(stateDir(), 'trim-applied.json');
|
|
|
32
32
|
const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '_');
|
|
33
33
|
const configFile = () => join(stateDir(), 'config.json');
|
|
34
34
|
|
|
35
|
+
/** Seeded the first time the keep-list is created. `trim --apply` must not turn this off. */
|
|
36
|
+
export const DEFAULT_KEEP = ['ego-browser'];
|
|
37
|
+
|
|
38
|
+
/** Shown when `--apply` would run with nothing protected. */
|
|
39
|
+
export const APPLY_BLOCKED =
|
|
40
|
+
'Nothing on the keep-list, so `trim --apply` would turn off every server that looks unused, including ego-browser. Run `limitcast trim keep ego-browser` first, or repeat with `--yes`.';
|
|
41
|
+
|
|
35
42
|
/** Names `trim --apply` never turns off or hides, from `limitcast trim keep`. @returns {string[]} */
|
|
36
43
|
export function getKeep() {
|
|
37
44
|
try {
|
|
@@ -42,6 +49,25 @@ export function getKeep() {
|
|
|
42
49
|
}
|
|
43
50
|
}
|
|
44
51
|
|
|
52
|
+
/**
|
|
53
|
+
* Write the default keep-list when `trimKeep` has never been set. An explicit empty list stays empty.
|
|
54
|
+
* @returns {{keep:string[], seeded:boolean}}
|
|
55
|
+
*/
|
|
56
|
+
export function ensureDefaultKeep() {
|
|
57
|
+
let cfg = {};
|
|
58
|
+
try {
|
|
59
|
+
cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
|
|
60
|
+
} catch {
|
|
61
|
+
cfg = {};
|
|
62
|
+
}
|
|
63
|
+
if (Object.hasOwn(cfg, 'trimKeep')) return { keep: getKeep(), seeded: false };
|
|
64
|
+
setKeep(DEFAULT_KEEP);
|
|
65
|
+
return { keep: [...DEFAULT_KEEP], seeded: true };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** True when `--apply` must stop because nothing is protected and the user did not pass `--yes`. */
|
|
69
|
+
export const applyBlocked = (/** @type {string[]} */ keep, /** @type {boolean} */ yes) => !yes && keep.length === 0;
|
|
70
|
+
|
|
45
71
|
/** @param {string[]} names */
|
|
46
72
|
export function setKeep(names) {
|
|
47
73
|
let cfg = {};
|
package/src/codex.mjs
CHANGED
|
@@ -118,14 +118,16 @@ export async function codexStartup(root = join(codexHome(), 'sessions')) {
|
|
|
118
118
|
}
|
|
119
119
|
|
|
120
120
|
/**
|
|
121
|
-
* @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, startup:{agentsMd:number, base:number}|null, days:number, pro:boolean, keep?:string[]}} r
|
|
122
|
-
* keep: the `trim keep` list; unused servers on it are reported as kept and left out of `unused
|
|
121
|
+
* @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, usedMonth?:Set<string>|null, startup:{agentsMd:number, base:number}|null, days:number, pro:boolean, keep?:string[]}} r
|
|
122
|
+
* keep: the `trim keep` list; unused servers on it are reported as kept and left out of `unused`.
|
|
123
|
+
* usedMonth: normalized names used in 30 days. Servers in it stay out of `unused`.
|
|
123
124
|
*/
|
|
124
|
-
export function codexTrimReport({ servers, used, startup, days, pro, keep = [] }) {
|
|
125
|
+
export function codexTrimReport({ servers, used, usedMonth = null, startup, days, pro, keep = [] }) {
|
|
125
126
|
const on = servers.filter((s) => s.enabled !== false);
|
|
126
127
|
const idle = on.filter((s) => !used.has(norm(s.name)));
|
|
127
128
|
const kept = idle.filter((s) => keep.some((k) => norm(k) === norm(s.name)));
|
|
128
|
-
const
|
|
129
|
+
const standing = usedMonth ? idle.filter((s) => !kept.includes(s) && usedMonth.has(norm(s.name))) : [];
|
|
130
|
+
const unused = idle.filter((s) => !kept.includes(s) && !standing.includes(s));
|
|
129
131
|
const tok = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
|
|
130
132
|
const out = ['# limitcast trim --codex', ''];
|
|
131
133
|
if (startup)
|
|
@@ -133,17 +135,28 @@ export function codexTrimReport({ servers, used, startup, days, pro, keep = [] }
|
|
|
133
135
|
`Codex sessions start with ~${tok(startup.agentsMd)} tokens of AGENTS.md (your instruction files) and ~${tok(startup.base)} of Codex's own instructions, re-sent on every turn.`,
|
|
134
136
|
'',
|
|
135
137
|
);
|
|
136
|
-
out.push(`## MCP servers: ${on.length} on, ${unused.length} not used in ${days} days`);
|
|
137
|
-
if (
|
|
138
|
+
out.push(`## MCP servers: ${on.length} on, ${unused.length + standing.length} not used in ${days} days`);
|
|
139
|
+
if (standing.length)
|
|
140
|
+
out.push('', `${standing.length} used in the last 30 days, so \`trim --apply\` leaves them on:`, ...standing.map((s) => `- ${s.name}`));
|
|
141
|
+
if (!unused.length) out.push(kept.length || standing.length ? 'Nothing else to turn off.' : 'Every server that is on was used.');
|
|
138
142
|
else if (pro)
|
|
139
|
-
out.push(
|
|
143
|
+
out.push(
|
|
144
|
+
...unused.map((s) => `- ${s.name}`),
|
|
145
|
+
'',
|
|
146
|
+
`${usedMonth ? 'Turn the servers that have been quiet for 30 days off' : 'Turn them off'}: \`limitcast trim --codex --apply\` (backed up; \`--undo\` reverses it).`,
|
|
147
|
+
);
|
|
140
148
|
else out.push(`Pro names them and turns them off for you: https://limitcast.dev/#pricing`);
|
|
141
149
|
if (kept.length) out.push('', `Would keep (your keep-list): ${kept.map((s) => s.name).join(', ')}.`);
|
|
142
150
|
out.push(
|
|
143
151
|
'',
|
|
144
152
|
'Each server that is on starts with every Codex session and adds its tool list to the context. AGENTS.md: every 1k tokens you move into files read on demand saves 1k per turn.',
|
|
145
153
|
);
|
|
146
|
-
return {
|
|
154
|
+
return {
|
|
155
|
+
text: out.join('\n'),
|
|
156
|
+
unused: unused.map((s) => s.name),
|
|
157
|
+
standing: standing.map((s) => s.name),
|
|
158
|
+
kept: kept.map((s) => s.name),
|
|
159
|
+
};
|
|
147
160
|
}
|
|
148
161
|
|
|
149
162
|
/** @param {string} path @param {string} text */
|