claudekit-terminal 0.2.0 → 0.3.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/lib/docs.js CHANGED
@@ -11,32 +11,39 @@ Set up (one command):
11
11
  ${say} remove undo it (--all also deletes ~/.claudekit)
12
12
 
13
13
  Your limits:
14
- usage every limit, run-out forecast, what prompts cost
14
+ usage every limit, what prompts cost, the run-out time from 70% (Pro: from 20%, replies left)
15
15
  week your Claude week: busiest day, days active, limit hits
16
- notify wait, then tell you when Claude is back after a limit
16
+ notify Pro wait, then tell you when Claude is back after a limit
17
17
 
18
18
  Your chats (Claude Code's own files on this computer):
19
- search <words> search every chat
19
+ search search your chats from the last 7 days (Pro: every chat)
20
20
  map [chat] numbered outline of a chat
21
- export [chat] save a chat as Markdown (--format json|txt, --turns 3-5, --out file)
22
- backup [folder] every chat as Markdown in ~/claudekit-backup (--auto: after each session)
23
- fork [chat] open a copy of a chat to try another direction
24
- reference [chat] save a chat to bring into another one with @
25
- brief your last Handoff Brief (--start: a new session from it)
21
+ export save a chat from the last 7 days as Markdown or text (Pro: any chat, json, --turns)
22
+ backup Pro every chat as Markdown in ~/claudekit-backup (--auto: after each session)
23
+ fork Pro open a copy of a chat to try another direction
24
+ reference Pro save a chat to bring into another one with @
25
+ brief your last Handoff Brief (--start, Pro: a new session from it)
26
26
  pins what you pinned with /ck-pin (pin "text" adds one)
27
27
 
28
28
  Prompts:
29
29
  prompts your /ck- commands (add, remove, show, packs, pack <name>)
30
30
  tokens [file] count words and tokens (or pipe text in)
31
31
 
32
+ ClaudeKit Pro (one licence with the browser extension):
33
+ pro get Pro from the terminal (checkout opens in your browser)
34
+ activate <key> use a key copied from the ClaudeKit popup
35
+ license what Pro this terminal has
36
+ telemetry off stop the anonymous usage counts (or DO_NOT_TRACK=1)
37
+
32
38
  docs every feature, explained
33
39
 
34
40
  Run each as: ${say} <command>
35
41
  [chat] is the newest chat in this folder unless you give a session id or words from its title.`;
36
42
 
37
43
  export const DOCS = (say = 'claudekit-terminal') => `ClaudeKit for the terminal ${VERSION}
38
- Your Claude limits, chats and prompts in the terminal: the free companion to the ClaudeKit
39
- browser extension (claudekit.app). No account, no network calls.
44
+ Your Claude limits, chats and prompts in the terminal, with the ClaudeKit browser extension
45
+ (claudekit.app). No account. Seeing your limits is free; acting on them is ClaudeKit Pro, one
46
+ licence for the terminal and the browser.
40
47
 
41
48
  SET UP
42
49
  npx claudekit-terminal setup
@@ -51,18 +58,38 @@ SET UP
51
58
  ~/.claudekit. Chat backups are never deleted.
52
59
  Faster start: npm install -g claudekit-terminal, then claudekit-terminal setup.
53
60
 
61
+ FREE AND PRO
62
+ Free: the status line (model, context, 5-hour and weekly use and resets, what a prompt cost, the
63
+ daily budget, the "use it" nudge, the near-limit hint, the warning before Claude Code
64
+ deletes chats), the run-out time once a limit is 70% used, usage, week, search and export
65
+ of chats from the last 7 days, prompts and packs, /ck- commands, tokens, pins, map, brief.
66
+ Pro: the run-out time from 20% used and replies left (status line and usage), notify,
67
+ search and export of every chat, export as JSON and --turns ranges, backup (and --auto),
68
+ fork, reference, brief --start.
69
+ If you used ClaudeKit in the terminal before 0.3.0, everything stays free for you until
70
+ Jan 31, 2027.
71
+ pro shows the price and opens a checkout in your browser; the key arrives by itself
72
+ (or later: ${say} pro check). pro monthly for monthly.
73
+ activate <key> a key from the ClaudeKit popup (Use Pro in your terminal). Keys are checked on
74
+ your computer and renew by themselves while your Pro does.
75
+ license what Pro this terminal has (--forget removes the key)
76
+
54
77
  THE STATUS LINE (inside Claude Code)
55
78
  Opus 5.5 · ctx 45% │ 5h 62% +3% · resets 3:10 PM · out ~2:40 PM · ~6 replies left │ week 41% · Thu 9:00 AM · ~13%/day
56
79
  ctx 45% how full this chat's context window is
57
80
  5h 62% your 5-hour session limit used (green, yellow from 70%, red from 90%)
58
81
  +3% what your current prompt has cost of the session so far
59
82
  resets 3:10 PM when the session resets, in your time (at 100%: "back 3:10 PM")
60
- out ~2:40 PM when you run out at your pace over the last hour (from 20% used)
61
- ~6 replies left about how many prompts are left at your pace on this model (from 50% used)
83
+ out ~2:40 PM when you run out at your pace over the last hour (from 70% used; Pro: from 20%)
84
+ ~6 replies left Pro: about how many prompts are left at your pace on this model (from 50% used)
62
85
  week 41% your weekly limit, when it resets, and a daily budget (~13%/day)
63
86
  use it in the last day before the weekly reset with 25%+ left: unused limit doesn't roll over
64
87
  spend 63% a spend limit, when your plan has one
65
88
  near limit at 90%: type /ck-handoff to save your context before you're cut off
89
+ Claude Code deletes 2 chats ≤3d
90
+ Claude Code deletes chats older than cleanupPeriodDays (30 by default) without a
91
+ word; this says when some are due within 3 days and aren't backed up. Once a day
92
+ at most, for an hour (usage says it too, once a day)
66
93
  Limits show for Claude Pro, Max and Ultra plans, after the first reply in a session.
67
94
  Options: --no-color (or NO_COLOR), --no-history (or CLAUDEKIT_NO_HISTORY=1) keeps no numbers.
68
95
 
@@ -78,28 +105,30 @@ COMMANDS IN CLAUDE CODE (type them; Claude never runs them on its own)
78
105
  Your prompts ${say} prompts add "name" "the prompt" → /ck-name
79
106
 
80
107
  YOUR LIMITS
81
- usage every limit with bars and reset times, the run-out forecast, replies left,
82
- what your last prompt and this chat cost, per-model cost, days without a limit
108
+ usage every limit with bars and reset times, what your last prompt and this chat
109
+ cost, per-model cost, days without a limit, the run-out time from 70% used
110
+ (Pro: from 20%, and replies left)
83
111
  week your Claude week: weekly % used, busiest day, days active, limit hits, by day
84
- notify at a limit, waits and sends a desktop notification when Claude is back
112
+ notify Pro at a limit, waits and sends a desktop notification when Claude is back
85
113
  (--test sends one now)
86
114
 
87
115
  YOUR CHATS
88
116
  Claude Code keeps every chat in ~/.claude/projects and deletes them after 30 days by default.
89
117
  These commands read those files; they never change them.
90
- search <words> every chat that has all the words, with the matching lines and how to reopen it
118
+ search every chat from the last 7 days that has all the words, with the matching lines
119
+ and how to reopen it (Pro: every chat, however old)
91
120
  map [chat] a numbered outline: one line per prompt
92
- export [chat] Markdown (default), --format json or txt; --turns 3-5 or 2,4 for some prompts;
93
- --out file.md, or --out - to print it
94
- backup [folder] one Markdown file per chat, by project, in ~/claudekit-backup; only new and
121
+ export a chat from the last 7 days as Markdown (default) or --format txt; --out file.md,
122
+ or --out - to print it. Pro: any chat, --format json, --turns 3-5 or 2,4
123
+ backup Pro one Markdown file per chat, by project, in ~/claudekit-backup; only new and
95
124
  changed chats are written. --auto turns on a backup after every session,
96
125
  --auto off turns it off
97
- fork [chat] opens a copy of the chat in Claude Code (claude --resume <id> --fork-session),
126
+ fork Pro opens a copy of the chat in Claude Code (claude --resume <id> --fork-session),
98
127
  so you can try another direction and keep the original. --print shows the command
99
- reference [chat] saves the chat in ~/.claudekit/references; type @<path> in Claude Code to use
128
+ reference Pro saves the chat in ~/.claudekit/references; type @<path> in Claude Code to use
100
129
  it as context in another chat (--out - prints it)
101
- brief shows your last Handoff Brief for this folder; --start opens a new session from
102
- it; --path prints where it is
130
+ brief shows your last Handoff Brief for this folder; --path prints where it is;
131
+ --start (Pro) opens a new session from it
103
132
  pins this folder's pins (--all: every folder); pin "text" adds one by hand
104
133
  [chat] is the newest chat in this folder, or a session id (or its first 4+ characters), or
105
134
  words from its title.
@@ -109,11 +138,22 @@ TOKENS
109
138
  The same estimator as the extension; Claude counts tokens its own way.
110
139
 
111
140
  PRIVACY
112
- No network calls. It reads the JSON Claude Code passes to the status line and Claude Code's
113
- chat files on your computer. It keeps a few usage numbers in ~/.claudekit/usage.json (percent
114
- used, reset times, when, the model family, and short numbers standing for the session and
115
- prompt; no chat text) for 8 days, plus what you save (pins, briefs, references). Nothing is
116
- sent anywhere. npx itself may check npm for a newer version; a global install avoids that.
141
+ It reads the JSON Claude Code passes to the status line and Claude Code's chat files on your
142
+ computer, and keeps usage numbers in ~/.claudekit/usage.json: readings for 8 days (percent used,
143
+ reset times, when, the model family, short numbers standing for the session and prompt) and one
144
+ line a day for 90 days (peak 5-hour and weekly %, limit hits). No chat text. Plus what you save
145
+ (pins, briefs, references) and your Pro key.
146
+ It sends anonymous usage counts: a random id for this terminal, the version, OS family and Node
147
+ major version; per command its name, flag names (never values), exit code and duration; words
148
+ like "pro_gate: notify"; and once a day whether limits show (a paid Claude plan), a limit hit and
149
+ a usage band. Never your chats, prompts, code, file paths, project or repo names, or your key.
150
+ Counts go out about once an hour from a command; the status line never waits on the network.
151
+ Setups may appear on claudekit.app as "someone in <country> set it up", with no other detail.
152
+ Nothing is sent before you've seen the notice once, and nothing at all after
153
+ ${say} telemetry off, with DO_NOT_TRACK=1, or in CI.
154
+ The Pro key is checked on your computer. The network is used to send those counts, to fetch or
155
+ renew a key, and by pro to show the price. npx itself may check npm for a newer version; a
156
+ global install avoids that.
117
157
 
118
158
  ON CLAUDE.AI TOO
119
159
  The ClaudeKit extension shows your limits, forecasts and more right on claude.ai:
package/lib/license.js ADDED
@@ -0,0 +1,77 @@
1
+ // The ClaudeKit Pro licence in the terminal (Terminal Pro, Dec 2026): one Pro for the browser
2
+ // extension and the terminal. A key looks like "ckp1.<payload>.<signature>": Ed25519, signed by
3
+ // ClaudeKit's backend, checked here offline against the public key below. No network is needed to
4
+ // check it; fetching or refreshing a key is the only time the network is used for the licence.
5
+
6
+ import { createPublicKey, verify } from 'node:crypto';
7
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+
10
+ import { kitDir } from './paths.js';
11
+
12
+ // The public half of the backend's TERMINAL_LICENSE_PRIVATE_KEY (SPKI, DER, base64).
13
+ export const LICENSE_PUBLIC_KEY = 'MCowBQYDK2VwAyEA+Hi+LLjwwx+O8TQUXrQPlQvvvgpv8s/5C+1R8SN2xko=';
14
+
15
+ const PREFIX = 'ckp1';
16
+ let publicKey = null;
17
+ let testPublicKey = null;
18
+
19
+ /** Tests only: check keys against another public key (the real one is above). */
20
+ export function useLicensePublicKeyForTests(pub) {
21
+ testPublicKey = pub;
22
+ publicKey = null;
23
+ }
24
+
25
+ function key(pub) {
26
+ if (pub) return createPublicKey({ key: Buffer.from(pub, 'base64'), format: 'der', type: 'spki' });
27
+ publicKey ??= createPublicKey({ key: Buffer.from(testPublicKey ?? LICENSE_PUBLIC_KEY, 'base64'), format: 'der', type: 'spki' });
28
+ return publicKey;
29
+ }
30
+
31
+ /**
32
+ * Check a key. Pure apart from the crypto.
33
+ * @returns {{ ok: true, payload: { kid: string, trial: boolean, exp: string } } | { ok: false, reason: 'format' | 'signature' | 'expired', payload?: object }}
34
+ */
35
+ export function checkKey(token, now = Date.now(), pub) {
36
+ if (typeof token !== 'string') return { ok: false, reason: 'format' };
37
+ const parts = token.trim().split('.');
38
+ if (parts.length !== 3 || parts[0] !== PREFIX) return { ok: false, reason: 'format' };
39
+ let payload;
40
+ try {
41
+ payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
42
+ } catch {
43
+ return { ok: false, reason: 'format' };
44
+ }
45
+ if (!payload || typeof payload !== 'object' || typeof payload.exp !== 'string' || typeof payload.kid !== 'string') return { ok: false, reason: 'format' };
46
+ let signed = false;
47
+ try {
48
+ signed = verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), key(pub), Buffer.from(parts[2], 'base64url'));
49
+ } catch {
50
+ signed = false;
51
+ }
52
+ if (!signed) return { ok: false, reason: 'signature' };
53
+ const exp = Date.parse(payload.exp);
54
+ const clean = { kid: payload.kid, trial: payload.trial === true, exp: payload.exp };
55
+ if (!Number.isFinite(exp) || exp <= now) return { ok: false, reason: 'expired', payload: clean };
56
+ return { ok: true, payload: clean };
57
+ }
58
+
59
+ const licensePath = (env) => join(kitDir(env), 'license.json');
60
+
61
+ export function readKey(env = process.env) {
62
+ try {
63
+ const data = JSON.parse(readFileSync(licensePath(env), 'utf8'));
64
+ return typeof data?.key === 'string' ? data.key : null;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+
70
+ export function saveKey(token, env = process.env) {
71
+ mkdirSync(kitDir(env), { recursive: true });
72
+ writeFileSync(licensePath(env), `${JSON.stringify({ key: token.trim() })}\n`, { mode: 0o600 });
73
+ }
74
+
75
+ export function forgetKey(env = process.env) {
76
+ rmSync(licensePath(env), { force: true });
77
+ }
package/lib/pro.js ADDED
@@ -0,0 +1,118 @@
1
+ // ClaudeKit Pro in the terminal (Terminal Pro, Dec 2026): "see your limits free; act on them with
2
+ // Pro", the same rule as the browser extension, and one licence for both.
3
+ // Free: the status line's numbers, usage, week, prompts and packs, tokens, pins, map, docs, brief,
4
+ // the run-out time once a limit is 70% used, and search and export of the last 7 days.
5
+ // Pro: the run-out time from 20% and replies left, notify, all-time search and export, JSON
6
+ // export and --turns ranges, backup (and --auto), fork, reference, brief --start.
7
+ // (Split changed Dec 4 by the owner, after the Competitors thread: free rivals give a run-out time,
8
+ // search and export; developers pay for history.)
9
+ // People who used ClaudeKit in the terminal before 0.3.0 keep everything until Jan 31, 2027.
10
+
11
+ import { checkKey, readKey, saveKey } from './license.js';
12
+ import { apiBase } from './telemetry.js';
13
+ import { grandfathered } from './terminal-state.js';
14
+
15
+ export const PRO_FEATURES = {
16
+ forecast: 'The early run-out forecast and replies left',
17
+ notify: '"Claude is back" notifications',
18
+ search_history: 'Searching chats older than 7 days',
19
+ export_history: 'Exporting chats older than 7 days',
20
+ export: 'JSON export and --turns ranges',
21
+ backup: 'Chat backups',
22
+ backup_warning: 'Chat backups',
23
+ backup_auto: 'Automatic chat backups',
24
+ fork: 'Forking a chat',
25
+ reference: 'Reference chats',
26
+ brief_start: 'Starting a session from a brief',
27
+ };
28
+
29
+ const REFRESH_BEFORE_MS = 5 * 24 * 60 * 60 * 1000;
30
+
31
+ /**
32
+ * What Pro this terminal has, offline.
33
+ * @returns {{ pro: boolean, via: 'key' | 'grandfather' | null, trial: boolean, exp: string | null, key: 'none' | 'ok' | 'expired' | 'invalid' }}
34
+ */
35
+ export function proStatus(env, state, now = Date.now()) {
36
+ const token = readKey(env);
37
+ const checked = token ? checkKey(token, now) : null;
38
+ const keyState = !token ? 'none' : checked.ok ? 'ok' : checked.reason === 'expired' ? 'expired' : 'invalid';
39
+ if (checked?.ok) return { pro: true, via: 'key', trial: checked.payload.trial, exp: checked.payload.exp, key: keyState };
40
+ if (grandfathered(state, now)) return { pro: true, via: 'grandfather', trial: false, exp: state.grandfatherUntil, key: keyState };
41
+ return { pro: false, via: null, trial: Boolean(checked?.payload?.trial), exp: checked?.payload?.exp ?? null, key: keyState };
42
+ }
43
+
44
+ async function fetchJson(fetchImpl, url, init = {}, timeoutMs = 4000) {
45
+ if (typeof fetchImpl !== 'function') return null;
46
+ const controller = new AbortController();
47
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
48
+ try {
49
+ const response = await fetchImpl(url, { ...init, signal: controller.signal });
50
+ const body = await response.json().catch(() => null);
51
+ return { status: response.status, body };
52
+ } catch {
53
+ return null;
54
+ } finally {
55
+ clearTimeout(timer);
56
+ }
57
+ }
58
+
59
+ /** A key that has ended, or ends within 5 days, gets a new expiry if its Pro is still on. Quiet. */
60
+ export async function refreshKeyIfDue(env, fetchImpl, now = Date.now()) {
61
+ const token = readKey(env);
62
+ if (!token) return false;
63
+ const checked = checkKey(token, now);
64
+ const exp = checked.payload ? Date.parse(checked.payload.exp) : NaN;
65
+ if (checked.reason === 'signature' || checked.reason === 'format') return false;
66
+ if (Number.isFinite(exp) && exp - now > REFRESH_BEFORE_MS) return false;
67
+ const result = await fetchJson(fetchImpl, `${apiBase(env)}/v1/terminal/refresh`, {
68
+ method: 'POST',
69
+ headers: { 'content-type': 'application/json' },
70
+ body: JSON.stringify({ key: token }),
71
+ }, 2500);
72
+ const fresh = result?.body?.key;
73
+ if (typeof fresh === 'string' && checkKey(fresh, now).ok) {
74
+ saveKey(fresh, env);
75
+ return true;
76
+ }
77
+ return false;
78
+ }
79
+
80
+ /** Ask the backend for this install's key (after a checkout from the terminal). */
81
+ export async function fetchKeyFor(env, fetchImpl, installId) {
82
+ const result = await fetchJson(fetchImpl, `${apiBase(env)}/v1/terminal/key?installId=${encodeURIComponent(installId)}`);
83
+ const key = result?.body?.key;
84
+ return typeof key === 'string' ? key : null;
85
+ }
86
+
87
+ /** The running yearly offer and prices, for `pro` (null offline). */
88
+ export async function fetchOffer(env, fetchImpl) {
89
+ const result = await fetchJson(fetchImpl, `${apiBase(env)}/v1/offer`, {}, 2500);
90
+ return result?.body && typeof result.body === 'object' ? result.body : null;
91
+ }
92
+
93
+ const dollars = (cents) => (cents % 100 === 0 ? `$${cents / 100}` : `$${(cents / 100).toFixed(2)}`);
94
+
95
+ /** "Holiday price: $20 for your first year (then $28/year), until Dec 31." or today's prices. */
96
+ export function offerLine(offer) {
97
+ const prices = offer?.prices;
98
+ const yearly = Number(prices?.yearlyCents);
99
+ const monthly = Number(prices?.monthlyCents);
100
+ const yo = offer?.yearlyOffer;
101
+ if (yo && Number.isFinite(Number(yo.priceCents)) && Date.parse(yo.endsAt) > Date.now()) {
102
+ const ends = new Date(yo.endsAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
103
+ return `${yo.name}: ${dollars(Number(yo.priceCents))} for your first year${Number.isFinite(yearly) ? ` (then ${dollars(yearly)}/year)` : ''}, until ${ends}.${Number.isFinite(monthly) ? ` Or ${dollars(monthly)}/month.` : ''}`;
104
+ }
105
+ if (Number.isFinite(yearly) && Number.isFinite(monthly)) return `${dollars(yearly)}/year or ${dollars(monthly)}/month.`;
106
+ return 'See prices at claudekit.app/pricing.';
107
+ }
108
+
109
+ /** The lines a Pro command prints when this terminal doesn't have Pro. */
110
+ const PLURAL = new Set(['forecast', 'notify', 'export', 'backup', 'backup_warning', 'backup_auto', 'reference']);
111
+
112
+ export function gateLines(feature, say, status) {
113
+ const what = PRO_FEATURES[feature] ?? 'This';
114
+ const lines = [`${what} ${PLURAL.has(feature) ? 'are' : 'is'} part of ClaudeKit Pro: one licence for the terminal and the browser extension.`];
115
+ if (status.key === 'expired') lines.push(`Your Pro key ended on ${new Date(status.exp).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}. Copy a new one from the ClaudeKit popup, or keep Pro: ${say} pro`);
116
+ else lines.push(`Get it: ${say} pro · Have a key? ${say} activate <key>`);
117
+ return lines;
118
+ }
package/lib/state.js CHANGED
@@ -13,10 +13,19 @@ import { usagePath } from './paths.js';
13
13
  const KEEP_MS = 8 * DAY_MS;
14
14
  const MAX_READINGS = 4000;
15
15
  const MAX_HITS = 100;
16
+ // One summary per day, kept 90 days (Competitors, Dec 4: history can't be filled in later): the
17
+ // day's peak 5-hour and weekly %, and its limit hits. Numbers only.
18
+ const KEEP_DAYS = 90;
16
19
  const QUIET_MS = 10 * 60 * 1000; // an unchanged reading is kept again only after this long
17
20
 
18
21
  export function emptyState() {
19
- return { v: 1, readings: [], hits: [] };
22
+ return { v: 1, readings: [], hits: [], days: [] };
23
+ }
24
+
25
+ /** "2026-12-04" in this computer's time zone. */
26
+ export function localDay(ms) {
27
+ const d = new Date(ms);
28
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
20
29
  }
21
30
 
22
31
  export function historyEnabled(argv = [], env = {}) {
@@ -32,6 +41,7 @@ export function loadState(env = process.env) {
32
41
  v: 1,
33
42
  readings: Array.isArray(data.readings) ? data.readings.filter((r) => r && Number.isFinite(r.t)) : [],
34
43
  hits: Array.isArray(data.hits) ? data.hits.filter((h) => h && Number.isFinite(h.r)) : [],
44
+ days: Array.isArray(data.days) ? data.days.filter((d) => d && typeof d.d === 'string') : [],
35
45
  };
36
46
  } catch {
37
47
  return emptyState();
@@ -107,12 +117,28 @@ export function addReading(state, reading) {
107
117
  if (hits.some((h) => h.k === k && sameWindow(h.r, reset))) return;
108
118
  hits.push({ k, at: now, r: reset });
109
119
  };
120
+ const before = hits.length;
110
121
  noteHit('5h', reading.h, reading.hr);
111
122
  noteHit('week', reading.w, reading.wr);
123
+ // The day's summary: peaks and limit hits.
124
+ const days = Array.isArray(state.days) ? state.days.map((d) => ({ ...d })) : [];
125
+ if (hasLimits) {
126
+ const key = localDay(now);
127
+ let today = days.find((d) => d.d === key);
128
+ if (!today) {
129
+ today = { d: key, h: null, w: null, hits: 0 };
130
+ days.push(today);
131
+ }
132
+ if (reading.h !== null) today.h = Math.max(today.h ?? 0, reading.h);
133
+ if (reading.w !== null) today.w = Math.max(today.w ?? 0, reading.w);
134
+ today.hits += hits.length - before;
135
+ }
136
+ const oldest = localDay(now - KEEP_DAYS * DAY_MS);
112
137
  return {
113
138
  v: 1,
114
139
  readings: readings.slice(-MAX_READINGS),
115
140
  hits: hits.slice(-MAX_HITS),
141
+ days: days.filter((d) => d.d > oldest).sort((a, b) => (a.d < b.d ? -1 : 1)).slice(-KEEP_DAYS),
116
142
  };
117
143
  }
118
144
 
@@ -121,7 +147,7 @@ export function recordReading(data, now, env = process.env) {
121
147
  const reading = readingFromInput(data, now);
122
148
  const before = loadState(env);
123
149
  const after = addReading(before, reading);
124
- if (after.readings.length !== before.readings.length || after.hits.length !== before.hits.length || after.readings.at(-1) !== before.readings.at(-1)) {
150
+ if (after.readings.length !== before.readings.length || after.hits.length !== before.hits.length || after.readings.at(-1) !== before.readings.at(-1) || JSON.stringify(after.days.at(-1)) !== JSON.stringify(before.days?.at(-1))) {
125
151
  saveState(after, env);
126
152
  }
127
153
  return { state: after, reading };
package/lib/statusline.js CHANGED
@@ -173,6 +173,7 @@ function spendPart(rateLimits, now, opts) {
173
173
  * @param {(d: Date) => string} [options.formatWeekday] e.g. "Thu"
174
174
  * @param {{promptCost?: number|null, forecast?: object|null, repliesLeft?: number|null}} [options.insights]
175
175
  * @param {boolean} [options.handoffHint] show "/ck-handoff" near a limit (the command is installed)
176
+ * @param {string|null} [options.notice] a short notice for the end of the line (the Jan 31 carve-out)
176
177
  */
177
178
  export function formatStatusLine(input, options = {}) {
178
179
  let model = FALLBACK;
@@ -199,6 +200,7 @@ export function formatStatusLine(input, options = {}) {
199
200
  if (spend) segments.push(spend);
200
201
  const top = Math.max(session?.used ?? 0, weekly?.used ?? 0);
201
202
  if (options.handoffHint && top >= 90 && top < 100) segments.push('near limit: /ck-handoff');
203
+ if (typeof options.notice === 'string' && options.notice) segments.push(options.notice);
202
204
  return segments.join(SEP);
203
205
  } catch {
204
206
  return model;
@@ -0,0 +1,127 @@
1
+ // Anonymous usage counts (Terminal Pro, Dec 2026; the owner asked to measure the terminal funnel).
2
+ // What is sent: this terminal's random id, the package version, and allowlisted words such as
3
+ // "command: search" or "pro_gate: notify". Never prompts, chat text, file paths, project names or
4
+ // the licence key. Nothing is sent until the notice has been shown once in a command (never from the
5
+ // status line alone), and nothing at all with `claudekit-terminal telemetry off`, DO_NOT_TRACK=1,
6
+ // CLAUDEKIT_TELEMETRY=0 or in CI.
7
+
8
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+
11
+ import { kitDir } from './paths.js';
12
+
13
+ const MAX_QUEUE = 200;
14
+ const queuePath = (env) => join(kitDir(env), 'events.json');
15
+
16
+ /** Said on the site's terminal page from 0.3.1 (Sales spec, Dec 4): country only, no other detail. */
17
+ export const SITE_LINE = "Setups may appear on claudekit.app as 'someone in <country> set it up', with no other detail.";
18
+
19
+ export const TELEMETRY_NOTICE = (say) =>
20
+ `ClaudeKit for the terminal sends anonymous usage counts (which commands run and when a Pro feature is asked for; never your chats, code, file paths or keys) so we can make it better. ${SITE_LINE} Turn it off any time: ${say} telemetry off (or set DO_NOT_TRACK=1).`;
21
+
22
+ /** For people who saw the notice before 0.3.1 said that. */
23
+ export const SITE_NOTICE = (say) => `New in 0.3.1: ${SITE_LINE} Turn usage counts off: ${say} telemetry off`;
24
+
25
+ export function apiBase(env = process.env) {
26
+ return (env.CLAUDEKIT_API || 'https://api.claudekit.app').replace(/\/$/, '');
27
+ }
28
+
29
+ function truthy(value) {
30
+ return typeof value === 'string' && value !== '' && value !== '0' && value.toLowerCase() !== 'false';
31
+ }
32
+
33
+ /** Whether counts may be sent at all (the notice must have been shown, too). */
34
+ export function telemetryAllowed(env, state) {
35
+ if (truthy(env.DO_NOT_TRACK) || truthy(env.CI) || env.CLAUDEKIT_TELEMETRY === '0') return false;
36
+ if (state?.telemetry === false) return false;
37
+ return state?.noticeShown?.telemetry === true;
38
+ }
39
+
40
+ function readQueue(env) {
41
+ try {
42
+ const list = JSON.parse(readFileSync(queuePath(env), 'utf8'));
43
+ return Array.isArray(list) ? list : [];
44
+ } catch {
45
+ return [];
46
+ }
47
+ }
48
+
49
+ function writeQueue(env, list) {
50
+ try {
51
+ mkdirSync(kitDir(env), { recursive: true });
52
+ writeFileSync(queuePath(env), JSON.stringify(list.slice(-MAX_QUEUE)));
53
+ } catch {
54
+ // Never in the way.
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Queue one count, if allowed. `extra` may add a command's exit code (c), duration (ms) and the
60
+ * names of the flags it was run with (f), never their values.
61
+ */
62
+ export function track(env, state, event, detail = null, now = Date.now(), extra = {}) {
63
+ if (!telemetryAllowed(env, state)) return;
64
+ const list = readQueue(env);
65
+ list.push({ e: event, ...(detail ? { d: detail } : {}), at: now, ...extra });
66
+ writeQueue(env, list);
67
+ }
68
+
69
+ /** The flag names in argv ("--limit=5" → "limit"), never values or other words. */
70
+ export function flagNames(argv) {
71
+ return [...new Set((argv ?? []).filter((a) => typeof a === 'string' && a.startsWith('--')).map((a) => a.slice(2).split('=')[0]))].slice(0, 10);
72
+ }
73
+
74
+ /** OS family and Node major version, sent with each batch. */
75
+ export function runtimeInfo(platform = process.platform, nodeVersion = process.versions.node) {
76
+ const os = platform === 'darwin' ? 'mac' : platform === 'win32' ? 'win' : platform === 'linux' ? 'linux' : 'other';
77
+ return { os, node: Number.parseInt(String(nodeVersion), 10) || null };
78
+ }
79
+
80
+ const HOUR_MS = 60 * 60 * 1000;
81
+
82
+ /** Whether a command run should send now: about once an hour, sooner when 50 are queued. */
83
+ export function flushDue(env, state, now = Date.now()) {
84
+ if (!telemetryAllowed(env, state)) return false;
85
+ const last = Date.parse(state?.lastFlush ?? '');
86
+ return !Number.isFinite(last) || now - last >= HOUR_MS || readQueue(env).length >= 50;
87
+ }
88
+
89
+ /** Drop anything queued (telemetry off). */
90
+ export function clearQueue(env) {
91
+ writeQueue(env, []);
92
+ }
93
+
94
+ /** Send what is queued, 50 at a time. Never throws; gives up after `timeoutMs`. */
95
+ export async function flush(env, state, version, fetchImpl, timeoutMs = 2000) {
96
+ if (!telemetryAllowed(env, state) || typeof fetchImpl !== 'function') return 0;
97
+ const list = readQueue(env);
98
+ if (list.length === 0) return 0;
99
+ const batch = list.slice(0, 50);
100
+ const controller = new AbortController();
101
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
102
+ try {
103
+ const response = await fetchImpl(`${apiBase(env)}/v1/terminal/events`, {
104
+ method: 'POST',
105
+ headers: { 'content-type': 'application/json' },
106
+ body: JSON.stringify({ tid: state.id, v: version, ...runtimeInfo(), events: batch }),
107
+ signal: controller.signal,
108
+ });
109
+ if (!response.ok) return 0;
110
+ writeQueue(env, readQueue(env).slice(batch.length));
111
+ return batch.length;
112
+ } catch {
113
+ return 0;
114
+ } finally {
115
+ clearTimeout(timer);
116
+ }
117
+ }
118
+
119
+ /** The status line's coarse daily signals: paid Claude plan or API, a limit hit, a usage band. */
120
+ export function statusSignals(data) {
121
+ const limits = data?.rate_limits && typeof data.rate_limits === 'object' ? data.rate_limits : null;
122
+ if (!limits) return ['plan_api'];
123
+ const pct = (w) => (w && Number.isFinite(Number(w.used_percentage)) ? Number(w.used_percentage) : 0);
124
+ const top = Math.max(pct(limits.five_hour), pct(limits.seven_day));
125
+ const band = top >= 90 ? 'band_90' : top >= 75 ? 'band_75' : top >= 50 ? 'band_50' : top >= 25 ? 'band_25' : 'band_0';
126
+ return ['plan_paid', band, ...(top >= 100 ? ['limit_hit'] : [])];
127
+ }
@@ -0,0 +1,72 @@
1
+ // ~/.claudekit/terminal.json: this terminal's own settings.
2
+ // id random "ckt_…" id for the anonymous usage counts (never tied to a person)
3
+ // telemetry false once turned off
4
+ // noticeShown { telemetry, site, grandfather }: one-time notices already shown (site: the 0.3.1
5
+ // line that setups may appear on claudekit.app)
6
+ // grandfatherUntil set for people who used ClaudeKit in the terminal before 0.3.0: every
7
+ // feature stays free for them until then (Terminal Pro, Dec 2026)
8
+ // hints { command: 'YYYY-MM-DD' }: the last day a "Pro: …" hint was shown for it
9
+ // installId the id a terminal checkout used, so `pro` can pick up its key later
10
+ // lastDaily 'YYYY-MM-DD' of the status line's last daily count
11
+ // expiring { at, count }: chats Claude Code deletes within 3 days, checked hourly
12
+ // expiryNote { day, from }: the day's status-line deletion note (shown for its first hour)
13
+ // expiryWarnedAt when the deletion warning was last shown (a backup soon after counts it)
14
+
15
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
16
+ import { randomBytes } from 'node:crypto';
17
+ import { join } from 'node:path';
18
+
19
+ import { installedPath, kitDir, usagePath } from './paths.js';
20
+
21
+ /** Existing users keep every feature until the end of this day (UTC). */
22
+ export const GRANDFATHER_UNTIL = '2027-01-31T23:59:59.000Z';
23
+
24
+ const statePath = (env) => join(kitDir(env), 'terminal.json');
25
+
26
+ export function newTerminalId() {
27
+ return `ckt_${randomBytes(16).toString('hex')}`;
28
+ }
29
+
30
+ function read(env) {
31
+ try {
32
+ const data = JSON.parse(readFileSync(statePath(env), 'utf8'));
33
+ return data && typeof data === 'object' ? data : null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * This terminal's state, created on first use. Someone who already had ClaudeKit files from before
41
+ * 0.3.0 (setup done, or usage numbers kept) is an existing user: grandfathered until Jan 31.
42
+ */
43
+ export function loadTerminal(env = process.env, now = Date.now()) {
44
+ const existing = read(env);
45
+ if (existing && typeof existing.id === 'string') {
46
+ return { noticeShown: {}, hints: {}, ...existing };
47
+ }
48
+ const existingUser = existsSync(installedPath(env)) || existsSync(usagePath(env));
49
+ const state = {
50
+ id: newTerminalId(),
51
+ created: new Date(now).toISOString(),
52
+ firstVersion: existingUser ? 'before-0.3.0' : null,
53
+ grandfatherUntil: existingUser && now < Date.parse(GRANDFATHER_UNTIL) ? GRANDFATHER_UNTIL : null,
54
+ noticeShown: {},
55
+ hints: {},
56
+ };
57
+ saveTerminal(state, env);
58
+ return state;
59
+ }
60
+
61
+ export function saveTerminal(state, env = process.env) {
62
+ try {
63
+ mkdirSync(kitDir(env), { recursive: true });
64
+ writeFileSync(statePath(env), `${JSON.stringify(state, null, 2)}\n`);
65
+ } catch {
66
+ // Never in the way of a command.
67
+ }
68
+ }
69
+
70
+ export function grandfathered(state, now = Date.now()) {
71
+ return typeof state?.grandfatherUntil === 'string' && Date.parse(state.grandfatherUntil) > now;
72
+ }