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/README.md +38 -16
- package/lib/cleanup.js +90 -0
- package/lib/cli.js +411 -17
- package/lib/docs.js +68 -28
- package/lib/license.js +77 -0
- package/lib/pro.js +118 -0
- package/lib/state.js +28 -2
- package/lib/statusline.js +2 -0
- package/lib/telemetry.js +127 -0
- package/lib/terminal-state.js +72 -0
- package/package.json +3 -3
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 { SITE_NOTICE, 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,93 @@ 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
|
-
|
|
180
|
+
code = await command(rest, io);
|
|
140
181
|
} catch (error) {
|
|
141
182
|
io.err(error?.message ?? String(error));
|
|
142
|
-
|
|
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
|
+
}
|
|
143
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 (the early run-out forecast and replies left, notify, search and export beyond 7 days, 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
|
+
state.noticeShown.site = true;
|
|
212
|
+
changed = true;
|
|
213
|
+
track(io.env, state, 'notice', 'telemetry', io.now());
|
|
214
|
+
} else if (state.noticeShown.telemetry && !state.noticeShown.site && command !== 'telemetry') {
|
|
215
|
+
// Seen before 0.3.1: say once that setups may appear on the site (nothing to say if counts are off).
|
|
216
|
+
if (state.telemetry !== false) io.err(SITE_NOTICE(io.self.say));
|
|
217
|
+
state.noticeShown.site = true;
|
|
218
|
+
changed = true;
|
|
219
|
+
track(io.env, state, 'notice', 'site', io.now());
|
|
220
|
+
}
|
|
221
|
+
if (changed) saveTerminal(state, io.env);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** This terminal's Pro status; a key that has ended or ends within 5 days is refreshed first. */
|
|
225
|
+
async function currentPro(io, state) {
|
|
226
|
+
const status = proStatus(io.env, state, io.now());
|
|
227
|
+
if (status.key === 'expired' || (status.via === 'key' && Date.parse(status.exp) - io.now() < 5 * 86_400_000)) {
|
|
228
|
+
if (await refreshKeyIfDue(io.env, io.fetch, io.now())) return proStatus(io.env, state, io.now());
|
|
229
|
+
}
|
|
230
|
+
return status;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Pro, or the reason it isn't, printed. Counts the gate hit. A key near its end is refreshed first. */
|
|
234
|
+
async function requirePro(io, feature, { silent = false } = {}) {
|
|
235
|
+
const state = io.state ?? loadTerminal(io.env, io.now());
|
|
236
|
+
const status = await currentPro(io, state);
|
|
237
|
+
if (status.pro) return true;
|
|
238
|
+
track(io.env, state, 'pro_gate', feature, io.now());
|
|
239
|
+
if (status.key === 'expired') track(io.env, state, 'key_expired', status.trial ? 'trial' : 'paid', io.now());
|
|
240
|
+
if (!silent) io.out(gateLines(feature, io.self.say, status).join('\n'));
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// Owner, Dec 4 (after the Competitors thread): free shows the run-out time once a limit is 70% used,
|
|
245
|
+
// like the extension's free forecast; Pro shows it from 20%, plus replies left. Free search and
|
|
246
|
+
// export cover the last 7 days; Pro covers all time.
|
|
247
|
+
export const FREE_FORECAST_FROM = 70;
|
|
248
|
+
export const FREE_HISTORY_DAYS = 7;
|
|
249
|
+
const FREE_HISTORY_MS = FREE_HISTORY_DAYS * 86_400_000;
|
|
250
|
+
|
|
251
|
+
/** The run-out forecast for one limit, if this terminal may show it at this level. */
|
|
252
|
+
function forecastFor(readings, cur, key, pro) {
|
|
253
|
+
if (!pro && !(cur?.[key] >= FREE_FORECAST_FROM)) return null;
|
|
254
|
+
return forecast(readings, cur, key);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Pro, for a command with free and Pro parts. Nothing is printed or counted. */
|
|
258
|
+
async function hasPro(io) {
|
|
259
|
+
return (await currentPro(io, io.state ?? loadTerminal(io.env, io.now()))).pro;
|
|
144
260
|
}
|
|
145
261
|
|
|
146
262
|
// ---------------------------------------------------------------- status line
|
|
@@ -157,19 +273,29 @@ export function statusLineFor(raw, argv, io) {
|
|
|
157
273
|
const data = parseInput(raw);
|
|
158
274
|
if (!data) return FALLBACK;
|
|
159
275
|
const now = io.now();
|
|
276
|
+
let terminal = null;
|
|
277
|
+
let pro = false;
|
|
278
|
+
try {
|
|
279
|
+
terminal = loadTerminal(io.env, now);
|
|
280
|
+
pro = proStatus(io.env, terminal, now).pro;
|
|
281
|
+
} catch {
|
|
282
|
+
terminal = null;
|
|
283
|
+
}
|
|
160
284
|
let insights = null;
|
|
161
285
|
if (historyEnabled(argv, io.env)) {
|
|
162
286
|
try {
|
|
163
287
|
const { state, reading } = recordReading(data, now, io.env);
|
|
164
288
|
insights = {
|
|
165
289
|
promptCost: currentPromptCost(state.readings, reading),
|
|
166
|
-
|
|
167
|
-
|
|
290
|
+
// Free shows the run-out time from 70% used; Pro from 20%, plus replies left.
|
|
291
|
+
forecast: forecastFor(state.readings, reading, 'h', pro),
|
|
292
|
+
repliesLeft: pro ? repliesLeft(state.readings, reading) : null,
|
|
168
293
|
};
|
|
169
294
|
} catch {
|
|
170
295
|
insights = null;
|
|
171
296
|
}
|
|
172
297
|
}
|
|
298
|
+
if (terminal) dailyStatusCount(io, terminal, data, now);
|
|
173
299
|
let handoffHint = false;
|
|
174
300
|
try {
|
|
175
301
|
handoffHint = existsSync(join(skillsDir(io.env), 'ck-handoff', 'SKILL.md'));
|
|
@@ -181,11 +307,66 @@ export function statusLineFor(raw, argv, io) {
|
|
|
181
307
|
color,
|
|
182
308
|
insights,
|
|
183
309
|
handoffHint,
|
|
310
|
+
notice: terminal ? [statusNotice(terminal, now), expirySegment(io, terminal, now)].filter(Boolean).join(' │ ') || null : null,
|
|
184
311
|
formatTime: io.formatters.formatTime,
|
|
185
312
|
formatWeekday: io.formatters.formatWeekday,
|
|
186
313
|
});
|
|
187
314
|
}
|
|
188
315
|
|
|
316
|
+
/** Existing users are told on the line itself: the day after they get 0.3.0, and Jan 25–31. */
|
|
317
|
+
function statusNotice(terminal, now) {
|
|
318
|
+
if (!terminal.grandfatherUntil) return null;
|
|
319
|
+
const until = Date.parse(terminal.grandfatherUntil);
|
|
320
|
+
if (!(until > now)) return null;
|
|
321
|
+
const created = Date.parse(terminal.created);
|
|
322
|
+
if (Number.isFinite(created) && now - created < 86_400_000) return 'ClaudeKit Pro free for you until Jan 31';
|
|
323
|
+
if (until - now < 7 * 86_400_000) return 'Pro features end Jan 31: claudekit-terminal pro';
|
|
324
|
+
return null;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* "Claude Code deletes 3 chats ≤3d" when chats are about to go. Once a day at most (owner, Dec 4):
|
|
329
|
+
* the note stays for its first hour that day. The files are checked at most once an hour.
|
|
330
|
+
*/
|
|
331
|
+
function expirySegment(io, terminal, now) {
|
|
332
|
+
try {
|
|
333
|
+
const day = new Date(now).toISOString().slice(0, 10);
|
|
334
|
+
const shown = terminal.expiryNote;
|
|
335
|
+
if (shown?.day === day && now - Date.parse(shown.from) >= 3_600_000) return null;
|
|
336
|
+
const cached = terminal.expiring;
|
|
337
|
+
let count = cached && now - Date.parse(cached.at) < 3_600_000 ? cached.count : null;
|
|
338
|
+
if (count === null) {
|
|
339
|
+
count = expiringChats(io.env, now).count;
|
|
340
|
+
terminal.expiring = { at: new Date(now).toISOString(), count };
|
|
341
|
+
saveTerminal(terminal, io.env);
|
|
342
|
+
}
|
|
343
|
+
if (!(count > 0)) return null;
|
|
344
|
+
if (shown?.day !== day) {
|
|
345
|
+
terminal.expiryNote = { day, from: new Date(now).toISOString() };
|
|
346
|
+
terminal.expiryWarnedAt = new Date(now).toISOString();
|
|
347
|
+
saveTerminal(terminal, io.env);
|
|
348
|
+
}
|
|
349
|
+
return `Claude Code deletes ${count} ${count === 1 ? 'chat' : 'chats'} ≤3d`;
|
|
350
|
+
} catch {
|
|
351
|
+
return null;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Once a day, when counts are on: "the status line ran", plus plan, limit-hit and usage-band words. */
|
|
356
|
+
function dailyStatusCount(io, terminal, data, now) {
|
|
357
|
+
try {
|
|
358
|
+
const day = new Date(now).toISOString().slice(0, 10);
|
|
359
|
+
if (terminal.lastDaily === day || !telemetryAllowed(io.env, terminal)) return;
|
|
360
|
+
terminal.lastDaily = day;
|
|
361
|
+
saveTerminal(terminal, io.env);
|
|
362
|
+
track(io.env, terminal, 'command', 'statusline', now);
|
|
363
|
+
for (const signal of statusSignals(data)) track(io.env, terminal, 'signal', signal, now);
|
|
364
|
+
io.flushInBackground?.();
|
|
365
|
+
} catch {
|
|
366
|
+
// Never in the way of the line.
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
189
370
|
// ---------------------------------------------------------------- setup / remove
|
|
190
371
|
|
|
191
372
|
function setupCommand(argv, io) {
|
|
@@ -211,12 +392,26 @@ function setupCommand(argv, io) {
|
|
|
211
392
|
lines.push('Next: send a message in Claude Code. Your limits show after the first reply (Claude Pro, Max and Ultra plans).');
|
|
212
393
|
lines.push(`Everything it does: ${self.say} docs · Undo: ${self.say} remove`);
|
|
213
394
|
if (self.run.startsWith('npx')) lines.push(`Faster status line: npm install -g claudekit-terminal, then run "claudekit-terminal setup" once more.`);
|
|
395
|
+
const status = proStatus(io.env, io.state ?? loadTerminal(io.env, io.now()), io.now());
|
|
396
|
+
lines.push(status.via === 'key'
|
|
397
|
+
? `ClaudeKit Pro is on until ${new Date(status.exp).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}.`
|
|
398
|
+
: status.via === 'grandfather'
|
|
399
|
+
? 'Pro features stay free for you until Jan 31, 2027.'
|
|
400
|
+
: `Free: the status line, usage, week, the last 7 days of search and export, prompts, tokens, pins. Pro (early forecast, replies left, notify, all-time search, backup, fork): ${self.say} pro`);
|
|
214
401
|
io.out(lines.join('\n'));
|
|
402
|
+
if (io.state) {
|
|
403
|
+
if (!result.statusLine.kept) track(io.env, io.state, 'setup_step', 'settings', io.now());
|
|
404
|
+
if (result.written.length) track(io.env, io.state, 'setup_step', 'commands', io.now());
|
|
405
|
+
if (result.autoBackup) track(io.env, io.state, 'setup_step', 'hook', io.now());
|
|
406
|
+
track(io.env, io.state, 'setup', result.statusLine.kept ? 'kept_statusline' : 'done', io.now());
|
|
407
|
+
}
|
|
215
408
|
return 0;
|
|
216
409
|
}
|
|
217
410
|
|
|
218
411
|
function removeCommand(argv, io) {
|
|
219
412
|
const { flags } = parseArgs(argv);
|
|
413
|
+
// --all deletes ~/.claudekit, this terminal's id and queued counts with it: nothing more is sent.
|
|
414
|
+
if (flags.all) io.skipTracking = true;
|
|
220
415
|
const result = remove(io.env, { all: flags.all === true });
|
|
221
416
|
const lines = ['ClaudeKit for the terminal is removed.'];
|
|
222
417
|
if (result.settingsError) lines.push(` • Settings not changed: ${result.settingsError}`);
|
|
@@ -225,6 +420,7 @@ function removeCommand(argv, io) {
|
|
|
225
420
|
lines.push(result.deletedData ? ' ✓ ~/.claudekit deleted (usage numbers, pins, briefs, references)' : ' • Kept ~/.claudekit (usage numbers, pins, briefs). Delete it too: remove --all');
|
|
226
421
|
lines.push(` • Chat backups, if any, stay in ${defaultBackupDir(io.env)}`);
|
|
227
422
|
io.out(lines.join('\n'));
|
|
423
|
+
if (io.state && !flags.all) track(io.env, io.state, 'remove', 'done', io.now());
|
|
228
424
|
return 0;
|
|
229
425
|
}
|
|
230
426
|
|
|
@@ -249,9 +445,17 @@ function usageCommand(_argv, io) {
|
|
|
249
445
|
lines.push(`${label.padEnd(15)}${String(Math.round(used)).padStart(3)}% ${bar(used)} ${resetText}`);
|
|
250
446
|
if (extra) lines.push(`${''.padEnd(22)}${extra}`);
|
|
251
447
|
};
|
|
448
|
+
const pro = proStatus(io.env, io.state ?? loadTerminal(io.env, now), now).pro;
|
|
449
|
+
// What Pro would add right now: the run-out time between 20% and 70%, and replies left.
|
|
450
|
+
let withheld = null;
|
|
451
|
+
if (!pro && cur.h !== null && cur.h < 100) {
|
|
452
|
+
const early = cur.h >= 20 && cur.h < FREE_FORECAST_FROM && Number.isFinite(forecast(state.readings, cur, 'h')?.runsOutAt);
|
|
453
|
+
const replies = cur.h >= 50 && Number.isFinite(repliesLeft(state.readings, cur));
|
|
454
|
+
if (early || replies) withheld = early ? 'early' : 'replies';
|
|
455
|
+
}
|
|
252
456
|
if (cur.h !== null) {
|
|
253
|
-
const fc =
|
|
254
|
-
const left = repliesLeft(state.readings, cur);
|
|
457
|
+
const fc = forecastFor(state.readings, cur, 'h', pro);
|
|
458
|
+
const left = pro ? repliesLeft(state.readings, cur) : null;
|
|
255
459
|
const bits = [];
|
|
256
460
|
if (cur.h >= 100) bits.push('Limit reached');
|
|
257
461
|
else if (fc?.runsOutAt) bits.push(`At this pace: runs out ~${f.formatTime(new Date(fc.runsOutAt))}`);
|
|
@@ -260,7 +464,7 @@ function usageCommand(_argv, io) {
|
|
|
260
464
|
row('Session (5h)', cur.h, cur.hr, bits.join(' · '));
|
|
261
465
|
}
|
|
262
466
|
if (cur.w !== null) {
|
|
263
|
-
const fc =
|
|
467
|
+
const fc = forecastFor(state.readings, cur, 'w', pro);
|
|
264
468
|
const bits = [];
|
|
265
469
|
if (cur.wr > now && cur.w < 100) {
|
|
266
470
|
const days = (cur.wr - now) / 86_400_000;
|
|
@@ -281,10 +485,48 @@ function usageCommand(_argv, io) {
|
|
|
281
485
|
const days = daysWithoutLimit(state.hits, now);
|
|
282
486
|
if (days !== null) lines.push(days === 0 ? 'Limit you are at a limit now' : `No limit hit for ${days} ${days === 1 ? 'day' : 'days'}`);
|
|
283
487
|
if (lines.at(-1) === '') lines.pop();
|
|
488
|
+
if (withheld && io.state) {
|
|
489
|
+
track(io.env, io.state, 'pro_gate', 'forecast', now);
|
|
490
|
+
if (proHintDue(io, 'usage')) {
|
|
491
|
+
lines.push('', withheld === 'early'
|
|
492
|
+
? `Pro: when you'll run out from 20% used (free shows it from ${FREE_FORECAST_FROM}%), and replies left. ${io.self.say} pro`
|
|
493
|
+
: `Pro: about how many replies you have left at this pace. ${io.self.say} pro`);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
const warning = expiryWarning(io, now);
|
|
497
|
+
if (warning) lines.push('', warning);
|
|
284
498
|
io.out(lines.join('\n'));
|
|
285
499
|
return 0;
|
|
286
500
|
}
|
|
287
501
|
|
|
502
|
+
/**
|
|
503
|
+
* The free warning before Claude Code deletes chats (owner, Dec 4): at most once a day, in `usage`.
|
|
504
|
+
* Running `backup` without Pro within a day of it counts as pro_gate "backup_warning".
|
|
505
|
+
*/
|
|
506
|
+
function expiryWarning(io, now) {
|
|
507
|
+
const state = io.state;
|
|
508
|
+
if (!state) return '';
|
|
509
|
+
const day = new Date(now).toISOString().slice(0, 10);
|
|
510
|
+
if (state.hints?.expiry === day) return '';
|
|
511
|
+
const line = expiryLine(expiringChats(io.env, now), io.self.say);
|
|
512
|
+
if (!line) return '';
|
|
513
|
+
state.hints = { ...(state.hints ?? {}), expiry: day };
|
|
514
|
+
state.expiryWarnedAt = new Date(now).toISOString();
|
|
515
|
+
saveTerminal(state, io.env);
|
|
516
|
+
return line;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** At most one "Pro: …" hint per command per day. */
|
|
520
|
+
function proHintDue(io, command) {
|
|
521
|
+
const state = io.state;
|
|
522
|
+
if (!state) return false;
|
|
523
|
+
const day = new Date(io.now()).toISOString().slice(0, 10);
|
|
524
|
+
if (state.hints?.[command] === day) return false;
|
|
525
|
+
state.hints = { ...(state.hints ?? {}), [command]: day };
|
|
526
|
+
saveTerminal(state, io.env);
|
|
527
|
+
return true;
|
|
528
|
+
}
|
|
529
|
+
|
|
288
530
|
function weekCommand(_argv, io) {
|
|
289
531
|
const state = loadState(io.env);
|
|
290
532
|
if (state.readings.length === 0) return noUsage(io);
|
|
@@ -316,6 +558,7 @@ function weekCommand(_argv, io) {
|
|
|
316
558
|
|
|
317
559
|
async function notifyCommand(argv, io) {
|
|
318
560
|
const { flags } = parseArgs(argv);
|
|
561
|
+
if (!(await requirePro(io, 'notify'))) return 4;
|
|
319
562
|
if (flags.test) {
|
|
320
563
|
io.notify('ClaudeKit', 'Test: this is how "Claude is back" looks.');
|
|
321
564
|
io.out('Sent a test notification.');
|
|
@@ -354,17 +597,28 @@ function needChat(argv, io) {
|
|
|
354
597
|
const picked = pickSession(files, words.join(' '), io.cwd);
|
|
355
598
|
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
599
|
if (picked.note) io.err(picked.note);
|
|
357
|
-
return { session: picked.session ?? readSession(picked.file), flags };
|
|
600
|
+
return { session: picked.session ?? readSession(picked.file), file: picked.file, flags };
|
|
358
601
|
}
|
|
359
602
|
|
|
360
|
-
function searchCommand(argv, io) {
|
|
603
|
+
async function searchCommand(argv, io) {
|
|
361
604
|
const { words, flags } = parseArgs(argv, ['limit']);
|
|
362
605
|
const query = words.join(' ').trim();
|
|
363
606
|
if (!query) throw new Error(`What should it look for? ${io.self.say} search <words>`);
|
|
364
607
|
const limit = Number(flags.limit) > 0 ? Number(flags.limit) : 20;
|
|
365
|
-
const
|
|
608
|
+
const pro = await hasPro(io);
|
|
609
|
+
const files = listSessions(io.env);
|
|
610
|
+
// Free covers chats used in the last 7 days; Pro covers all time.
|
|
611
|
+
const since = io.now() - FREE_HISTORY_MS;
|
|
612
|
+
const results = searchSessions(pro ? files : files.filter((f) => f.mtimeMs >= since), query, { limit });
|
|
613
|
+
const older = pro ? 0 : searchSessions(files.filter((f) => f.mtimeMs < since), query, { limit: 100 }).length;
|
|
614
|
+
let olderLine = '';
|
|
615
|
+
if (older > 0 && io.state) {
|
|
616
|
+
track(io.env, io.state, 'pro_gate', 'search_history', io.now());
|
|
617
|
+
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`;
|
|
618
|
+
}
|
|
619
|
+
const scope = pro ? '' : ` from the last ${FREE_HISTORY_DAYS} days`;
|
|
366
620
|
if (results.length === 0) {
|
|
367
|
-
io.out(`No chat mentions "${query}"
|
|
621
|
+
io.out([`No chat${scope} mentions "${query}".`, olderLine].filter(Boolean).join('\n'));
|
|
368
622
|
return 0;
|
|
369
623
|
}
|
|
370
624
|
const f = io.formatters;
|
|
@@ -373,13 +627,14 @@ function searchCommand(argv, io) {
|
|
|
373
627
|
const re = new RegExp(query.split(/\s+/).map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'), 'gi');
|
|
374
628
|
return text.replace(re, (m) => `${BOLD}${m}${RESET}`);
|
|
375
629
|
};
|
|
376
|
-
const lines = [`${results.length} ${results.length === 1 ? 'chat mentions' : '
|
|
630
|
+
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
631
|
for (const { session, hits } of results) {
|
|
378
632
|
const when = Number.isFinite(session.updated) ? `${f.formatDate(new Date(session.updated))} ${f.formatTime(new Date(session.updated))}` : '';
|
|
379
633
|
lines.push(`${session.project ?? '?'} · ${when} · ${session.title} · ${hits.length} ${hits.length === 1 ? 'match' : 'matches'}`);
|
|
380
634
|
for (const hit of hits.slice(0, 3)) lines.push(` ${hit.turn.n}. ${hit.where === 'prompt' ? 'You' : 'Claude'}: ${hl(hit.snippet)}`);
|
|
381
635
|
lines.push(` open: claude --resume ${session.id}`, '');
|
|
382
636
|
}
|
|
637
|
+
if (olderLine) lines.push(olderLine);
|
|
383
638
|
io.out(lines.join('\n').trimEnd());
|
|
384
639
|
return 0;
|
|
385
640
|
}
|
|
@@ -413,8 +668,12 @@ function render(session, flags) {
|
|
|
413
668
|
return { text: toMarkdown(session, turns), ext: 'md', turns };
|
|
414
669
|
}
|
|
415
670
|
|
|
416
|
-
function exportCommand(argv, io) {
|
|
417
|
-
const { session, flags } = needChat(argv, io);
|
|
671
|
+
async function exportCommand(argv, io) {
|
|
672
|
+
const { session, file, flags } = needChat(argv, io);
|
|
673
|
+
// Free: Markdown or text of a whole chat used in the last 7 days. Pro: any chat, JSON, --turns.
|
|
674
|
+
const format = typeof flags.format === 'string' ? flags.format.toLowerCase() : 'md';
|
|
675
|
+
if ((format === 'json' || typeof flags.turns === 'string') && !(await requirePro(io, 'export'))) return 4;
|
|
676
|
+
if (file.mtimeMs < io.now() - FREE_HISTORY_MS && !(await requirePro(io, 'export_history'))) return 4;
|
|
418
677
|
const { text, ext, turns } = render(session, flags);
|
|
419
678
|
if (flags.out === '-') {
|
|
420
679
|
io.out(text);
|
|
@@ -427,7 +686,8 @@ function exportCommand(argv, io) {
|
|
|
427
686
|
return 0;
|
|
428
687
|
}
|
|
429
688
|
|
|
430
|
-
function referenceCommand(argv, io) {
|
|
689
|
+
async function referenceCommand(argv, io) {
|
|
690
|
+
if (!(await requirePro(io, 'reference'))) return 4;
|
|
431
691
|
const { session, flags } = needChat(argv, io);
|
|
432
692
|
const turns = selectTurns(session, parseTurns(typeof flags.turns === 'string' ? flags.turns : ''));
|
|
433
693
|
const text = toReference(session, turns);
|
|
@@ -443,7 +703,8 @@ function referenceCommand(argv, io) {
|
|
|
443
703
|
return 0;
|
|
444
704
|
}
|
|
445
705
|
|
|
446
|
-
function forkCommand(argv, io) {
|
|
706
|
+
async function forkCommand(argv, io) {
|
|
707
|
+
if (!(await requirePro(io, 'fork'))) return 4;
|
|
447
708
|
const { session, flags } = needChat(argv, io);
|
|
448
709
|
const args = ['--resume', session.id, '--fork-session'];
|
|
449
710
|
const cwd = session.cwd && existsSync(session.cwd) ? session.cwd : io.cwd;
|
|
@@ -496,6 +757,7 @@ async function briefCommand(argv, io) {
|
|
|
496
757
|
}
|
|
497
758
|
const text = readFileSync(path, 'utf8');
|
|
498
759
|
if (flags.start) {
|
|
760
|
+
if (!(await requirePro(io, 'brief_start'))) return 4;
|
|
499
761
|
io.out(`Starting a new Claude Code session from ${path}`);
|
|
500
762
|
return spawnClaude(io, [`Continue from this handoff brief:\n\n${text}`], io.cwd);
|
|
501
763
|
}
|
|
@@ -503,8 +765,16 @@ async function briefCommand(argv, io) {
|
|
|
503
765
|
return 0;
|
|
504
766
|
}
|
|
505
767
|
|
|
506
|
-
function backupCommand(argv, io) {
|
|
768
|
+
async function backupCommand(argv, io) {
|
|
507
769
|
const { words, flags } = parseArgs(argv);
|
|
770
|
+
const off = flags.auto === 'off' || words[0] === 'off';
|
|
771
|
+
// The automatic backup's hook runs with --quiet after every session: without Pro it stays quiet.
|
|
772
|
+
// A backup someone runs within a day of the deletion warning counts as that warning's click-through
|
|
773
|
+
// (the session-end hook's --quiet run doesn't).
|
|
774
|
+
const warned = Date.parse(io.state?.expiryWarnedAt ?? '');
|
|
775
|
+
const afterWarning = flags.quiet !== true && Number.isFinite(warned) && io.now() - warned < 86_400_000;
|
|
776
|
+
const feature = flags.auto !== undefined ? 'backup_auto' : afterWarning ? 'backup_warning' : 'backup';
|
|
777
|
+
if (!off && !(await requirePro(io, feature, { silent: flags.quiet === true }))) return flags.quiet ? 0 : 4;
|
|
508
778
|
if (flags.auto !== undefined) return autoBackup(words, flags, io);
|
|
509
779
|
const dir = resolve(io.cwd, words[0] ?? defaultBackupDir(io.env));
|
|
510
780
|
const manifestPath = join(dir, '.claudekit-backup.json');
|
|
@@ -701,3 +971,127 @@ async function tokensCommand(argv, io) {
|
|
|
701
971
|
io.out(lines.join('\n'));
|
|
702
972
|
return 0;
|
|
703
973
|
}
|
|
974
|
+
|
|
975
|
+
// ---------------------------------------------------------------- Pro: licence, checkout, telemetry
|
|
976
|
+
|
|
977
|
+
const fmtDay = (iso) => new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
|
|
978
|
+
|
|
979
|
+
function activateCommand(argv, io) {
|
|
980
|
+
const { words } = parseArgs(argv);
|
|
981
|
+
const token = (words[0] ?? '').trim();
|
|
982
|
+
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`);
|
|
983
|
+
const checked = checkKey(token, io.now());
|
|
984
|
+
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.");
|
|
985
|
+
if (!checked.ok) {
|
|
986
|
+
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`);
|
|
987
|
+
return 1;
|
|
988
|
+
}
|
|
989
|
+
saveKey(token, io.env);
|
|
990
|
+
if (io.state) {
|
|
991
|
+
track(io.env, io.state, 'key_activated', checked.payload.trial ? 'trial' : 'paid', io.now());
|
|
992
|
+
// A key pasted from the popup: this terminal is linked to the browser extension.
|
|
993
|
+
track(io.env, io.state, 'signal', 'linked_extension', io.now());
|
|
994
|
+
}
|
|
995
|
+
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.`);
|
|
996
|
+
return 0;
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
function licenseCommand(argv, io) {
|
|
1000
|
+
const { flags } = parseArgs(argv);
|
|
1001
|
+
if (flags.forget) {
|
|
1002
|
+
forgetKey(io.env);
|
|
1003
|
+
io.out('Removed the Pro key from this terminal.');
|
|
1004
|
+
return 0;
|
|
1005
|
+
}
|
|
1006
|
+
const status = proStatus(io.env, io.state ?? loadTerminal(io.env, io.now()), io.now());
|
|
1007
|
+
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());
|
|
1008
|
+
if (status.via === 'key') io.out(`ClaudeKit Pro${status.trial ? ' (free trial)' : ''} is on until ${fmtDay(status.exp)}.`);
|
|
1009
|
+
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`);
|
|
1010
|
+
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`);
|
|
1011
|
+
else io.out(`Free. Pro adds the run-out time from 20% and replies left, notify, all-time search and export, backup, fork and reference: ${io.self.say} pro`);
|
|
1012
|
+
return 0;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
async function proCommand(argv, io) {
|
|
1016
|
+
const { words, flags } = parseArgs(argv);
|
|
1017
|
+
const state = io.state ?? loadTerminal(io.env, io.now());
|
|
1018
|
+
const status = proStatus(io.env, state, io.now());
|
|
1019
|
+
if (status.via === 'key' && !flags.check) {
|
|
1020
|
+
io.out(`ClaudeKit Pro${status.trial ? ' (free trial)' : ''} is on in this terminal until ${fmtDay(status.exp)}.`);
|
|
1021
|
+
return 0;
|
|
1022
|
+
}
|
|
1023
|
+
// A checkout from the terminal uses its own install id, kept so the key can be picked up later.
|
|
1024
|
+
if (!state.installId) {
|
|
1025
|
+
state.installId = `ckx_${randomBytes(16).toString('hex')}`;
|
|
1026
|
+
saveTerminal(state, io.env);
|
|
1027
|
+
}
|
|
1028
|
+
if (flags.check || words[0] === 'check') return pickUpKey(io, state, 1);
|
|
1029
|
+
const period = words[0] === 'monthly' ? 'monthly' : 'yearly';
|
|
1030
|
+
const offer = await fetchOffer(io.env, io.fetch);
|
|
1031
|
+
const url = `${apiBase(io.env)}/v1/billing/checkout?period=${period}&installId=${state.installId}&source=terminal`;
|
|
1032
|
+
io.out([
|
|
1033
|
+
'ClaudeKit Pro: the run-out time from 20% and replies left, "Claude is back" notifications, all-time search and export, backups, fork and reference chats in the terminal, plus everything Pro in the browser extension. One licence.',
|
|
1034
|
+
offer ? offerLine(offer) : 'Prices: claudekit.app/pricing',
|
|
1035
|
+
'',
|
|
1036
|
+
`Checkout (${period}${period === 'yearly' ? `; monthly: ${io.self.say} pro monthly` : ''}):`,
|
|
1037
|
+
url,
|
|
1038
|
+
'',
|
|
1039
|
+
'Already have Pro in the browser extension? Open its popup → Use Pro in your terminal → copy the key, then:',
|
|
1040
|
+
`${io.self.say} activate <key>`,
|
|
1041
|
+
].join('\n'));
|
|
1042
|
+
track(io.env, state, 'upgrade_open', 'pro_command', io.now());
|
|
1043
|
+
track(io.env, state, 'checkout_start', period, io.now());
|
|
1044
|
+
if (flags['no-open'] || io.stdinIsTTY === false) return 0;
|
|
1045
|
+
io.openUrl?.(url);
|
|
1046
|
+
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)`);
|
|
1047
|
+
return pickUpKey(io, state, 300);
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
/** Ask for the key every 4 seconds (up to `tries` times); activate it when it arrives. */
|
|
1051
|
+
async function pickUpKey(io, state, tries) {
|
|
1052
|
+
for (let i = 0; i < tries; i += 1) {
|
|
1053
|
+
const token = await fetchKeyFor(io.env, io.fetch, state.installId);
|
|
1054
|
+
const checked = token ? checkKey(token, io.now()) : null;
|
|
1055
|
+
if (checked?.ok) {
|
|
1056
|
+
saveKey(token, io.env);
|
|
1057
|
+
track(io.env, state, 'key_activated', checked.payload.trial ? 'trial' : 'paid', io.now());
|
|
1058
|
+
io.out(`ClaudeKit Pro is on in this terminal until ${fmtDay(checked.payload.exp)}. Thank you!`);
|
|
1059
|
+
return 0;
|
|
1060
|
+
}
|
|
1061
|
+
if (i < tries - 1) await io.sleep(4000);
|
|
1062
|
+
}
|
|
1063
|
+
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.`);
|
|
1064
|
+
return 1;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
function telemetryCommand(argv, io) {
|
|
1068
|
+
const { words } = parseArgs(argv);
|
|
1069
|
+
const state = io.state ?? loadTerminal(io.env, io.now());
|
|
1070
|
+
const what = words[0] ?? 'status';
|
|
1071
|
+
if (what === 'off') {
|
|
1072
|
+
state.telemetry = false;
|
|
1073
|
+
state.noticeShown = { ...state.noticeShown, telemetry: true };
|
|
1074
|
+
saveTerminal(state, io.env);
|
|
1075
|
+
clearQueue(io.env);
|
|
1076
|
+
io.skipTracking = true;
|
|
1077
|
+
io.out('Usage counts are off. Nothing more is sent from this terminal.');
|
|
1078
|
+
return 0;
|
|
1079
|
+
}
|
|
1080
|
+
if (what === 'on') {
|
|
1081
|
+
state.telemetry = true;
|
|
1082
|
+
state.noticeShown = { ...state.noticeShown, telemetry: true };
|
|
1083
|
+
saveTerminal(state, io.env);
|
|
1084
|
+
io.out('Usage counts are on: which commands run, never your chats, code, file paths or keys. Off again: ' + `${io.self.say} telemetry off`);
|
|
1085
|
+
return 0;
|
|
1086
|
+
}
|
|
1087
|
+
const blocked = ['DO_NOT_TRACK', 'CI'].filter((name) => {
|
|
1088
|
+
const v = io.env[name];
|
|
1089
|
+
return typeof v === 'string' && v !== '' && v !== '0' && v.toLowerCase() !== 'false';
|
|
1090
|
+
});
|
|
1091
|
+
io.out(state.telemetry === false
|
|
1092
|
+
? 'Usage counts are off.'
|
|
1093
|
+
: blocked.length
|
|
1094
|
+
? `Usage counts are off here (${blocked.join(', ')} is set).`
|
|
1095
|
+
: `Usage counts are on (anonymous: which commands run, never your chats, code, file paths or keys). Turn off: ${io.self.say} telemetry off`);
|
|
1096
|
+
return 0;
|
|
1097
|
+
}
|