limitcast 0.20.0 → 0.20.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/bin/limitcast.mjs +2 -1
- package/package.json +2 -2
- package/src/apply.mjs +32 -3
- package/src/forecast.mjs +1 -1
- package/src/guard.mjs +1 -1
- package/src/optimize-cli.mjs +39 -4
- package/src/optimize.mjs +48 -11
- package/src/store.mjs +24 -5
- package/src/trim.mjs +20 -8
- package/src/usage.mjs +26 -10
package/bin/limitcast.mjs
CHANGED
|
@@ -108,7 +108,7 @@ import {
|
|
|
108
108
|
import { forTerminal } from '../src/term.mjs';
|
|
109
109
|
import { firstFlag, resultTokens, toolKey, toolNotice } from '../src/toolcheck.mjs';
|
|
110
110
|
import { loadLiveStats, loadToolStats, recordToolSize, saveToolStats, toolLimitDecision, toolStats } from '../src/toollimit.mjs';
|
|
111
|
-
import { baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
|
|
111
|
+
import { activityKnown, baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport, UNKNOWN_ACTIVITY } from '../src/trim.mjs';
|
|
112
112
|
import { claudeRoot, grokRoot, readUsage } from '../src/usage.mjs';
|
|
113
113
|
import { dailyDue, foldEvents, loadValue, saveValue, scanSessions, valuePeriod, valueSection, valueTotals } from '../src/value.mjs';
|
|
114
114
|
import { attribute, jobsReport, whyReport, whySessions } from '../src/where.mjs';
|
|
@@ -1309,6 +1309,7 @@ async function refreshValue(preread) {
|
|
|
1309
1309
|
*/
|
|
1310
1310
|
function applyMessage(latest, used, usedMonth) {
|
|
1311
1311
|
if (!latest) return '`limitcast trim --apply` needs one Claude Code session first.';
|
|
1312
|
+
if (!activityKnown(used) || !activityKnown(usedMonth ?? used)) return UNKNOWN_ACTIVITY;
|
|
1312
1313
|
const s = measuredSavings(latest.pieces, used, getKeep(), usedMonth);
|
|
1313
1314
|
const cwd = transcriptCwd(latest.file) ?? process.cwd();
|
|
1314
1315
|
const plan = planTrim({
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "limitcast",
|
|
3
|
-
"version": "0.20.
|
|
3
|
+
"version": "0.20.2",
|
|
4
4
|
"description": "Claude Code usage limits: forecast Codex and Grok too.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -35,6 +35,6 @@
|
|
|
35
35
|
"type": "git",
|
|
36
36
|
"url": "git+https://github.com/SamStull9007/limitcast.git"
|
|
37
37
|
},
|
|
38
|
-
"author": "Sam Stull",
|
|
38
|
+
"author": "Sam Stull <support@limitcast.dev> (https://limitcast.dev/sam-stull/)",
|
|
39
39
|
"license": "MIT"
|
|
40
40
|
}
|
package/src/apply.mjs
CHANGED
|
@@ -106,6 +106,8 @@ export function installedPlugins(dir = configDir()) {
|
|
|
106
106
|
* localSkills: folder names of personal and project skills; keep: the `trim keep` list, never hidden or disabled
|
|
107
107
|
*/
|
|
108
108
|
export function planTrim({ skills, mcp, cwd, settings, claudeJson, plugins, projectMcpJson, localSkills, keep = [] }) {
|
|
109
|
+
validateTrimSettings(settings);
|
|
110
|
+
validateTrimSettings(claudeJson);
|
|
109
111
|
// "x:y" is a plugin skill (namespaced by its plugin) unless x is one of your own skill folders with nested skills.
|
|
110
112
|
// Plugins can load from places installed_plugins.json doesn't list, so the namespace alone decides.
|
|
111
113
|
const isPluginSkill = (/** @type {string} */ n) => n.includes(':') && !localSkills.has(n.split(':')[0]);
|
|
@@ -144,10 +146,33 @@ function backup(path) {
|
|
|
144
146
|
if (existsSync(path)) copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
|
|
145
147
|
}
|
|
146
148
|
|
|
149
|
+
function validateTrimSettings(cfg) {
|
|
150
|
+
const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
151
|
+
if (!object(cfg)) throw new Error('invalid settings object; original configuration preserved');
|
|
152
|
+
for (const key of ['skillOverrides', 'projects'])
|
|
153
|
+
if (Object.hasOwn(cfg, key) && !object(cfg[key])) throw new Error(`invalid ${key}; original configuration preserved`);
|
|
154
|
+
for (const project of Object.values(cfg.projects ?? {})) {
|
|
155
|
+
if (!object(project)) throw new Error('invalid project settings; original configuration preserved');
|
|
156
|
+
const list = project.disabledMcpServers;
|
|
157
|
+
if (list !== undefined && (!Array.isArray(list) || list.some((name) => typeof name !== 'string')))
|
|
158
|
+
throw new Error('invalid disabledMcpServers; original configuration preserved');
|
|
159
|
+
}
|
|
160
|
+
return cfg;
|
|
161
|
+
}
|
|
162
|
+
|
|
147
163
|
/** @returns {{at:number, cwd:string, skills:{name:string, prev?:string}[], mcp:string[]}[]} */
|
|
148
164
|
export function loadLedger() {
|
|
149
165
|
const entries = readLedger(ledgerPath());
|
|
150
|
-
if (
|
|
166
|
+
if (
|
|
167
|
+
entries.some(
|
|
168
|
+
(e) =>
|
|
169
|
+
typeof e.cwd !== 'string' ||
|
|
170
|
+
!Array.isArray(e.skills) ||
|
|
171
|
+
!Array.isArray(e.mcp) ||
|
|
172
|
+
e.skills.some((s) => !s || typeof s.name !== 'string' || (s.prev !== undefined && typeof s.prev !== 'string')) ||
|
|
173
|
+
e.mcp.some((name) => typeof name !== 'string'),
|
|
174
|
+
)
|
|
175
|
+
)
|
|
151
176
|
throw new Error('invalid Claude trim ledger');
|
|
152
177
|
return entries;
|
|
153
178
|
}
|
|
@@ -166,6 +191,7 @@ export function applyTrim(plan, { cwd, now, settings = settingsPath(), claudeJso
|
|
|
166
191
|
if (plan.hide.length) {
|
|
167
192
|
updates.push(
|
|
168
193
|
editJson(settings, (cfg) => {
|
|
194
|
+
validateTrimSettings(cfg);
|
|
169
195
|
cfg.skillOverrides ??= {};
|
|
170
196
|
for (const name of plan.hide) {
|
|
171
197
|
if (cfg.skillOverrides[name] !== undefined && cfg.skillOverrides[name] !== 'on') continue;
|
|
@@ -178,6 +204,7 @@ export function applyTrim(plan, { cwd, now, settings = settingsPath(), claudeJso
|
|
|
178
204
|
if (plan.disable.length) {
|
|
179
205
|
updates.push(
|
|
180
206
|
editJson(claudeJson, (cj) => {
|
|
207
|
+
validateTrimSettings(cj);
|
|
181
208
|
cj.projects ??= {};
|
|
182
209
|
cj.projects[cwd] ??= {};
|
|
183
210
|
const list = (cj.projects[cwd].disabledMcpServers ??= []);
|
|
@@ -212,6 +239,7 @@ export function undoTrim({ settings = settingsPath(), claudeJson = claudeJsonPat
|
|
|
212
239
|
if (last.skills.length && existsSync(settings)) {
|
|
213
240
|
updates.push(
|
|
214
241
|
editJson(settings, (cfg) => {
|
|
242
|
+
validateTrimSettings(cfg);
|
|
215
243
|
for (const s of last.skills) {
|
|
216
244
|
if (cfg.skillOverrides?.[s.name] !== 'user-invocable-only') continue;
|
|
217
245
|
if (s.prev === undefined) delete cfg.skillOverrides[s.name];
|
|
@@ -223,6 +251,7 @@ export function undoTrim({ settings = settingsPath(), claudeJson = claudeJsonPat
|
|
|
223
251
|
if (last.mcp.length && existsSync(claudeJson)) {
|
|
224
252
|
updates.push(
|
|
225
253
|
editJson(claudeJson, (cj) => {
|
|
254
|
+
validateTrimSettings(cj);
|
|
226
255
|
const p = cj.projects?.[last.cwd];
|
|
227
256
|
if (p?.disabledMcpServers) p.disabledMcpServers = p.disabledMcpServers.filter((/** @type {string} */ n) => !last.mcp.includes(n));
|
|
228
257
|
}),
|
|
@@ -247,7 +276,7 @@ export function reapplyTrim({ settings = settingsPath(), claudeJson = claudeJson
|
|
|
247
276
|
const out = { reapplied: /** @type {string[]} */ ([]), released: /** @type {string[]} */ ([]) };
|
|
248
277
|
if (!last) return out;
|
|
249
278
|
if (last.skills.length) {
|
|
250
|
-
const cfg = existsSync(settings) ? readSettings(settings) : {};
|
|
279
|
+
const cfg = validateTrimSettings(existsSync(settings) ? readSettings(settings) : {});
|
|
251
280
|
const gone = last.skills.filter((s) => cfg.skillOverrides?.[s.name] !== 'user-invocable-only');
|
|
252
281
|
if (gone.length) {
|
|
253
282
|
last.skills = last.skills.filter((s) => !gone.includes(s));
|
|
@@ -255,7 +284,7 @@ export function reapplyTrim({ settings = settingsPath(), claudeJson = claudeJson
|
|
|
255
284
|
}
|
|
256
285
|
}
|
|
257
286
|
if (last.mcp.length) {
|
|
258
|
-
const cj = existsSync(claudeJson) ? readSettings(claudeJson) : {};
|
|
287
|
+
const cj = validateTrimSettings(existsSync(claudeJson) ? readSettings(claudeJson) : {});
|
|
259
288
|
const list = cj.projects?.[last.cwd]?.disabledMcpServers ?? [];
|
|
260
289
|
const gone = last.mcp.filter((n) => !list.includes(n));
|
|
261
290
|
if (gone.length) {
|
package/src/forecast.mjs
CHANGED
|
@@ -24,7 +24,7 @@ export function forecast(samples, now) {
|
|
|
24
24
|
|
|
25
25
|
const window = sorted.filter((s) => Math.abs(s.reset - last.reset) <= RESET_JITTER_S);
|
|
26
26
|
const recent = window.filter((s) => s.t >= now - RECENT_MS);
|
|
27
|
-
const short = slopePerHour(recent
|
|
27
|
+
const short = slopePerHour(recent);
|
|
28
28
|
// NEAR: so close to the limit that one heavy turn can finish it, even with no burn rate to go on yet.
|
|
29
29
|
const calm = last.pct >= NEAR_PCT ? 'NEAR' : 'OK';
|
|
30
30
|
const runout = (/** @type {number|null} */ r) => (r === null || r <= 0 ? null : last.t + ((100 - last.pct) / r) * 3600_000);
|
package/src/guard.mjs
CHANGED
|
@@ -60,7 +60,7 @@ export function guardDecision(tool, forecasts, now, minutes) {
|
|
|
60
60
|
*/
|
|
61
61
|
function blockingForecast(tool, forecasts, now, minutes) {
|
|
62
62
|
const src = spawnSource(tool);
|
|
63
|
-
return forecasts.find((f) => f.src === src && f.verdict === 'AT_RISK' && f.wall !== null && f.wall - now <= minutes * 60_000);
|
|
63
|
+
return forecasts.find((f) => f.src === src && f.verdict === 'AT_RISK' && f.wall !== null && f.wall >= now && f.wall - now <= minutes * 60_000);
|
|
64
64
|
}
|
|
65
65
|
|
|
66
66
|
/**
|
package/src/optimize-cli.mjs
CHANGED
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
import { closeSync, openSync, readFileSync, readSync, statSync } from 'node:fs';
|
|
2
2
|
import { applyCapabilities, capabilityStatus, configuredServers, restoreCapabilities } from './capabilities.mjs';
|
|
3
3
|
import { reserveModelJob, startModelWorker } from './model-optimize.mjs';
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
CATALOG_LIMIT,
|
|
6
|
+
capabilityProposals,
|
|
7
|
+
changeOptimization,
|
|
8
|
+
HOSTS,
|
|
9
|
+
normalizeEvent,
|
|
10
|
+
processEvent,
|
|
11
|
+
readOptimization,
|
|
12
|
+
repository,
|
|
13
|
+
} from './optimize.mjs';
|
|
5
14
|
import { installOptimizerHost } from './optimizer-hosts.mjs';
|
|
6
15
|
import { repositoryMap } from './repomap.mjs';
|
|
7
16
|
|
|
@@ -10,9 +19,14 @@ export function runOptimizationHook(hook, host) {
|
|
|
10
19
|
if (hook.is_subagent || hook.subagent_id || hook.isSidechain) return {};
|
|
11
20
|
const repo = repository(hook.cwd ?? hook.workdir ?? process.cwd());
|
|
12
21
|
if (host === 'claude' && ['Stop', 'SessionEnd'].includes(hook.hook_event_name) && typeof hook.transcript_path === 'string') {
|
|
13
|
-
|
|
22
|
+
const tools = transcriptTools(hook.transcript_path);
|
|
23
|
+
hook = { ...hook, tools, tools_complete: tools.complete };
|
|
14
24
|
}
|
|
15
25
|
const event = normalizeEvent(hook, host);
|
|
26
|
+
if (['codex', 'grok'].includes(host) && ['SessionStart', 'UserPromptSubmit', 'Stop', 'SessionEnd'].includes(event.event))
|
|
27
|
+
event.servers = configuredServers(host)
|
|
28
|
+
.filter((s) => s.enabled !== false)
|
|
29
|
+
.map((s) => s.name);
|
|
16
30
|
let job;
|
|
17
31
|
const result = changeOptimization(repo, (state) => {
|
|
18
32
|
const result = processEvent(state, event);
|
|
@@ -41,16 +55,22 @@ export function transcriptTools(path) {
|
|
|
41
55
|
const buffer = Buffer.alloc(256_000);
|
|
42
56
|
const bytes = readSync(fd, buffer, 0, buffer.length, 0);
|
|
43
57
|
const names = [];
|
|
58
|
+
let complete = statSync(path).size <= buffer.length;
|
|
44
59
|
for (const line of buffer.toString('utf8', 0, bytes).split('\n')) {
|
|
60
|
+
if (!line.trim()) continue;
|
|
45
61
|
try {
|
|
46
62
|
const row = JSON.parse(line);
|
|
47
63
|
if (row.attachment?.type === 'deferred_tools_delta') names.push(...(row.attachment.addedNames ?? []));
|
|
48
64
|
if (row.type === 'system' && row.subtype === 'init') names.push(...(row.tools ?? []));
|
|
49
65
|
} catch {
|
|
66
|
+
complete = false;
|
|
50
67
|
/* a partial line is not evidence */
|
|
51
68
|
}
|
|
52
69
|
}
|
|
53
|
-
|
|
70
|
+
const unique = [...new Set(names)].filter((n) => typeof n === 'string' && /^[\w:.-]{1,100}$/.test(n));
|
|
71
|
+
const tools = unique.slice(0, CATALOG_LIMIT);
|
|
72
|
+
tools.complete = complete && unique.length <= CATALOG_LIMIT;
|
|
73
|
+
return tools;
|
|
54
74
|
} finally {
|
|
55
75
|
closeSync(fd);
|
|
56
76
|
}
|
|
@@ -129,12 +149,27 @@ export function runOptimize(args, cwd = process.cwd()) {
|
|
|
129
149
|
config: state.config,
|
|
130
150
|
facts: state.facts.length,
|
|
131
151
|
hosts: Object.fromEntries(
|
|
132
|
-
HOSTS.map((h) => [
|
|
152
|
+
HOSTS.map((h) => [
|
|
153
|
+
h,
|
|
154
|
+
{
|
|
155
|
+
completedSessions: state.hosts[h]?.completed ?? 0,
|
|
156
|
+
proposed: capabilityProposals(state, h, configuredServers(h)),
|
|
157
|
+
catalogComplete: state.hosts[h]?.catalogComplete ?? null,
|
|
158
|
+
learningEvidence: state.hosts[h]?.learningEvidence ?? null,
|
|
159
|
+
},
|
|
160
|
+
]),
|
|
133
161
|
),
|
|
134
162
|
receipts: state.receipts,
|
|
135
163
|
measurements: {
|
|
136
164
|
injectedContext: state.measurements ?? { injections: 0, contextChars: 0, estimatedContextTokens: 0 },
|
|
137
165
|
modelCalls: state.model?.receipts ?? [],
|
|
166
|
+
learning: {
|
|
167
|
+
eligibleChecks: Object.values(state.hosts).reduce((n, h) => n + (h.learningEvidence?.eligible ?? 0), 0),
|
|
168
|
+
activeFacts: state.facts.filter((f) => f.state === 'active').length,
|
|
169
|
+
scope: 'Counters start with this version; unsupported and ambiguous command text is never retained.',
|
|
170
|
+
requirements:
|
|
171
|
+
'Learning needs allowlisted checks with definite success and three independent sessions; model learning also requires the opt-in model backend. Inspect per-host learningEvidence for excluded or ambiguous calls.',
|
|
172
|
+
},
|
|
138
173
|
taskSuccess: 'unmeasured; completed sessions are not proof of task success',
|
|
139
174
|
netSavings: 'unproven; injected context and model calls add overhead',
|
|
140
175
|
},
|
package/src/optimize.mjs
CHANGED
|
@@ -15,7 +15,7 @@ const CAPABILITIES = {
|
|
|
15
15
|
};
|
|
16
16
|
const validTool = (name) => typeof name === 'string' && /^[\w:.-]{1,100}$/.test(name) && !Object.hasOwn(Object.prototype, name);
|
|
17
17
|
/** The tool catalog a session can declare, per host. Claude sessions with many connectors declare a few hundred tools. */
|
|
18
|
-
const CATALOG_LIMIT = 400;
|
|
18
|
+
export const CATALOG_LIMIT = 400;
|
|
19
19
|
export const normServer = (name) =>
|
|
20
20
|
String(name)
|
|
21
21
|
.toLowerCase()
|
|
@@ -193,12 +193,20 @@ export function normalizeEvent(hook, host) {
|
|
|
193
193
|
const edit = /^(?:Edit|Write|MultiEdit|apply_patch|replace_file_content|write_to_file)$/i.test(name) || /\btools\.apply_patch\s*\(/.test(rawCode);
|
|
194
194
|
const succeeded = Boolean(command) && !failed && (status === 0 || /(?:^|\n)(?:# fail 0|.*\b\d+ passed\b|OK)\s*$/m.test(text));
|
|
195
195
|
const id = hook.tool_use_id ?? hook.toolUseId ?? hook.call_id;
|
|
196
|
+
const tools = Array.isArray(hook.tools) ? [...new Set(hook.tools.map((t) => (typeof t === 'string' ? t : t?.name)).filter(validTool))] : [];
|
|
196
197
|
return {
|
|
197
198
|
host,
|
|
198
199
|
sid: digest(`${host}:${sid}`).slice(0, 24),
|
|
199
200
|
event,
|
|
200
201
|
name,
|
|
201
202
|
command,
|
|
203
|
+
checkEvidence: command
|
|
204
|
+
? 'eligible'
|
|
205
|
+
: nested.length > 1
|
|
206
|
+
? 'ambiguous'
|
|
207
|
+
: typeof input?.command === 'string' || typeof input?.cmd === 'string' || nestedCommand
|
|
208
|
+
? 'unsupported'
|
|
209
|
+
: undefined,
|
|
202
210
|
failed,
|
|
203
211
|
succeeded,
|
|
204
212
|
edit,
|
|
@@ -210,12 +218,8 @@ export function normalizeEvent(hook, host) {
|
|
|
210
218
|
capabilities: Object.entries(CAPABILITIES)
|
|
211
219
|
.filter(([, re]) => re.test(`${name} ${JSON.stringify(input).slice(0, 32000)}`))
|
|
212
220
|
.map(([key]) => key),
|
|
213
|
-
tools:
|
|
214
|
-
|
|
215
|
-
.map((t) => (typeof t === 'string' ? t : t?.name))
|
|
216
|
-
.filter(validTool)
|
|
217
|
-
.slice(0, CATALOG_LIMIT)
|
|
218
|
-
: [],
|
|
221
|
+
tools: tools.slice(0, CATALOG_LIMIT),
|
|
222
|
+
toolsComplete: Array.isArray(hook.tools) ? hook.tools_complete !== false && tools.length <= CATALOG_LIMIT : undefined,
|
|
219
223
|
};
|
|
220
224
|
}
|
|
221
225
|
|
|
@@ -290,13 +294,32 @@ export function processEvent(state, e, now = Date.now()) {
|
|
|
290
294
|
state.receipts = [...state.receipts, { kind, host: e.host, session: e.sid, t: now }].slice(-200);
|
|
291
295
|
};
|
|
292
296
|
host.used = [...new Set([...host.used, ...e.capabilities])];
|
|
293
|
-
if (validTool(e.name) && host.usedTools.length <
|
|
294
|
-
// Servers are tracked on their own: a used server must stay protected after the
|
|
297
|
+
if (validTool(e.name) && host.usedTools.length < CATALOG_LIMIT) host.usedTools = [...new Set([...host.usedTools, e.name])];
|
|
298
|
+
// Servers are tracked on their own: a used server must stay protected after the tool-name list fills up.
|
|
295
299
|
const server = serverOf(e.host, e.name);
|
|
296
300
|
if (server && (host.usedServers ??= []).length < 200) host.usedServers = [...new Set([...host.usedServers, normServer(server)])];
|
|
301
|
+
// Record use before catalog discovery, even when the bounded tool-name history is full.
|
|
302
|
+
if (e.host === 'claude' && validTool(e.name) && Object.keys(host.catalog).length < CATALOG_LIMIT)
|
|
303
|
+
host.catalog[e.name] ??= { used: true, sessions: [] };
|
|
297
304
|
for (const tool of e.tools) {
|
|
298
305
|
if (Object.keys(host.catalog).length < CATALOG_LIMIT) host.catalog[tool] ??= { used: host.usedTools.includes(tool), sessions: [] };
|
|
299
306
|
}
|
|
307
|
+
if (e.toolsComplete !== undefined) host.catalogComplete = e.toolsComplete;
|
|
308
|
+
if (Array.isArray(e.servers)) {
|
|
309
|
+
const available = [...new Set(e.servers.filter(validTool).map(normServer).filter(validTool))].slice(0, CATALOG_LIMIT);
|
|
310
|
+
host.serverSessions ??= {};
|
|
311
|
+
if (['SessionStart', 'UserPromptSubmit'].includes(e.event)) {
|
|
312
|
+
for (const name of Object.keys(host.serverSessions)) if (!available.includes(name)) delete host.serverSessions[name];
|
|
313
|
+
session.servers ??= available;
|
|
314
|
+
}
|
|
315
|
+
if (['Stop', 'SessionEnd'].includes(e.event) && !host.finished.includes(e.sid)) {
|
|
316
|
+
for (const name of session.servers ?? []) {
|
|
317
|
+
if (!available.includes(name)) continue;
|
|
318
|
+
if (!Object.hasOwn(host.serverSessions, name) && Object.keys(host.serverSessions).length >= CATALOG_LIMIT) continue;
|
|
319
|
+
host.serverSessions[name] = [...new Set([...(host.serverSessions[name] ?? []), e.sid])].slice(-5);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
300
323
|
if (Object.hasOwn(host.catalog, e.name)) host.catalog[e.name].used = true;
|
|
301
324
|
if (e.event === 'SessionStart' || (e.host === 'grok' && /^PostToolUse(?:Failure)?$/.test(e.event) && !session.injected)) {
|
|
302
325
|
if (e.host === 'grok' && e.event === 'SessionStart') return {};
|
|
@@ -320,12 +343,18 @@ export function processEvent(state, e, now = Date.now()) {
|
|
|
320
343
|
if (!host.finished.includes(e.sid)) {
|
|
321
344
|
host.finished = [...host.finished, e.sid].slice(-1000);
|
|
322
345
|
host.completed++;
|
|
323
|
-
for (const name of e.tools) {
|
|
346
|
+
for (const name of e.toolsComplete === false ? [] : e.tools) {
|
|
324
347
|
const tool = host.catalog[name];
|
|
325
348
|
if (tool) tool.sessions = [...new Set([...tool.sessions, e.sid])].slice(-5);
|
|
326
349
|
}
|
|
327
350
|
}
|
|
328
351
|
} else if (/^PostToolUse(?:Failure)?$/.test(e.event)) {
|
|
352
|
+
if (e.checkEvidence) {
|
|
353
|
+
const evidence = (host.learningEvidence ??= { eligible: 0, passed: 0, failed: 0, unsupported: 0, ambiguous: 0 });
|
|
354
|
+
evidence[e.checkEvidence]++;
|
|
355
|
+
if (e.command && e.succeeded) evidence.passed++;
|
|
356
|
+
if (e.command && e.failed) evidence.failed++;
|
|
357
|
+
}
|
|
329
358
|
const turn = session.turn;
|
|
330
359
|
turn.calls++;
|
|
331
360
|
turn.trace = [
|
|
@@ -432,7 +461,15 @@ export function capabilityProposals(state, host, servers = []) {
|
|
|
432
461
|
.map(normServer),
|
|
433
462
|
]);
|
|
434
463
|
const kept = new Set(keep.map(normServer));
|
|
435
|
-
return servers
|
|
464
|
+
return servers
|
|
465
|
+
.filter(
|
|
466
|
+
(s) =>
|
|
467
|
+
s.enabled !== false &&
|
|
468
|
+
!used.has(normServer(s.name)) &&
|
|
469
|
+
!kept.has(normServer(s.name)) &&
|
|
470
|
+
(h.serverSessions?.[normServer(s.name)]?.length ?? 0) >= 5,
|
|
471
|
+
)
|
|
472
|
+
.map((s) => s.name);
|
|
436
473
|
};
|
|
437
474
|
if (host === 'codex') return [...Object.keys(CAPABILITIES).filter((c) => !h.used.includes(c) && !keep.includes(c)), ...idleServers()];
|
|
438
475
|
if (host === 'grok') return idleServers();
|
package/src/store.mjs
CHANGED
|
@@ -130,7 +130,7 @@ export function record(samples) {
|
|
|
130
130
|
const dir = stateDir();
|
|
131
131
|
mkdirSync(dir, { recursive: true });
|
|
132
132
|
const lastPath = join(dir, 'last.json');
|
|
133
|
-
/** @type {Record<string,
|
|
133
|
+
/** @type {Record<string, Sample>} */
|
|
134
134
|
let last = {};
|
|
135
135
|
try {
|
|
136
136
|
last = JSON.parse(readFileSync(lastPath, 'utf8'));
|
|
@@ -142,11 +142,11 @@ export function record(samples) {
|
|
|
142
142
|
const prev = last[key(s)];
|
|
143
143
|
return !prev || prev.pct !== s.pct || prev.reset !== s.reset;
|
|
144
144
|
});
|
|
145
|
+
for (const s of samples) if (!Number.isFinite(last[key(s)]?.t) || s.t >= last[key(s)].t) last[key(s)] = s;
|
|
146
|
+
writeAtomic(lastPath, JSON.stringify(last));
|
|
145
147
|
if (!fresh.length) return;
|
|
146
148
|
const file = join(dir, 'samples.jsonl');
|
|
147
149
|
appendFileSync(file, `${fresh.map((s) => JSON.stringify(s)).join('\n')}\n`);
|
|
148
|
-
for (const s of fresh) last[key(s)] = { pct: s.pct, reset: s.reset };
|
|
149
|
-
writeAtomic(lastPath, JSON.stringify(last));
|
|
150
150
|
if (statSync(file).size > PRUNE_BYTES)
|
|
151
151
|
writeAtomic(
|
|
152
152
|
file,
|
|
@@ -162,10 +162,9 @@ export function record(samples) {
|
|
|
162
162
|
*/
|
|
163
163
|
export function load(since) {
|
|
164
164
|
const file = join(stateDir(), 'samples.jsonl');
|
|
165
|
-
if (!existsSync(file)) return [];
|
|
166
165
|
/** @type {Sample[]} */
|
|
167
166
|
const out = [];
|
|
168
|
-
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
167
|
+
for (const line of (existsSync(file) ? readFileSync(file, 'utf8') : '').split('\n')) {
|
|
169
168
|
if (!line) continue;
|
|
170
169
|
try {
|
|
171
170
|
const s = JSON.parse(line);
|
|
@@ -174,5 +173,25 @@ export function load(since) {
|
|
|
174
173
|
/* skip a torn line from a concurrent write */
|
|
175
174
|
}
|
|
176
175
|
}
|
|
176
|
+
// The latest observation can be unchanged; keep one heartbeat per series rather than appending duplicates.
|
|
177
|
+
try {
|
|
178
|
+
const latest = JSON.parse(readFileSync(join(stateDir(), 'last.json'), 'utf8'));
|
|
179
|
+
for (const s of Object.values(latest)) {
|
|
180
|
+
if (
|
|
181
|
+
!s ||
|
|
182
|
+
!Number.isFinite(s.t) ||
|
|
183
|
+
s.t < since ||
|
|
184
|
+
!Number.isFinite(s.pct) ||
|
|
185
|
+
!Number.isFinite(s.reset) ||
|
|
186
|
+
s.reset <= 0 ||
|
|
187
|
+
typeof s.src !== 'string' ||
|
|
188
|
+
typeof s.win !== 'string'
|
|
189
|
+
)
|
|
190
|
+
continue;
|
|
191
|
+
if (!out.some((p) => p.src === s.src && p.win === s.win && p.sid === s.sid && p.t >= s.t)) out.push(s);
|
|
192
|
+
}
|
|
193
|
+
} catch {
|
|
194
|
+
/* legacy or unavailable heartbeat: retain the recorded observations */
|
|
195
|
+
}
|
|
177
196
|
return out;
|
|
178
197
|
}
|
package/src/trim.mjs
CHANGED
|
@@ -6,7 +6,11 @@ import { memoryDir } from './memory.mjs';
|
|
|
6
6
|
import { fmt } from './report.mjs';
|
|
7
7
|
|
|
8
8
|
/** @typedef {import('./usage.mjs').Usage} Usage */
|
|
9
|
-
/** @typedef {{skills:Set<string>, mcp:Set<string
|
|
9
|
+
/** @typedef {{skills:Set<string>, mcp:Set<string>, observed?:boolean, complete?:boolean}} Activity skills and MCP servers used in the period */
|
|
10
|
+
|
|
11
|
+
export const activityKnown = (/** @type {Activity} */ activity) => activity.observed !== false && activity.complete !== false;
|
|
12
|
+
export const UNKNOWN_ACTIVITY =
|
|
13
|
+
'Usage history is missing or incomplete; no configuration changes are authorized. Unverified servers and skills stay on.';
|
|
10
14
|
|
|
11
15
|
const DESC_CAP = 1536; // Claude Code's default skillListingMaxDescChars
|
|
12
16
|
|
|
@@ -129,9 +133,11 @@ const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '_');
|
|
|
129
133
|
* @param {Activity} used
|
|
130
134
|
*/
|
|
131
135
|
export function savings(c, used) {
|
|
132
|
-
const unusedSkills =
|
|
136
|
+
const unusedSkills = activityKnown(used)
|
|
137
|
+
? c.skills.filter((s) => !s.hidden && !skillUsed(s.name, used.skills)).sort((a, b) => b.tokens - a.tokens)
|
|
138
|
+
: [];
|
|
133
139
|
const usedMcp = new Set([...used.mcp].map(norm));
|
|
134
|
-
const unusedMcp = c.mcp.filter((s) => !usedMcp.has(norm(s)));
|
|
140
|
+
const unusedMcp = activityKnown(used) ? c.mcp.filter((s) => !usedMcp.has(norm(s))) : [];
|
|
135
141
|
return { unusedSkills, skillTokens: unusedSkills.reduce((a, s) => a + s.tokens, 0), unusedMcp };
|
|
136
142
|
}
|
|
137
143
|
|
|
@@ -143,6 +149,7 @@ export function savings(c, used) {
|
|
|
143
149
|
* @param {boolean} [share] totals only, including when no startup transcript is available
|
|
144
150
|
*/
|
|
145
151
|
export function trimReport(base, c, used, days, share = false) {
|
|
152
|
+
if (share && !activityKnown(used)) return `${UNKNOWN_ACTIVITY}\nTotals unavailable. https://limitcast.dev`;
|
|
146
153
|
const s = savings(c, used);
|
|
147
154
|
const fileTokens = c.files.reduce((a, f) => a + f.tokens, 0);
|
|
148
155
|
const visible = c.skills.filter((k) => !k.hidden);
|
|
@@ -156,6 +163,7 @@ export function trimReport(base, c, used, days, share = false) {
|
|
|
156
163
|
'Totals only; no configuration names or paths. https://limitcast.dev',
|
|
157
164
|
].join('\n');
|
|
158
165
|
const lines = ['# limitcast trim', ''];
|
|
166
|
+
if (!activityKnown(used)) lines.push(UNKNOWN_ACTIVITY, '');
|
|
159
167
|
if (base) {
|
|
160
168
|
lines.push(
|
|
161
169
|
`Your recorded Claude Code sessions start at **${fmt(base.median)} tokens** before your first message (median of ${base.sessions} interactive sessions, max ${fmt(base.max)}).`,
|
|
@@ -172,7 +180,7 @@ export function trimReport(base, c, used, days, share = false) {
|
|
|
172
180
|
`- **Hide ${s.unusedSkills.length} skills you haven't used in ${days} days** (~${fmt(s.skillTokens)} tokens): ${names.join(', ')}${s.unusedSkills.length > 12 ? ', ...' : ''}.`,
|
|
173
181
|
' In `~/.claude/settings.json`, set each to `"user-invocable-only"` under `skillOverrides`: `/name` still works, the model just stops seeing it.',
|
|
174
182
|
);
|
|
175
|
-
} else if (visible.length) lines.push(`- Every visible skill was used in the last ${days} days.`);
|
|
183
|
+
} else if (visible.length && activityKnown(used)) lines.push(`- Every visible skill was used in the last ${days} days.`);
|
|
176
184
|
if (s.unusedMcp.length) {
|
|
177
185
|
lines.push(
|
|
178
186
|
`- **Disable ${s.unusedMcp.length} MCP servers you haven't used in ${days} days**: ${s.unusedMcp.join(', ')}.`,
|
|
@@ -210,6 +218,7 @@ const tok = (/** @type {number} */ chars) => Math.round(chars / 4);
|
|
|
210
218
|
* @param {Activity|null} [usedMonth] servers used in 30 days. When set, only servers missing here are removable.
|
|
211
219
|
*/
|
|
212
220
|
export function measuredSavings(pieces, used, keep = [], usedMonth = null) {
|
|
221
|
+
const verified = activityKnown(used) && activityKnown(usedMonth ?? used);
|
|
213
222
|
const usedMcp = new Set([...used.mcp].map(norm));
|
|
214
223
|
const month = usedMonth ? new Set([...usedMonth.mcp].map(norm)) : null;
|
|
215
224
|
// Instructions and tool names spell a server differently ("claude.ai Postman" / "claude_ai_Postman"): merge by normalized name.
|
|
@@ -227,10 +236,10 @@ export function measuredSavings(pieces, used, keep = [], usedMonth = null) {
|
|
|
227
236
|
const skills = pieces.filter((p) => p.group === 'Skill listing' && !skillUsed(p.name, used.skills)).sort((a, b) => b.chars - a.chars);
|
|
228
237
|
const kept = [...mcp.values(), ...skills].filter((x) => keep.some((k) => norm(k) === norm(x.name))).map((x) => x.name);
|
|
229
238
|
const isKept = (/** @type {{name:string}} */ x) => kept.includes(x.name);
|
|
230
|
-
const unusedMcp = [...mcp.values()].filter((m) => !isKept(m)).sort((a, b) => b.chars - a.chars);
|
|
239
|
+
const unusedMcp = verified ? [...mcp.values()].filter((m) => !isKept(m)).sort((a, b) => b.chars - a.chars) : [];
|
|
231
240
|
const standingMcp = month ? unusedMcp.filter((m) => month.has(norm(m.name))) : [];
|
|
232
|
-
const staleMcp = month ? unusedMcp.filter((m) => !month.has(norm(m.name))) : unusedMcp;
|
|
233
|
-
const unusedSkills = skills.filter((s) => !isKept(s));
|
|
241
|
+
const staleMcp = verified ? (month ? unusedMcp.filter((m) => !month.has(norm(m.name))) : unusedMcp) : [];
|
|
242
|
+
const unusedSkills = verified ? skills.filter((s) => !isKept(s)) : [];
|
|
234
243
|
const chars = staleMcp.reduce((a, m) => a + m.chars, 0) + unusedSkills.reduce((a, s) => a + s.chars, 0);
|
|
235
244
|
return { unusedMcp, standingMcp, staleMcp, unusedSkills, tokens: tok(chars), kept };
|
|
236
245
|
}
|
|
@@ -248,6 +257,7 @@ export function startupReport(base, b, used, days, keep = [], usedMonth = null)
|
|
|
248
257
|
const s = measuredSavings(b.pieces, used, keep, usedMonth);
|
|
249
258
|
const median = base?.median ?? 0;
|
|
250
259
|
const lines = ['# limitcast trim', ''];
|
|
260
|
+
if (!activityKnown(used) || !activityKnown(usedMonth ?? used)) lines.push(UNKNOWN_ACTIVITY, '');
|
|
251
261
|
if (base) {
|
|
252
262
|
lines.push(
|
|
253
263
|
`Your recorded Claude Code sessions start at **${fmt(median)} tokens** before your first message (median of ${base.sessions} interactive sessions).`,
|
|
@@ -294,7 +304,8 @@ export function startupReport(base, b, used, days, keep = [], usedMonth = null)
|
|
|
294
304
|
);
|
|
295
305
|
}
|
|
296
306
|
if (s.kept.length) lines.push(`- **Would keep ${s.kept.length} on your keep-list** (\`trim --apply\` never touches them): ${s.kept.join(', ')}.`);
|
|
297
|
-
else if (!s.unusedMcp.length && !s.unusedSkills.length
|
|
307
|
+
else if (!s.unusedMcp.length && !s.unusedSkills.length && activityKnown(used) && activityKnown(usedMonth ?? used))
|
|
308
|
+
lines.push('- Nothing unused. Everything that loads was used in the period.');
|
|
298
309
|
|
|
299
310
|
/** @type {Map<string, number>} */
|
|
300
311
|
const groups = new Map();
|
|
@@ -334,6 +345,7 @@ export function startupReport(base, b, used, days, keep = [], usedMonth = null)
|
|
|
334
345
|
* @param {Activity|null} [usedMonth] servers used in 30 days
|
|
335
346
|
*/
|
|
336
347
|
export function shareSummary(base, b, used, days, keep = [], usedMonth = null) {
|
|
348
|
+
if (!activityKnown(used) || !activityKnown(usedMonth ?? used)) return `${UNKNOWN_ACTIVITY}\nTotals unavailable. https://limitcast.dev`;
|
|
337
349
|
const s = measuredSavings(b.pieces, used, keep, usedMonth);
|
|
338
350
|
/** @type {Map<string, number>} */
|
|
339
351
|
const groups = new Map();
|
package/src/usage.mjs
CHANGED
|
@@ -61,20 +61,30 @@ export function claudeUsage(line, seen, session) {
|
|
|
61
61
|
* @param {import('./trim.mjs').Activity} act
|
|
62
62
|
*/
|
|
63
63
|
export function claudeActivity(line, act) {
|
|
64
|
-
if (line.
|
|
65
|
-
for (const m of line.matchAll(/<command-name>\/?([^<\s]+)<\/command-name>/g)) act.skills.add(m[1]);
|
|
66
|
-
}
|
|
67
|
-
if (!line.includes('"name":"Skill"') && !line.includes('"name":"mcp__')) return;
|
|
64
|
+
if (!line.trim()) return;
|
|
68
65
|
let ev;
|
|
69
66
|
try {
|
|
70
67
|
ev = JSON.parse(line);
|
|
71
68
|
} catch {
|
|
69
|
+
act.complete = false;
|
|
72
70
|
return;
|
|
73
71
|
}
|
|
74
72
|
const content = ev?.message?.content;
|
|
73
|
+
const texts =
|
|
74
|
+
typeof content === 'string'
|
|
75
|
+
? [content]
|
|
76
|
+
: Array.isArray(content)
|
|
77
|
+
? content.filter((c) => c?.type === 'text' && typeof c.text === 'string').map((c) => c.text)
|
|
78
|
+
: [];
|
|
79
|
+
for (const text of texts) for (const m of text.matchAll(/<command-name>\/?([^<\s]+)<\/command-name>/g)) act.skills.add(m[1]);
|
|
75
80
|
if (!Array.isArray(content)) return;
|
|
81
|
+
if (ev.type === 'assistant') act.observed = true;
|
|
76
82
|
for (const c of content) {
|
|
77
|
-
if (c?.type !== 'tool_use'
|
|
83
|
+
if (c?.type !== 'tool_use') continue;
|
|
84
|
+
if (typeof c.name !== 'string') {
|
|
85
|
+
act.complete = false;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
78
88
|
if (c.name === 'Skill' && c.input?.skill) act.skills.add(String(c.input.skill));
|
|
79
89
|
else if (c.name.startsWith('mcp__')) act.mcp.add(c.name.split('__')[1] ?? '');
|
|
80
90
|
}
|
|
@@ -226,6 +236,10 @@ function summaryKind(dir) {
|
|
|
226
236
|
* @returns {Promise<Usage[]>}
|
|
227
237
|
*/
|
|
228
238
|
export async function readUsage(since, roots = {}, activity) {
|
|
239
|
+
if (activity) {
|
|
240
|
+
activity.observed = false;
|
|
241
|
+
activity.complete = true;
|
|
242
|
+
}
|
|
229
243
|
/** @type {Usage[]} */
|
|
230
244
|
const out = [];
|
|
231
245
|
// Parsed transcripts are cached by size and mtime: only new or changed ones are read again.
|
|
@@ -235,7 +249,7 @@ export async function readUsage(since, roots = {}, activity) {
|
|
|
235
249
|
const next = {};
|
|
236
250
|
/**
|
|
237
251
|
* @param {string} file
|
|
238
|
-
* @param {(file:string)=>Promise<{u:Usage[], a?:{skills:string[], mcp:string[]}}>} parse
|
|
252
|
+
* @param {(file:string)=>Promise<{u:Usage[], a?:{skills:string[], mcp:string[], observed:boolean, complete:boolean}}>} parse
|
|
239
253
|
*/
|
|
240
254
|
const cached = async (file, parse) => {
|
|
241
255
|
const st = statSync(file);
|
|
@@ -251,17 +265,19 @@ export async function readUsage(since, roots = {}, activity) {
|
|
|
251
265
|
const seen = new Set();
|
|
252
266
|
const session = basename(f, '.jsonl');
|
|
253
267
|
/** @type {import('./trim.mjs').Activity} */
|
|
254
|
-
const act = { skills: new Set(), mcp: new Set() };
|
|
268
|
+
const act = { skills: new Set(), mcp: new Set(), observed: false, complete: true };
|
|
255
269
|
const u = [];
|
|
256
270
|
for await (const line of lines(f)) {
|
|
257
271
|
claudeActivity(line, act);
|
|
258
272
|
const x = claudeUsage(line, seen, session);
|
|
259
273
|
if (x) u.push(x);
|
|
260
274
|
}
|
|
261
|
-
return { u, a: { skills: [...act.skills], mcp: [...act.mcp] } };
|
|
275
|
+
return { u, a: { skills: [...act.skills], mcp: [...act.mcp], observed: act.observed, complete: act.complete } };
|
|
262
276
|
});
|
|
263
277
|
for (const u of e.u) if (u.t >= since) out.push(u);
|
|
264
278
|
if (activity && e.a) {
|
|
279
|
+
activity.observed ||= e.a.observed === true;
|
|
280
|
+
activity.complete &&= e.a.complete === true;
|
|
265
281
|
for (const s of e.a.skills) activity.skills.add(s);
|
|
266
282
|
for (const m of e.a.mcp) activity.mcp.add(m);
|
|
267
283
|
}
|
|
@@ -296,10 +312,10 @@ export async function readUsage(since, roots = {}, activity) {
|
|
|
296
312
|
}
|
|
297
313
|
|
|
298
314
|
const CACHE_KEEP_MS = 35 * 86400_000;
|
|
299
|
-
const USAGE_CACHE_VERSION =
|
|
315
|
+
const USAGE_CACHE_VERSION = 6; // 6: text-block slash commands; 5: activity completeness. Re-read older entries before pruning.
|
|
300
316
|
const usageCacheFile = () => join(stateDir(), 'usage-cache.json');
|
|
301
317
|
|
|
302
|
-
/** @returns {Record<string, {s:number, m:number, u:Usage[], a?:{skills:string[], mcp:string[]}}>} */
|
|
318
|
+
/** @returns {Record<string, {s:number, m:number, u:Usage[], a?:{skills:string[], mcp:string[], observed:boolean, complete:boolean}}>} */
|
|
303
319
|
function loadUsageCache() {
|
|
304
320
|
try {
|
|
305
321
|
const d = JSON.parse(readFileSync(usageCacheFile(), 'utf8'));
|