limitcast 0.19.4 → 0.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/bin/limitcast.mjs +9 -8
- package/package.json +2 -2
- package/src/apply.mjs +123 -114
- package/src/codex.mjs +70 -51
- package/src/forecast.mjs +1 -1
- package/src/grok.mjs +38 -29
- package/src/guard.mjs +1 -1
- package/src/install.mjs +3 -14
- package/src/optimize-cli.mjs +52 -4
- package/src/optimize.mjs +48 -11
- package/src/store.mjs +100 -36
- package/src/toollimit.mjs +6 -5
- package/src/transaction.mjs +93 -0
- package/src/trim.mjs +20 -8
- package/src/usage.mjs +26 -10
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
<a href="https://www.npmjs.com/package/limitcast"><code>npm · limitcast</code></a>
|
|
7
7
|
<a href="https://github.com/SamStull9007/limitcast/actions/workflows/ci.yml"><img src="https://github.com/SamStull9007/limitcast/actions/workflows/ci.yml/badge.svg" alt="CI status"></a>
|
|
8
8
|
<a href="LICENSE"><code>MIT license</code></a>
|
|
9
|
-
<a href="https://nodejs.org"><code>Node.js
|
|
9
|
+
<a href="https://nodejs.org"><code>Node.js 22+</code></a>
|
|
10
10
|
</p>
|
|
11
11
|
|
|
12
12
|
<p align="center">
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
|
|
43
43
|
<a id="free-and-open-source"></a>
|
|
44
44
|
|
|
45
|
-
**Free and open source.** All features are included. No Limitcast account, license key, or subscription required. Runs locally on **macOS and Linux** with **Node.js
|
|
45
|
+
**Free and open source.** All features are included. No Limitcast account, license key, or subscription required. Runs locally on **macOS and Linux** with **Node.js 22+**.
|
|
46
46
|
|
|
47
47
|
<a id="install"></a>
|
|
48
48
|
|
|
@@ -140,10 +140,11 @@ Your findings depend on your local sessions. `trim` inspects first. Use `trim ke
|
|
|
140
140
|
|
|
141
141
|
Limitcast reads usage readings and session logs already on your machine. Reports remain local, sharing totals is voluntary, and no billing-service connection is required.
|
|
142
142
|
|
|
143
|
-
|
|
143
|
+
Three optional features make network requests, all **off by default**:
|
|
144
144
|
|
|
145
145
|
- **Phone or webhook notifications** send notification text to the service you choose.
|
|
146
146
|
- **Grok weekly usage** reads Grok's existing login and sends it only to grok.com to retrieve your usage. Redirects are refused; the login is never stored or logged by Limitcast.
|
|
147
|
+
- **Optimizer model learning/judging** uses your authenticated Codex CLI and its configured model service. It sends allowlisted check commands, counts and hashed identities; it excludes raw prompts, source text, transcripts and tool output. Calls consume your Codex allowance. [Scope and controls →](docs/optimizer.md#optional-model-learning-and-judging)
|
|
147
148
|
|
|
148
149
|
Context reductions are estimates against a recorded baseline, not measured causal savings or a lower subscription bill. Forecasts depend on observed usage. [How forecasting and measurement work →](docs/usage.md#how-the-forecast-works)
|
|
149
150
|
|
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';
|
|
@@ -888,7 +888,9 @@ if (cmd === '_optimize-hook') {
|
|
|
888
888
|
console.log(
|
|
889
889
|
(changed.length
|
|
890
890
|
? `✓ 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`
|
|
891
|
-
:
|
|
891
|
+
: r.unknown.length
|
|
892
|
+
? 'Nothing to turn off: usage history is missing or incomplete, so unverified servers stay on.'
|
|
893
|
+
: 'Nothing to turn off: every server that is on was used or is on your keep-list.') + keptNote(r.kept),
|
|
892
894
|
);
|
|
893
895
|
} else
|
|
894
896
|
console.log(
|
|
@@ -1001,12 +1003,10 @@ if (cmd === '_optimize-hook') {
|
|
|
1001
1003
|
: null;
|
|
1002
1004
|
if (hook) {
|
|
1003
1005
|
const lines = d?.alert ? [driftMessage(d, host)] : [];
|
|
1004
|
-
//
|
|
1005
|
-
const re = host === 'claude' ? reapplyTrim() : { reapplied: [] };
|
|
1006
|
-
if (re.
|
|
1007
|
-
lines.push(
|
|
1008
|
-
`limitcast: Claude Code had undone ${re.reapplied.length} of your trim cuts; they're back from your next session. (limitcast trim --undo to drop them)`,
|
|
1009
|
-
);
|
|
1006
|
+
// A host rewrite cannot be distinguished from a user edit: preserve the current settings.
|
|
1007
|
+
const re = host === 'claude' ? reapplyTrim() : { reapplied: [], released: [] };
|
|
1008
|
+
if (re.released.length)
|
|
1009
|
+
lines.push(`limitcast: ${re.released.length} trim settings changed; your current choices were preserved. Run limitcast trim to review.`);
|
|
1010
1010
|
// Once a week, what limitcast did: shown to the user at session start, never to the model.
|
|
1011
1011
|
if (weeklyDue(now)) {
|
|
1012
1012
|
const since = now - 7 * 86400_000;
|
|
@@ -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.
|
|
3
|
+
"version": "0.20.1",
|
|
4
4
|
"description": "Claude Code usage limits: forecast Codex and Grok too.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"src"
|
|
12
12
|
],
|
|
13
13
|
"engines": {
|
|
14
|
-
"node": ">=
|
|
14
|
+
"node": ">=22"
|
|
15
15
|
},
|
|
16
16
|
"os": [
|
|
17
17
|
"darwin",
|
package/src/apply.mjs
CHANGED
|
@@ -1,22 +1,10 @@
|
|
|
1
1
|
// @ts-check
|
|
2
|
-
import {
|
|
3
|
-
chmodSync,
|
|
4
|
-
closeSync,
|
|
5
|
-
copyFileSync,
|
|
6
|
-
existsSync,
|
|
7
|
-
mkdirSync,
|
|
8
|
-
openSync,
|
|
9
|
-
readdirSync,
|
|
10
|
-
readFileSync,
|
|
11
|
-
readSync,
|
|
12
|
-
renameSync,
|
|
13
|
-
statSync,
|
|
14
|
-
writeFileSync,
|
|
15
|
-
} from 'node:fs';
|
|
2
|
+
import { closeSync, copyFileSync, existsSync, openSync, readdirSync, readFileSync, readSync } from 'node:fs';
|
|
16
3
|
import { homedir } from 'node:os';
|
|
17
4
|
import { join } from 'node:path';
|
|
18
5
|
import { readSettings, settingsPath } from './install.mjs';
|
|
19
|
-
import { stateDir, updateConfig } from './store.mjs';
|
|
6
|
+
import { stateDir, updateConfig, withStateLock } from './store.mjs';
|
|
7
|
+
import { commitTransaction, editJson, readLedger, recoverTransaction } from './transaction.mjs';
|
|
20
8
|
|
|
21
9
|
// `trim --apply`: hide unused skills and turn off unused MCP servers through Claude Code's own settings.
|
|
22
10
|
// Skills: `skillOverrides` in ~/.claude/settings.json ("user-invocable-only": the model stops seeing it, /name still works).
|
|
@@ -118,6 +106,8 @@ export function installedPlugins(dir = configDir()) {
|
|
|
118
106
|
* localSkills: folder names of personal and project skills; keep: the `trim keep` list, never hidden or disabled
|
|
119
107
|
*/
|
|
120
108
|
export function planTrim({ skills, mcp, cwd, settings, claudeJson, plugins, projectMcpJson, localSkills, keep = [] }) {
|
|
109
|
+
validateTrimSettings(settings);
|
|
110
|
+
validateTrimSettings(claudeJson);
|
|
121
111
|
// "x:y" is a plugin skill (namespaced by its plugin) unless x is one of your own skill folders with nested skills.
|
|
122
112
|
// Plugins can load from places installed_plugins.json doesn't list, so the namespace alone decides.
|
|
123
113
|
const isPluginSkill = (/** @type {string} */ n) => n.includes(':') && !localSkills.has(n.split(':')[0]);
|
|
@@ -156,26 +146,35 @@ function backup(path) {
|
|
|
156
146
|
if (existsSync(path)) copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
|
|
157
147
|
}
|
|
158
148
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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;
|
|
170
161
|
}
|
|
171
162
|
|
|
172
163
|
/** @returns {{at:number, cwd:string, skills:{name:string, prev?:string}[], mcp:string[]}[]} */
|
|
173
164
|
export function loadLedger() {
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
165
|
+
const entries = readLedger(ledgerPath());
|
|
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
|
+
)
|
|
176
|
+
throw new Error('invalid Claude trim ledger');
|
|
177
|
+
return entries;
|
|
179
178
|
}
|
|
180
179
|
|
|
181
180
|
/**
|
|
@@ -184,32 +183,45 @@ export function loadLedger() {
|
|
|
184
183
|
* @param {{cwd:string, now:number, settings?:string, claudeJson?:string}} o
|
|
185
184
|
*/
|
|
186
185
|
export function applyTrim(plan, { cwd, now, settings = settingsPath(), claudeJson = claudeJsonPath() }) {
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
186
|
+
return withStateLock(() => {
|
|
187
|
+
recoverTransaction(ledgerPath());
|
|
188
|
+
const ledger = loadLedger();
|
|
189
|
+
const updates = [];
|
|
190
|
+
const entry = { at: now, cwd, skills: /** @type {{name:string, prev?:string}[]} */ ([]), mcp: /** @type {string[]} */ ([]) };
|
|
191
|
+
if (plan.hide.length) {
|
|
192
|
+
updates.push(
|
|
193
|
+
editJson(settings, (cfg) => {
|
|
194
|
+
validateTrimSettings(cfg);
|
|
195
|
+
cfg.skillOverrides ??= {};
|
|
196
|
+
for (const name of plan.hide) {
|
|
197
|
+
if (cfg.skillOverrides[name] !== undefined && cfg.skillOverrides[name] !== 'on') continue;
|
|
198
|
+
entry.skills.push(name in cfg.skillOverrides ? { name, prev: cfg.skillOverrides[name] } : { name });
|
|
199
|
+
cfg.skillOverrides[name] = 'user-invocable-only';
|
|
200
|
+
}
|
|
201
|
+
}),
|
|
202
|
+
);
|
|
195
203
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
204
|
+
if (plan.disable.length) {
|
|
205
|
+
updates.push(
|
|
206
|
+
editJson(claudeJson, (cj) => {
|
|
207
|
+
validateTrimSettings(cj);
|
|
208
|
+
cj.projects ??= {};
|
|
209
|
+
cj.projects[cwd] ??= {};
|
|
210
|
+
const list = (cj.projects[cwd].disabledMcpServers ??= []);
|
|
211
|
+
for (const name of plan.disable)
|
|
212
|
+
if (!list.includes(name)) {
|
|
213
|
+
list.push(name);
|
|
214
|
+
entry.mcp.push(name);
|
|
215
|
+
}
|
|
216
|
+
}),
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
if (entry.skills.length || entry.mcp.length) {
|
|
220
|
+
for (const change of updates) backup(change.path);
|
|
221
|
+
commitTransaction(ledgerPath(), [...ledger, entry], updates);
|
|
222
|
+
}
|
|
223
|
+
return entry;
|
|
224
|
+
});
|
|
213
225
|
}
|
|
214
226
|
|
|
215
227
|
/**
|
|
@@ -218,74 +230,71 @@ export function applyTrim(plan, { cwd, now, settings = settingsPath(), claudeJso
|
|
|
218
230
|
* @param {{settings?:string, claudeJson?:string}} [o]
|
|
219
231
|
*/
|
|
220
232
|
export function undoTrim({ settings = settingsPath(), claudeJson = claudeJsonPath() } = {}) {
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
233
|
+
return withStateLock(() => {
|
|
234
|
+
recoverTransaction(ledgerPath());
|
|
235
|
+
const ledger = loadLedger();
|
|
236
|
+
const last = ledger.pop();
|
|
237
|
+
if (!last) return null;
|
|
238
|
+
const updates = [];
|
|
239
|
+
if (last.skills.length && existsSync(settings)) {
|
|
240
|
+
updates.push(
|
|
241
|
+
editJson(settings, (cfg) => {
|
|
242
|
+
validateTrimSettings(cfg);
|
|
243
|
+
for (const s of last.skills) {
|
|
244
|
+
if (cfg.skillOverrides?.[s.name] !== 'user-invocable-only') continue;
|
|
245
|
+
if (s.prev === undefined) delete cfg.skillOverrides[s.name];
|
|
246
|
+
else cfg.skillOverrides[s.name] = s.prev;
|
|
247
|
+
}
|
|
248
|
+
}),
|
|
249
|
+
);
|
|
231
250
|
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
251
|
+
if (last.mcp.length && existsSync(claudeJson)) {
|
|
252
|
+
updates.push(
|
|
253
|
+
editJson(claudeJson, (cj) => {
|
|
254
|
+
validateTrimSettings(cj);
|
|
255
|
+
const p = cj.projects?.[last.cwd];
|
|
256
|
+
if (p?.disabledMcpServers) p.disabledMcpServers = p.disabledMcpServers.filter((/** @type {string} */ n) => !last.mcp.includes(n));
|
|
257
|
+
}),
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
for (const change of updates) backup(change.path);
|
|
261
|
+
commitTransaction(ledgerPath(), ledger, updates);
|
|
262
|
+
return last;
|
|
263
|
+
});
|
|
243
264
|
}
|
|
244
265
|
|
|
245
266
|
/**
|
|
246
|
-
*
|
|
247
|
-
* every change at once: then put them back. When only some are gone, you turned those back on yourself (/mcp,
|
|
248
|
-
* /skills): leave them and forget them, so limitcast never fights your choice. Checked per file.
|
|
267
|
+
* Release ownership of settings that changed after apply. Never infer that a user's choice was a host rewrite.
|
|
249
268
|
* @param {{settings?:string, claudeJson?:string}} [o]
|
|
250
269
|
* @returns {{reapplied:string[], released:string[]}}
|
|
251
270
|
*/
|
|
252
271
|
export function reapplyTrim({ settings = settingsPath(), claudeJson = claudeJsonPath() } = {}) {
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
cfg.skillOverrides
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
} else if (gone.length) {
|
|
267
|
-
last.skills = last.skills.filter((s) => !gone.includes(s));
|
|
268
|
-
out.released.push(...gone.map((s) => s.name));
|
|
272
|
+
return withStateLock(() => {
|
|
273
|
+
recoverTransaction(ledgerPath());
|
|
274
|
+
const ledger = loadLedger();
|
|
275
|
+
const last = ledger.at(-1);
|
|
276
|
+
const out = { reapplied: /** @type {string[]} */ ([]), released: /** @type {string[]} */ ([]) };
|
|
277
|
+
if (!last) return out;
|
|
278
|
+
if (last.skills.length) {
|
|
279
|
+
const cfg = validateTrimSettings(existsSync(settings) ? readSettings(settings) : {});
|
|
280
|
+
const gone = last.skills.filter((s) => cfg.skillOverrides?.[s.name] !== 'user-invocable-only');
|
|
281
|
+
if (gone.length) {
|
|
282
|
+
last.skills = last.skills.filter((s) => !gone.includes(s));
|
|
283
|
+
out.released.push(...gone.map((s) => s.name));
|
|
284
|
+
}
|
|
269
285
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
cj.projects[last.cwd].disabledMcpServers = [...list, ...gone];
|
|
279
|
-
backup(claudeJson);
|
|
280
|
-
writeJson(claudeJson, cj);
|
|
281
|
-
out.reapplied.push(...gone);
|
|
282
|
-
} else if (gone.length) {
|
|
283
|
-
last.mcp = last.mcp.filter((n) => !gone.includes(n));
|
|
284
|
-
out.released.push(...gone);
|
|
286
|
+
if (last.mcp.length) {
|
|
287
|
+
const cj = validateTrimSettings(existsSync(claudeJson) ? readSettings(claudeJson) : {});
|
|
288
|
+
const list = cj.projects?.[last.cwd]?.disabledMcpServers ?? [];
|
|
289
|
+
const gone = last.mcp.filter((n) => !list.includes(n));
|
|
290
|
+
if (gone.length) {
|
|
291
|
+
last.mcp = last.mcp.filter((n) => !gone.includes(n));
|
|
292
|
+
out.released.push(...gone);
|
|
293
|
+
}
|
|
285
294
|
}
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
295
|
+
if (out.released.length) commitTransaction(ledgerPath(), ledger, []);
|
|
296
|
+
return out;
|
|
297
|
+
});
|
|
289
298
|
}
|
|
290
299
|
|
|
291
300
|
/**
|
package/src/codex.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// @ts-check
|
|
2
|
-
import {
|
|
2
|
+
import { copyFileSync, createReadStream, existsSync, 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
|
-
import { stateDir } from './store.mjs';
|
|
6
|
+
import { stateDir, withStateLock } from './store.mjs';
|
|
7
|
+
import { commitTransaction, editText, readLedger, recoverTransaction } from './transaction.mjs';
|
|
7
8
|
import { jsonlFiles } from './usage.mjs';
|
|
8
9
|
|
|
9
10
|
// `limitcast trim --codex`: what Codex loads before you type (AGENTS.md, MCP servers) and which servers you never use.
|
|
@@ -71,19 +72,30 @@ export function setEnabled(toml, changes) {
|
|
|
71
72
|
*/
|
|
72
73
|
export async function codexUsedServers(since, root = join(codexHome(), 'sessions')) {
|
|
73
74
|
const used = new Set();
|
|
75
|
+
used.observed = false;
|
|
76
|
+
used.complete = true;
|
|
74
77
|
for (const f of jsonlFiles(root, since, (n) => n.startsWith('rollout-'))) {
|
|
75
78
|
const rl = createInterface({ input: createReadStream(f), crlfDelay: Infinity });
|
|
76
79
|
for await (const line of rl) {
|
|
77
|
-
if (line.
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
80
|
+
if (!line.trim()) continue;
|
|
81
|
+
try {
|
|
82
|
+
const row = JSON.parse(line);
|
|
83
|
+
const p = row.payload;
|
|
84
|
+
const item = p?.item;
|
|
85
|
+
if (row.type === 'response_item' && ['function_call', 'custom_tool_call'].includes(p?.type)) {
|
|
86
|
+
used.observed = true;
|
|
87
|
+
const server = /^mcp__(.+?)(?:__|$)/.exec(p.namespace ?? '')?.[1] ?? /^mcp__(.+?)__/.exec(p.name ?? '')?.[1];
|
|
88
|
+
if (server) used.add(norm(server));
|
|
89
|
+
if (typeof p.name !== 'string') used.complete = false;
|
|
90
|
+
if ([p.name, p.namespace].some((n) => typeof n === 'string' && n.startsWith('mcp__')) && !server) used.complete = false;
|
|
91
|
+
} else if (item?.type === 'McpToolCall') {
|
|
92
|
+
used.observed = true;
|
|
93
|
+
if (typeof item.server === 'string') used.add(norm(item.server));
|
|
94
|
+
else used.complete = false;
|
|
95
|
+
} else if (item?.type === 'CommandExecution') used.observed = true;
|
|
96
|
+
else if (/ToolCall$/.test(item?.type ?? '')) used.complete = false;
|
|
97
|
+
} catch {
|
|
98
|
+
used.complete = false;
|
|
87
99
|
}
|
|
88
100
|
}
|
|
89
101
|
}
|
|
@@ -156,8 +168,10 @@ export function codexTrimReport({ servers, used, usedMonth = null, startup, days
|
|
|
156
168
|
const on = servers.filter((s) => s.enabled !== false);
|
|
157
169
|
const idle = on.filter((s) => !used.has(norm(s.name)));
|
|
158
170
|
const kept = idle.filter((s) => keep.some((k) => norm(k) === norm(s.name)));
|
|
171
|
+
const history = usedMonth ?? used;
|
|
172
|
+
const unknown = history.complete === false || history.observed === false ? idle.filter((s) => !kept.includes(s)) : [];
|
|
159
173
|
const standing = usedMonth ? idle.filter((s) => !kept.includes(s) && usedMonth.has(norm(s.name))) : [];
|
|
160
|
-
const unused = idle.filter((s) => !kept.includes(s) && !standing.includes(s));
|
|
174
|
+
const unused = idle.filter((s) => !kept.includes(s) && !standing.includes(s) && !unknown.includes(s));
|
|
161
175
|
const tok = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
|
|
162
176
|
const out = ['# limitcast trim --codex', ''];
|
|
163
177
|
if (startup)
|
|
@@ -168,9 +182,14 @@ export function codexTrimReport({ servers, used, usedMonth = null, startup, days
|
|
|
168
182
|
'',
|
|
169
183
|
);
|
|
170
184
|
out.push(`## MCP servers: ${on.length} on, ${unused.length + standing.length} not used in ${days} days`);
|
|
185
|
+
if (unknown.length)
|
|
186
|
+
out.push(
|
|
187
|
+
'',
|
|
188
|
+
`Usage history is missing or incomplete; leaving ${unknown.length} unverified servers on. No pruning is authorized by missing telemetry.`,
|
|
189
|
+
);
|
|
171
190
|
if (standing.length)
|
|
172
191
|
out.push('', `${standing.length} used in the last 30 days, so \`trim --apply\` leaves them on:`, ...standing.map((s) => `- ${s.name}`));
|
|
173
|
-
if (!unused.length) out.push(kept.length || standing.length ? 'Nothing else to turn off.' : 'Every server that is on was used.');
|
|
192
|
+
if (!unused.length) out.push(kept.length || standing.length || unknown.length ? 'Nothing else to turn off.' : 'Every server that is on was used.');
|
|
174
193
|
else if (pro)
|
|
175
194
|
out.push(
|
|
176
195
|
...unused.map((s) => `- ${s.name}`),
|
|
@@ -188,25 +207,15 @@ export function codexTrimReport({ servers, used, usedMonth = null, startup, days
|
|
|
188
207
|
unused: unused.map((s) => s.name),
|
|
189
208
|
standing: standing.map((s) => s.name),
|
|
190
209
|
kept: kept.map((s) => s.name),
|
|
210
|
+
unknown: unknown.map((s) => s.name),
|
|
191
211
|
};
|
|
192
212
|
}
|
|
193
213
|
|
|
194
|
-
/** @param {string} path @param {string} text */
|
|
195
|
-
function writeText(path, text) {
|
|
196
|
-
const tmp = `${path}.limitcast-tmp`;
|
|
197
|
-
const mode = existsSync(path) ? statSync(path).mode & 0o777 : 0o600;
|
|
198
|
-
writeFileSync(tmp, text, { mode });
|
|
199
|
-
chmodSync(tmp, mode);
|
|
200
|
-
renameSync(tmp, path);
|
|
201
|
-
}
|
|
202
|
-
|
|
203
214
|
/** @returns {{at:number, servers:{name:string, prev:boolean|null}[]}[]} */
|
|
204
215
|
function loadLedger() {
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
return [];
|
|
209
|
-
}
|
|
216
|
+
const entries = readLedger(ledgerPath());
|
|
217
|
+
if (entries.some((e) => !Array.isArray(e.servers))) throw new Error('invalid Codex trim ledger');
|
|
218
|
+
return entries;
|
|
210
219
|
}
|
|
211
220
|
|
|
212
221
|
/**
|
|
@@ -214,31 +223,41 @@ function loadLedger() {
|
|
|
214
223
|
* @param {string[]} names
|
|
215
224
|
*/
|
|
216
225
|
export function applyCodexTrim(names, { now = Date.now(), path = codexConfigPath() } = {}) {
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
+
return withStateLock(() => {
|
|
227
|
+
recoverTransaction(ledgerPath());
|
|
228
|
+
const ledger = loadLedger();
|
|
229
|
+
if (!names.length || !existsSync(path)) return [];
|
|
230
|
+
let toml;
|
|
231
|
+
const update = editText(path, (text) => {
|
|
232
|
+
toml = text;
|
|
233
|
+
return setEnabled(text, Object.fromEntries(names.map((n) => [n, false])));
|
|
234
|
+
});
|
|
235
|
+
const before = new Map(codexServers(toml).map((s) => [s.name, s.enabled]));
|
|
236
|
+
copyFileSync(path, `${path}.limitcast-backup-${new Date(now).toISOString().replace(/[:.]/g, '-')}`);
|
|
237
|
+
const servers = names.map((name) => ({ name, prev: before.get(name) ?? null }));
|
|
238
|
+
commitTransaction(ledgerPath(), [...ledger, { at: now, servers }], [update]);
|
|
239
|
+
return servers;
|
|
240
|
+
});
|
|
226
241
|
}
|
|
227
242
|
|
|
228
243
|
/** Reverse the last --apply: each server goes back to its previous setting (or no `enabled` key). */
|
|
229
244
|
export function undoCodexTrim({ path = codexConfigPath() } = {}) {
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
245
|
+
return withStateLock(() => {
|
|
246
|
+
recoverTransaction(ledgerPath());
|
|
247
|
+
const ledger = loadLedger();
|
|
248
|
+
const last = ledger.pop();
|
|
249
|
+
if (!last || !existsSync(path)) return null;
|
|
250
|
+
const update = editText(path, (toml) => {
|
|
251
|
+
// Only servers still off: anything turned back on since is left as the user set it.
|
|
252
|
+
const off = new Set(
|
|
253
|
+
codexServers(toml)
|
|
254
|
+
.filter((s) => s.enabled === false)
|
|
255
|
+
.map((s) => s.name),
|
|
256
|
+
);
|
|
257
|
+
return setEnabled(toml, Object.fromEntries(last.servers.filter((s) => off.has(s.name)).map((s) => [s.name, s.prev])));
|
|
258
|
+
});
|
|
259
|
+
copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
|
|
260
|
+
commitTransaction(ledgerPath(), ledger, [update]);
|
|
261
|
+
return last;
|
|
262
|
+
});
|
|
244
263
|
}
|
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);
|