limitcast 0.18.2 → 0.18.3

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 CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  applyBlocked,
10
10
  applyTrim,
11
11
  claudeJsonPath,
12
+ editKeep,
12
13
  ensureDefaultKeep,
13
14
  getKeep,
14
15
  installedPlugins,
@@ -17,7 +18,6 @@ import {
17
18
  planTrim,
18
19
  projectMcpServers,
19
20
  reapplyTrim,
20
- setKeep,
21
21
  stillLoading,
22
22
  transcriptCwd,
23
23
  undoTrim,
@@ -723,7 +723,7 @@ if (cmd === 'status') {
723
723
  .split(',')
724
724
  .map((n) => n.trim())
725
725
  .filter(Boolean);
726
- if (names.length) setKeep(drop ? getKeep().filter((k) => !isKept(names, k)) : [...getKeep(), ...names]);
726
+ if (names.length) editKeep((keep) => (drop ? keep.filter((k) => !isKept(names, k)) : [...keep, ...names]));
727
727
  const keep = getKeep();
728
728
  console.log(keep.length ? `Kept by \`trim --apply\`: ${keep.join(', ')}` : 'Nothing on the keep-list. Example: limitcast trim keep ego-browser');
729
729
  process.exit(0);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limitcast",
3
- "version": "0.18.2",
3
+ "version": "0.18.3",
4
4
  "description": "Claude Code usage limits: forecast Codex and Grok too.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/apply.mjs CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  import { homedir } from 'node:os';
17
17
  import { join } from 'node:path';
18
18
  import { readSettings, settingsPath } from './install.mjs';
19
- import { stateDir, writeAtomic } from './store.mjs';
19
+ import { stateDir, updateConfig } from './store.mjs';
20
20
 
21
21
  // `trim --apply`: hide unused skills and turn off unused MCP servers through Claude Code's own settings.
22
22
  // Skills: `skillOverrides` in ~/.claude/settings.json ("user-invocable-only": the model stops seeing it, /name still works).
@@ -39,11 +39,13 @@ export const DEFAULT_KEEP = ['ego-browser'];
39
39
  export const APPLY_BLOCKED =
40
40
  'Nothing on the keep-list, so `trim --apply` would turn off every server that looks unused, including ego-browser. Run `limitcast trim keep ego-browser` first, or repeat with `--yes`.';
41
41
 
42
+ const keepFrom = (/** @type {any} */ cfg) =>
43
+ Array.isArray(cfg.trimKeep) ? cfg.trimKeep.filter((/** @type {unknown} */ n) => typeof n === 'string') : [];
44
+
42
45
  /** Names `trim --apply` never turns off or hides, from `limitcast trim keep`. @returns {string[]} */
43
46
  export function getKeep() {
44
47
  try {
45
- const k = JSON.parse(readFileSync(configFile(), 'utf8')).trimKeep;
46
- return Array.isArray(k) ? k.filter((n) => typeof n === 'string') : [];
48
+ return keepFrom(JSON.parse(readFileSync(configFile(), 'utf8')));
47
49
  } catch {
48
50
  return [];
49
51
  }
@@ -54,32 +56,29 @@ export function getKeep() {
54
56
  * @returns {{keep:string[], seeded:boolean}}
55
57
  */
56
58
  export function ensureDefaultKeep() {
57
- let cfg = {};
58
- try {
59
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
60
- } catch {
61
- cfg = {};
62
- }
63
- if (Object.hasOwn(cfg, 'trimKeep')) return { keep: getKeep(), seeded: false };
64
- setKeep(DEFAULT_KEEP);
65
- return { keep: [...DEFAULT_KEEP], seeded: true };
59
+ let seeded = false;
60
+ updateConfig((cfg) => {
61
+ if (Object.hasOwn(cfg, 'trimKeep')) return cfg;
62
+ seeded = true;
63
+ return { ...cfg, trimKeep: [...DEFAULT_KEEP] };
64
+ });
65
+ return { keep: seeded ? [...DEFAULT_KEEP] : getKeep(), seeded };
66
66
  }
67
67
 
68
68
  /** True when `--apply` must stop because nothing is protected and the user did not pass `--yes`. */
69
69
  export const applyBlocked = (/** @type {string[]} */ keep, /** @type {boolean} */ yes) => !yes && keep.length === 0;
70
70
 
71
- /** @param {string[]} names */
72
- export function setKeep(names) {
73
- let cfg = {};
74
- try {
75
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
76
- } catch {
77
- /* new */
78
- }
79
- mkdirSync(stateDir(), { recursive: true });
80
- writeAtomic(configFile(), JSON.stringify({ ...cfg, trimKeep: [...new Set(names)] }));
71
+ /**
72
+ * Change the keep-list under the settings lock, so two `trim keep` runs cannot undo each other.
73
+ * @param {(keep: string[]) => string[]} change
74
+ */
75
+ export function editKeep(change) {
76
+ updateConfig((cfg) => ({ ...cfg, trimKeep: [...new Set(change(keepFrom(cfg)))] }));
81
77
  }
82
78
 
79
+ /** @param {string[]} names */
80
+ export const setKeep = (names) => editKeep(() => names);
81
+
83
82
  /** Same server or skill under another spelling ("ego-browser" / "ego_browser") counts. @param {string[]} keep @param {string} name */
84
83
  export const isKept = (keep, name) => keep.some((k) => norm(k) === norm(name));
85
84
 
package/src/grok.mjs CHANGED
@@ -4,7 +4,7 @@ import { homedir } from 'node:os';
4
4
  import { dirname, join } from 'node:path';
5
5
  import { codexServers, setEnabled } from './codex.mjs';
6
6
  import { windowMs } from './forecast.mjs';
7
- import { KEEP_MS, stateDir, writeAtomic } from './store.mjs';
7
+ import { KEEP_MS, stateDir, updateConfig } from './store.mjs';
8
8
  import { grokRoot } from './usage.mjs';
9
9
 
10
10
  /** @typedef {import('./forecast.mjs').Sample} Sample */
@@ -182,18 +182,13 @@ export function getGrokBudget() {
182
182
  * @param {'5h'|'7d'} [win]
183
183
  */
184
184
  export function setGrokBudget(usd, win = '5h') {
185
- let cfg = {};
186
- try {
187
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
188
- } catch {
189
- /* new */
190
- }
191
- /** @type {{'5h'?:number, '7d'?:number}} */
192
- const cur = typeof cfg.grokBudget === 'number' ? { '5h': cfg.grokBudget } : { ...(cfg.grokBudget ?? {}) };
193
- if (usd === null) delete cur[win];
194
- else cur[win] = usd;
195
- mkdirSync(stateDir(), { recursive: true });
196
- writeAtomic(configFile(), JSON.stringify({ ...cfg, grokBudget: Object.keys(cur).length ? cur : null }));
185
+ updateConfig((cfg) => {
186
+ /** @type {{'5h'?:number, '7d'?:number}} */
187
+ const cur = typeof cfg.grokBudget === 'number' ? { '5h': cfg.grokBudget } : { ...(cfg.grokBudget ?? {}) };
188
+ if (usd === null) delete cur[win];
189
+ else cur[win] = usd;
190
+ return { ...cfg, grokBudget: Object.keys(cur).length ? cur : null };
191
+ });
197
192
  }
198
193
 
199
194
  /**
@@ -234,14 +229,7 @@ export function grokQuotaEnabled() {
234
229
 
235
230
  /** @param {boolean} on */
236
231
  export function setGrokQuota(on) {
237
- let cfg = {};
238
- try {
239
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
240
- } catch {
241
- /* new */
242
- }
243
- mkdirSync(stateDir(), { recursive: true });
244
- writeAtomic(configFile(), JSON.stringify({ ...cfg, grokQuota: on }));
232
+ updateConfig((cfg) => ({ ...cfg, grokQuota: on }));
245
233
  }
246
234
 
247
235
  /** @returns {QuotaState} */
package/src/plan.mjs CHANGED
@@ -3,7 +3,7 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { claudeAccounts } from './forecast.mjs';
5
5
  import { fmtUsd } from './prices.mjs';
6
- import { stateDir, writeAtomic } from './store.mjs';
6
+ import { stateDir, updateConfig } from './store.mjs';
7
7
 
8
8
  // `limitcast plan`: does your Claude plan fit how much you use? From a long-lived record of the peak of every
9
9
  // 5-hour and weekly window (the samples themselves are only kept for 8 days), it says whether you hit your limits often
@@ -42,14 +42,7 @@ export function getPlan() {
42
42
 
43
43
  /** @param {PlanId|null} plan */
44
44
  export function setPlan(plan) {
45
- let cfg = {};
46
- try {
47
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
48
- } catch {
49
- /* new */
50
- }
51
- mkdirSync(stateDir(), { recursive: true });
52
- writeAtomic(configFile(), JSON.stringify({ ...cfg, plan }));
45
+ updateConfig((cfg) => ({ ...cfg, plan }));
53
46
  }
54
47
 
55
48
  /**
package/src/store.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // @ts-check
2
- import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
 
@@ -19,6 +19,51 @@ export function writeAtomic(/** @type {string} */ path, /** @type {string} */ te
19
19
  renameSync(tmp, path);
20
20
  }
21
21
 
22
+ const LOCK_STALE_MS = 2_000; // the lock is held for one read and one write; older than this means its owner died
23
+ const LOCK_WAIT_MS = 5_000;
24
+
25
+ /**
26
+ * Change config.json under a lock: read it, let `change` return the new settings (or the same object to leave the file
27
+ * alone), write it. Without the lock, two commands that each read the file and then each write it lose one change.
28
+ * shortcut: two waiters that break the same stale lock in the same instant can both write; fix with a lockfile library if seen.
29
+ * @param {(cfg: any) => any} change
30
+ */
31
+ export function updateConfig(change) {
32
+ const dir = stateDir();
33
+ mkdirSync(dir, { recursive: true });
34
+ const file = join(dir, 'config.json');
35
+ const lock = `${file}.lock`;
36
+ const start = Date.now();
37
+ for (;;) {
38
+ try {
39
+ mkdirSync(lock); // atomic: exactly one process creates it
40
+ break;
41
+ } catch (e) {
42
+ if (/** @type {NodeJS.ErrnoException} */ (e).code !== 'EEXIST') throw e;
43
+ try {
44
+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) rmSync(lock, { recursive: true, force: true });
45
+ } catch {
46
+ /* released while we looked */
47
+ }
48
+ if (Date.now() - start > LOCK_WAIT_MS) throw new Error(`could not lock ${file}: another limitcast command is changing settings`);
49
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
50
+ }
51
+ }
52
+ try {
53
+ let cfg = {};
54
+ try {
55
+ cfg = JSON.parse(readFileSync(file, 'utf8'));
56
+ } catch {
57
+ /* new or corrupt: start fresh */
58
+ }
59
+ if (!cfg || typeof cfg !== 'object') cfg = {};
60
+ const next = change(cfg);
61
+ if (next !== cfg) writeAtomic(file, JSON.stringify(next));
62
+ } finally {
63
+ rmSync(lock, { recursive: true, force: true });
64
+ }
65
+ }
66
+
22
67
  /**
23
68
  * Append samples whose pct or reset changed since the last one for the same series.
24
69
  * The status line fires on every message, so unchanged readings are skipped.
package/src/subagents.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
- import { stateDir, writeAtomic } from './store.mjs';
5
+ import { stateDir, updateConfig } from './store.mjs';
6
6
 
7
7
  // Subagent receipts and budgets. A SubagentStop hook prices each finished subagent against the 5-hour window
8
8
  // (from the user's own calibration) and logs it; the guard holds new subagents once a window's budget is spent.
@@ -121,14 +121,7 @@ export function getBudget() {
121
121
 
122
122
  /** @param {number|null} pct */
123
123
  export function setBudget(pct) {
124
- let cfg = {};
125
- try {
126
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
127
- } catch {
128
- /* new */
129
- }
130
- mkdirSync(stateDir(), { recursive: true });
131
- writeAtomic(configFile(), JSON.stringify({ ...cfg, subagentBudget: pct }));
124
+ updateConfig((cfg) => ({ ...cfg, subagentBudget: pct }));
132
125
  }
133
126
 
134
127
  /** Whether the guard holds new subagents once today's share of a weekly window is used up (`limitcast budget today on`). */
@@ -142,14 +135,7 @@ export function getTodayHold() {
142
135
 
143
136
  /** @param {boolean} on */
144
137
  export function setTodayHold(on) {
145
- let cfg = {};
146
- try {
147
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
148
- } catch {
149
- /* new */
150
- }
151
- mkdirSync(stateDir(), { recursive: true });
152
- writeAtomic(configFile(), JSON.stringify({ ...cfg, todayHold: on }));
138
+ updateConfig((cfg) => ({ ...cfg, todayHold: on }));
153
139
  }
154
140
 
155
141
  /** A model a subagent type can be pinned to: sonnet, opus, haiku, a claude-... id, or a grok-... id. */
@@ -183,17 +169,12 @@ export function getSubagentModels() {
183
169
  * @param {string|null} model
184
170
  */
185
171
  export function setSubagentModel(type, model) {
186
- let cfg = /** @type {any} */ ({});
187
- try {
188
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
189
- } catch {
190
- /* new */
191
- }
192
- const models = { ...cfg.subagentModels };
193
- if (model === null) delete models[type];
194
- else models[type] = model;
195
- mkdirSync(stateDir(), { recursive: true });
196
- writeAtomic(configFile(), JSON.stringify({ ...cfg, subagentModels: models }));
172
+ updateConfig((cfg) => {
173
+ const models = { ...cfg.subagentModels };
174
+ if (model === null) delete models[type];
175
+ else models[type] = model;
176
+ return { ...cfg, subagentModels: models };
177
+ });
197
178
  }
198
179
 
199
180
  /**