limitcast 0.18.0 → 0.18.2
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 +2 -2
- package/bin/limitcast.mjs +81 -22
- package/package.json +2 -2
- package/src/apply.mjs +28 -2
- package/src/codex.mjs +21 -8
- package/src/flags.mjs +38 -0
- package/src/grok.mjs +24 -11
- package/src/guard.mjs +15 -4
- package/src/hints.mjs +1 -1
- package/src/notify.mjs +2 -2
- package/src/plan.mjs +3 -3
- package/src/results.mjs +1 -1
- package/src/store.mjs +10 -3
- package/src/subagents.mjs +6 -6
- package/src/toolcheck.mjs +1 -1
- package/src/trim.mjs +30 -13
- package/src/usage.mjs +8 -5
- package/src/value.mjs +17 -3
- package/src/where.mjs +15 -9
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
</p>
|
|
11
11
|
|
|
12
12
|
<p align="center">
|
|
13
|
-
<strong>
|
|
13
|
+
<strong>Claude Code usage limits: forecast Codex and Grok too.</strong><br>
|
|
14
14
|
See when your usage window will run out, control subagent burn,<br>
|
|
15
15
|
and remove starting context you never use.
|
|
16
16
|
</p>
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
|
|
37
37
|
- **Keep agents in check.** Hold new subagents when capacity is tight, with receipts and optional budgets. The guard also holds a second subagent of the same type and prompt while the first is still running. `limitcast install --guard`
|
|
38
38
|
|
|
39
|
-
- **Start lighter.** Inspect unused skills and MCP servers, then trim with backups and undo. `limitcast trim`
|
|
39
|
+
- **Start lighter.** Inspect unused skills and MCP servers, then trim with backups and undo. Apply turns off only MCP servers quiet for 30 days. `limitcast trim`
|
|
40
40
|
|
|
41
41
|
<a id="free-and-open-source"></a>
|
|
42
42
|
|
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,
|
|
@@ -22,6 +25,7 @@ import {
|
|
|
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
27
|
import { coldCost, coldMessage, coldNotice, firstNotice, firstWarning } from '../src/cold.mjs';
|
|
28
|
+
import { unknownFlag } from '../src/flags.mjs';
|
|
25
29
|
import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
|
|
26
30
|
import { formatChecks } from '../src/formats.mjs';
|
|
27
31
|
import {
|
|
@@ -115,9 +119,12 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
115
119
|
All features are free (MIT License)
|
|
116
120
|
limitcast trim [--days N] [--share] names what to cut and what each costs
|
|
117
121
|
(--share: totals only, no names, safe to post)
|
|
118
|
-
limitcast trim --apply / --undo
|
|
119
|
-
|
|
120
|
-
|
|
122
|
+
limitcast trim --apply [--yes] / --undo hide unused skills and turn off MCP servers quiet for 30 days
|
|
123
|
+
(backed up, reversible). Refuses while the keep-list is empty
|
|
124
|
+
unless you pass --yes. install, doctor --fix, and trim
|
|
125
|
+
seed ego-browser when that list was never set.
|
|
126
|
+
limitcast trim --codex --apply [--yes] / --undo the same for Codex MCP servers (enabled = false; reversible)
|
|
127
|
+
limitcast trim --grok --apply [--yes] / --undo the same for Grok MCP servers (enabled = false; reversible)
|
|
121
128
|
limitcast trim keep <name>[,<name>…] never hide or turn off these (any --apply); --remove <name> drops one, no name lists them
|
|
122
129
|
limitcast saved tokens saved since limitcast first measured you
|
|
123
130
|
limitcast install --guard block new subagents when a window is on pace to run out, and run
|
|
@@ -162,6 +169,14 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
162
169
|
|
|
163
170
|
const [cmd, ...args] = process.argv.slice(2);
|
|
164
171
|
const now = Date.now();
|
|
172
|
+
// Hooks run unattended and fail open; everything else rejects a mistyped option instead of ignoring it.
|
|
173
|
+
const typo = ['guard', 'prompt-check', 'tool-check', 'tool-limit', 'subagent-receipt', 'drift', 'statusline'].includes(cmd)
|
|
174
|
+
? undefined
|
|
175
|
+
: unknownFlag(args);
|
|
176
|
+
if (typo) {
|
|
177
|
+
console.error(`Unknown option ${typo}. Run "limitcast help" for the options.`);
|
|
178
|
+
process.exit(1);
|
|
179
|
+
}
|
|
165
180
|
const flag = (/** @type {string} */ name) => {
|
|
166
181
|
const i = args.indexOf(name);
|
|
167
182
|
return i >= 0 ? args[i + 1] : undefined;
|
|
@@ -584,6 +599,7 @@ if (cmd === 'status') {
|
|
|
584
599
|
const wantGuard = args.includes('--guard');
|
|
585
600
|
const wantAlerts = args.includes('--alerts');
|
|
586
601
|
for (const c of install({ guard: wantGuard, alerts: wantAlerts })) console.log(`✓ ${c}`);
|
|
602
|
+
if (ensureDefaultKeep().seeded) console.log('Kept ego-browser: trim --apply will not turn it off. Add more with limitcast trim keep <name>.');
|
|
587
603
|
console.log('Restart Claude Code, Codex and Grok to load it. Then: limitcast doctor');
|
|
588
604
|
if (wantGuard && grokPresent() && !getGrokBudget())
|
|
589
605
|
console.log('Grok stores spend, not a % used. Set a 5-hour dollar cap so the guard can block: limitcast budget grok <usd>');
|
|
@@ -644,6 +660,7 @@ if (cmd === 'status') {
|
|
|
644
660
|
if (!f.statusLine) console.log('limitcast is not installed. Run `limitcast install` first.');
|
|
645
661
|
else {
|
|
646
662
|
for (const c of install({ guard: f.guard, alerts: f.alerts })) console.log(`✓ ${c}`);
|
|
663
|
+
ensureDefaultKeep();
|
|
647
664
|
console.log('Restart Claude Code, Codex and Grok to load it. Codex asks you to approve the guard again: start Codex and accept it.');
|
|
648
665
|
}
|
|
649
666
|
}
|
|
@@ -691,6 +708,12 @@ if (cmd === 'status') {
|
|
|
691
708
|
console.error('--share is read-only; run keep, --apply, or --undo separately.');
|
|
692
709
|
process.exit(1);
|
|
693
710
|
}
|
|
711
|
+
if (cmd === 'trim' && args[0] !== 'keep' && !args.includes('--undo') && !args.includes('--share')) ensureDefaultKeep();
|
|
712
|
+
if (cmd === 'trim' && args.includes('--apply') && applyBlocked(getKeep(), args.includes('--yes'))) {
|
|
713
|
+
console.log(APPLY_BLOCKED);
|
|
714
|
+
process.exit(1);
|
|
715
|
+
}
|
|
716
|
+
const monthSince = now - 30 * 86400_000;
|
|
694
717
|
if (cmd === 'trim' && args[0] === 'keep') {
|
|
695
718
|
// The keep-list: servers and skills `trim --apply` never touches (Claude, Codex and Grok). Free to manage; apply is Pro.
|
|
696
719
|
const drop = args[1] === '--remove';
|
|
@@ -723,7 +746,17 @@ if (cmd === 'status') {
|
|
|
723
746
|
process.exit(0);
|
|
724
747
|
}
|
|
725
748
|
const servers = codexServers(readFileSync(codexConfigPath(), 'utf8'));
|
|
726
|
-
const
|
|
749
|
+
const usedCodex = await codexUsedServers(since);
|
|
750
|
+
const usedCodexMonth = days() >= 30 ? null : await codexUsedServers(monthSince);
|
|
751
|
+
const r = codexTrimReport({
|
|
752
|
+
servers,
|
|
753
|
+
used: usedCodex,
|
|
754
|
+
usedMonth: usedCodexMonth,
|
|
755
|
+
startup: await codexStartup(),
|
|
756
|
+
days: days(),
|
|
757
|
+
pro,
|
|
758
|
+
keep: getKeep(),
|
|
759
|
+
});
|
|
727
760
|
if (args.includes('--apply')) {
|
|
728
761
|
const changed = applyCodexTrim(r.unused);
|
|
729
762
|
console.log(
|
|
@@ -734,7 +767,7 @@ if (cmd === 'status') {
|
|
|
734
767
|
} else
|
|
735
768
|
console.log(
|
|
736
769
|
args.includes('--share')
|
|
737
|
-
? `Codex trim: ${r.unused.length} unused MCP servers, ${r.kept.length} kept. Totals only; no names or paths. https://limitcast.dev`
|
|
770
|
+
? `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`
|
|
738
771
|
: forTerminal(r.text),
|
|
739
772
|
);
|
|
740
773
|
process.exit(0);
|
|
@@ -758,6 +791,7 @@ if (cmd === 'status') {
|
|
|
758
791
|
const r = grokTrimReport({
|
|
759
792
|
servers: grokServers(),
|
|
760
793
|
used: grokUsedServers(since),
|
|
794
|
+
usedMonth: days() >= 30 ? null : grokUsedServers(monthSince),
|
|
761
795
|
startup: grokStartup(),
|
|
762
796
|
days: days(),
|
|
763
797
|
pro,
|
|
@@ -773,7 +807,7 @@ if (cmd === 'status') {
|
|
|
773
807
|
} else
|
|
774
808
|
console.log(
|
|
775
809
|
args.includes('--share')
|
|
776
|
-
? `Grok trim: ${r.unused.length} unused MCP servers, ${r.kept.length} kept. Totals only; no names or paths. https://limitcast.dev`
|
|
810
|
+
? `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`
|
|
777
811
|
: forTerminal(r.text),
|
|
778
812
|
);
|
|
779
813
|
process.exit(0);
|
|
@@ -783,6 +817,12 @@ if (cmd === 'status') {
|
|
|
783
817
|
const jobs = cmd === 'report' && args.includes('--jobs');
|
|
784
818
|
const why = cmd === 'report' && args.includes('--why');
|
|
785
819
|
const usage = why || jobs ? [] : await readUsage(since, {}, cmd === 'trim' ? used : undefined);
|
|
820
|
+
/** @type {import('../src/trim.mjs').Activity|null} */
|
|
821
|
+
let usedMonth = null;
|
|
822
|
+
if (cmd === 'trim' && days() < 30) {
|
|
823
|
+
usedMonth = { skills: new Set(), mcp: new Set() };
|
|
824
|
+
await readUsage(monthSince, {}, usedMonth);
|
|
825
|
+
}
|
|
786
826
|
let text;
|
|
787
827
|
if (why || jobs) {
|
|
788
828
|
const r = attribute(await whySessions(claudeRoot(), since), since);
|
|
@@ -795,21 +835,21 @@ if (cmd === 'status') {
|
|
|
795
835
|
if (latest) recordOverhead(snapshot(latest));
|
|
796
836
|
// The share view omits private names; the local view includes actionable detail.
|
|
797
837
|
if (args.includes('--apply') || args.includes('--undo')) {
|
|
798
|
-
console.log(args.includes('--undo') ? undoMessage(undoTrim()) : applyMessage(latest, used));
|
|
838
|
+
console.log(args.includes('--undo') ? undoMessage(undoTrim()) : applyMessage(latest, used, usedMonth));
|
|
799
839
|
process.exit(0);
|
|
800
840
|
}
|
|
801
841
|
const keep = getKeep();
|
|
802
|
-
if (latest && args.includes('--share')) text = shareSummary(baseline(usage), latest, used, days(), keep);
|
|
842
|
+
if (latest && args.includes('--share')) text = shareSummary(baseline(usage), latest, used, days(), keep, usedMonth);
|
|
803
843
|
else
|
|
804
844
|
text = latest
|
|
805
|
-
? startupReport(baseline(usage), latest, used, days(), keep)
|
|
845
|
+
? startupReport(baseline(usage), latest, used, days(), keep, usedMonth)
|
|
806
846
|
: trimReport(baseline(usage), contributors(), used, days(), args.includes('--share'));
|
|
807
847
|
if (latest && !args.includes('--share')) {
|
|
808
848
|
const still = stillLoading(latest);
|
|
809
849
|
text += still.length
|
|
810
850
|
? `\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.`
|
|
811
|
-
: measuredSavings(latest.pieces, used, keep).tokens > 0
|
|
812
|
-
? '\n\nApply these cuts: `limitcast trim --apply` (backed up; `limitcast trim --undo` reverses it).'
|
|
851
|
+
: measuredSavings(latest.pieces, used, keep, usedMonth).tokens > 0
|
|
852
|
+
? '\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).'
|
|
813
853
|
: '';
|
|
814
854
|
}
|
|
815
855
|
}
|
|
@@ -863,10 +903,13 @@ if (cmd === 'status') {
|
|
|
863
903
|
const since = now - days() * 86400_000;
|
|
864
904
|
let saved = '';
|
|
865
905
|
let perSession = null;
|
|
906
|
+
/** @type {{first:number, last:number}|null} */
|
|
907
|
+
let start = null;
|
|
866
908
|
if (pro) {
|
|
867
909
|
const latest = await latestInteractiveTranscript(claudeRoot());
|
|
868
910
|
if (latest) recordOverhead(snapshot(latest));
|
|
869
911
|
const s = loadOverhead();
|
|
912
|
+
start = s ? { first: s.first.chars, last: s.last.chars } : null;
|
|
870
913
|
perSession = s ? savedPerSession(s) : null;
|
|
871
914
|
saved =
|
|
872
915
|
s && !args.includes('--share')
|
|
@@ -875,9 +918,10 @@ if (cmd === 'status') {
|
|
|
875
918
|
}
|
|
876
919
|
const samples = [...load(since), ...(await readCodex(since))];
|
|
877
920
|
const blocks = loadBlocks(since);
|
|
878
|
-
const
|
|
921
|
+
const usage = await readUsage(Math.min(since - days() * 86400_000, now - KEEP_MS), {}); // one read feeds both below
|
|
922
|
+
const value = await refreshValue(usage);
|
|
879
923
|
const totals = valueTotals(value);
|
|
880
|
-
const insight = periodInsights({ value, usage:
|
|
924
|
+
const insight = periodInsights({ value, usage: usage.filter((u) => u.t >= since - days() * 86400_000), blocks, since, until: now });
|
|
881
925
|
if (args.includes('--share'))
|
|
882
926
|
console.log(
|
|
883
927
|
resultsShare(resultsStats({ now, days: days(), samples, blocks, pro }), {
|
|
@@ -892,10 +936,22 @@ if (cmd === 'status') {
|
|
|
892
936
|
else if (args.includes('--html')) {
|
|
893
937
|
// results, the current windows and the burn report on one page, opened in the browser.
|
|
894
938
|
const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS))]), now);
|
|
895
|
-
const burn = burnReport(
|
|
939
|
+
const burn = burnReport(
|
|
940
|
+
usage.filter((u) => u.t >= since),
|
|
941
|
+
{ since, now },
|
|
942
|
+
).replace(/^(#{1,2}) /gm, '#$1 ');
|
|
896
943
|
const md = [
|
|
897
944
|
insightsReport(insight, pro),
|
|
898
|
-
resultsReport({
|
|
945
|
+
resultsReport({
|
|
946
|
+
now,
|
|
947
|
+
days: days(),
|
|
948
|
+
samples,
|
|
949
|
+
blocks,
|
|
950
|
+
pro,
|
|
951
|
+
saved,
|
|
952
|
+
value: valueSection(totals, { now, pro, start }),
|
|
953
|
+
subagents: loadSubagents(since),
|
|
954
|
+
}),
|
|
899
955
|
'## Right now',
|
|
900
956
|
'```',
|
|
901
957
|
rows.length ? table(rows) : 'No readings yet.',
|
|
@@ -922,7 +978,7 @@ if (cmd === 'status') {
|
|
|
922
978
|
blocks,
|
|
923
979
|
pro,
|
|
924
980
|
saved,
|
|
925
|
-
value: valueSection(totals, { now, pro }),
|
|
981
|
+
value: valueSection(totals, { now, pro, start }),
|
|
926
982
|
subagents: loadSubagents(since),
|
|
927
983
|
}),
|
|
928
984
|
].join('\n\n'),
|
|
@@ -1064,8 +1120,11 @@ function healthHint() {
|
|
|
1064
1120
|
}
|
|
1065
1121
|
}
|
|
1066
1122
|
|
|
1067
|
-
/**
|
|
1068
|
-
|
|
1123
|
+
/**
|
|
1124
|
+
* Fold the last 8 days of readings and blocks, and any new sessions, into the long-term value record.
|
|
1125
|
+
* @param {import('../src/usage.mjs').Usage[]} [preread] usage already read since at least KEEP_MS ago, to skip a second walk of the transcripts
|
|
1126
|
+
*/
|
|
1127
|
+
async function refreshValue(preread) {
|
|
1069
1128
|
const since = now - KEEP_MS;
|
|
1070
1129
|
const claude = load(since);
|
|
1071
1130
|
recordPeaks(claude, now); // the long-lived record of window peaks behind `limitcast plan`
|
|
@@ -1075,7 +1134,7 @@ async function refreshValue() {
|
|
|
1075
1134
|
const v = foldEvents(loadValue(), { now, samples: [...claude, ...(await readCodex(since))], blocks: loadBlocks(since), start });
|
|
1076
1135
|
await scanSessions(v, { root: claudeRoot(), baseline: o ? { at: o.first.at, chars: o.first.chars } : null, now });
|
|
1077
1136
|
// Recalibrate from the last 8 days when there is enough data; keep the last good calibration otherwise.
|
|
1078
|
-
const usage = await readUsage(since, {});
|
|
1137
|
+
const usage = preread ? preread.filter((u) => u.t >= since) : await readUsage(since, {});
|
|
1079
1138
|
const c = calibrate(claude, usage);
|
|
1080
1139
|
if (c) v.calib = { ...c, at: now };
|
|
1081
1140
|
// Once a day, the last 3 days on their own: a lasting shift against earlier days means the limit itself changed.
|
|
@@ -1102,13 +1161,13 @@ async function refreshValue() {
|
|
|
1102
1161
|
* @param {Awaited<ReturnType<typeof latestInteractiveTranscript>>} latest
|
|
1103
1162
|
* @param {import('../src/trim.mjs').Activity} used
|
|
1104
1163
|
*/
|
|
1105
|
-
function applyMessage(latest, used) {
|
|
1164
|
+
function applyMessage(latest, used, usedMonth) {
|
|
1106
1165
|
if (!latest) return '`limitcast trim --apply` needs one Claude Code session first.';
|
|
1107
|
-
const s = measuredSavings(latest.pieces, used);
|
|
1166
|
+
const s = measuredSavings(latest.pieces, used, getKeep(), usedMonth);
|
|
1108
1167
|
const cwd = transcriptCwd(latest.file) ?? process.cwd();
|
|
1109
1168
|
const plan = planTrim({
|
|
1110
1169
|
skills: s.unusedSkills.map((k) => k.name),
|
|
1111
|
-
mcp: s.
|
|
1170
|
+
mcp: s.staleMcp.map((m) => m.name),
|
|
1112
1171
|
cwd,
|
|
1113
1172
|
settings: readSettings(settingsPath()),
|
|
1114
1173
|
claudeJson: readSettings(claudeJsonPath()),
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "limitcast",
|
|
3
|
-
"version": "0.18.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.18.2",
|
|
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
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
import { homedir } from 'node:os';
|
|
17
17
|
import { join } from 'node:path';
|
|
18
18
|
import { readSettings, settingsPath } from './install.mjs';
|
|
19
|
-
import { stateDir } from './store.mjs';
|
|
19
|
+
import { stateDir, writeAtomic } from './store.mjs';
|
|
20
20
|
|
|
21
21
|
// `trim --apply`: hide unused skills and turn off unused MCP servers through Claude Code's own settings.
|
|
22
22
|
// Skills: `skillOverrides` in ~/.claude/settings.json ("user-invocable-only": the model stops seeing it, /name still works).
|
|
@@ -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 = {};
|
|
@@ -51,7 +77,7 @@ export function setKeep(names) {
|
|
|
51
77
|
/* new */
|
|
52
78
|
}
|
|
53
79
|
mkdirSync(stateDir(), { recursive: true });
|
|
54
|
-
|
|
80
|
+
writeAtomic(configFile(), JSON.stringify({ ...cfg, trimKeep: [...new Set(names)] }));
|
|
55
81
|
}
|
|
56
82
|
|
|
57
83
|
/** Same server or skill under another spelling ("ego-browser" / "ego_browser") counts. @param {string[]} keep @param {string} name */
|
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 */
|
package/src/flags.mjs
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
/** Every option the CLI reads. test/flags.test.mjs keeps this list in step with bin/limitcast.mjs. */
|
|
4
|
+
export const KNOWN_FLAGS = [
|
|
5
|
+
'--alerts',
|
|
6
|
+
'--apply',
|
|
7
|
+
'--codex',
|
|
8
|
+
'--days',
|
|
9
|
+
'--detach',
|
|
10
|
+
'--fix',
|
|
11
|
+
'--grok',
|
|
12
|
+
'--guard',
|
|
13
|
+
'--help',
|
|
14
|
+
'--hook',
|
|
15
|
+
'--html',
|
|
16
|
+
'--jobs',
|
|
17
|
+
'--json',
|
|
18
|
+
'--no-open',
|
|
19
|
+
'--out',
|
|
20
|
+
'--refresh',
|
|
21
|
+
'--remove',
|
|
22
|
+
'--share',
|
|
23
|
+
'--src',
|
|
24
|
+
'--undo',
|
|
25
|
+
'--why',
|
|
26
|
+
'--window',
|
|
27
|
+
'--yes',
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The first mistyped --option before any `--` separator, or undefined. Without this a typo such as
|
|
32
|
+
* `install --gaurd` runs the plain command and looks like it worked.
|
|
33
|
+
* @param {string[]} args
|
|
34
|
+
*/
|
|
35
|
+
export function unknownFlag(args) {
|
|
36
|
+
const sep = args.indexOf('--');
|
|
37
|
+
return (sep < 0 ? args : args.slice(0, sep)).find((a) => a.startsWith('--') && !KNOWN_FLAGS.includes(a));
|
|
38
|
+
}
|
package/src/grok.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { homedir } from 'node:os';
|
|
|
4
4
|
import { dirname, join } from 'node:path';
|
|
5
5
|
import { codexServers, setEnabled } from './codex.mjs';
|
|
6
6
|
import { windowMs } from './forecast.mjs';
|
|
7
|
-
import { KEEP_MS, stateDir } from './store.mjs';
|
|
7
|
+
import { KEEP_MS, stateDir, writeAtomic } from './store.mjs';
|
|
8
8
|
import { grokRoot } from './usage.mjs';
|
|
9
9
|
|
|
10
10
|
/** @typedef {import('./forecast.mjs').Sample} Sample */
|
|
@@ -73,14 +73,16 @@ export function grokStartup(root = grokRoot()) {
|
|
|
73
73
|
}
|
|
74
74
|
|
|
75
75
|
/**
|
|
76
|
-
* @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, startup:{prompt:number, tools:number}|null, days:number, pro:boolean, keep?:string[]}} r
|
|
77
|
-
* keep: the `trim keep` list; unused servers on it are reported as kept and left out of `unused
|
|
76
|
+
* @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, usedMonth?:Set<string>|null, startup:{prompt:number, tools:number}|null, days:number, pro:boolean, keep?:string[]}} r
|
|
77
|
+
* keep: the `trim keep` list; unused servers on it are reported as kept and left out of `unused`.
|
|
78
|
+
* usedMonth: normalized names used in 30 days. Servers in it stay out of `unused`.
|
|
78
79
|
*/
|
|
79
|
-
export function grokTrimReport({ servers, used, startup, days, pro, keep = [] }) {
|
|
80
|
+
export function grokTrimReport({ servers, used, usedMonth = null, startup, days, pro, keep = [] }) {
|
|
80
81
|
const on = servers.filter((s) => s.enabled !== false);
|
|
81
82
|
const idle = on.filter((s) => !used.has(norm(s.name)));
|
|
82
83
|
const kept = idle.filter((s) => keep.some((k) => norm(k) === norm(s.name)));
|
|
83
|
-
const
|
|
84
|
+
const standing = usedMonth ? idle.filter((s) => !kept.includes(s) && usedMonth.has(norm(s.name))) : [];
|
|
85
|
+
const unused = idle.filter((s) => !kept.includes(s) && !standing.includes(s));
|
|
84
86
|
const tok = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
|
|
85
87
|
const out = ['# limitcast trim --grok', ''];
|
|
86
88
|
if (startup)
|
|
@@ -88,17 +90,28 @@ export function grokTrimReport({ servers, used, startup, days, pro, keep = [] })
|
|
|
88
90
|
`Grok sessions start with ~${tok(startup.prompt)} tokens of system prompt and ~${tok(startup.tools)} of tool definitions, re-sent on every turn.`,
|
|
89
91
|
'',
|
|
90
92
|
);
|
|
91
|
-
out.push(`## MCP servers: ${on.length} on, ${unused.length} not used in ${days} days`);
|
|
92
|
-
if (
|
|
93
|
+
out.push(`## MCP servers: ${on.length} on, ${unused.length + standing.length} not used in ${days} days`);
|
|
94
|
+
if (standing.length)
|
|
95
|
+
out.push('', `${standing.length} used in the last 30 days, so \`trim --apply\` leaves them on:`, ...standing.map((s) => `- ${s.name}`));
|
|
96
|
+
if (!unused.length) out.push(kept.length || standing.length ? 'Nothing else to turn off.' : 'Every server that is on was used.');
|
|
93
97
|
else if (pro)
|
|
94
|
-
out.push(
|
|
98
|
+
out.push(
|
|
99
|
+
...unused.map((s) => `- ${s.name}`),
|
|
100
|
+
'',
|
|
101
|
+
`${usedMonth ? 'Turn the servers that have been quiet for 30 days off' : 'Turn them off'}: \`limitcast trim --grok --apply\` (backed up; \`--undo\` reverses it).`,
|
|
102
|
+
);
|
|
95
103
|
else out.push(`Pro names them and turns them off for you: https://limitcast.dev/#pricing`);
|
|
96
104
|
if (kept.length) out.push('', `Would keep (your keep-list): ${kept.map((s) => s.name).join(', ')}.`);
|
|
97
105
|
out.push(
|
|
98
106
|
'',
|
|
99
107
|
'Each server that is on starts with every Grok session and adds its tool list to the context. Moving unused servers off is `enabled = false` in ~/.grok/config.toml.',
|
|
100
108
|
);
|
|
101
|
-
return {
|
|
109
|
+
return {
|
|
110
|
+
text: out.join('\n'),
|
|
111
|
+
unused: unused.map((s) => s.name),
|
|
112
|
+
standing: standing.map((s) => s.name),
|
|
113
|
+
kept: kept.map((s) => s.name),
|
|
114
|
+
};
|
|
102
115
|
}
|
|
103
116
|
|
|
104
117
|
/**
|
|
@@ -180,7 +193,7 @@ export function setGrokBudget(usd, win = '5h') {
|
|
|
180
193
|
if (usd === null) delete cur[win];
|
|
181
194
|
else cur[win] = usd;
|
|
182
195
|
mkdirSync(stateDir(), { recursive: true });
|
|
183
|
-
|
|
196
|
+
writeAtomic(configFile(), JSON.stringify({ ...cfg, grokBudget: Object.keys(cur).length ? cur : null }));
|
|
184
197
|
}
|
|
185
198
|
|
|
186
199
|
/**
|
|
@@ -228,7 +241,7 @@ export function setGrokQuota(on) {
|
|
|
228
241
|
/* new */
|
|
229
242
|
}
|
|
230
243
|
mkdirSync(stateDir(), { recursive: true });
|
|
231
|
-
|
|
244
|
+
writeAtomic(configFile(), JSON.stringify({ ...cfg, grokQuota: on }));
|
|
232
245
|
}
|
|
233
246
|
|
|
234
247
|
/** @returns {QuotaState} */
|
package/src/guard.mjs
CHANGED
|
@@ -8,6 +8,16 @@ import { budgetMessage, budgetSpent, getBudget, getTodayHold, loadSubagents, pin
|
|
|
8
8
|
|
|
9
9
|
const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
|
|
10
10
|
|
|
11
|
+
/**
|
|
12
|
+
* How far back a Codex guard read must go. Today's share of a weekly window needs a reading from before
|
|
13
|
+
* local midnight. Just after midnight, keep the last two hours so the pace still has a slope.
|
|
14
|
+
* @param {number} now epoch ms
|
|
15
|
+
*/
|
|
16
|
+
export function codexGuardSince(now) {
|
|
17
|
+
const midnight = new Date(now).setHours(0, 0, 0, 0);
|
|
18
|
+
return Math.min(now - 2 * 3600_000, midnight - 60_000);
|
|
19
|
+
}
|
|
20
|
+
|
|
11
21
|
/**
|
|
12
22
|
* Whose limits a subagent-spawning tool call draws on, or null if the call spawns nothing.
|
|
13
23
|
* Claude Code: Task/Agent. Codex: spawn_agent (reported with a namespace prefix). Grok: spawn_subagent.
|
|
@@ -65,12 +75,13 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
|
|
|
65
75
|
const tool = String(hook?.tool_name ?? hook?.toolName ?? hook?.tool ?? '');
|
|
66
76
|
const src = spawnSource(tool);
|
|
67
77
|
const operation = hook?.tool_use_id ?? hook?.toolUseId ?? hook?.call_id;
|
|
68
|
-
// Codex:
|
|
78
|
+
// Codex: back to local midnight, and at least two hours, so today's share can see a reading from before midnight.
|
|
79
|
+
// A two-hour cap hid that reading and the share read low. Grok: spend vs the user's dollar cap.
|
|
69
80
|
const samples =
|
|
70
81
|
src === 'claude'
|
|
71
82
|
? oneClaudeAccount(load(now - KEEP_MS), hook.session_id ?? hook.sessionId)
|
|
72
83
|
: src === 'codex'
|
|
73
|
-
? await readCodex(now
|
|
84
|
+
? await readCodex(codexGuardSince(now))
|
|
74
85
|
: src === 'grok'
|
|
75
86
|
? grokSamples(now)
|
|
76
87
|
: [];
|
|
@@ -99,7 +110,7 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
|
|
|
99
110
|
if (reason) return preview ? null : reason;
|
|
100
111
|
// Today's share of a weekly window is used up: hold new subagents until local midnight, when the share starts over.
|
|
101
112
|
// Opt-in for Pro (`limitcast budget today on`; the default is a notification at 80%); a free preview records it either way.
|
|
102
|
-
// A window already at 100% is left to the tool.
|
|
113
|
+
// A window already at 100% is left to the tool.
|
|
103
114
|
const day = todayOver(src, forecasts);
|
|
104
115
|
if (day && (preview || getTodayHold())) {
|
|
105
116
|
try {
|
|
@@ -119,7 +130,7 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
|
|
|
119
130
|
}
|
|
120
131
|
if (!preview) return todayMessage(day);
|
|
121
132
|
}
|
|
122
|
-
//
|
|
133
|
+
// Hold new Claude subagents once those of this account have used their budget of the current 5-hour window.
|
|
123
134
|
const budget = src === 'claude' ? getBudget() : null;
|
|
124
135
|
if (budget) {
|
|
125
136
|
const start = windowStart(forecasts, now);
|
package/src/hints.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { closeSync, openSync, readSync, statSync } from 'node:fs';
|
|
3
3
|
import { claudeAccounts, forecastAll } from './forecast.mjs';
|
|
4
4
|
|
|
5
|
-
//
|
|
5
|
+
// Hints for the status line: another account with room, and when a long session is worth compacting.
|
|
6
6
|
|
|
7
7
|
/** @typedef {import('./forecast.mjs').Sample} Sample */
|
|
8
8
|
|
package/src/notify.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileS
|
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { stateDir } from './store.mjs';
|
|
6
6
|
|
|
7
|
-
// Desktop notifications (
|
|
7
|
+
// Desktop notifications (opt-in): one per change of state, raised from the status line.
|
|
8
8
|
// Optionally also sent to a phone (ntfy) or a Slack/Discord webhook.
|
|
9
9
|
|
|
10
10
|
const flag = () => join(stateDir(), 'notify.on');
|
|
@@ -94,7 +94,7 @@ export function notifyChanges(rows, clock) {
|
|
|
94
94
|
* @param {string} message
|
|
95
95
|
*/
|
|
96
96
|
export function send(message) {
|
|
97
|
-
//
|
|
97
|
+
// The same message to the phone (ntfy) or a chat webhook, by a detached curl so no hook waits on the network.
|
|
98
98
|
try {
|
|
99
99
|
for (const a of remoteArgs(loadChannels(), message)) run('curl', a);
|
|
100
100
|
} catch {
|
package/src/plan.mjs
CHANGED
|
@@ -3,9 +3,9 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { claudeAccounts } from './forecast.mjs';
|
|
5
5
|
import { fmtUsd } from './prices.mjs';
|
|
6
|
-
import { stateDir } from './store.mjs';
|
|
6
|
+
import { stateDir, writeAtomic } from './store.mjs';
|
|
7
7
|
|
|
8
|
-
// `limitcast plan
|
|
8
|
+
// `limitcast plan`: does your Claude plan fit how much you use? From a long-lived record of the peak of every
|
|
9
9
|
// 5-hour and weekly window (the samples themselves are only kept for 8 days), it says whether you hit your limits often
|
|
10
10
|
// enough to justify the next plan, or use so little that a smaller one would do, with the monthly price difference.
|
|
11
11
|
|
|
@@ -49,7 +49,7 @@ export function setPlan(plan) {
|
|
|
49
49
|
/* new */
|
|
50
50
|
}
|
|
51
51
|
mkdirSync(stateDir(), { recursive: true });
|
|
52
|
-
|
|
52
|
+
writeAtomic(configFile(), JSON.stringify({ ...cfg, plan }));
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
/**
|
package/src/results.mjs
CHANGED
|
@@ -234,7 +234,7 @@ const fmtK = (/** @type {number} */ n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M`
|
|
|
234
234
|
|
|
235
235
|
/**
|
|
236
236
|
* @param {{now:number, days:number, samples:Sample[], blocks:Block[], pro:boolean, saved:string|null, value?:string, subagents?:import('./subagents.mjs').SubagentEntry[]}} r
|
|
237
|
-
* blocks: every logged block (
|
|
237
|
+
* blocks: every logged block (blocks and free previews); saved: the starting-context text, if any;
|
|
238
238
|
* value: the "since you installed" section, shown first; subagents: the finished-subagent ledger
|
|
239
239
|
*/
|
|
240
240
|
export function resultsReport({ now, days, samples, blocks, pro, saved, value = '', subagents = [] }) {
|
package/src/store.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @ts-check
|
|
2
|
-
import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
|
|
@@ -12,6 +12,13 @@ export function stateDir() {
|
|
|
12
12
|
return process.env.LIMITCAST_STATE ?? join(process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'), 'limitcast');
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
/** Write through a temp file and rename, so a hook reading at the same moment never sees a half-written file. */
|
|
16
|
+
export function writeAtomic(/** @type {string} */ path, /** @type {string} */ text) {
|
|
17
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
18
|
+
writeFileSync(tmp, text);
|
|
19
|
+
renameSync(tmp, path);
|
|
20
|
+
}
|
|
21
|
+
|
|
15
22
|
/**
|
|
16
23
|
* Append samples whose pct or reset changed since the last one for the same series.
|
|
17
24
|
* The status line fires on every message, so unchanged readings are skipped.
|
|
@@ -38,9 +45,9 @@ export function record(samples) {
|
|
|
38
45
|
const file = join(dir, 'samples.jsonl');
|
|
39
46
|
appendFileSync(file, `${fresh.map((s) => JSON.stringify(s)).join('\n')}\n`);
|
|
40
47
|
for (const s of fresh) last[key(s)] = { pct: s.pct, reset: s.reset };
|
|
41
|
-
|
|
48
|
+
writeAtomic(lastPath, JSON.stringify(last));
|
|
42
49
|
if (statSync(file).size > PRUNE_BYTES)
|
|
43
|
-
|
|
50
|
+
writeAtomic(
|
|
44
51
|
file,
|
|
45
52
|
load(Date.now() - KEEP_MS)
|
|
46
53
|
.map((s) => `${JSON.stringify(s)}\n`)
|
package/src/subagents.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @ts-check
|
|
2
|
-
import { appendFileSync, existsSync, mkdirSync, readFileSync
|
|
2
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
|
-
import { stateDir } from './store.mjs';
|
|
5
|
+
import { stateDir, writeAtomic } from './store.mjs';
|
|
6
6
|
|
|
7
|
-
// Subagent receipts and budgets
|
|
7
|
+
// Subagent receipts and budgets. A SubagentStop hook prices each finished subagent against the 5-hour window
|
|
8
8
|
// (from the user's own calibration) and logs it; the guard holds new subagents once a window's budget is spent.
|
|
9
9
|
|
|
10
10
|
/** @typedef {{t:number, id?:string, sid?:string, type?:string, calls:number, fresh:number, read:number, pct?:number}} SubagentEntry */
|
|
@@ -128,7 +128,7 @@ export function setBudget(pct) {
|
|
|
128
128
|
/* new */
|
|
129
129
|
}
|
|
130
130
|
mkdirSync(stateDir(), { recursive: true });
|
|
131
|
-
|
|
131
|
+
writeAtomic(configFile(), JSON.stringify({ ...cfg, subagentBudget: pct }));
|
|
132
132
|
}
|
|
133
133
|
|
|
134
134
|
/** Whether the guard holds new subagents once today's share of a weekly window is used up (`limitcast budget today on`). */
|
|
@@ -149,7 +149,7 @@ export function setTodayHold(on) {
|
|
|
149
149
|
/* new */
|
|
150
150
|
}
|
|
151
151
|
mkdirSync(stateDir(), { recursive: true });
|
|
152
|
-
|
|
152
|
+
writeAtomic(configFile(), JSON.stringify({ ...cfg, todayHold: on }));
|
|
153
153
|
}
|
|
154
154
|
|
|
155
155
|
/** A model a subagent type can be pinned to: sonnet, opus, haiku, a claude-... id, or a grok-... id. */
|
|
@@ -193,7 +193,7 @@ export function setSubagentModel(type, model) {
|
|
|
193
193
|
if (model === null) delete models[type];
|
|
194
194
|
else models[type] = model;
|
|
195
195
|
mkdirSync(stateDir(), { recursive: true });
|
|
196
|
-
|
|
196
|
+
writeAtomic(configFile(), JSON.stringify({ ...cfg, subagentModels: models }));
|
|
197
197
|
}
|
|
198
198
|
|
|
199
199
|
/**
|
package/src/toolcheck.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { stateDir } from './store.mjs';
|
|
5
5
|
|
|
6
|
-
// Large tool-output notice (
|
|
6
|
+
// Large tool-output notice (PostToolUse hook, installed with --alerts). A tool result enters the context once as
|
|
7
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
8
|
// the user (systemMessage), never the model, once per tool per session, with what to ask for next time.
|
|
9
9
|
|
package/src/trim.mjs
CHANGED
|
@@ -207,9 +207,11 @@ const tok = (/** @type {number} */ chars) => Math.round(chars / 4);
|
|
|
207
207
|
* @param {import('./startup.mjs').Piece[]} pieces
|
|
208
208
|
* @param {Activity} used
|
|
209
209
|
* @param {string[]} [keep] the `trim keep` list: unused, but never counted as a cut; named in `kept`
|
|
210
|
+
* @param {Activity|null} [usedMonth] servers used in 30 days. When set, only servers missing here are removable.
|
|
210
211
|
*/
|
|
211
|
-
export function measuredSavings(pieces, used, keep = []) {
|
|
212
|
+
export function measuredSavings(pieces, used, keep = [], usedMonth = null) {
|
|
212
213
|
const usedMcp = new Set([...used.mcp].map(norm));
|
|
214
|
+
const month = usedMonth ? new Set([...usedMonth.mcp].map(norm)) : null;
|
|
213
215
|
// Instructions and tool names spell a server differently ("claude.ai Postman" / "claude_ai_Postman"): merge by normalized name.
|
|
214
216
|
/** @type {Map<string, {name:string, chars:number}>} */
|
|
215
217
|
const mcp = new Map();
|
|
@@ -226,9 +228,11 @@ export function measuredSavings(pieces, used, keep = []) {
|
|
|
226
228
|
const kept = [...mcp.values(), ...skills].filter((x) => keep.some((k) => norm(k) === norm(x.name))).map((x) => x.name);
|
|
227
229
|
const isKept = (/** @type {{name:string}} */ x) => kept.includes(x.name);
|
|
228
230
|
const unusedMcp = [...mcp.values()].filter((m) => !isKept(m)).sort((a, b) => b.chars - a.chars);
|
|
231
|
+
const standingMcp = month ? unusedMcp.filter((m) => month.has(norm(m.name))) : [];
|
|
232
|
+
const staleMcp = month ? unusedMcp.filter((m) => !month.has(norm(m.name))) : unusedMcp;
|
|
229
233
|
const unusedSkills = skills.filter((s) => !isKept(s));
|
|
230
|
-
const chars =
|
|
231
|
-
return { unusedMcp, unusedSkills, tokens: tok(chars), kept };
|
|
234
|
+
const chars = staleMcp.reduce((a, m) => a + m.chars, 0) + unusedSkills.reduce((a, s) => a + s.chars, 0);
|
|
235
|
+
return { unusedMcp, standingMcp, staleMcp, unusedSkills, tokens: tok(chars), kept };
|
|
232
236
|
}
|
|
233
237
|
|
|
234
238
|
/**
|
|
@@ -238,9 +242,10 @@ export function measuredSavings(pieces, used, keep = []) {
|
|
|
238
242
|
* @param {Activity} used
|
|
239
243
|
* @param {number} days
|
|
240
244
|
* @param {string[]} [keep] the `trim keep` list
|
|
245
|
+
* @param {Activity|null} [usedMonth] servers used in 30 days; `--apply` leaves those on
|
|
241
246
|
*/
|
|
242
|
-
export function startupReport(base, b, used, days, keep = []) {
|
|
243
|
-
const s = measuredSavings(b.pieces, used, keep);
|
|
247
|
+
export function startupReport(base, b, used, days, keep = [], usedMonth = null) {
|
|
248
|
+
const s = measuredSavings(b.pieces, used, keep, usedMonth);
|
|
244
249
|
const median = base?.median ?? 0;
|
|
245
250
|
const lines = ['# limitcast trim', ''];
|
|
246
251
|
if (base) {
|
|
@@ -254,16 +259,27 @@ export function startupReport(base, b, used, days, keep = []) {
|
|
|
254
259
|
lines.push(
|
|
255
260
|
`## Estimated removable context: ~${fmt(s.tokens)} tokens per session${pct}`,
|
|
256
261
|
'',
|
|
257
|
-
|
|
262
|
+
usedMonth
|
|
263
|
+
? `From skills unused in the last ${days} days and MCP servers quiet for 30 days:`
|
|
264
|
+
: `From things you haven't used in the last ${days} days:`,
|
|
258
265
|
'',
|
|
259
266
|
);
|
|
260
|
-
if (s.
|
|
261
|
-
|
|
267
|
+
if (s.standingMcp.length) {
|
|
268
|
+
lines.push(
|
|
269
|
+
`- **Leave on ${s.standingMcp.length} MCP servers** used in the last 30 days but not in ${days} days: ${s.standingMcp
|
|
270
|
+
.slice(0, 10)
|
|
271
|
+
.map((m) => m.name)
|
|
272
|
+
.join(', ')}${s.standingMcp.length > 10 ? ', ...' : ''}.`,
|
|
273
|
+
' `trim --apply` does not turn these off.',
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
if (s.staleMcp.length) {
|
|
277
|
+
const total = s.staleMcp.reduce((a, m) => a + m.chars, 0);
|
|
262
278
|
lines.push(
|
|
263
|
-
`- **Disable ${s.
|
|
279
|
+
`- **Disable ${s.staleMcp.length} MCP servers** ${usedMonth ? 'quiet for 30 days' : `you haven't used in ${days} days`} (~${fmt(tok(total))}): ${s.staleMcp
|
|
264
280
|
.slice(0, 10)
|
|
265
281
|
.map((m) => `${m.name} ~${fmt(tok(m.chars))}`)
|
|
266
|
-
.join(', ')}${s.
|
|
282
|
+
.join(', ')}${s.staleMcp.length > 10 ? ', ...' : ''}.`,
|
|
267
283
|
' Their instructions and tool names load into every session. Remove them in `/mcp`, or move them to the projects that use them.',
|
|
268
284
|
);
|
|
269
285
|
}
|
|
@@ -315,16 +331,17 @@ export function startupReport(base, b, used, days, keep = []) {
|
|
|
315
331
|
* @param {Activity} used
|
|
316
332
|
* @param {number} days
|
|
317
333
|
* @param {string[]} [keep] the `trim keep` list; only its count is shown
|
|
334
|
+
* @param {Activity|null} [usedMonth] servers used in 30 days
|
|
318
335
|
*/
|
|
319
|
-
export function shareSummary(base, b, used, days, keep = []) {
|
|
320
|
-
const s = measuredSavings(b.pieces, used, keep);
|
|
336
|
+
export function shareSummary(base, b, used, days, keep = [], usedMonth = null) {
|
|
337
|
+
const s = measuredSavings(b.pieces, used, keep, usedMonth);
|
|
321
338
|
/** @type {Map<string, number>} */
|
|
322
339
|
const groups = new Map();
|
|
323
340
|
for (const p of b.pieces) groups.set(p.group, (groups.get(p.group) ?? 0) + p.chars);
|
|
324
341
|
const median = base?.median ?? 0;
|
|
325
342
|
const lines = [
|
|
326
343
|
`My Claude Code sessions start at ${fmt(median)} tokens before I type.`,
|
|
327
|
-
`limitcast found ~${fmt(s.tokens)} per session${median ? ` (${Math.round((s.tokens / median) * 100)}%)` : ''} I haven't used in ${days} days: ${s.unusedMcp.length} MCP servers, ${s.unusedSkills.length} skills${s.kept.length ? ` (${s.kept.length} more kept on my keep-list)` : ''}.`,
|
|
344
|
+
`limitcast found ~${fmt(s.tokens)} per session${median ? ` (${Math.round((s.tokens / median) * 100)}%)` : ''} I haven't used in ${days} days: ${s.unusedMcp.length} MCP servers, ${s.unusedSkills.length} skills${s.standingMcp.length ? ` (${s.standingMcp.length} of the servers were used in 30 days and stay on)` : ''}${s.kept.length ? ` (${s.kept.length} more kept on my keep-list)` : ''}.`,
|
|
328
345
|
'Where it comes from:',
|
|
329
346
|
...[...groups].sort((x, y) => y[1] - x[1]).map(([g, c]) => ` ${g}: ${fmt(tok(c))}`),
|
|
330
347
|
];
|
package/src/usage.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// @ts-check
|
|
2
|
-
import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, statSync
|
|
2
|
+
import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { basename, join } from 'node:path';
|
|
5
5
|
import { createInterface } from 'node:readline';
|
|
6
|
-
import { stateDir } from './store.mjs';
|
|
6
|
+
import { stateDir, writeAtomic } from './store.mjs';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* One model response's token usage.
|
|
@@ -171,6 +171,7 @@ export async function readUsage(since, roots = {}, activity) {
|
|
|
171
171
|
const out = [];
|
|
172
172
|
// Parsed transcripts are cached by size and mtime: only new or changed ones are read again.
|
|
173
173
|
const cache = loadUsageCache();
|
|
174
|
+
let dirty = false; // a parsed file or a dropped entry: only then is the cache file rewritten
|
|
174
175
|
/** @type {typeof cache} */
|
|
175
176
|
const next = {};
|
|
176
177
|
/**
|
|
@@ -180,7 +181,9 @@ export async function readUsage(since, roots = {}, activity) {
|
|
|
180
181
|
const cached = async (file, parse) => {
|
|
181
182
|
const st = statSync(file);
|
|
182
183
|
const hit = cache[file];
|
|
183
|
-
const
|
|
184
|
+
const fresh = !(hit && hit.s === st.size && hit.m === st.mtimeMs);
|
|
185
|
+
if (fresh) dirty = true;
|
|
186
|
+
const entry = fresh ? { s: st.size, m: st.mtimeMs, ...(await parse(file)) } : hit;
|
|
184
187
|
next[file] = entry;
|
|
185
188
|
return entry;
|
|
186
189
|
};
|
|
@@ -220,7 +223,7 @@ export async function readUsage(since, roots = {}, activity) {
|
|
|
220
223
|
}
|
|
221
224
|
// Keep entries for files this run didn't need (another period) while they are recent; drop the rest.
|
|
222
225
|
for (const [f, e] of Object.entries(cache)) if (!next[f] && e.m >= Date.now() - CACHE_KEEP_MS && existsSync(f)) next[f] = e;
|
|
223
|
-
saveUsageCache(next);
|
|
226
|
+
if (dirty || Object.keys(next).length !== Object.keys(cache).length) saveUsageCache(next);
|
|
224
227
|
for (const { file, session, project } of grokLedgers(roots.grok ?? grokRoot(), since)) {
|
|
225
228
|
let ledger;
|
|
226
229
|
try {
|
|
@@ -251,7 +254,7 @@ function loadUsageCache() {
|
|
|
251
254
|
function saveUsageCache(c) {
|
|
252
255
|
try {
|
|
253
256
|
mkdirSync(stateDir(), { recursive: true });
|
|
254
|
-
|
|
257
|
+
writeAtomic(usageCacheFile(), JSON.stringify({ v: USAGE_CACHE_VERSION, files: c }));
|
|
255
258
|
} catch {
|
|
256
259
|
/* a cache: the next run just reads the transcripts */
|
|
257
260
|
}
|
package/src/value.mjs
CHANGED
|
@@ -149,6 +149,7 @@ export function valueTotals(v) {
|
|
|
149
149
|
return {
|
|
150
150
|
since: v.since,
|
|
151
151
|
sessions: sessions.length,
|
|
152
|
+
contributed: sessions.filter((s) => s.savedPerTurn > 0).length,
|
|
152
153
|
turns: sessions.reduce((a, s) => a + s.turns, 0),
|
|
153
154
|
tokens: sessions.reduce((a, s) => a + s.turns * s.savedPerTurn, 0),
|
|
154
155
|
hits: hits.length,
|
|
@@ -197,15 +198,28 @@ export function valuePeriod(v, since, until) {
|
|
|
197
198
|
/**
|
|
198
199
|
* The "since you installed" section at the top of `limitcast results`.
|
|
199
200
|
* @param {ReturnType<typeof valueTotals>} t
|
|
200
|
-
* @param {{now:number, pro:boolean}} o
|
|
201
|
+
* @param {{now:number, pro:boolean, start?:{first:number, last:number}|null}} o
|
|
202
|
+
* start: controllable starting context, in characters, the first time it was measured and now
|
|
201
203
|
*/
|
|
202
|
-
export function valueSection(t, { now, pro }) {
|
|
204
|
+
export function valueSection(t, { now, pro, start = null }) {
|
|
203
205
|
if (!t.since) return '';
|
|
204
206
|
const days = Math.max(1, Math.round((now - t.since) / 86400_000));
|
|
205
207
|
const out = [`## Since limitcast started watching (${new Date(t.since).toLocaleDateString()}, ${days} day${days === 1 ? '' : 's'})`];
|
|
208
|
+
if (start) {
|
|
209
|
+
const from = Math.round(start.first / 4);
|
|
210
|
+
const to = Math.round(start.last / 4);
|
|
211
|
+
const delta = to - from;
|
|
212
|
+
const change = delta === 0 ? 'no change' : `${delta > 0 ? '+' : '-'}${fmtBig(Math.abs(delta))}`;
|
|
213
|
+
out.push(`- The part of your starting context you control went from ~${fmtBig(from)} to ~${fmtBig(to)} tokens (${change}).`);
|
|
214
|
+
}
|
|
206
215
|
if (pro && t.tokens > 0) {
|
|
216
|
+
const rest = Number.isFinite(t.contributed) ? t.sessions - t.contributed : null;
|
|
217
|
+
const who =
|
|
218
|
+
rest === null
|
|
219
|
+
? ''
|
|
220
|
+
: ` ${t.contributed} of ${t.sessions} sessions started below that first snapshot${rest > 0 ? `; the other ${rest} were the same size or larger` : ''}.`;
|
|
207
221
|
out.push(
|
|
208
|
-
`- **Estimated ${fmtBig(t.tokens)} context tokens not re-sent.** Compared with your first recorded Claude Code starting context: ${t.turns.toLocaleString()} calls across ${t.sessions} sessions
|
|
222
|
+
`- **Estimated ${fmtBig(t.tokens)} context tokens not re-sent.** Compared with your first recorded Claude Code starting context: ${t.turns.toLocaleString()} calls across ${t.sessions} sessions.${who} Estimated from characters / 4; most would have been cached input. Project or manual configuration changes can also change this baseline; this is not a causal savings measurement.`,
|
|
209
223
|
);
|
|
210
224
|
if (t.windowPct !== null && t.calib)
|
|
211
225
|
out.push(
|
package/src/where.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
// @ts-check
|
|
2
|
-
import { createReadStream, existsSync, mkdirSync, readFileSync, statSync
|
|
2
|
+
import { createReadStream, existsSync, mkdirSync, readFileSync, statSync } from 'node:fs';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { createInterface } from 'node:readline';
|
|
6
6
|
import { fmt } from './report.mjs';
|
|
7
7
|
import { attachmentPieces, pieceDiff } from './startup.mjs';
|
|
8
|
-
import { stateDir } from './store.mjs';
|
|
8
|
+
import { stateDir, writeAtomic } from './store.mjs';
|
|
9
9
|
import { BIG_RESULT, tipFor, toolKey } from './toolcheck.mjs';
|
|
10
10
|
import { jsonlFiles } from './usage.mjs';
|
|
11
11
|
|
|
12
|
-
// `limitcast report --why
|
|
12
|
+
// `limitcast report --why`: where the new tokens went, which is what moves the limit (cached reads barely count).
|
|
13
13
|
// A model call's new tokens are input + cache writes + output. The input of call i is what entered the context since
|
|
14
14
|
// call i-1: its own output (written to the cache) plus the tool results it asked for plus your messages. So the input
|
|
15
15
|
// of call i, less call i-1's output, is attributed to the tools call i-1 used. Claude Code transcripts only.
|
|
@@ -480,16 +480,22 @@ export async function whySessions(root, since) {
|
|
|
480
480
|
/** @type {typeof cache} */
|
|
481
481
|
const next = {};
|
|
482
482
|
const files = jsonlFiles(root, since, () => true);
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
483
|
+
const stats = files.map((f) => statSync(f));
|
|
484
|
+
const fresh = (/** @type {number} */ i) => !(cache[files[i]] && cache[files[i]].s === stats[i].size && cache[files[i]].m === stats[i].mtimeMs);
|
|
485
|
+
const cold = files.filter((_, i) => fresh(i)).length;
|
|
486
|
+
// The first run reads every transcript (up to a minute on a big machine); say so instead of sitting silent.
|
|
487
|
+
if (cold > 100) console.error(`limitcast: reading ${cold} transcripts for the first time. This can take a minute; later runs use a cache.`);
|
|
488
|
+
for (const [i, f] of files.entries()) {
|
|
489
|
+
next[f] = fresh(i) ? { s: stats[i].size, m: stats[i].mtimeMs, c: await readCalls(f) } : cache[f];
|
|
487
490
|
}
|
|
488
491
|
// Keep entries this run didn't need (another period) while they are recent; drop the rest.
|
|
489
492
|
for (const [f, e] of Object.entries(cache)) if (!next[f] && e.m >= Date.now() - CACHE_KEEP_MS && existsSync(f)) next[f] = e;
|
|
490
493
|
try {
|
|
491
|
-
|
|
492
|
-
|
|
494
|
+
// Rewrite the file only when something was read or dropped; it is several MB on a busy machine.
|
|
495
|
+
if (cold || Object.keys(next).length !== Object.keys(cache).length) {
|
|
496
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
497
|
+
writeAtomic(cacheFile(), JSON.stringify({ v: CACHE_VERSION, files: next }));
|
|
498
|
+
}
|
|
493
499
|
} catch {
|
|
494
500
|
/* a cache: the next run just reads the transcripts */
|
|
495
501
|
}
|