claudekit-terminal 0.2.0 → 0.3.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/lib/cli.js CHANGED
@@ -24,6 +24,13 @@ import { PACK_IDS, myPromptSkill, packList, packSkills, skillBody, skillDescript
24
24
  import { historyEnabled, latestReading, loadState, recordReading } from './state.js';
25
25
  import { FALLBACK, colorEnabled, formatStatusLine, parseInput } from './statusline.js';
26
26
  import { countWords, estimateTokens } from './tokens.js';
27
+ import { checkKey, forgetKey, saveKey } from './license.js';
28
+ import { fetchKeyFor, fetchOffer, gateLines, offerLine, proStatus, refreshKeyIfDue } from './pro.js';
29
+ import { TELEMETRY_NOTICE, apiBase, clearQueue, flagNames, flush, flushDue, statusSignals, telemetryAllowed, track } from './telemetry.js';
30
+ import { GRANDFATHER_UNTIL, loadTerminal, saveTerminal } from './terminal-state.js';
31
+ import { expiringChats, expiryLine } from './cleanup.js';
32
+ import { randomBytes } from 'node:crypto';
33
+ import { fileURLToPath } from 'node:url';
27
34
  import {
28
35
  listSessions,
29
36
  parseTurns,
@@ -74,9 +81,29 @@ export function defaultIo() {
74
81
  notify: (title, message) => desktopNotify(title, message),
75
82
  self: selfCommand(),
76
83
  formatters: makeFormatters(),
84
+ fetch: globalThis.fetch,
85
+ openUrl: (url) => openInBrowser(url),
86
+ // The status line's once-a-day counts are sent by a detached copy, so it never waits on the network.
87
+ flushInBackground: () => {
88
+ try {
89
+ nodeSpawn(process.execPath, [fileURLToPath(new URL('../bin/claudekit-terminal.js', import.meta.url)), '__flush'], { detached: true, stdio: 'ignore' }).unref();
90
+ } catch {
91
+ // Next time.
92
+ }
93
+ },
77
94
  };
78
95
  }
79
96
 
97
+ function openInBrowser(url) {
98
+ const [cmd, args] = process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
99
+ try {
100
+ nodeSpawn(cmd, args, { detached: true, stdio: 'ignore' }).unref();
101
+ return true;
102
+ } catch {
103
+ return false;
104
+ }
105
+ }
106
+
80
107
  function readAllStdin() {
81
108
  return new Promise((resolveText) => {
82
109
  const chunks = [];
@@ -116,6 +143,14 @@ const COMMANDS = {
116
143
  pin: pinCommand,
117
144
  prompts: promptsCommand,
118
145
  tokens: tokensCommand,
146
+ activate: activateCommand,
147
+ pro: proCommand,
148
+ license: licenseCommand,
149
+ telemetry: telemetryCommand,
150
+ __flush: async (_args, io) => {
151
+ await flush(io.env, loadTerminal(io.env, io.now()), VERSION, io.fetch, 4000);
152
+ return 0;
153
+ },
119
154
  docs: (_args, io) => (io.out(DOCS(io.self.say)), 0),
120
155
  help: (_args, io) => (io.out(HELP(io.self.say)), 0),
121
156
  version: (_args, io) => (io.out(VERSION), 0),
@@ -135,12 +170,85 @@ export async function run(argv, io = defaultIo()) {
135
170
  io.err(`Unknown command "${first}". Run "${io.self.say} help" for the list.`);
136
171
  return 2;
137
172
  }
173
+ if (first === '__flush' || first === 'version') return command(rest, io);
174
+ const state = loadTerminal(io.env, io.now());
175
+ io.state = state;
176
+ showNotices(io, state, first);
177
+ const started = Date.now();
178
+ let code;
138
179
  try {
139
- return await command(rest, io);
180
+ code = await command(rest, io);
140
181
  } catch (error) {
141
182
  io.err(error?.message ?? String(error));
142
- return 1;
183
+ code = 1;
184
+ }
185
+ if (!io.skipTracking) {
186
+ track(io.env, io.state, 'command', first, io.now(), { c: Number.isInteger(code) ? code : 1, ms: Math.max(0, Date.now() - started), f: flagNames(rest) });
187
+ if (first === 'setup' && code !== 0) track(io.env, io.state, 'setup_step', 'failed', io.now());
188
+ // About once an hour, from a normal command; at once for the steps that matter most to the funnel.
189
+ if (['setup', 'pro', 'activate'].includes(first) || flushDue(io.env, io.state, io.now())) {
190
+ // An attempt counts even if it fails, so an offline terminal doesn't wait on every command.
191
+ await flush(io.env, io.state, VERSION, io.fetch, 1500);
192
+ io.state.lastFlush = new Date(io.now()).toISOString();
193
+ saveTerminal(io.state, io.env);
194
+ }
195
+ }
196
+ return code;
197
+ }
198
+
199
+ /** The one-time notices: what is counted (and how to stop it), and the Jan 31 carve-out for existing users. */
200
+ function showNotices(io, state, command) {
201
+ let changed = false;
202
+ if (!state.noticeShown.grandfather && state.grandfatherUntil && Date.parse(state.grandfatherUntil) > io.now()) {
203
+ io.err(`Heads-up: ClaudeKit Pro features in the terminal (run-out forecast, notify, search, export, backup, fork, reference) are part of ClaudeKit Pro from 0.3.0. They stay free for you until Jan 31, 2027. After that they're in ClaudeKit Pro, one licence with the browser extension: ${io.self.say} pro`);
204
+ state.noticeShown.grandfather = true;
205
+ changed = true;
206
+ track(io.env, state, 'notice', 'grandfather', io.now());
207
+ }
208
+ if (!state.noticeShown.telemetry && command !== 'telemetry') {
209
+ io.err(TELEMETRY_NOTICE(io.self.say));
210
+ state.noticeShown.telemetry = true;
211
+ changed = true;
212
+ track(io.env, state, 'notice', 'telemetry', io.now());
143
213
  }
214
+ if (changed) saveTerminal(state, io.env);
215
+ }
216
+
217
+ /** Pro, or the reason it isn't, printed. Counts the gate hit. A key near its end is refreshed first. */
218
+ async function requirePro(io, feature, { silent = false } = {}) {
219
+ const state = io.state ?? loadTerminal(io.env, io.now());
220
+ let status = proStatus(io.env, state, io.now());
221
+ if (status.key === 'expired' || (status.via === 'key' && Date.parse(status.exp) - io.now() < 5 * 86_400_000)) {
222
+ if (await refreshKeyIfDue(io.env, io.fetch, io.now())) status = proStatus(io.env, state, io.now());
223
+ }
224
+ if (status.pro) return true;
225
+ track(io.env, state, 'pro_gate', feature, io.now());
226
+ if (status.key === 'expired') track(io.env, state, 'key_expired', status.trial ? 'trial' : 'paid', io.now());
227
+ if (!silent) io.out(gateLines(feature, io.self.say, status).join('\n'));
228
+ return false;
229
+ }
230
+
231
+ // Owner, Dec 4 (after the Competitors thread): free shows the run-out time once a limit is 70% used,
232
+ // like the extension's free forecast; Pro shows it from 20%, plus replies left. Free search and
233
+ // export cover the last 7 days; Pro covers all time.
234
+ export const FREE_FORECAST_FROM = 70;
235
+ export const FREE_HISTORY_DAYS = 7;
236
+ const FREE_HISTORY_MS = FREE_HISTORY_DAYS * 86_400_000;
237
+
238
+ /** The run-out forecast for one limit, if this terminal may show it at this level. */
239
+ function forecastFor(readings, cur, key, pro) {
240
+ if (!pro && !(cur?.[key] >= FREE_FORECAST_FROM)) return null;
241
+ return forecast(readings, cur, key);
242
+ }
243
+
244
+ /** Pro status for a command with free and Pro parts (a key near its end is refreshed first). */
245
+ async function hasPro(io) {
246
+ const state = io.state ?? loadTerminal(io.env, io.now());
247
+ const status = proStatus(io.env, state, io.now());
248
+ if (status.pro && !(status.via === 'key' && Date.parse(status.exp) - io.now() < 5 * 86_400_000)) return true;
249
+ if (status.key === 'none' && !status.pro) return false;
250
+ if (await refreshKeyIfDue(io.env, io.fetch, io.now())) return proStatus(io.env, state, io.now()).pro;
251
+ return status.pro;
144
252
  }
145
253
 
146
254
  // ---------------------------------------------------------------- status line
@@ -157,19 +265,29 @@ export function statusLineFor(raw, argv, io) {
157
265
  const data = parseInput(raw);
158
266
  if (!data) return FALLBACK;
159
267
  const now = io.now();
268
+ let terminal = null;
269
+ let pro = false;
270
+ try {
271
+ terminal = loadTerminal(io.env, now);
272
+ pro = proStatus(io.env, terminal, now).pro;
273
+ } catch {
274
+ terminal = null;
275
+ }
160
276
  let insights = null;
161
277
  if (historyEnabled(argv, io.env)) {
162
278
  try {
163
279
  const { state, reading } = recordReading(data, now, io.env);
164
280
  insights = {
165
281
  promptCost: currentPromptCost(state.readings, reading),
166
- forecast: forecast(state.readings, reading, 'h'),
167
- repliesLeft: repliesLeft(state.readings, reading),
282
+ // Free shows the run-out time from 70% used; Pro from 20%, plus replies left.
283
+ forecast: forecastFor(state.readings, reading, 'h', pro),
284
+ repliesLeft: pro ? repliesLeft(state.readings, reading) : null,
168
285
  };
169
286
  } catch {
170
287
  insights = null;
171
288
  }
172
289
  }
290
+ if (terminal) dailyStatusCount(io, terminal, data, now);
173
291
  let handoffHint = false;
174
292
  try {
175
293
  handoffHint = existsSync(join(skillsDir(io.env), 'ck-handoff', 'SKILL.md'));
@@ -181,11 +299,54 @@ export function statusLineFor(raw, argv, io) {
181
299
  color,
182
300
  insights,
183
301
  handoffHint,
302
+ notice: terminal ? [statusNotice(terminal, now), expirySegment(io, terminal, now)].filter(Boolean).join(' │ ') || null : null,
184
303
  formatTime: io.formatters.formatTime,
185
304
  formatWeekday: io.formatters.formatWeekday,
186
305
  });
187
306
  }
188
307
 
308
+ /** Existing users are told on the line itself: the day after they get 0.3.0, and Jan 25–31. */
309
+ function statusNotice(terminal, now) {
310
+ if (!terminal.grandfatherUntil) return null;
311
+ const until = Date.parse(terminal.grandfatherUntil);
312
+ if (!(until > now)) return null;
313
+ const created = Date.parse(terminal.created);
314
+ if (Number.isFinite(created) && now - created < 86_400_000) return 'ClaudeKit Pro free for you until Jan 31';
315
+ if (until - now < 7 * 86_400_000) return 'Pro features end Jan 31: claudekit-terminal pro';
316
+ return null;
317
+ }
318
+
319
+ /** "3 chats expire ≤3d" when Claude Code is about to delete chats; checked at most once an hour. */
320
+ function expirySegment(io, terminal, now) {
321
+ try {
322
+ const cached = terminal.expiring;
323
+ let count = cached && now - Date.parse(cached.at) < 3_600_000 ? cached.count : null;
324
+ if (count === null) {
325
+ count = expiringChats(io.env, now).count;
326
+ terminal.expiring = { at: new Date(now).toISOString(), count };
327
+ saveTerminal(terminal, io.env);
328
+ }
329
+ return count > 0 ? `${count} ${count === 1 ? 'chat expires' : 'chats expire'} ≤3d` : null;
330
+ } catch {
331
+ return null;
332
+ }
333
+ }
334
+
335
+ /** Once a day, when counts are on: "the status line ran", plus plan, limit-hit and usage-band words. */
336
+ function dailyStatusCount(io, terminal, data, now) {
337
+ try {
338
+ const day = new Date(now).toISOString().slice(0, 10);
339
+ if (terminal.lastDaily === day || !telemetryAllowed(io.env, terminal)) return;
340
+ terminal.lastDaily = day;
341
+ saveTerminal(terminal, io.env);
342
+ track(io.env, terminal, 'command', 'statusline', now);
343
+ for (const signal of statusSignals(data)) track(io.env, terminal, 'signal', signal, now);
344
+ io.flushInBackground?.();
345
+ } catch {
346
+ // Never in the way of the line.
347
+ }
348
+ }
349
+
189
350
  // ---------------------------------------------------------------- setup / remove
190
351
 
191
352
  function setupCommand(argv, io) {
@@ -211,12 +372,26 @@ function setupCommand(argv, io) {
211
372
  lines.push('Next: send a message in Claude Code. Your limits show after the first reply (Claude Pro, Max and Ultra plans).');
212
373
  lines.push(`Everything it does: ${self.say} docs · Undo: ${self.say} remove`);
213
374
  if (self.run.startsWith('npx')) lines.push(`Faster status line: npm install -g claudekit-terminal, then run "claudekit-terminal setup" once more.`);
375
+ const status = proStatus(io.env, io.state ?? loadTerminal(io.env, io.now()), io.now());
376
+ lines.push(status.via === 'key'
377
+ ? `ClaudeKit Pro is on until ${new Date(status.exp).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}.`
378
+ : status.via === 'grandfather'
379
+ ? 'Pro features stay free for you until Jan 31, 2027.'
380
+ : `Free: the status line, usage, week, prompts, tokens, pins. Pro (forecast, notify, search, export, backup, fork): ${self.say} pro`);
214
381
  io.out(lines.join('\n'));
382
+ if (io.state) {
383
+ if (!result.statusLine.kept) track(io.env, io.state, 'setup_step', 'settings', io.now());
384
+ if (result.written.length) track(io.env, io.state, 'setup_step', 'commands', io.now());
385
+ if (result.autoBackup) track(io.env, io.state, 'setup_step', 'hook', io.now());
386
+ track(io.env, io.state, 'setup', result.statusLine.kept ? 'kept_statusline' : 'done', io.now());
387
+ }
215
388
  return 0;
216
389
  }
217
390
 
218
391
  function removeCommand(argv, io) {
219
392
  const { flags } = parseArgs(argv);
393
+ // --all deletes ~/.claudekit, this terminal's id and queued counts with it: nothing more is sent.
394
+ if (flags.all) io.skipTracking = true;
220
395
  const result = remove(io.env, { all: flags.all === true });
221
396
  const lines = ['ClaudeKit for the terminal is removed.'];
222
397
  if (result.settingsError) lines.push(` • Settings not changed: ${result.settingsError}`);
@@ -225,6 +400,7 @@ function removeCommand(argv, io) {
225
400
  lines.push(result.deletedData ? ' ✓ ~/.claudekit deleted (usage numbers, pins, briefs, references)' : ' • Kept ~/.claudekit (usage numbers, pins, briefs). Delete it too: remove --all');
226
401
  lines.push(` • Chat backups, if any, stay in ${defaultBackupDir(io.env)}`);
227
402
  io.out(lines.join('\n'));
403
+ if (io.state && !flags.all) track(io.env, io.state, 'remove', 'done', io.now());
228
404
  return 0;
229
405
  }
230
406
 
@@ -249,9 +425,17 @@ function usageCommand(_argv, io) {
249
425
  lines.push(`${label.padEnd(15)}${String(Math.round(used)).padStart(3)}% ${bar(used)} ${resetText}`);
250
426
  if (extra) lines.push(`${''.padEnd(22)}${extra}`);
251
427
  };
428
+ const pro = proStatus(io.env, io.state ?? loadTerminal(io.env, now), now).pro;
429
+ // What Pro would add right now: the run-out time between 20% and 70%, and replies left.
430
+ let withheld = null;
431
+ if (!pro && cur.h !== null && cur.h < 100) {
432
+ const early = cur.h >= 20 && cur.h < FREE_FORECAST_FROM && Number.isFinite(forecast(state.readings, cur, 'h')?.runsOutAt);
433
+ const replies = cur.h >= 50 && Number.isFinite(repliesLeft(state.readings, cur));
434
+ if (early || replies) withheld = early ? 'early' : 'replies';
435
+ }
252
436
  if (cur.h !== null) {
253
- const fc = forecast(state.readings, cur, 'h');
254
- const left = repliesLeft(state.readings, cur);
437
+ const fc = forecastFor(state.readings, cur, 'h', pro);
438
+ const left = pro ? repliesLeft(state.readings, cur) : null;
255
439
  const bits = [];
256
440
  if (cur.h >= 100) bits.push('Limit reached');
257
441
  else if (fc?.runsOutAt) bits.push(`At this pace: runs out ~${f.formatTime(new Date(fc.runsOutAt))}`);
@@ -260,7 +444,7 @@ function usageCommand(_argv, io) {
260
444
  row('Session (5h)', cur.h, cur.hr, bits.join(' · '));
261
445
  }
262
446
  if (cur.w !== null) {
263
- const fc = forecast(state.readings, cur, 'w');
447
+ const fc = forecastFor(state.readings, cur, 'w', pro);
264
448
  const bits = [];
265
449
  if (cur.wr > now && cur.w < 100) {
266
450
  const days = (cur.wr - now) / 86_400_000;
@@ -281,10 +465,48 @@ function usageCommand(_argv, io) {
281
465
  const days = daysWithoutLimit(state.hits, now);
282
466
  if (days !== null) lines.push(days === 0 ? 'Limit you are at a limit now' : `No limit hit for ${days} ${days === 1 ? 'day' : 'days'}`);
283
467
  if (lines.at(-1) === '') lines.pop();
468
+ if (withheld && io.state) {
469
+ track(io.env, io.state, 'pro_gate', 'forecast', now);
470
+ if (proHintDue(io, 'usage')) {
471
+ lines.push('', withheld === 'early'
472
+ ? `Pro: when you'll run out from 20% used (free shows it from ${FREE_FORECAST_FROM}%), and replies left. ${io.self.say} pro`
473
+ : `Pro: about how many replies you have left at this pace. ${io.self.say} pro`);
474
+ }
475
+ }
476
+ const warning = expiryWarning(io, now);
477
+ if (warning) lines.push('', warning);
284
478
  io.out(lines.join('\n'));
285
479
  return 0;
286
480
  }
287
481
 
482
+ /**
483
+ * The free warning before Claude Code deletes chats (owner, Dec 4): at most once a day, in `usage`.
484
+ * Running `backup` without Pro within a day of it counts as pro_gate "backup_warning".
485
+ */
486
+ function expiryWarning(io, now) {
487
+ const state = io.state;
488
+ if (!state) return '';
489
+ const day = new Date(now).toISOString().slice(0, 10);
490
+ if (state.hints?.expiry === day) return '';
491
+ const line = expiryLine(expiringChats(io.env, now), io.self.say);
492
+ if (!line) return '';
493
+ state.hints = { ...(state.hints ?? {}), expiry: day };
494
+ state.expiryWarnedAt = new Date(now).toISOString();
495
+ saveTerminal(state, io.env);
496
+ return line;
497
+ }
498
+
499
+ /** At most one "Pro: …" hint per command per day. */
500
+ function proHintDue(io, command) {
501
+ const state = io.state;
502
+ if (!state) return false;
503
+ const day = new Date(io.now()).toISOString().slice(0, 10);
504
+ if (state.hints?.[command] === day) return false;
505
+ state.hints = { ...(state.hints ?? {}), [command]: day };
506
+ saveTerminal(state, io.env);
507
+ return true;
508
+ }
509
+
288
510
  function weekCommand(_argv, io) {
289
511
  const state = loadState(io.env);
290
512
  if (state.readings.length === 0) return noUsage(io);
@@ -316,6 +538,7 @@ function weekCommand(_argv, io) {
316
538
 
317
539
  async function notifyCommand(argv, io) {
318
540
  const { flags } = parseArgs(argv);
541
+ if (!(await requirePro(io, 'notify'))) return 4;
319
542
  if (flags.test) {
320
543
  io.notify('ClaudeKit', 'Test: this is how "Claude is back" looks.');
321
544
  io.out('Sent a test notification.');
@@ -354,17 +577,28 @@ function needChat(argv, io) {
354
577
  const picked = pickSession(files, words.join(' '), io.cwd);
355
578
  if (!picked) throw new Error(`No chat matches "${words.join(' ')}". Try a session id, words from its title, or leave it out for the latest.`);
356
579
  if (picked.note) io.err(picked.note);
357
- return { session: picked.session ?? readSession(picked.file), flags };
580
+ return { session: picked.session ?? readSession(picked.file), file: picked.file, flags };
358
581
  }
359
582
 
360
- function searchCommand(argv, io) {
583
+ async function searchCommand(argv, io) {
361
584
  const { words, flags } = parseArgs(argv, ['limit']);
362
585
  const query = words.join(' ').trim();
363
586
  if (!query) throw new Error(`What should it look for? ${io.self.say} search <words>`);
364
587
  const limit = Number(flags.limit) > 0 ? Number(flags.limit) : 20;
365
- const results = searchSessions(listSessions(io.env), query, { limit });
588
+ const pro = await hasPro(io);
589
+ const files = listSessions(io.env);
590
+ // Free covers chats used in the last 7 days; Pro covers all time.
591
+ const since = io.now() - FREE_HISTORY_MS;
592
+ const results = searchSessions(pro ? files : files.filter((f) => f.mtimeMs >= since), query, { limit });
593
+ const older = pro ? 0 : searchSessions(files.filter((f) => f.mtimeMs < since), query, { limit: 100 }).length;
594
+ let olderLine = '';
595
+ if (older > 0 && io.state) {
596
+ track(io.env, io.state, 'pro_gate', 'search_history', io.now());
597
+ if (proHintDue(io, 'search_history')) olderLine = `${older >= 100 ? '100+' : older} more ${older === 1 ? 'result is' : 'results are'} older than ${FREE_HISTORY_DAYS} days (Pro): ${io.self.say} pro`;
598
+ }
599
+ const scope = pro ? '' : ` from the last ${FREE_HISTORY_DAYS} days`;
366
600
  if (results.length === 0) {
367
- io.out(`No chat mentions "${query}".`);
601
+ io.out([`No chat${scope} mentions "${query}".`, olderLine].filter(Boolean).join('\n'));
368
602
  return 0;
369
603
  }
370
604
  const f = io.formatters;
@@ -373,13 +607,14 @@ function searchCommand(argv, io) {
373
607
  const re = new RegExp(query.split(/\s+/).map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'), 'gi');
374
608
  return text.replace(re, (m) => `${BOLD}${m}${RESET}`);
375
609
  };
376
- const lines = [`${results.length} ${results.length === 1 ? 'chat mentions' : 'chats mention'} "${query}"${results.length >= limit ? ' (showing the newest; --limit for more)' : ''}:`, ''];
610
+ const lines = [`${results.length} ${results.length === 1 ? 'chat' : 'chats'}${scope} ${results.length === 1 ? 'mentions' : 'mention'} "${query}"${results.length >= limit ? ' (showing the newest; --limit for more)' : ''}:`, ''];
377
611
  for (const { session, hits } of results) {
378
612
  const when = Number.isFinite(session.updated) ? `${f.formatDate(new Date(session.updated))} ${f.formatTime(new Date(session.updated))}` : '';
379
613
  lines.push(`${session.project ?? '?'} · ${when} · ${session.title} · ${hits.length} ${hits.length === 1 ? 'match' : 'matches'}`);
380
614
  for (const hit of hits.slice(0, 3)) lines.push(` ${hit.turn.n}. ${hit.where === 'prompt' ? 'You' : 'Claude'}: ${hl(hit.snippet)}`);
381
615
  lines.push(` open: claude --resume ${session.id}`, '');
382
616
  }
617
+ if (olderLine) lines.push(olderLine);
383
618
  io.out(lines.join('\n').trimEnd());
384
619
  return 0;
385
620
  }
@@ -413,8 +648,12 @@ function render(session, flags) {
413
648
  return { text: toMarkdown(session, turns), ext: 'md', turns };
414
649
  }
415
650
 
416
- function exportCommand(argv, io) {
417
- const { session, flags } = needChat(argv, io);
651
+ async function exportCommand(argv, io) {
652
+ const { session, file, flags } = needChat(argv, io);
653
+ // Free: Markdown or text of a whole chat used in the last 7 days. Pro: any chat, JSON, --turns.
654
+ const format = typeof flags.format === 'string' ? flags.format.toLowerCase() : 'md';
655
+ if ((format === 'json' || typeof flags.turns === 'string') && !(await requirePro(io, 'export'))) return 4;
656
+ if (file.mtimeMs < io.now() - FREE_HISTORY_MS && !(await requirePro(io, 'export_history'))) return 4;
418
657
  const { text, ext, turns } = render(session, flags);
419
658
  if (flags.out === '-') {
420
659
  io.out(text);
@@ -427,7 +666,8 @@ function exportCommand(argv, io) {
427
666
  return 0;
428
667
  }
429
668
 
430
- function referenceCommand(argv, io) {
669
+ async function referenceCommand(argv, io) {
670
+ if (!(await requirePro(io, 'reference'))) return 4;
431
671
  const { session, flags } = needChat(argv, io);
432
672
  const turns = selectTurns(session, parseTurns(typeof flags.turns === 'string' ? flags.turns : ''));
433
673
  const text = toReference(session, turns);
@@ -443,7 +683,8 @@ function referenceCommand(argv, io) {
443
683
  return 0;
444
684
  }
445
685
 
446
- function forkCommand(argv, io) {
686
+ async function forkCommand(argv, io) {
687
+ if (!(await requirePro(io, 'fork'))) return 4;
447
688
  const { session, flags } = needChat(argv, io);
448
689
  const args = ['--resume', session.id, '--fork-session'];
449
690
  const cwd = session.cwd && existsSync(session.cwd) ? session.cwd : io.cwd;
@@ -496,6 +737,7 @@ async function briefCommand(argv, io) {
496
737
  }
497
738
  const text = readFileSync(path, 'utf8');
498
739
  if (flags.start) {
740
+ if (!(await requirePro(io, 'brief_start'))) return 4;
499
741
  io.out(`Starting a new Claude Code session from ${path}`);
500
742
  return spawnClaude(io, [`Continue from this handoff brief:\n\n${text}`], io.cwd);
501
743
  }
@@ -503,8 +745,11 @@ async function briefCommand(argv, io) {
503
745
  return 0;
504
746
  }
505
747
 
506
- function backupCommand(argv, io) {
748
+ async function backupCommand(argv, io) {
507
749
  const { words, flags } = parseArgs(argv);
750
+ const off = flags.auto === 'off' || words[0] === 'off';
751
+ // The automatic backup's hook runs with --quiet after every session: without Pro it stays quiet.
752
+ if (!off && !(await requirePro(io, flags.auto !== undefined ? 'backup_auto' : 'backup', { silent: flags.quiet === true }))) return flags.quiet ? 0 : 4;
508
753
  if (flags.auto !== undefined) return autoBackup(words, flags, io);
509
754
  const dir = resolve(io.cwd, words[0] ?? defaultBackupDir(io.env));
510
755
  const manifestPath = join(dir, '.claudekit-backup.json');
@@ -701,3 +946,127 @@ async function tokensCommand(argv, io) {
701
946
  io.out(lines.join('\n'));
702
947
  return 0;
703
948
  }
949
+
950
+ // ---------------------------------------------------------------- Pro: licence, checkout, telemetry
951
+
952
+ const fmtDay = (iso) => new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
953
+
954
+ function activateCommand(argv, io) {
955
+ const { words } = parseArgs(argv);
956
+ const token = (words[0] ?? '').trim();
957
+ if (!token) throw new Error(`Paste your key after the command: ${io.self.say} activate <key>. Get one from the ClaudeKit popup (Use Pro in your terminal), or with: ${io.self.say} pro`);
958
+ const checked = checkKey(token, io.now());
959
+ if (!checked.ok && checked.reason !== 'expired') throw new Error("That isn't a ClaudeKit Pro key. Copy it again from the ClaudeKit popup: Use Pro in your terminal.");
960
+ if (!checked.ok) {
961
+ io.out(`That key ended on ${fmtDay(checked.payload.exp)}. Copy a new one from the ClaudeKit popup, or keep Pro: ${io.self.say} pro`);
962
+ return 1;
963
+ }
964
+ saveKey(token, io.env);
965
+ if (io.state) {
966
+ track(io.env, io.state, 'key_activated', checked.payload.trial ? 'trial' : 'paid', io.now());
967
+ // A key pasted from the popup: this terminal is linked to the browser extension.
968
+ track(io.env, io.state, 'signal', 'linked_extension', io.now());
969
+ }
970
+ io.out(`ClaudeKit Pro is on in this terminal${checked.payload.trial ? ' for your free trial' : ''}, until ${fmtDay(checked.payload.exp)}. The key is checked on this computer; it renews by itself while your Pro does.`);
971
+ return 0;
972
+ }
973
+
974
+ function licenseCommand(argv, io) {
975
+ const { flags } = parseArgs(argv);
976
+ if (flags.forget) {
977
+ forgetKey(io.env);
978
+ io.out('Removed the Pro key from this terminal.');
979
+ return 0;
980
+ }
981
+ const status = proStatus(io.env, io.state ?? loadTerminal(io.env, io.now()), io.now());
982
+ if (io.state) track(io.env, io.state, 'license', status.via === 'key' ? (status.trial ? 'trial' : 'pro') : status.via === 'grandfather' ? 'grandfather' : status.key === 'expired' ? 'expired' : 'free', io.now());
983
+ if (status.via === 'key') io.out(`ClaudeKit Pro${status.trial ? ' (free trial)' : ''} is on until ${fmtDay(status.exp)}.`);
984
+ else if (status.via === 'grandfather') io.out(`Pro features are free for you until ${fmtDay(GRANDFATHER_UNTIL)}, because you used ClaudeKit in the terminal before 0.3.0. Keep them after that: ${io.self.say} pro`);
985
+ else if (status.key === 'expired') io.out(`Your Pro key ended on ${fmtDay(status.exp)}. Copy a new one from the ClaudeKit popup, or: ${io.self.say} pro`);
986
+ else io.out(`Free. Pro adds the run-out forecast, notify, search, export, backup, fork and reference: ${io.self.say} pro`);
987
+ return 0;
988
+ }
989
+
990
+ async function proCommand(argv, io) {
991
+ const { words, flags } = parseArgs(argv);
992
+ const state = io.state ?? loadTerminal(io.env, io.now());
993
+ const status = proStatus(io.env, state, io.now());
994
+ if (status.via === 'key' && !flags.check) {
995
+ io.out(`ClaudeKit Pro${status.trial ? ' (free trial)' : ''} is on in this terminal until ${fmtDay(status.exp)}.`);
996
+ return 0;
997
+ }
998
+ // A checkout from the terminal uses its own install id, kept so the key can be picked up later.
999
+ if (!state.installId) {
1000
+ state.installId = `ckx_${randomBytes(16).toString('hex')}`;
1001
+ saveTerminal(state, io.env);
1002
+ }
1003
+ if (flags.check || words[0] === 'check') return pickUpKey(io, state, 1);
1004
+ const period = words[0] === 'monthly' ? 'monthly' : 'yearly';
1005
+ const offer = await fetchOffer(io.env, io.fetch);
1006
+ const url = `${apiBase(io.env)}/v1/billing/checkout?period=${period}&installId=${state.installId}&source=terminal`;
1007
+ io.out([
1008
+ 'ClaudeKit Pro: the run-out forecast and replies left, "Claude is back" notifications, search, export, backup, fork and reference chats in the terminal, plus everything Pro in the browser extension. One licence.',
1009
+ offer ? offerLine(offer) : 'Prices: claudekit.app/pricing',
1010
+ '',
1011
+ `Checkout (${period}${period === 'yearly' ? `; monthly: ${io.self.say} pro monthly` : ''}):`,
1012
+ url,
1013
+ '',
1014
+ 'Already have Pro in the browser extension? Open its popup → Use Pro in your terminal → copy the key, then:',
1015
+ `${io.self.say} activate <key>`,
1016
+ ].join('\n'));
1017
+ track(io.env, state, 'upgrade_open', 'pro_command', io.now());
1018
+ track(io.env, state, 'checkout_start', period, io.now());
1019
+ if (flags['no-open'] || io.stdinIsTTY === false) return 0;
1020
+ io.openUrl?.(url);
1021
+ io.out('\nOpened it in your browser. Waiting for the payment to finish… (Ctrl+C to stop; pick the key up later with: ' + `${io.self.say} pro check)`);
1022
+ return pickUpKey(io, state, 300);
1023
+ }
1024
+
1025
+ /** Ask for the key every 4 seconds (up to `tries` times); activate it when it arrives. */
1026
+ async function pickUpKey(io, state, tries) {
1027
+ for (let i = 0; i < tries; i += 1) {
1028
+ const token = await fetchKeyFor(io.env, io.fetch, state.installId);
1029
+ const checked = token ? checkKey(token, io.now()) : null;
1030
+ if (checked?.ok) {
1031
+ saveKey(token, io.env);
1032
+ track(io.env, state, 'key_activated', checked.payload.trial ? 'trial' : 'paid', io.now());
1033
+ io.out(`ClaudeKit Pro is on in this terminal until ${fmtDay(checked.payload.exp)}. Thank you!`);
1034
+ return 0;
1035
+ }
1036
+ if (i < tries - 1) await io.sleep(4000);
1037
+ }
1038
+ io.out(tries > 1 ? `No payment yet. When it's done, run: ${io.self.say} pro check` : `No Pro for this terminal's checkout yet. Finish the payment, then run this again.`);
1039
+ return 1;
1040
+ }
1041
+
1042
+ function telemetryCommand(argv, io) {
1043
+ const { words } = parseArgs(argv);
1044
+ const state = io.state ?? loadTerminal(io.env, io.now());
1045
+ const what = words[0] ?? 'status';
1046
+ if (what === 'off') {
1047
+ state.telemetry = false;
1048
+ state.noticeShown = { ...state.noticeShown, telemetry: true };
1049
+ saveTerminal(state, io.env);
1050
+ clearQueue(io.env);
1051
+ io.skipTracking = true;
1052
+ io.out('Usage counts are off. Nothing more is sent from this terminal.');
1053
+ return 0;
1054
+ }
1055
+ if (what === 'on') {
1056
+ state.telemetry = true;
1057
+ state.noticeShown = { ...state.noticeShown, telemetry: true };
1058
+ saveTerminal(state, io.env);
1059
+ io.out('Usage counts are on: which commands run, never your chats, code, file paths or keys. Off again: ' + `${io.self.say} telemetry off`);
1060
+ return 0;
1061
+ }
1062
+ const blocked = ['DO_NOT_TRACK', 'CI'].filter((name) => {
1063
+ const v = io.env[name];
1064
+ return typeof v === 'string' && v !== '' && v !== '0' && v.toLowerCase() !== 'false';
1065
+ });
1066
+ io.out(state.telemetry === false
1067
+ ? 'Usage counts are off.'
1068
+ : blocked.length
1069
+ ? `Usage counts are off here (${blocked.join(', ')} is set).`
1070
+ : `Usage counts are on (anonymous: which commands run, never your chats, code, file paths or keys). Turn off: ${io.self.say} telemetry off`);
1071
+ return 0;
1072
+ }