limitcast 0.17.2 → 0.18.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 +147 -84
- package/bin/limitcast.mjs +215 -50
- package/package.json +1 -1
- package/src/cold.mjs +47 -10
- 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 +10 -1
- package/src/where.mjs +53 -3
package/bin/limitcast.mjs
CHANGED
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
} from '../src/apply.mjs';
|
|
22
22
|
import { calibrate, limitChange, limitChangeMessage, windowPct } from '../src/calibrate.mjs';
|
|
23
23
|
import { applyCodexTrim, codexConfigPath, codexServers, codexStartup, codexTrimReport, codexUsedServers, undoCodexTrim } from '../src/codex.mjs';
|
|
24
|
-
import { coldCost, coldMessage, firstWarning } from '../src/cold.mjs';
|
|
24
|
+
import { coldCost, coldMessage, coldNotice, firstNotice, firstWarning } from '../src/cold.mjs';
|
|
25
25
|
import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
|
|
26
26
|
import { formatChecks } from '../src/formats.mjs';
|
|
27
27
|
import {
|
|
@@ -49,6 +49,16 @@ import {
|
|
|
49
49
|
import { runGuard } from '../src/guard.mjs';
|
|
50
50
|
import { accountForecasts, bindingLine, compactHint, headroom, lastCall, lastCallTokens } from '../src/hints.mjs';
|
|
51
51
|
import { htmlPage } from '../src/html.mjs';
|
|
52
|
+
import {
|
|
53
|
+
duplicateReason,
|
|
54
|
+
findDuplicate,
|
|
55
|
+
forgetInflight,
|
|
56
|
+
loadInflight,
|
|
57
|
+
pruneInflight,
|
|
58
|
+
rememberInflight,
|
|
59
|
+
saveInflight,
|
|
60
|
+
spawnIdentity,
|
|
61
|
+
} from '../src/inflight.mjs';
|
|
52
62
|
import { insightsReport, insightsShare, periodInsights } from '../src/insights.mjs';
|
|
53
63
|
import { doctor, install, installedFeatures, readSettings, settingsPath, uninstall } from '../src/install.mjs';
|
|
54
64
|
import { memoryCheck, memoryDir, memoryReport, scanMemory } from '../src/memory.mjs';
|
|
@@ -79,6 +89,7 @@ import {
|
|
|
79
89
|
} from '../src/subagents.mjs';
|
|
80
90
|
import { forTerminal } from '../src/term.mjs';
|
|
81
91
|
import { firstFlag, toolKey, toolNotice } from '../src/toolcheck.mjs';
|
|
92
|
+
import { loadToolStats, saveToolStats, toolLimitDecision, toolStats } from '../src/toollimit.mjs';
|
|
82
93
|
import { baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
|
|
83
94
|
import { claudeRoot, grokRoot, readUsage } from '../src/usage.mjs';
|
|
84
95
|
import { dailyDue, foldEvents, loadValue, saveValue, scanSessions, valuePeriod, valueSection, valueTotals } from '../src/value.mjs';
|
|
@@ -112,8 +123,10 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
112
123
|
limitcast install --guard block new subagents when a window is on pace to run out, and run
|
|
113
124
|
them on Sonnet while a window is tight (NEAR or AT_RISK); show what
|
|
114
125
|
each finished subagent cost, and what that kind has cost before a new
|
|
115
|
-
one starts; hold
|
|
116
|
-
|
|
126
|
+
one starts; hold a second spawn of the same type and prompt
|
|
127
|
+
while the first is still running; announce a message after the
|
|
128
|
+
cheap cache expires (idle over 5 min, LIMITCAST_CACHE_NOTICE_MINUTES)
|
|
129
|
+
and hold the first one after 60 min (LIMITCAST_CACHE_MINUTES)
|
|
117
130
|
limitcast budget subagents <percent>|off hold new subagents once they used that much of the 5-hour window
|
|
118
131
|
limitcast subagent-model <type> <model>|off run new subagents of that type on sonnet, opus, haiku, grok-… or a model id
|
|
119
132
|
limitcast plan [--days N] does your Claude plan fit your use? Hit-limit and headroom evidence, and the monthly price difference
|
|
@@ -122,8 +135,9 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
122
135
|
needs this cap to block spawn_subagent). Optional: budget grok 7d <usd>
|
|
123
136
|
limitcast budget today on|off hold new subagents once today's share of a weekly window is used up, until
|
|
124
137
|
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),
|
|
138
|
+
limitcast install --alerts tell you when your starting context grows, plus a weekly summary,
|
|
139
|
+
when one tool result is very large (about 20k tokens), and, before it
|
|
140
|
+
runs, when a tool report --why has shown to be fat sets no limit
|
|
127
141
|
limitcast notify on|off|test desktop notification when a window turns NEAR, AT_RISK or HIT, or resets,
|
|
128
142
|
and when your Claude limit itself changes
|
|
129
143
|
limitcast notify ntfy <topic|url>|off also send them to your phone (ntfy.sh)
|
|
@@ -133,13 +147,15 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
133
147
|
limitcast results --html [--out FILE] results, current windows and the burn report as one page
|
|
134
148
|
limitcast report [--days N] [--out FILE] tokens by tool, day, project, model and session
|
|
135
149
|
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
|
|
150
|
+
limitcast report --jobs [--days N] the scheduled (headless) jobs that spend the most tokens just starting,
|
|
151
|
+
and which startup piece changed between two runs of the same job
|
|
137
152
|
(status line: points to another account with room, and suggests /compact past ~150k tokens a call)
|
|
138
153
|
|
|
139
154
|
Used by Claude Code, Codex and Grok (set up by install)
|
|
140
155
|
limitcast statusline [-- <cmd...>] record limit readings, then run your status-line command
|
|
141
156
|
limitcast guard PreToolUse hook
|
|
142
|
-
limitcast prompt-check UserPromptSubmit hook: the cold-cache
|
|
157
|
+
limitcast prompt-check UserPromptSubmit hook: the cold-cache notice and hold
|
|
158
|
+
limitcast tool-limit PreToolUse hook: a fat tool call that sets no limit
|
|
143
159
|
limitcast subagent-receipt SubagentStop hook: what the subagent cost
|
|
144
160
|
limitcast drift [--hook] SessionStart hook: compare starting context with the last session
|
|
145
161
|
`;
|
|
@@ -229,7 +245,12 @@ if (cmd === 'status') {
|
|
|
229
245
|
// Grok spend/forecast stays on the Grok status line. Claude's feed has rate_limits; mixing the two
|
|
230
246
|
// would print grok $ on Claude Code and break "waiting for data" when there are no Claude readings.
|
|
231
247
|
const grokExtra = grokOwn ? grokSamples(now) : [];
|
|
232
|
-
line =
|
|
248
|
+
line = statusLines(
|
|
249
|
+
forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...grokExtra], sid), now),
|
|
250
|
+
grokOwn ? grokSpendLine(now) : '',
|
|
251
|
+
hints,
|
|
252
|
+
grokOwn ? 'grok' : 'claude',
|
|
253
|
+
).join('\n');
|
|
233
254
|
} catch {
|
|
234
255
|
/* never break the status line */
|
|
235
256
|
}
|
|
@@ -238,33 +259,62 @@ if (cmd === 'status') {
|
|
|
238
259
|
// Your status line stays as it was; limitcast adds its own line under it (status scripts often printf without a newline).
|
|
239
260
|
const yours = r.stdout?.toString() ?? '';
|
|
240
261
|
process.stdout.write(yours && !yours.endsWith('\n') ? `${yours}\n` : yours);
|
|
241
|
-
|
|
262
|
+
emitStatus(line);
|
|
242
263
|
process.exit(r.status ?? 1);
|
|
243
264
|
}
|
|
244
265
|
if (grokOwn) console.log(grokOwn);
|
|
245
|
-
|
|
266
|
+
emitStatus(line);
|
|
246
267
|
} else if (cmd === 'guard') {
|
|
247
268
|
// The installed guard protects all users; LIMITCAST_ALLOW=1 remains the explicit override.
|
|
248
269
|
if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
|
|
249
270
|
try {
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
271
|
+
const hook = JSON.parse(readStdin());
|
|
272
|
+
const id = spawnIdentity(hook);
|
|
273
|
+
const live = pruneInflight(loadInflight(), now);
|
|
274
|
+
const dup = id ? findDuplicate(live, id) : null;
|
|
275
|
+
if (id && dup) {
|
|
276
|
+
saveInflight(live);
|
|
277
|
+
logBlock({
|
|
278
|
+
t: now,
|
|
279
|
+
kind: 'duplicate',
|
|
280
|
+
src: id.src,
|
|
281
|
+
win: '5h',
|
|
282
|
+
pct: 0,
|
|
283
|
+
wall: now,
|
|
284
|
+
reset: now,
|
|
285
|
+
type: id.type,
|
|
286
|
+
sid: id.sid,
|
|
287
|
+
...(typeof hook?.tool_use_id === 'string' ? { operation: hook.tool_use_id } : {}),
|
|
288
|
+
});
|
|
258
289
|
console.log(
|
|
259
290
|
JSON.stringify({
|
|
260
|
-
hookSpecificOutput: {
|
|
261
|
-
hookEventName: 'PreToolUse',
|
|
262
|
-
permissionDecision: 'allow',
|
|
263
|
-
permissionDecisionReason: d.reason,
|
|
264
|
-
updatedInput: d.updatedInput,
|
|
265
|
-
},
|
|
291
|
+
hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: duplicateReason(id) },
|
|
266
292
|
}),
|
|
267
293
|
);
|
|
294
|
+
} else {
|
|
295
|
+
const d = await runGuard(hook, now, Number(process.env.LIMITCAST_GUARD_MINUTES ?? 30), { preview: false });
|
|
296
|
+
if (typeof d === 'string') {
|
|
297
|
+
saveInflight(live);
|
|
298
|
+
console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: d } }));
|
|
299
|
+
} else {
|
|
300
|
+
if (id) saveInflight(rememberInflight(live, id, now));
|
|
301
|
+
if (d && 'notice' in d) {
|
|
302
|
+
// Allowed as is, with what this kind of subagent has cost so far (shown to the user, never the model).
|
|
303
|
+
console.log(JSON.stringify({ systemMessage: d.notice }));
|
|
304
|
+
} else if (d) {
|
|
305
|
+
// Model switch: allow the spawn with the same input and model "sonnet" (updatedInput replaces the whole input).
|
|
306
|
+
console.log(
|
|
307
|
+
JSON.stringify({
|
|
308
|
+
hookSpecificOutput: {
|
|
309
|
+
hookEventName: 'PreToolUse',
|
|
310
|
+
permissionDecision: 'allow',
|
|
311
|
+
permissionDecisionReason: d.reason,
|
|
312
|
+
updatedInput: d.updatedInput,
|
|
313
|
+
},
|
|
314
|
+
}),
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
268
318
|
}
|
|
269
319
|
} catch (e) {
|
|
270
320
|
// Fail open: a broken governor must not stop the agent.
|
|
@@ -277,9 +327,13 @@ if (cmd === 'status') {
|
|
|
277
327
|
const hook = JSON.parse(readStdin());
|
|
278
328
|
const path = hook?.transcript_path;
|
|
279
329
|
const last = process.env.LIMITCAST_ALLOW !== '1' && typeof path === 'string' && existsSync(path) ? lastCall(path) : null;
|
|
280
|
-
const c = coldCost(hook?.prompt, last, now, {
|
|
281
|
-
|
|
282
|
-
|
|
330
|
+
const c = coldCost(hook?.prompt, last, now, {
|
|
331
|
+
minutes: Number(process.env.LIMITCAST_CACHE_MINUTES ?? 60),
|
|
332
|
+
noticeMinutes: Number(process.env.LIMITCAST_CACHE_NOTICE_MINUTES ?? 5),
|
|
333
|
+
calib: loadValue().calib,
|
|
334
|
+
});
|
|
335
|
+
const sid = String(hook.session_id ?? '');
|
|
336
|
+
if (c && last && c.hold && firstWarning(sid, last.t)) {
|
|
283
337
|
logBlock({
|
|
284
338
|
t: now,
|
|
285
339
|
kind: 'cold',
|
|
@@ -290,13 +344,74 @@ if (cmd === 'status') {
|
|
|
290
344
|
reset: now,
|
|
291
345
|
tokens: c.tokens,
|
|
292
346
|
sid: hook.session_id,
|
|
293
|
-
...(pro ? {} : { shadow: true }),
|
|
294
347
|
});
|
|
295
|
-
|
|
348
|
+
console.log(JSON.stringify({ decision: 'block', reason: coldMessage(c) }));
|
|
349
|
+
} else if (c && last && !c.hold && firstNotice(sid, last.t)) {
|
|
350
|
+
logBlock({
|
|
351
|
+
t: now,
|
|
352
|
+
kind: 'cold-notice',
|
|
353
|
+
src: 'claude',
|
|
354
|
+
win: '5h',
|
|
355
|
+
pct: c.pct ?? 0,
|
|
356
|
+
wall: now,
|
|
357
|
+
reset: now,
|
|
358
|
+
tokens: c.tokens,
|
|
359
|
+
sid: hook.session_id,
|
|
360
|
+
});
|
|
361
|
+
console.log(JSON.stringify({ systemMessage: coldNotice(c) }));
|
|
296
362
|
}
|
|
297
363
|
} catch {
|
|
298
364
|
/* a hook must never stop a prompt by failing */
|
|
299
365
|
}
|
|
366
|
+
} else if (cmd === 'tool-limit') {
|
|
367
|
+
// PreToolUse hook (installed with --alerts). A fat tool with no limit is denied so the model can retry smaller.
|
|
368
|
+
// A limit that is only too large is lowered. Fail open, and LIMITCAST_ALLOW=1 skips it.
|
|
369
|
+
if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
|
|
370
|
+
try {
|
|
371
|
+
const hook = JSON.parse(readStdin());
|
|
372
|
+
const name = String(hook?.tool_name ?? hook?.toolName ?? '');
|
|
373
|
+
const d = name ? toolLimitDecision(name, hook?.tool_input ?? hook?.toolInput, loadToolStats()) : null;
|
|
374
|
+
if (d && 'deny' in d) {
|
|
375
|
+
logBlock({
|
|
376
|
+
t: now,
|
|
377
|
+
kind: 'tool-limit',
|
|
378
|
+
src: 'claude',
|
|
379
|
+
win: '5h',
|
|
380
|
+
pct: 0,
|
|
381
|
+
wall: now,
|
|
382
|
+
reset: now,
|
|
383
|
+
sid: hook.session_id,
|
|
384
|
+
...(typeof hook?.tool_use_id === 'string' ? { operation: hook.tool_use_id } : {}),
|
|
385
|
+
});
|
|
386
|
+
console.log(
|
|
387
|
+
JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: d.deny } }),
|
|
388
|
+
);
|
|
389
|
+
} else if (d) {
|
|
390
|
+
logBlock({
|
|
391
|
+
t: now,
|
|
392
|
+
kind: 'tool-cap',
|
|
393
|
+
src: 'claude',
|
|
394
|
+
win: '5h',
|
|
395
|
+
pct: 0,
|
|
396
|
+
wall: now,
|
|
397
|
+
reset: now,
|
|
398
|
+
sid: hook.session_id,
|
|
399
|
+
...(typeof hook?.tool_use_id === 'string' ? { operation: hook.tool_use_id } : {}),
|
|
400
|
+
});
|
|
401
|
+
console.log(
|
|
402
|
+
JSON.stringify({
|
|
403
|
+
hookSpecificOutput: {
|
|
404
|
+
hookEventName: 'PreToolUse',
|
|
405
|
+
permissionDecision: 'allow',
|
|
406
|
+
permissionDecisionReason: d.reason,
|
|
407
|
+
updatedInput: d.updatedInput,
|
|
408
|
+
},
|
|
409
|
+
}),
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
} catch {
|
|
413
|
+
/* a hook must never break the session */
|
|
414
|
+
}
|
|
300
415
|
} else if (cmd === 'tool-check') {
|
|
301
416
|
// PostToolUse hook (installed with --alerts): tell the user, once per tool per session, about a very large tool
|
|
302
417
|
// result and what to ask for next time. Never reaches the model.
|
|
@@ -315,6 +430,7 @@ if (cmd === 'status') {
|
|
|
315
430
|
// Pro shows the receipt to the user (systemMessage, never the model). Internal agents (empty type) are skipped.
|
|
316
431
|
try {
|
|
317
432
|
const hook = JSON.parse(readStdin());
|
|
433
|
+
saveInflight(forgetInflight(loadInflight(), String(hook?.session_id ?? ''), String(hook?.agent_type ?? ''), now));
|
|
318
434
|
const path = hook?.agent_transcript_path;
|
|
319
435
|
if (hook?.agent_type && typeof path === 'string') {
|
|
320
436
|
const u = subagentUsage(path);
|
|
@@ -571,6 +687,10 @@ if (cmd === 'status') {
|
|
|
571
687
|
} else if (cmd === 'report' || cmd === 'trim') {
|
|
572
688
|
const pro = true;
|
|
573
689
|
const since = now - days() * 86400_000;
|
|
690
|
+
if (cmd === 'trim' && args.includes('--share') && (args[0] === 'keep' || args.includes('--apply') || args.includes('--undo'))) {
|
|
691
|
+
console.error('--share is read-only; run keep, --apply, or --undo separately.');
|
|
692
|
+
process.exit(1);
|
|
693
|
+
}
|
|
574
694
|
if (cmd === 'trim' && args[0] === 'keep') {
|
|
575
695
|
// The keep-list: servers and skills `trim --apply` never touches (Claude, Codex and Grok). Free to manage; apply is Pro.
|
|
576
696
|
const drop = args[1] === '--remove';
|
|
@@ -595,7 +715,11 @@ if (cmd === 'status') {
|
|
|
595
715
|
process.exit(0);
|
|
596
716
|
}
|
|
597
717
|
if (!existsSync(codexConfigPath())) {
|
|
598
|
-
console.log(
|
|
718
|
+
console.log(
|
|
719
|
+
args.includes('--share')
|
|
720
|
+
? 'Codex context summary: unavailable (no setup found).'
|
|
721
|
+
: `No Codex setup found (${codexConfigPath()}). Set CODEX_HOME if Codex keeps it elsewhere.`,
|
|
722
|
+
);
|
|
599
723
|
process.exit(0);
|
|
600
724
|
}
|
|
601
725
|
const servers = codexServers(readFileSync(codexConfigPath(), 'utf8'));
|
|
@@ -607,7 +731,12 @@ if (cmd === 'status') {
|
|
|
607
731
|
? `✓ 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`
|
|
608
732
|
: 'Nothing to turn off: every server that is on was used or is on your keep-list.') + keptNote(r.kept),
|
|
609
733
|
);
|
|
610
|
-
} else
|
|
734
|
+
} else
|
|
735
|
+
console.log(
|
|
736
|
+
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`
|
|
738
|
+
: forTerminal(r.text),
|
|
739
|
+
);
|
|
611
740
|
process.exit(0);
|
|
612
741
|
}
|
|
613
742
|
if (cmd === 'trim' && args.includes('--grok')) {
|
|
@@ -619,7 +748,11 @@ if (cmd === 'status') {
|
|
|
619
748
|
process.exit(0);
|
|
620
749
|
}
|
|
621
750
|
if (!existsSync(grokConfigPath())) {
|
|
622
|
-
console.log(
|
|
751
|
+
console.log(
|
|
752
|
+
args.includes('--share')
|
|
753
|
+
? 'Grok context summary: unavailable (no setup found).'
|
|
754
|
+
: `No Grok setup found (${grokConfigPath()}). Set GROK_HOME if Grok keeps it elsewhere.`,
|
|
755
|
+
);
|
|
623
756
|
process.exit(0);
|
|
624
757
|
}
|
|
625
758
|
const r = grokTrimReport({
|
|
@@ -637,7 +770,12 @@ if (cmd === 'status') {
|
|
|
637
770
|
? `✓ 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`
|
|
638
771
|
: 'Nothing to turn off: every server that is on was used or is on your keep-list.') + keptNote(r.kept),
|
|
639
772
|
);
|
|
640
|
-
} else
|
|
773
|
+
} else
|
|
774
|
+
console.log(
|
|
775
|
+
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`
|
|
777
|
+
: forTerminal(r.text),
|
|
778
|
+
);
|
|
641
779
|
process.exit(0);
|
|
642
780
|
}
|
|
643
781
|
/** @type {import('../src/trim.mjs').Activity} */
|
|
@@ -648,6 +786,7 @@ if (cmd === 'status') {
|
|
|
648
786
|
let text;
|
|
649
787
|
if (why || jobs) {
|
|
650
788
|
const r = attribute(await whySessions(claudeRoot(), since), since);
|
|
789
|
+
saveToolStats(toolStats(r.tools));
|
|
651
790
|
text = jobs ? jobsReport(r, { since, now }) : whyReport(r, { since, now, calib: loadValue().calib });
|
|
652
791
|
} else if (cmd === 'report') text = burnReport(usage, { since, now });
|
|
653
792
|
else {
|
|
@@ -661,7 +800,10 @@ if (cmd === 'status') {
|
|
|
661
800
|
}
|
|
662
801
|
const keep = getKeep();
|
|
663
802
|
if (latest && args.includes('--share')) text = shareSummary(baseline(usage), latest, used, days(), keep);
|
|
664
|
-
else
|
|
803
|
+
else
|
|
804
|
+
text = latest
|
|
805
|
+
? startupReport(baseline(usage), latest, used, days(), keep)
|
|
806
|
+
: trimReport(baseline(usage), contributors(), used, days(), args.includes('--share'));
|
|
665
807
|
if (latest && !args.includes('--share')) {
|
|
666
808
|
const still = stillLoading(latest);
|
|
667
809
|
text += still.length
|
|
@@ -674,7 +816,7 @@ if (cmd === 'status') {
|
|
|
674
816
|
const out = flag('--out');
|
|
675
817
|
if (out) {
|
|
676
818
|
writeFileSync(out, `${text}\n`);
|
|
677
|
-
console.log(`Wrote ${out}`);
|
|
819
|
+
console.log(cmd === 'trim' && args.includes('--share') ? 'Wrote shared summary.' : `Wrote ${out}`);
|
|
678
820
|
} else console.log(forTerminal(text));
|
|
679
821
|
} else if (cmd === 'drift') {
|
|
680
822
|
// SessionStart hook: tells the user (systemMessage, never the model's context) when starting context grew.
|
|
@@ -1056,29 +1198,52 @@ function table(rows) {
|
|
|
1056
1198
|
.join('\n');
|
|
1057
1199
|
}
|
|
1058
1200
|
|
|
1059
|
-
/**
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1201
|
+
/**
|
|
1202
|
+
* One window on a status-line row. Host Grok/Codex windows keep their src prefix;
|
|
1203
|
+
* a labeled `limitcast claude:` / `limitcast grok:` row does not repeat it.
|
|
1204
|
+
* @param {NonNullable<ReturnType<typeof forecastAll>>[number]} f
|
|
1205
|
+
* @param {boolean} labeled
|
|
1206
|
+
*/
|
|
1207
|
+
function windowBit(f, labeled = false) {
|
|
1208
|
+
const name = labeled || f.src === 'claude' ? '' : `${f.src} `;
|
|
1209
|
+
return (
|
|
1210
|
+
`${name}${f.win} ${Math.round(f.pct)}%` +
|
|
1211
|
+
(f.verdict === 'AT_RISK' ? ` ⚠ out ${clock(f.wall)}` : f.verdict === 'NEAR' ? ' ⚠ near limit' : f.verdict === 'HIT' ? ' ⛔' : '') +
|
|
1212
|
+
(f.today && f.verdict !== 'HIT' ? ` · today ${todayLabel(f.today)}` : '')
|
|
1065
1213
|
);
|
|
1066
|
-
return bits.join(' · ') || 'limitcast: waiting for data';
|
|
1067
1214
|
}
|
|
1068
1215
|
|
|
1069
1216
|
/**
|
|
1070
|
-
* Status-line
|
|
1217
|
+
* Status-line rows: one provider per line, Grok spend on the Grok row, then hints on the host row.
|
|
1071
1218
|
* @param {ReturnType<typeof forecastAll>} rows
|
|
1072
1219
|
* @param {string} spend
|
|
1073
1220
|
* @param {string[]} hints
|
|
1221
|
+
* @param {string} host
|
|
1074
1222
|
*/
|
|
1075
|
-
function
|
|
1076
|
-
const
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1223
|
+
function statusLines(rows, spend, hints, host = 'claude') {
|
|
1224
|
+
const order = host === 'grok' ? ['grok', 'claude', 'codex'] : ['claude', 'codex', 'grok'];
|
|
1225
|
+
/** @type {string[]} */
|
|
1226
|
+
const lines = [];
|
|
1227
|
+
for (const src of order) {
|
|
1228
|
+
const group = rows.filter((f) => f.src === src);
|
|
1229
|
+
if (!group.length && !(src === 'grok' && spend)) continue;
|
|
1230
|
+
const labeled = src !== host;
|
|
1231
|
+
const bits = group.map((f) => windowBit(f, labeled));
|
|
1232
|
+
if (src === 'grok' && spend) bits.push(spend);
|
|
1233
|
+
if (!bits.length) continue;
|
|
1234
|
+
const tag = src === host ? 'limitcast' : `limitcast ${src}`;
|
|
1235
|
+
lines.push(`${tag}: ${bits.join(' · ')}`);
|
|
1236
|
+
}
|
|
1237
|
+
if (hints.length) {
|
|
1238
|
+
if (lines.length) lines[0] += ` · ${hints.join(' · ')}`;
|
|
1239
|
+
else lines.push(`limitcast: ${hints.join(' · ')}`);
|
|
1240
|
+
}
|
|
1241
|
+
return lines.length ? lines : ['limitcast: waiting for data'];
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
/** Print limitcast rows. `limitcast claude:` already has the prefix; `waiting for data` does not. */
|
|
1245
|
+
function emitStatus(line) {
|
|
1246
|
+
console.log(line.startsWith('limitcast') ? line : `limitcast: ${line}`);
|
|
1082
1247
|
}
|
|
1083
1248
|
|
|
1084
1249
|
/** Grok spend line when no dollar cap is set (a cap becomes a forecast row instead). */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "limitcast",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"description": "Stretch your Claude Code plan: measure what every session loads before you type, cut what you never use, and stop runaway subagents before they burn your window.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/cold.mjs
CHANGED
|
@@ -3,9 +3,10 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { stateDir } from './store.mjs';
|
|
5
5
|
|
|
6
|
-
// Cold-cache warning (
|
|
7
|
-
//
|
|
8
|
-
//
|
|
6
|
+
// Cold-cache warning (UserPromptSubmit hook). After a pause the prompt cache has expired, so the next message
|
|
7
|
+
// re-sends the whole context as new tokens, which count against the limit far more than cached ones.
|
|
8
|
+
// From 5 minutes (the cheap cache) the first message is announced and still sent. From 60 minutes it is held
|
|
9
|
+
// once with its cost; sending it again goes through.
|
|
9
10
|
|
|
10
11
|
const MIN_TOKENS = 100_000;
|
|
11
12
|
const stateFile = () => join(stateDir(), 'cold.json');
|
|
@@ -15,18 +16,21 @@ const stateFile = () => join(stateDir(), 'cold.json');
|
|
|
15
16
|
* @param {unknown} prompt
|
|
16
17
|
* @param {{tokens:number, t:number}|null} last the session's latest model call
|
|
17
18
|
* @param {number} now epoch ms
|
|
18
|
-
* @param {{minutes:number, calib?:{fresh:number, read:number}|null}} o
|
|
19
|
-
*
|
|
19
|
+
* @param {{minutes:number, noticeMinutes?:number, calib?:{fresh:number, read:number}|null}} o
|
|
20
|
+
* minutes: idle time that holds the message. noticeMinutes: idle time that only announces it (default: the hold).
|
|
21
|
+
* @returns {{tokens:number, idle:number, pct:number|null, warm:number|null, hold:boolean}|null} pct/warm: % of the 5h window cold/warm
|
|
20
22
|
*/
|
|
21
|
-
export function coldCost(prompt, last, now, { minutes, calib }) {
|
|
23
|
+
export function coldCost(prompt, last, now, { minutes, noticeMinutes, calib }) {
|
|
22
24
|
if (!last?.t || last.tokens < MIN_TOKENS) return null;
|
|
23
25
|
const p = String(prompt ?? '').trimStart();
|
|
24
26
|
// Background agents and other sessions report back as prompts; /compact and /clear are what the warning suggests.
|
|
25
27
|
if (p.startsWith('<') || /^\/(compact|clear)\b/.test(p)) return null;
|
|
26
28
|
const idle = Math.round((now - last.t) / 60_000);
|
|
27
|
-
|
|
29
|
+
// A notice threshold past the hold would skip the hold entirely. Keep the notice at or before it.
|
|
30
|
+
const noticeAt = Math.min(noticeMinutes ?? minutes, minutes);
|
|
31
|
+
if (idle < noticeAt) return null;
|
|
28
32
|
const m = last.tokens / 1e6;
|
|
29
|
-
return { tokens: last.tokens, idle, pct: calib ? m * calib.fresh : null, warm: calib ? m * calib.read : null };
|
|
33
|
+
return { tokens: last.tokens, idle, pct: calib ? m * calib.fresh : null, warm: calib ? m * calib.read : null, hold: idle >= minutes };
|
|
30
34
|
}
|
|
31
35
|
|
|
32
36
|
/** @param {NonNullable<ReturnType<typeof coldCost>>} c */
|
|
@@ -42,6 +46,22 @@ export function coldMessage(c) {
|
|
|
42
46
|
);
|
|
43
47
|
}
|
|
44
48
|
|
|
49
|
+
/**
|
|
50
|
+
* The short-idle announcement. The message is not held.
|
|
51
|
+
* @param {NonNullable<ReturnType<typeof coldCost>>} c
|
|
52
|
+
*/
|
|
53
|
+
export function coldNotice(c) {
|
|
54
|
+
const idle = c.idle >= 120 ? `${Math.round(c.idle / 60)} hours` : `${c.idle} minutes`;
|
|
55
|
+
const cost =
|
|
56
|
+
c.pct !== null && c.warm !== null
|
|
57
|
+
? `≈${pct(c.pct)} of your 5-hour window (≈${pct(c.warm)} if the cache were still warm)`
|
|
58
|
+
: 'all at the new-token rate instead of the much cheaper cached one';
|
|
59
|
+
return (
|
|
60
|
+
`limitcast: this session sat idle for ${idle}, so its cheap prompt cache may have expired. Your message re-sends ${Math.round(c.tokens / 1000)}k tokens of context: ${cost}. ` +
|
|
61
|
+
'It is going through. Run /compact before a longer pause to shrink the next one.'
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
45
65
|
const pct = (/** @type {number} */ x) => `${x < 1 ? x.toFixed(2) : x.toFixed(1)}%`;
|
|
46
66
|
|
|
47
67
|
/**
|
|
@@ -51,6 +71,23 @@ const pct = (/** @type {number} */ x) => `${x < 1 ? x.toFixed(2) : x.toFixed(1)}
|
|
|
51
71
|
* @param {number} lastT the latest model call's time
|
|
52
72
|
*/
|
|
53
73
|
export function firstWarning(sid, lastT) {
|
|
74
|
+
return claim(lastT, sid);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* True the first time this pause is announced (the message still goes through). Independent of the hold.
|
|
79
|
+
* @param {string} sid
|
|
80
|
+
* @param {number} lastT
|
|
81
|
+
*/
|
|
82
|
+
export function firstNotice(sid, lastT) {
|
|
83
|
+
return claim(lastT, `n:${sid}`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* @param {number} lastT
|
|
88
|
+
* @param {string} key session id, or `n:` plus the session id for the idle notice
|
|
89
|
+
*/
|
|
90
|
+
function claim(lastT, key) {
|
|
54
91
|
/** @type {Record<string, number>} */
|
|
55
92
|
let seen = {};
|
|
56
93
|
try {
|
|
@@ -58,9 +95,9 @@ export function firstWarning(sid, lastT) {
|
|
|
58
95
|
} catch {
|
|
59
96
|
/* first warning */
|
|
60
97
|
}
|
|
61
|
-
if (seen[
|
|
98
|
+
if (seen[key] === lastT) return false;
|
|
62
99
|
const keep = Object.entries(seen).slice(-49); // the 49 most recent other sessions
|
|
63
100
|
mkdirSync(stateDir(), { recursive: true });
|
|
64
|
-
writeFileSync(stateFile(), JSON.stringify(Object.fromEntries([...keep.filter(([k]) => k !==
|
|
101
|
+
writeFileSync(stateFile(), JSON.stringify(Object.fromEntries([...keep.filter(([k]) => k !== key), [key, lastT]])));
|
|
65
102
|
return true;
|
|
66
103
|
}
|
package/src/inflight.mjs
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { spawnSource } from './guard.mjs';
|
|
6
|
+
import { stateDir } from './store.mjs';
|
|
7
|
+
|
|
8
|
+
// A second spawn of the same type and prompt, in the same session, while the first has not finished.
|
|
9
|
+
// SubagentStop clears the Claude one. Codex and Grok have no stop event here, so a record older than
|
|
10
|
+
// 30 minutes is forgotten: a missed stop must not hold the same prompt for the rest of the day.
|
|
11
|
+
|
|
12
|
+
export const INFLIGHT_MS = 30 * 60_000;
|
|
13
|
+
|
|
14
|
+
/** @typedef {{sid:string, type:string, hash:string, t:number}} Inflight */
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Identity of a spawn the duplicate hold can see, or null when the call is not one.
|
|
18
|
+
* An empty prompt or type is not tracked: those retries are how a host re-sends, and they are not the same request.
|
|
19
|
+
* @param {any} hook
|
|
20
|
+
*/
|
|
21
|
+
export function spawnIdentity(hook) {
|
|
22
|
+
const tool = String(hook?.tool_name ?? hook?.toolName ?? hook?.tool ?? '');
|
|
23
|
+
const src = spawnSource(tool);
|
|
24
|
+
if (!src) return null;
|
|
25
|
+
const input = hook?.tool_input ?? hook?.toolInput ?? {};
|
|
26
|
+
const type = String(input?.subagent_type ?? input?.subagentType ?? input?.agent_type ?? '').trim();
|
|
27
|
+
const prompt = String(input?.prompt ?? input?.description ?? input?.task ?? '')
|
|
28
|
+
.replace(/\s+/g, ' ')
|
|
29
|
+
.trim();
|
|
30
|
+
const sid = String(hook?.session_id ?? hook?.sessionId ?? '').trim();
|
|
31
|
+
if (!type || !prompt || !sid) return null;
|
|
32
|
+
const hash = createHash('sha256').update(`${type.toLowerCase()}\0${prompt}`).digest('hex').slice(0, 16);
|
|
33
|
+
return { src, type, prompt, hash, sid };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** @param {Inflight[]} entries @param {number} now @param {number} [maxAge] */
|
|
37
|
+
export function pruneInflight(entries, now, maxAge = INFLIGHT_MS) {
|
|
38
|
+
return entries.filter((e) => now - e.t >= 0 && now - e.t < maxAge);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The still-running spawn with this session, type and prompt, if any.
|
|
43
|
+
* @param {Inflight[]} entries already pruned
|
|
44
|
+
* @param {{sid:string, type:string, hash:string}} id
|
|
45
|
+
*/
|
|
46
|
+
export function findDuplicate(entries, id) {
|
|
47
|
+
return entries.find((e) => e.sid === id.sid && e.hash === id.hash) ?? null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @param {Inflight[]} entries already pruned
|
|
52
|
+
* @param {{sid:string, type:string, hash:string}} id
|
|
53
|
+
* @param {number} now
|
|
54
|
+
*/
|
|
55
|
+
export function rememberInflight(entries, id, now) {
|
|
56
|
+
return [...entries, { sid: id.sid, type: id.type, hash: id.hash, t: now }];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Drop the oldest still-running spawn of this type in this session (SubagentStop does not carry the prompt).
|
|
61
|
+
* Clearing the oldest fails open: the spawn that is still running may be a different prompt, and that one is then allowed again.
|
|
62
|
+
* @param {Inflight[]} entries
|
|
63
|
+
* @param {string} sid
|
|
64
|
+
* @param {string} type
|
|
65
|
+
* @param {number} now
|
|
66
|
+
*/
|
|
67
|
+
export function forgetInflight(entries, sid, type, now) {
|
|
68
|
+
const live = pruneInflight(entries, now);
|
|
69
|
+
if (!sid || !type) return live;
|
|
70
|
+
const i = live.findIndex((e) => e.sid === sid && e.type.toLowerCase() === type.toLowerCase());
|
|
71
|
+
if (i >= 0) live.splice(i, 1);
|
|
72
|
+
return live;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** @param {{type:string}} id */
|
|
76
|
+
export function duplicateReason(id) {
|
|
77
|
+
return (
|
|
78
|
+
`limitcast: a ${id.type} subagent with this same prompt is already running in this session. ` +
|
|
79
|
+
'Wait for it to finish, or set LIMITCAST_ALLOW=1 to spawn another.'
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const file = () => join(stateDir(), 'inflight.json');
|
|
84
|
+
|
|
85
|
+
/** @returns {Inflight[]} */
|
|
86
|
+
export function loadInflight() {
|
|
87
|
+
try {
|
|
88
|
+
const parsed = JSON.parse(readFileSync(file(), 'utf8'));
|
|
89
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
90
|
+
} catch {
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** @param {Inflight[]} entries */
|
|
96
|
+
export function saveInflight(entries) {
|
|
97
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
98
|
+
writeFileSync(file(), JSON.stringify(entries.slice(-100)));
|
|
99
|
+
}
|