limitcast 0.15.0 → 0.17.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limitcast",
3
- "version": "0.15.0",
3
+ "version": "0.17.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": {
@@ -36,5 +36,5 @@
36
36
  "url": "git+https://github.com/SamStull9007/limitcast.git"
37
37
  },
38
38
  "author": "Sam Stull",
39
- "license": "Elastic-2.0"
39
+ "license": "MIT"
40
40
  }
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 { stateDir } from './store.mjs';
7
+ import { KEEP_MS, stateDir } from './store.mjs';
8
8
  import { grokRoot } from './usage.mjs';
9
9
 
10
10
  /** @typedef {import('./forecast.mjs').Sample} Sample */
@@ -202,21 +202,252 @@ export function grokSpend(now, root = grokRoot()) {
202
202
  return out;
203
203
  }
204
204
 
205
+ // Grok weekly %, opt-in (`limitcast grok-usage on`). Grok keeps no % on disk, so limitcast asks grok.com the same billing
206
+ // question Grok Build asks, with the login Grok already holds in auth.json. That login is read in this process, sent only to
207
+ // grok.com, and never stored or logged.
208
+ const QUOTA_URL = 'https://grok.com/grok_api_v2.GrokBuildBilling/GetGrokCreditsConfig';
209
+ const QUOTA_EVERY_MS = 5 * 60_000;
210
+ const quotaFile = () => join(stateDir(), 'grok-quota.json');
211
+
212
+ /** @typedef {{at:number, ok:boolean, error?:string, label?:string, pct?:number, reset?:number, readings:{t:number, pct:number, reset:number}[]}} QuotaState */
213
+
214
+ export function grokQuotaEnabled() {
215
+ try {
216
+ return JSON.parse(readFileSync(configFile(), 'utf8')).grokQuota === true;
217
+ } catch {
218
+ return false;
219
+ }
220
+ }
221
+
222
+ /** @param {boolean} on */
223
+ export function setGrokQuota(on) {
224
+ let cfg = {};
225
+ try {
226
+ cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
227
+ } catch {
228
+ /* new */
229
+ }
230
+ mkdirSync(stateDir(), { recursive: true });
231
+ writeFileSync(configFile(), JSON.stringify({ ...cfg, grokQuota: on }));
232
+ }
233
+
234
+ /** @returns {QuotaState} */
235
+ export function readGrokQuota() {
236
+ try {
237
+ return { at: 0, ok: false, readings: [], ...JSON.parse(readFileSync(quotaFile(), 'utf8')) };
238
+ } catch {
239
+ return { at: 0, ok: false, readings: [] };
240
+ }
241
+ }
242
+
243
+ /** @param {QuotaState} s */
244
+ function writeGrokQuota(s) {
245
+ mkdirSync(stateDir(), { recursive: true });
246
+ writeFileSync(quotaFile(), JSON.stringify(s));
247
+ }
248
+
249
+ /** True when the feature is on, Grok is installed, and the last attempt is older than the refresh interval. */
250
+ export function grokQuotaDue(now, home = grokHome()) {
251
+ return grokQuotaEnabled() && grokPresent(home) && now - readGrokQuota().at >= QUOTA_EVERY_MS;
252
+ }
253
+
254
+ /** Mark an attempt before a background refresh starts, so a burst of status lines starts only one. */
255
+ export function touchGrokQuota(now) {
256
+ writeGrokQuota({ ...readGrokQuota(), at: now });
257
+ }
258
+
259
+ /**
260
+ * Protobuf fields of one message as [field, value, wireType]: varints as numbers, length-delimited as Buffers,
261
+ * fixed32 as its 4 bytes. Stops quietly at a truncated message.
262
+ * @param {Buffer} buf
263
+ * @returns {Generator<[number, any, number]>}
264
+ */
265
+ function* fields(buf) {
266
+ let pos = 0;
267
+ const varint = () => {
268
+ let r = 0;
269
+ let mul = 1;
270
+ while (pos < buf.length) {
271
+ const b = buf[pos++];
272
+ r += (b & 0x7f) * mul;
273
+ if (!(b & 0x80)) return r;
274
+ mul *= 128;
275
+ }
276
+ return null;
277
+ };
278
+ while (pos < buf.length) {
279
+ const key = varint();
280
+ if (key === null) return;
281
+ const field = Math.floor(key / 8);
282
+ const wire = key % 8;
283
+ if (wire === 0) {
284
+ const v = varint();
285
+ if (v === null) return;
286
+ yield [field, v, 0];
287
+ } else if (wire === 1) {
288
+ if (pos + 8 > buf.length) return;
289
+ pos += 8;
290
+ } else if (wire === 2) {
291
+ const len = varint();
292
+ if (len === null || pos + len > buf.length) return;
293
+ yield [field, buf.subarray(pos, pos + len), 2];
294
+ pos += len;
295
+ } else if (wire === 5) {
296
+ if (pos + 4 > buf.length) return;
297
+ yield [field, buf.subarray(pos, pos + 4), 5];
298
+ pos += 4;
299
+ } else return;
300
+ }
301
+ }
302
+
303
+ /** Seconds of a protobuf Timestamp. @param {Buffer} msg */
304
+ const timestamp = (msg) => {
305
+ for (const [f, v, w] of fields(msg)) if (f === 1 && w === 0) return /** @type {number} */ (v);
306
+ return null;
307
+ };
308
+
205
309
  /**
206
- * Forecast samples from Grok spend against the user's dollar cap. Empty without a budget: there is no % to judge.
310
+ * The billing cycle from a gRPC-web `GetGrokCreditsConfig` reply: % used and the cycle's start and end (epoch seconds).
311
+ * Null when the reply holds no percentage.
312
+ * @param {Uint8Array} body
313
+ * @returns {{pct:number, start:number|null, end:number|null}|null}
314
+ */
315
+ export function parseGrokBilling(body) {
316
+ const buf = Buffer.from(body);
317
+ for (let pos = 0; pos + 5 <= buf.length; ) {
318
+ const flag = buf[pos];
319
+ const len = buf.readUInt32BE(pos + 1);
320
+ pos += 5;
321
+ if (pos + len > buf.length) return null;
322
+ const payload = buf.subarray(pos, pos + len);
323
+ pos += len;
324
+ if (flag & 0x80) continue; // trailers
325
+ for (const [f, cfg, w] of fields(payload)) {
326
+ if (f !== 1 || w !== 2) continue;
327
+ let pct = null;
328
+ let start = null;
329
+ let end = null;
330
+ for (const [g, v, ww] of fields(cfg)) {
331
+ if (g === 1 && ww === 5) {
332
+ const x = v.readFloatLE(0);
333
+ if (Number.isFinite(x)) pct = Math.min(100, Math.max(0, x));
334
+ } else if (g === 4 && ww === 2) start = timestamp(v);
335
+ else if (g === 5 && ww === 2) end = timestamp(v);
336
+ }
337
+ if (pct !== null) return { pct, start, end };
338
+ }
339
+ }
340
+ return null;
341
+ }
342
+
343
+ /** Grok's logins from auth.json, the auth.x.ai one first. @param {string} home */
344
+ function grokTokens(home) {
345
+ try {
346
+ const doc = JSON.parse(readFileSync(join(home, 'auth.json'), 'utf8'));
347
+ return Object.entries(doc ?? {})
348
+ .filter(([, v]) => typeof (/** @type {any} */ (v)?.key) === 'string' && /** @type {any} */ (v).key)
349
+ .sort(([a], [b]) => Number(b.includes('auth.x.ai')) - Number(a.includes('auth.x.ai')))
350
+ .map(([, v]) => /** @type {string} */ (/** @type {any} */ (v).key));
351
+ } catch {
352
+ return [];
353
+ }
354
+ }
355
+
356
+ /**
357
+ * @param {string} token
358
+ * @param {typeof fetch} fetchFn
359
+ */
360
+ async function askGrok(token, fetchFn) {
361
+ let r;
362
+ try {
363
+ r = await fetchFn(QUOTA_URL, {
364
+ method: 'POST',
365
+ redirect: 'error', // the login must never follow a redirect to another host
366
+ signal: AbortSignal.timeout(8000),
367
+ headers: {
368
+ authorization: `Bearer ${token}`,
369
+ 'x-xai-token-auth': 'xai-grok-cli',
370
+ accept: 'application/grpc-web+proto',
371
+ 'content-type': 'application/grpc-web+proto',
372
+ 'user-agent': 'Grok Build',
373
+ },
374
+ body: new Uint8Array([0, 0, 0, 0, 0]),
375
+ });
376
+ } catch {
377
+ throw new Error('could not reach grok.com');
378
+ }
379
+ if (r.status === 401 || r.status === 403) throw new Error('Grok login expired: run `grok login`');
380
+ if (!r.ok) throw new Error(`grok.com answered HTTP ${r.status}`);
381
+ return parseGrokBilling(new Uint8Array(await r.arrayBuffer()));
382
+ }
383
+
384
+ /**
385
+ * Ask grok.com for the weekly % (at most every 5 minutes unless `force`), keep the reading, and say what happened.
386
+ * Never throws: a failure is recorded in the state for `status` and `doctor`.
387
+ * @param {number} now
388
+ * @param {{force?:boolean, home?:string, fetchFn?:typeof fetch}} [opts]
389
+ * @returns {Promise<QuotaState>}
390
+ */
391
+ export async function refreshGrokQuota(now, { force = false, home = grokHome(), fetchFn = fetch } = {}) {
392
+ const prev = readGrokQuota();
393
+ if (!force && now - prev.at < QUOTA_EVERY_MS) return prev;
394
+ /** @type {QuotaState} */
395
+ const next = { ...prev, at: now, ok: false };
396
+ delete next.error;
397
+ const tokens = grokTokens(home);
398
+ if (!tokens.length) next.error = 'no Grok login found: run `grok login`';
399
+ for (const token of tokens) {
400
+ try {
401
+ const b = await askGrok(token, fetchFn);
402
+ if (!b) {
403
+ next.error = 'grok.com sent a billing reply limitcast does not recognise';
404
+ continue;
405
+ }
406
+ const days = b.start !== null && b.end !== null ? Math.trunc((b.end - b.start) / 86400) : null;
407
+ next.label = days !== null && days >= 6 && days <= 8 ? 'Weekly' : days !== null && days >= 27 && days <= 33 ? 'Monthly' : 'Credits';
408
+ next.ok = true;
409
+ next.pct = b.pct;
410
+ if (b.end !== null) next.reset = b.end;
411
+ delete next.error;
412
+ const last = next.readings[next.readings.length - 1];
413
+ if (next.label === 'Weekly' && b.end !== null && (!last || last.pct !== b.pct || last.reset !== b.end))
414
+ next.readings = [...next.readings, { t: now, pct: b.pct, reset: b.end }];
415
+ break;
416
+ } catch (e) {
417
+ next.error = e instanceof Error ? e.message : 'unknown error';
418
+ }
419
+ }
420
+ next.readings = next.readings.filter((r) => r.t >= now - KEEP_MS);
421
+ writeGrokQuota(next);
422
+ return next;
423
+ }
424
+
425
+ /** Forecast samples from the recorded weekly readings; none unless the feature is on. @param {number} now @returns {Sample[]} */
426
+ export function grokQuotaSamples(now) {
427
+ if (!grokQuotaEnabled()) return [];
428
+ return readGrokQuota()
429
+ .readings.filter((r) => r.t >= now - KEEP_MS)
430
+ .map((r) => ({ t: r.t, src: 'grok', win: '7d', pct: r.pct, reset: r.reset }));
431
+ }
432
+
433
+ /**
434
+ * Forecast samples for Grok: the real weekly % when `grok-usage` is on, plus spend against the user's dollar cap
435
+ * for the windows with a cap (a weekly cap steps aside for the real %). Empty without either.
207
436
  * @param {number} now
208
437
  * @param {{root?:string, budget?:ReturnType<typeof getGrokBudget>}} [opts]
209
438
  * @returns {Sample[]}
210
439
  */
211
440
  export function grokSamples(now, { root = grokRoot(), budget = getGrokBudget() } = {}) {
212
- if (!budget) return [];
441
+ const quota = grokQuotaSamples(now);
442
+ if (!budget) return quota;
213
443
  const since = now - windowMs('7d');
214
444
  const turns = grokCosts(root, since);
215
445
  /** @type {Sample[]} */
216
- const out = [];
446
+ const out = [...quota];
217
447
  for (const win of /** @type {const} */ (['5h', '7d'])) {
218
448
  const cap = budget[win];
219
449
  if (!(cap > 0)) continue;
450
+ if (win === '7d' && quota.length) continue;
220
451
  const start = alignedStart(now, win);
221
452
  const reset = (start + windowMs(win)) / 1000;
222
453
  let spent = 0;
@@ -334,10 +565,18 @@ export function grokDoctor(home = grokHome()) {
334
565
  line: guard ? 'Grok subagent guard installed' : 'Grok subagent guard not installed (optional: `limitcast install --guard`)',
335
566
  });
336
567
  const budget = getGrokBudget();
337
- if (guard && !budget)
568
+ if (grokQuotaEnabled()) {
569
+ const q = readGrokQuota();
570
+ const ago = q.at ? `${Math.max(0, Math.round((Date.now() - q.at) / 60_000))} min ago` : 'not yet';
571
+ out.push(
572
+ q.ok
573
+ ? { ok: true, line: `Grok ${q.label?.toLowerCase() ?? 'usage'}: ${Math.round(q.pct ?? 0)}% used (checked ${ago})` }
574
+ : { ok: false, line: `Grok usage unavailable (checked ${ago}): ${q.error ?? 'no reading yet'}` },
575
+ );
576
+ } else if (guard && !budget)
338
577
  out.push({
339
578
  ok: true,
340
- line: 'Grok has no % limit on disk: set a 5-hour dollar cap so the guard can block (`limitcast budget grok <usd>`)',
579
+ line: 'Grok has no % limit on disk: turn on the weekly % with `limitcast grok-usage on`, or set a 5-hour dollar cap so the guard can block (`limitcast budget grok <usd>`)',
341
580
  });
342
581
  else if (budget)
343
582
  out.push({
package/src/guard.mjs CHANGED
@@ -64,6 +64,7 @@ function blockingForecast(tool, forecasts, now, minutes) {
64
64
  export async function runGuard(hook, now, minutes, { preview = false } = {}) {
65
65
  const tool = String(hook?.tool_name ?? hook?.toolName ?? hook?.tool ?? '');
66
66
  const src = spawnSource(tool);
67
+ const operation = hook?.tool_use_id ?? hook?.toolUseId ?? hook?.call_id;
67
68
  // Codex: only the last two hours of rollouts, so the hook stays fast. Grok: spend vs the user's dollar cap.
68
69
  const samples =
69
70
  src === 'claude'
@@ -81,6 +82,7 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
81
82
  const sid = f.src === 'claude' ? samples.find((s) => s.src === 'claude' && s.sid)?.sid : undefined;
82
83
  try {
83
84
  logBlock({
85
+ ...(typeof operation === 'string' ? { operation } : {}),
84
86
  t: now,
85
87
  src: f.src,
86
88
  win: f.win,
@@ -102,6 +104,7 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
102
104
  if (day && (preview || getTodayHold())) {
103
105
  try {
104
106
  logBlock({
107
+ ...(typeof operation === 'string' ? { operation } : {}),
105
108
  t: now,
106
109
  kind: 'today',
107
110
  src: day.src,
@@ -126,6 +129,7 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
126
129
  if (spent >= budget) {
127
130
  try {
128
131
  logBlock({
132
+ ...(typeof operation === 'string' ? { operation } : {}),
129
133
  t: now,
130
134
  kind: 'budget',
131
135
  src: 'claude',
@@ -147,13 +151,14 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
147
151
  const tight = forecasts.find((x) => x.src === 'claude' && (x.verdict === 'AT_RISK' || x.verdict === 'NEAR'));
148
152
  const type = String(input?.subagent_type ?? input?.subagentType ?? '');
149
153
  const pinned = isUnset(input?.model) && type ? pinnedModel(type) : undefined;
150
- if (src === 'grok') return grokPinOrNotice(input, type, pinned, forecasts, now, preview);
154
+ if (src === 'grok') return grokPinOrNotice(input, type, pinned, forecasts, now, preview, operation);
151
155
  if (src !== 'claude') return null;
152
156
  const model = pinned ?? input?.model;
153
157
  if (!tight || !switchable(model)) {
154
158
  if (pinned) {
155
159
  try {
156
160
  logBlock({
161
+ ...(typeof operation === 'string' ? { operation } : {}),
157
162
  t: now,
158
163
  kind: 'default',
159
164
  src: 'claude',
@@ -183,6 +188,7 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
183
188
  }
184
189
  try {
185
190
  logBlock({
191
+ ...(typeof operation === 'string' ? { operation } : {}),
186
192
  t: now,
187
193
  kind: 'switch',
188
194
  src: 'claude',
@@ -238,13 +244,15 @@ const isUnset = (model) => model === undefined || model === null || model === ''
238
244
  * @param {ReturnType<typeof import('./forecast.mjs').forecastAll>} forecasts
239
245
  * @param {number} now
240
246
  * @param {boolean} preview
247
+ * @param {unknown} operation
241
248
  */
242
- function grokPinOrNotice(input, type, pinned, forecasts, now, preview) {
249
+ function grokPinOrNotice(input, type, pinned, forecasts, now, preview, operation) {
243
250
  const grokPin = pinned && /^grok-/i.test(pinned) ? pinned : undefined;
244
251
  const hasModelField = input && typeof input === 'object' && Object.hasOwn(input, 'model');
245
252
  if (grokPin && hasModelField) {
246
253
  try {
247
254
  logBlock({
255
+ ...(typeof operation === 'string' ? { operation } : {}),
248
256
  t: now,
249
257
  kind: 'default',
250
258
  src: 'grok',
@@ -0,0 +1,127 @@
1
+ // @ts-check
2
+ import { fmtBig, valuePeriod } from './value.mjs';
3
+
4
+ const DAY = 86400_000;
5
+ const ACTIONS = {
6
+ hold: 'Forecast holds',
7
+ budget: 'Subagent-budget holds',
8
+ today: 'Daily-share holds',
9
+ switch: 'Tight-window model changes',
10
+ default: 'Per-type model choices',
11
+ cold: 'Cold-cache holds',
12
+ };
13
+
14
+ /** Totals without prompts, projects, paths, account names or session IDs.
15
+ * @param {{value:import('./value.mjs').Value, usage:import('./usage.mjs').Usage[], blocks:import('./results.mjs').Block[], since:number, until:number}} r
16
+ */
17
+ export function periodInsights({ value, usage, blocks, since, until }) {
18
+ const current = usage.filter((u) => u.t >= since && u.t < until);
19
+ const providers = ['claude', 'codex', 'grok'].map((src) => {
20
+ const mine = current.filter((u) => u.src === src);
21
+ return {
22
+ src,
23
+ calls: mine.length,
24
+ activeDays: new Set(mine.map((u) => new Date(u.t).toISOString().slice(0, 10))).size,
25
+ fresh: mine.reduce((n, u) => n + u.input + u.cacheWrite, 0),
26
+ read: mine.reduce((n, u) => n + u.cacheRead, 0),
27
+ output: mine.reduce((n, u) => n + u.output, 0),
28
+ };
29
+ });
30
+ const seen = new Set();
31
+ const actions = Object.fromEntries(Object.keys(ACTIONS).map((kind) => [kind, { actual: 0, preview: 0 }]));
32
+ let attempts = 0;
33
+ for (const b of blocks.filter((b) => b.t >= since && b.t < until)) {
34
+ const kind = b.kind ?? 'hold';
35
+ if (!actions[kind]) continue;
36
+ // Older hooks have no operation ID: retain and label their attempts instead of guessing duplicates.
37
+ const key = b.operation ? JSON.stringify([b.src, b.sid, b.operation, Boolean(b.shadow)]) : null;
38
+ if (key && seen.has(key)) continue;
39
+ if (key) seen.add(key);
40
+ else attempts++;
41
+ actions[kind][b.shadow ? 'preview' : 'actual']++;
42
+ }
43
+ const previous = valuePeriod(value, since - (until - since), since);
44
+ const context = valuePeriod(value, since, until);
45
+ const comparison =
46
+ value.contextSince && value.contextSince <= since - (until - since) && !context.legacy && !previous.legacy ? previous.tokens : null;
47
+ return {
48
+ since,
49
+ until,
50
+ days: (until - since) / DAY,
51
+ providers,
52
+ actions,
53
+ attempts,
54
+ context,
55
+ contextAvailable: Number.isFinite(value.contextSince),
56
+ previousContext: comparison,
57
+ };
58
+ }
59
+
60
+ /** @param {ReturnType<typeof periodInsights>} r @param {boolean} pro */
61
+ export function insightsReport(r, pro) {
62
+ const out = [
63
+ '## Your capacity report',
64
+ '',
65
+ `${new Date(r.since).toISOString()} to ${new Date(r.until).toISOString()} (UTC; activity timestamps).`,
66
+ '',
67
+ '| Tool | New input + cache writes | Cached reads | Output | Active days |',
68
+ '|---|---:|---:|---:|---:|',
69
+ ];
70
+ for (const p of r.providers) out.push(`| ${p.src} | ${fmtBig(p.fresh)} | ${fmtBig(p.read)} | ${fmtBig(p.output)} | ${p.activeDays} |`);
71
+ out.push('', 'Usage above is recorded consumption, not savings. No recorded activity does not prove a tool was unused.');
72
+ if (pro) {
73
+ if (r.contextAvailable)
74
+ out.push(
75
+ '',
76
+ `Claude context reduction: **estimated ${fmtBig(r.context.tokens)} input tokens not re-sent** across ${r.context.calls} calls in this period, relative to your first recorded starting context (characters / 4).`,
77
+ );
78
+ else out.push('Claude context reduction: unavailable. Run `limitcast trim` to record a baseline before estimating avoided input.');
79
+ out.push(
80
+ 'This estimate can include project or manual configuration changes. It is not proof that Limitcast caused the reduction. Codex/Grok context savings: unavailable.',
81
+ );
82
+ if (r.context.legacy) out.push(`${r.context.legacy} legacy session record(s) lack timestamps and are excluded from this period estimate.`);
83
+ if (r.previousContext !== null)
84
+ out.push(`Previous equal period: estimated ${fmtBig(r.previousContext)} context tokens not re-sent. Neither figure measures cash savings.`);
85
+ else out.push('Previous-period comparison: unavailable until two complete periods have been observed.');
86
+ }
87
+ out.push('', '| Protection event | Applied | Historical preview: would have acted |', '|---|---:|---:|');
88
+ for (const [kind, label] of Object.entries(ACTIONS)) out.push(`| ${label} | ${r.actions[kind].actual} | ${r.actions[kind].preview} |`);
89
+ out.push(
90
+ '',
91
+ `Operation IDs deduplicate retries when supplied. ${r.attempts} older/unidentified event(s) are recorded attempts. Holds and warnings are not measured saved tokens or proven prevented interruptions.`,
92
+ );
93
+ out.push('', '### What to do next');
94
+ const claude = r.providers[0];
95
+ const held = Object.values(r.actions).reduce((n, a) => n + a.actual, 0);
96
+ const previewed = Object.values(r.actions).reduce((n, a) => n + a.preview, 0);
97
+ if (!r.providers.some((p) => p.calls)) out.push('- Run `limitcast onboard` to check setup and the next useful step.');
98
+ else if (r.actions.cold.actual || r.actions.cold.preview)
99
+ out.push('- Before resuming a long idle Claude session, consider `/compact`; a warning alone does not reduce its input.');
100
+ else if (claude.fresh > 0)
101
+ out.push('- Run `limitcast report --why` to find the largest sources of new Claude tokens before changing a budget or model.');
102
+ else out.push('- Check `limitcast status` before a heavy run; each provider has its own limits.');
103
+ if (!held && !previewed)
104
+ out.push('- No protection actions recorded. `limitcast onboard` distinguishes missing setup from a period that needed no intervention.');
105
+ if (!pro && previewed)
106
+ out.push(
107
+ `- ${previewed} historical preview event(s) were recorded. All features are now free; enable protection with limitcast install --guard --alerts.`,
108
+ );
109
+ out.push('- Share voluntarily with `limitcast results --share`; nothing is uploaded automatically.');
110
+ return out.join('\n');
111
+ }
112
+
113
+ /** @param {ReturnType<typeof periodInsights>} r @param {boolean} pro */
114
+ export function insightsShare(r, pro) {
115
+ const parts = r.providers
116
+ .filter((p) => p.calls)
117
+ .map(
118
+ (p) =>
119
+ `${p.src}: ${p.activeDays} UTC active days, ${fmtBig(p.fresh)} new input/write, ${fmtBig(p.read)} cached, ${fmtBig(p.output)} output tokens`,
120
+ );
121
+ const actual = Object.values(r.actions).reduce((n, a) => n + a.actual, 0);
122
+ const preview = Object.values(r.actions).reduce((n, a) => n + a.preview, 0);
123
+ parts.push(`${actual} applied protection events; ${preview} historical-preview events (${r.attempts} unidentified attempts)`);
124
+ if (pro && r.contextAvailable) parts.push(`estimated ${fmtBig(r.context.tokens)} Claude context tokens not re-sent this period vs baseline`);
125
+ if (pro && !r.contextAvailable) parts.push('Claude context estimate unavailable');
126
+ return `Voluntary capacity check-in, ${r.days} days: ${parts.join('; ')}. No prompts, project names or account IDs. https://limitcast.dev`;
127
+ }
package/src/install.mjs CHANGED
@@ -280,11 +280,11 @@ function codexGuardCheck(codexPath) {
280
280
  }
281
281
 
282
282
  /**
283
- * Health checks: settings wired, the node path in them still exists, data arriving, license state.
284
- * @param {{path?:string, codexPath?:string, samplesAgeMs:number|null, license:ReturnType<typeof import('./license.mjs').currentLicense>}} info
283
+ * Health checks: settings wired, the node path in them still exists, data arriving, and the free distribution.
284
+ * @param {{path?:string, codexPath?:string, samplesAgeMs:number|null, license?:ReturnType<typeof import('./license.mjs').currentLicense>}} info
285
285
  * @returns {{ok:boolean, line:string}[]}
286
286
  */
287
- export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), samplesAgeMs, license }) {
287
+ export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), samplesAgeMs }) {
288
288
  /** @type {{ok:boolean, line:string}[]} */
289
289
  const out = [];
290
290
  const major = Number(process.versions.node.split('.')[0]);
@@ -332,7 +332,7 @@ export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), sa
332
332
  const newer = (hooks.UserPromptSubmit ?? []).some(isPromptCheck) && (hooks.SubagentStop ?? []).some(isReceipt);
333
333
  if (guard && !newer)
334
334
  out.push({
335
- ok: !license?.ok,
335
+ ok: false,
336
336
  line: 'Cold-cache warning and subagent receipts not installed yet: run `limitcast doctor --fix`',
337
337
  });
338
338
  if (existsSync(codexPath)) out.push(codexGuardCheck(codexPath));
@@ -343,16 +343,8 @@ export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), sa
343
343
  : { ok: samplesAgeMs < 24 * 3600_000, line: `Last Claude reading ${Math.round(samplesAgeMs / 60_000)} min ago` },
344
344
  );
345
345
  out.push({
346
- ok: license?.ok !== false,
347
- line: license === null ? 'Free tier' : license.ok ? `Pro: ${license.claims.e}${proTerm(license.claims)}` : `License problem: ${license.reason}`,
346
+ ok: true,
347
+ line: 'Free and open source (MIT License); all features available',
348
348
  });
349
349
  return out;
350
350
  }
351
-
352
- /** @param {{p:string, i:number, x:number}} c */
353
- function proTerm(c) {
354
- const day = (/** @type {number} */ s) => new Date(s * 1000).toISOString().slice(0, 10);
355
- if (c.x) return `, ${c.p === 'polar' ? 'valid until' : 'renews'} ${day(c.x)}`;
356
- // A Polar key has no end date for Lifetime or an active subscription; the weekly check is what keeps it honest.
357
- return c.p === 'polar' ? `, last checked with Polar ${day(c.i)}` : ', lifetime';
358
- }
package/src/license.mjs CHANGED
@@ -69,7 +69,8 @@ export function activate(key) {
69
69
  return res;
70
70
  }
71
71
 
72
- export const isPro = () => currentLicense()?.ok === true || trialStatus()?.active === true;
72
+ // Compatibility for old integrations; feature access no longer depends on billing state.
73
+ export const isPro = () => true;
73
74
 
74
75
  const TRIAL_MS = 7 * 86400_000;
75
76
  const trialFile = () => join(stateDir(), 'trial.json');
package/src/notify.mjs CHANGED
@@ -2,7 +2,6 @@
2
2
  import { spawn, spawnSync } from 'node:child_process';
3
3
  import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
- import { isPro } from './license.mjs';
6
5
  import { stateDir } from './store.mjs';
7
6
 
8
7
  // Desktop notifications (Pro, opt-in): one per change of state, raised from the status line.
@@ -97,7 +96,7 @@ export function notifyChanges(rows, clock) {
97
96
  export function send(message) {
98
97
  // Pro: the same message to the phone (ntfy) or a chat webhook, by a detached curl so no hook waits on the network.
99
98
  try {
100
- if (isPro()) for (const a of remoteArgs(loadChannels(), message)) run('curl', a);
99
+ for (const a of remoteArgs(loadChannels(), message)) run('curl', a);
101
100
  } catch {
102
101
  /* a broken channel config must not stop the desktop notification */
103
102
  }
@@ -0,0 +1,46 @@
1
+ // @ts-check
2
+
3
+ /** Read-only guidance; installation and cuts always remain explicit commands.
4
+ * @param {{checks:{ok:boolean,line:string}[], features:{statusLine:boolean,guard:boolean,alerts:boolean}, contextTokens:number|null, providers:string[]}} r
5
+ */
6
+ export function onboardingReport({ checks, features, contextTokens, providers }) {
7
+ const out = [
8
+ '# Get started with limitcast',
9
+ '',
10
+ `Found local setup/logs for: ${providers.join(', ') || 'none yet'}.`,
11
+ 'Free and open source (MIT License). All features are available without an account, license key or trial.',
12
+ '',
13
+ '## Setup checks',
14
+ ];
15
+ for (const c of checks) out.push(`- ${c.ok ? 'OK' : 'Needs attention'}: ${c.line}`);
16
+ out.push('', '## Your next step');
17
+ if (!features.statusLine)
18
+ out.push('1. Run `limitcast install` to back up settings and add the recorder. Restart your coding tool, then run `limitcast doctor`.');
19
+ else out.push('1. Run `limitcast status` for your current windows. No readings yet? Restart your tool and complete one normal turn.');
20
+ if (contextTokens !== null)
21
+ out.push(
22
+ `2. Your latest Claude starting context contains about ${Math.round(contextTokens).toLocaleString('en-US')} tokens of controllable setup. Run limitcast trim to inspect unused items.`,
23
+ );
24
+ else
25
+ out.push(
26
+ '2. After a normal session, run `limitcast trim` (Claude), `limitcast trim --codex`, or `limitcast trim --grok` for a personal finding. Doctor checks setup; Trim analyzes context.',
27
+ );
28
+ if (!features.guard || !features.alerts)
29
+ out.push(
30
+ '3. Run limitcast install --guard --alerts to configure protection and weekly summaries. Restart; approve the Codex hook if asked. Run limitcast doctor to check configuration.',
31
+ );
32
+ else
33
+ out.push(
34
+ 'Protection is configured. Configuration is not proof of a live block: confirm the hook is loaded in your coding tool; review real events with `limitcast results`.',
35
+ );
36
+ out.push(
37
+ '',
38
+ '## Stay in control',
39
+ '- Inspect first. Add essential servers/skills with `limitcast trim keep <name>` before choosing `trim --apply`. Undo with `limitcast trim --undo` (add `--codex` or `--grok` for that tool).',
40
+ '- The guard holds new spawns; it does not cancel existing agents or guarantee no lockouts. `LIMITCAST_ALLOW=1` bypasses a hold for a command/session; unset it to restore protection.',
41
+ '- Grok needs an explicit dollar cap for blocking: `limitcast budget grok <usd>`. Claude model defaults/budgets and cold-cache notices do not have identical support in every host.',
42
+ '- In a week, run `limitcast results`. It separates usage, estimated context reduction, applied controls and historical previews. Share totals voluntarily with `limitcast results --share`.',
43
+ '- Nothing here changes settings or uploads usage. `limitcast uninstall` restores the recorder setup; trim changes have their own undo.',
44
+ );
45
+ return out.join('\n');
46
+ }