@emesoft/tokenhub 0.9.1 → 0.9.2
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 +2 -0
- package/bin/tokenhub.js +6 -2
- package/lib/install-log.d.ts +2 -0
- package/lib/install-log.js +46 -0
- package/lib/install-ui.d.ts +27 -0
- package/lib/install-ui.js +66 -0
- package/lib/pair.d.ts +6 -0
- package/lib/pair.js +72 -29
- package/lib/progress.d.ts +39 -0
- package/lib/progress.js +231 -0
- package/lib/remote-download.d.ts +4 -0
- package/lib/remote-download.js +67 -7
- package/lib/remote-install.d.ts +4 -1
- package/lib/remote-install.js +145 -53
- package/lib/remote-text.js +57 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -56,6 +56,8 @@ Prefer not to install? Use `npx @emesoft/tokenhub connect <your tenant name>` in
|
|
|
56
56
|
| `--no-statusline` | `connect` | Don't add the spend status line to Claude Code. |
|
|
57
57
|
| `--no-model-picker` | `connect` | Don't offer to install the TokenHub model picker. |
|
|
58
58
|
| `--remote` / `--no-remote` | `connect` | Set up TokenHub Remote without asking / skip its question. |
|
|
59
|
+
| `--plain` | `connect` | One plain line per finished step instead of the progress bar (also used without a terminal or with `NO_COLOR`). |
|
|
60
|
+
| `--verbose` | `connect` | Also print what is otherwise only kept in `~/.tokenhub/remote/install.log` (download sizes, backup paths, the settings diff, PATH details). |
|
|
59
61
|
| `--force` | `disconnect` | Stop the Remote daemon even while it hosts Claude sessions (they end). |
|
|
60
62
|
| `--admin` | `connect`, `disconnect` | Pair (or forget) this machine as an admin device. See [For admins](#for-admins). |
|
|
61
63
|
| `--json` | `usage` | Print the raw report. |
|
package/bin/tokenhub.js
CHANGED
|
@@ -17,7 +17,7 @@ import { fetchUsage, formatUsage, resolveCredentials } from "../lib/usage.js";
|
|
|
17
17
|
const HELP = `tokenhub - pair Claude Code with your TokenHub tenant
|
|
18
18
|
|
|
19
19
|
Usage:
|
|
20
|
-
tokenhub connect [tenant] [--no-statusline] [--no-model-picker] [--remote | --no-remote]
|
|
20
|
+
tokenhub connect [tenant] [--no-statusline] [--no-model-picker] [--remote | --no-remote] [--plain] [--verbose]
|
|
21
21
|
Pair this machine and write ~/.claude/settings.json, including the status line
|
|
22
22
|
(today's spend under the prompt) unless --no-statusline. Then offers to install the
|
|
23
23
|
TokenHub model picker (a bare /model in Claude Code lists TokenHub models) unless
|
|
@@ -27,7 +27,9 @@ Usage:
|
|
|
27
27
|
the daemon, pairs this computer (one more approval in the browser), adds the /tf-remote
|
|
28
28
|
command to Claude Code and, if you agree, a launcher that makes claude use it, first on your PATH
|
|
29
29
|
tenant is your tenant name (acme = https://acme.${TENANT_DOMAIN}) or a full URL;
|
|
30
|
-
it is asked for when left out
|
|
30
|
+
it is asked for when left out. One progress bar shows the steps; --plain prints one
|
|
31
|
+
line per finished step instead (also used without a terminal or with NO_COLOR) and
|
|
32
|
+
--verbose prints what is otherwise only kept in ~/.tokenhub/remote/install.log
|
|
31
33
|
tokenhub connect [tenant] --admin
|
|
32
34
|
Pair this machine as an admin device (for the desktop overlay's pool view): the admin
|
|
33
35
|
confirms in the console, the token is saved to ~/.tokenhub/admin.json
|
|
@@ -94,6 +96,8 @@ async function main(argv) {
|
|
|
94
96
|
adminFile: adminConfigPath(),
|
|
95
97
|
modelPicker: !flags.includes("--no-model-picker"),
|
|
96
98
|
remote: flags.includes("--remote") ? true : flags.includes("--no-remote") ? false : undefined,
|
|
99
|
+
plain: flags.includes("--plain"),
|
|
100
|
+
verbose: flags.includes("--verbose"),
|
|
97
101
|
});
|
|
98
102
|
}
|
|
99
103
|
if (command === "desktop") {
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Where the installer's log goes: `<remote dir>/install.log`.
|
|
6
|
+
* @param {string} root The Remote folder (`remoteDir()`).
|
|
7
|
+
* @returns {string} Absolute path.
|
|
8
|
+
*/
|
|
9
|
+
export function installLogPath(root) {
|
|
10
|
+
return join(root, "install.log");
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The installer's log: a file that every run appends to, each run under a header with its time. It holds what a quiet install
|
|
14
|
+
* does not print (download sizes, backup paths, the settings diff, the hook script's output, PATH and launcher details) and what
|
|
15
|
+
* it printed. Writing never throws: a log that cannot be written must not stop an install.
|
|
16
|
+
*
|
|
17
|
+
* @param {object} options
|
|
18
|
+
* @param {string} options.file Path of the log (created with its folder).
|
|
19
|
+
* @param {string} [options.title] What the run is, for the header (`tokenhub connect --remote`).
|
|
20
|
+
* @param {() => Date} [options.now] Clock (tests).
|
|
21
|
+
* @returns {{ file: string, write: (line: string) => void }} The log. The header is written with the first line.
|
|
22
|
+
*/
|
|
23
|
+
export function openInstallLog({ file, title = "tokenhub connect", now = () => new Date() }) {
|
|
24
|
+
let started = false;
|
|
25
|
+
let broken = false;
|
|
26
|
+
/** @param {string} text Text to append. */
|
|
27
|
+
const append = (text) => {
|
|
28
|
+
if (broken) return;
|
|
29
|
+
try {
|
|
30
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
31
|
+
appendFileSync(file, text);
|
|
32
|
+
} catch {
|
|
33
|
+
broken = true;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
file,
|
|
38
|
+
write(line) {
|
|
39
|
+
if (!started) {
|
|
40
|
+
started = true;
|
|
41
|
+
append(`\n=== ${now().toISOString()} ${title} ===\n`);
|
|
42
|
+
}
|
|
43
|
+
append(`${line}\n`);
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Progress, ProgressStream } from "./progress.js";
|
|
2
|
+
|
|
3
|
+
export interface InstallUi {
|
|
4
|
+
readonly progress: Progress;
|
|
5
|
+
/** Path of the log once `useLog` has been called. */
|
|
6
|
+
readonly logFile: string | undefined;
|
|
7
|
+
useLog(file: string, title?: string): void;
|
|
8
|
+
say(line: string): void;
|
|
9
|
+
detail(line: string): void;
|
|
10
|
+
ask(question: (text: string, defaultYes?: boolean) => Promise<boolean>): (text: string, defaultYes?: boolean) => Promise<boolean>;
|
|
11
|
+
begin(label: string): void;
|
|
12
|
+
update(change: { label?: string; within?: number }): void;
|
|
13
|
+
complete(text: string): void;
|
|
14
|
+
addSteps(count: number): void;
|
|
15
|
+
finish(label: string): void;
|
|
16
|
+
close(): void;
|
|
17
|
+
}
|
|
18
|
+
export interface InstallUiOptions {
|
|
19
|
+
log?: (line: string) => void;
|
|
20
|
+
stream?: ProgressStream;
|
|
21
|
+
env?: Record<string, string | undefined>;
|
|
22
|
+
plain?: boolean;
|
|
23
|
+
verbose?: boolean;
|
|
24
|
+
total?: number;
|
|
25
|
+
now?: () => Date;
|
|
26
|
+
}
|
|
27
|
+
export function createInstallUi(options?: InstallUiOptions): InstallUi;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { openInstallLog } from "./install-log.js";
|
|
2
|
+
import { createProgress } from "./progress.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* What `tokenhub connect` shows while it works: the progress bar, plain lines for what the user must read, and a log file for the rest.
|
|
6
|
+
*
|
|
7
|
+
* - `say(line)` is for what the user must read or act on (a code, a question's text, a warning, an error): the bar is paused first,
|
|
8
|
+
* so the line is printed plainly below it and the bar is drawn again on a fresh line by the next step.
|
|
9
|
+
* - `detail(line)` is for what a quiet install keeps to itself (sizes, paths, diffs, hook output): it goes to the log file, and is printed
|
|
10
|
+
* only with `verbose` (which also turns the bar into plain step lines, so the output reads in order).
|
|
11
|
+
* - `ask(fn)` wraps a yes/no prompt so the bar is paused before it is shown.
|
|
12
|
+
* - the step methods (`begin`, `update`, `complete`, `finish`, `addSteps`) drive the bar.
|
|
13
|
+
*
|
|
14
|
+
* @param {object} options
|
|
15
|
+
* @param {(line: string) => void} [options.log] Where plain lines go (console.log).
|
|
16
|
+
* @param {import("./progress.js").ProgressStream} [options.stream] Where the bar is drawn (stdout).
|
|
17
|
+
* @param {Record<string, string | undefined>} [options.env] Environment (NO_COLOR, TERM, CI).
|
|
18
|
+
* @param {boolean} [options.plain] `--plain`: plain step lines, no bar.
|
|
19
|
+
* @param {boolean} [options.verbose] `--verbose`: print the details too (and no bar).
|
|
20
|
+
* @param {number} [options.total] Steps in all.
|
|
21
|
+
* @param {() => Date} [options.now] Clock for the log's headers (tests).
|
|
22
|
+
* @returns {InstallUi} The interface.
|
|
23
|
+
*/
|
|
24
|
+
export function createInstallUi({ log = console.log, stream = process.stdout, env = process.env, plain = false, verbose = false, total = 1, now } = {}) {
|
|
25
|
+
const progress = createProgress({ stream, log, env, plain: plain || verbose, total });
|
|
26
|
+
/** @type {{ file: string, write: (line: string) => void } | undefined} */
|
|
27
|
+
let logFile;
|
|
28
|
+
return {
|
|
29
|
+
progress,
|
|
30
|
+
get logFile() {
|
|
31
|
+
return logFile?.file;
|
|
32
|
+
},
|
|
33
|
+
useLog(file, title) {
|
|
34
|
+
logFile = openInstallLog({ file, title, now });
|
|
35
|
+
},
|
|
36
|
+
say(line) {
|
|
37
|
+
progress.pause();
|
|
38
|
+
logFile?.write(line);
|
|
39
|
+
log(line);
|
|
40
|
+
},
|
|
41
|
+
detail(line) {
|
|
42
|
+
logFile?.write(line);
|
|
43
|
+
if (verbose) {
|
|
44
|
+
progress.pause();
|
|
45
|
+
log(` ${line}`);
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
ask(question) {
|
|
49
|
+
return async (text, defaultYes) => {
|
|
50
|
+
progress.pause();
|
|
51
|
+
const answer = await question(text, defaultYes);
|
|
52
|
+
logFile?.write(`? ${text} ${answer ? "yes" : "no"}`);
|
|
53
|
+
return answer;
|
|
54
|
+
};
|
|
55
|
+
},
|
|
56
|
+
begin: (label) => progress.begin(label),
|
|
57
|
+
update: (change) => progress.update(change),
|
|
58
|
+
complete(text) {
|
|
59
|
+
logFile?.write(`step ${progress.done + 1}/${progress.total}: ${text}`);
|
|
60
|
+
progress.complete(text);
|
|
61
|
+
},
|
|
62
|
+
addSteps: (count) => progress.setTotal(progress.total + count),
|
|
63
|
+
finish: (label) => progress.finish(label),
|
|
64
|
+
close: () => progress.close(),
|
|
65
|
+
};
|
|
66
|
+
}
|
package/lib/pair.d.ts
CHANGED
|
@@ -51,4 +51,10 @@ export function runConnect(options: {
|
|
|
51
51
|
home?: string;
|
|
52
52
|
/** Yes/no prompt; answers false without a terminal. */
|
|
53
53
|
ask?: (question: string, defaultYes?: boolean) => Promise<boolean>;
|
|
54
|
+
/** One plain line per finished step instead of the progress bar (--plain). */
|
|
55
|
+
plain?: boolean;
|
|
56
|
+
/** Also print what is otherwise only in the install log; plain lines, no bar (--verbose). */
|
|
57
|
+
verbose?: boolean;
|
|
58
|
+
/** Where the progress bar is drawn; stdout by default. */
|
|
59
|
+
stream?: import("./progress.js").ProgressStream;
|
|
54
60
|
}): Promise<number>;
|
package/lib/pair.js
CHANGED
|
@@ -3,6 +3,7 @@ import { homedir, hostname } from "node:os";
|
|
|
3
3
|
import { emitKeypressEvents } from "node:readline";
|
|
4
4
|
import { createInterface } from "node:readline/promises";
|
|
5
5
|
import { writeAdminConfig } from "./admin.js";
|
|
6
|
+
import { createInstallUi } from "./install-ui.js";
|
|
6
7
|
import { askYesNo, enableFullscreen, installModelPicker, layoutUnset, modelPickerDir } from "./model-picker.js";
|
|
7
8
|
import { installRemote } from "./remote-install.js";
|
|
8
9
|
import { detectLang, text } from "./remote-text.js";
|
|
@@ -300,6 +301,9 @@ export async function pairDevice({ pool, admin = false, deviceName, log, open, s
|
|
|
300
301
|
* @param {typeof installRemote} [options.installRemoteFn] The Remote installer (tests replace it).
|
|
301
302
|
* @param {string} [options.home] Home directory the Remote installer uses.
|
|
302
303
|
* @param {(question: string, defaultYes?: boolean) => Promise<boolean>} [options.ask] Yes/no prompt (tests); false without a terminal.
|
|
304
|
+
* @param {boolean} [options.plain] `--plain`: one plain line per finished step instead of the progress bar.
|
|
305
|
+
* @param {boolean} [options.verbose] `--verbose`: also print what is otherwise only kept in the install log (plain lines, no bar).
|
|
306
|
+
* @param {import("./progress.js").ProgressStream} [options.stream] Where the progress bar is drawn (stdout).
|
|
303
307
|
* @returns {Promise<number>} Process exit code.
|
|
304
308
|
*/
|
|
305
309
|
export async function runConnect({
|
|
@@ -320,6 +324,9 @@ export async function runConnect({
|
|
|
320
324
|
installRemoteFn = installRemote,
|
|
321
325
|
home = homedir(),
|
|
322
326
|
ask = (question, defaultYes = true) => askYesNo(question, { defaultYes }),
|
|
327
|
+
plain = false,
|
|
328
|
+
verbose = false,
|
|
329
|
+
stream = process.stdout,
|
|
323
330
|
}) {
|
|
324
331
|
let pool;
|
|
325
332
|
try {
|
|
@@ -329,54 +336,90 @@ export async function runConnect({
|
|
|
329
336
|
log(`Error: ${error.message}`);
|
|
330
337
|
return 1;
|
|
331
338
|
}
|
|
339
|
+
const lang = detectLang(env);
|
|
340
|
+
const t = text(lang);
|
|
341
|
+
// The bar counts the steps that apply: the key, the status line and the picker when asked for, and Remote's four when chosen up front
|
|
342
|
+
// (when it is asked about, they are added on a yes).
|
|
343
|
+
const ui = createInstallUi({ log, stream, env, plain, verbose, total: 1 + (statusLine ? 1 : 0) + (modelPicker ? 1 : 0) + (remote === true ? 4 : 0) });
|
|
344
|
+
/** What is said after the bar is full: the gateway part's results, then Remote's summary. */
|
|
345
|
+
const notes = [];
|
|
346
|
+
/**
|
|
347
|
+
* End the run: fill the bar on success (or close it), then print the notes and the summary.
|
|
348
|
+
* @param {number} code Exit code.
|
|
349
|
+
* @param {string[]} [summary] Closing lines of the Remote install.
|
|
350
|
+
* @returns {number} The code.
|
|
351
|
+
*/
|
|
352
|
+
const end = (code, summary = []) => {
|
|
353
|
+
if (code === 0) ui.finish(t.finished);
|
|
354
|
+
else ui.close();
|
|
355
|
+
for (const line of [...notes, ...summary]) ui.say(line);
|
|
356
|
+
ui.close();
|
|
357
|
+
return code;
|
|
358
|
+
};
|
|
359
|
+
const question = ui.ask(ask);
|
|
332
360
|
try {
|
|
333
|
-
const paired = await pairDevice({ pool, admin, deviceName, log, open, signal, intervalOverrideMs });
|
|
334
|
-
if (!paired.ok) return paired.code;
|
|
335
|
-
const { baseUrl } = paired;
|
|
336
361
|
if (admin) {
|
|
362
|
+
const paired = await pairDevice({ pool, admin, deviceName, log, open, signal, intervalOverrideMs });
|
|
363
|
+
if (!paired.ok) return paired.code;
|
|
337
364
|
if (paired.kind !== "admin") {
|
|
338
365
|
log("Error: the pool did not issue an admin device token. Update the pool, then run the command again.");
|
|
339
366
|
return 1;
|
|
340
367
|
}
|
|
341
|
-
writeAdminConfig(adminFile, baseUrl, paired.key);
|
|
368
|
+
writeAdminConfig(adminFile, paired.baseUrl, paired.key);
|
|
342
369
|
log(`Admin device paired. Token saved to ${adminFile}`);
|
|
343
|
-
log(`Revoke it any time on the pool's admin Devices page (${baseUrl}/admin/pair).`);
|
|
370
|
+
log(`Revoke it any time on the pool's admin Devices page (${paired.baseUrl}/admin/pair).`);
|
|
344
371
|
return 0;
|
|
345
372
|
}
|
|
373
|
+
ui.begin(t.stepKey);
|
|
374
|
+
const paired = await pairDevice({ pool, admin, deviceName, log: ui.say, open, signal, intervalOverrideMs });
|
|
375
|
+
if (!paired.ok) return end(paired.code);
|
|
376
|
+
const { baseUrl } = paired;
|
|
346
377
|
const statusResult = connectSettings(settingsFile, baseUrl, paired.key, { statusLine });
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
if (
|
|
350
|
-
|
|
378
|
+
notes.push(`Connected. Claude Code settings updated: ${settingsFile}`);
|
|
379
|
+
ui.complete(t.doneKey);
|
|
380
|
+
if (statusLine) {
|
|
381
|
+
ui.begin(t.stepStatusLine);
|
|
382
|
+
ui.complete(t.doneStatusLine(statusResult));
|
|
383
|
+
}
|
|
384
|
+
if (statusResult === "installed") notes.push("Status line added: today's spend and credit show under the Claude Code prompt.");
|
|
385
|
+
if (statusResult === "updated") notes.push("Status line refreshed with your new key.");
|
|
386
|
+
if (statusResult === "kept") notes.push("Your existing statusLine was left as is. The setup guide on the pool site has the TokenHub one if you want it.");
|
|
351
387
|
const overriding = overridingEnvVars(env);
|
|
352
388
|
if (overriding.length > 0) {
|
|
353
|
-
|
|
389
|
+
notes.push(`Warning: ${overriding.join(", ")} set in your shell overrides settings.json. Unset it to use the pool.`);
|
|
354
390
|
}
|
|
355
|
-
if (modelPicker
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
391
|
+
if (modelPicker) {
|
|
392
|
+
ui.begin(t.stepPicker);
|
|
393
|
+
let installed = false;
|
|
394
|
+
if (await question("Install the TokenHub model picker for Claude Code (/model lists TokenHub models)?")) {
|
|
395
|
+
try {
|
|
396
|
+
installModelPicker(settingsFile, pickerDir);
|
|
397
|
+
installed = true;
|
|
398
|
+
notes.push("Model picker installed. Restart Claude Code, then type /model to pick a TokenHub model.");
|
|
399
|
+
// Claude Code reports the mouse only in its fullscreen layout (#766): offer it, never force it.
|
|
400
|
+
if (layoutUnset(settingsFile) && (await question("Turn on Claude Code's fullscreen layout so the picker takes the mouse?", false))) {
|
|
401
|
+
enableFullscreen(settingsFile);
|
|
402
|
+
notes.push('Fullscreen layout on ("tui": "fullscreen"). Switch back any time with /tui default.');
|
|
403
|
+
}
|
|
404
|
+
} catch (error) {
|
|
405
|
+
notes.push(`Model picker not installed: ${error.message}`);
|
|
363
406
|
}
|
|
364
|
-
} catch (error) {
|
|
365
|
-
log(`Model picker not installed: ${error.message}`);
|
|
366
407
|
}
|
|
408
|
+
ui.complete(t.donePicker(installed));
|
|
367
409
|
}
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
const installed = await installRemoteFn({ pool, baseUrl, settingsFile, lang,
|
|
371
|
-
if (!installed.ok) return installed.code;
|
|
410
|
+
if (remote ?? (await question(t.askRemote, false))) {
|
|
411
|
+
if (remote !== true) ui.addSteps(4);
|
|
412
|
+
const installed = await installRemoteFn({ pool, baseUrl, settingsFile, lang, ui, open, signal, ask, deviceName, intervalOverrideMs, env, home });
|
|
413
|
+
if (!installed.ok) return end(installed.code);
|
|
414
|
+
return end(0, installed.summary);
|
|
372
415
|
}
|
|
373
|
-
return 0;
|
|
416
|
+
return end(0);
|
|
374
417
|
} catch (error) {
|
|
375
418
|
if (signal?.aborted) {
|
|
376
|
-
|
|
377
|
-
return 130;
|
|
419
|
+
ui.say("Cancelled.");
|
|
420
|
+
return end(130);
|
|
378
421
|
}
|
|
379
|
-
|
|
380
|
-
return 1;
|
|
422
|
+
ui.say(`Error: ${error.message}`);
|
|
423
|
+
return end(1);
|
|
381
424
|
}
|
|
382
425
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export interface ProgressStream {
|
|
2
|
+
write(text: string): unknown;
|
|
3
|
+
isTTY?: boolean;
|
|
4
|
+
columns?: number;
|
|
5
|
+
hasColors?: (count?: number) => boolean;
|
|
6
|
+
}
|
|
7
|
+
export interface Progress {
|
|
8
|
+
/** True when the bar is drawn in place; false when each finished step is a plain line. */
|
|
9
|
+
readonly live: boolean;
|
|
10
|
+
/** Steps completed. */
|
|
11
|
+
readonly done: number;
|
|
12
|
+
/** Steps in all. */
|
|
13
|
+
readonly total: number;
|
|
14
|
+
begin(label: string): void;
|
|
15
|
+
update(change: { label?: string; within?: number }): void;
|
|
16
|
+
complete(text: string): void;
|
|
17
|
+
setTotal(count: number): void;
|
|
18
|
+
pause(): void;
|
|
19
|
+
finish(label: string): void;
|
|
20
|
+
close(): void;
|
|
21
|
+
}
|
|
22
|
+
export interface ProgressOptions {
|
|
23
|
+
stream?: ProgressStream;
|
|
24
|
+
log?: (line: string) => void;
|
|
25
|
+
env?: Record<string, string | undefined>;
|
|
26
|
+
plain?: boolean;
|
|
27
|
+
total?: number;
|
|
28
|
+
now?: () => number;
|
|
29
|
+
minInterval?: number;
|
|
30
|
+
brand?: string;
|
|
31
|
+
}
|
|
32
|
+
export function barParts(fraction: number, width: number): { filled: string; empty: string };
|
|
33
|
+
export function overallFraction(done: number, total: number, within?: number): number;
|
|
34
|
+
export function formatSize(bytes: number): string;
|
|
35
|
+
export function formatTransfer(done: number, total: number): string;
|
|
36
|
+
export function truncate(text: string, width: number): string;
|
|
37
|
+
export function renderLine(state: { done: number; total: number; within?: number; label: string; columns: number; color?: boolean; brand?: string }): string;
|
|
38
|
+
export function canDraw(stream: { isTTY?: boolean; hasColors?: (count?: number) => boolean } | undefined, env?: Record<string, string | undefined>): boolean;
|
|
39
|
+
export function createProgress(options?: ProgressOptions): Progress;
|
package/lib/progress.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/** The bar's filled and empty cells. */
|
|
2
|
+
const FILLED = "━";
|
|
3
|
+
const EMPTY = "─";
|
|
4
|
+
/** Terminal control sequences (VT, which Windows 10 and later consoles understand). */
|
|
5
|
+
const ESC = String.fromCharCode(27);
|
|
6
|
+
const HIDE_CURSOR = `${ESC}[?25l`;
|
|
7
|
+
const SHOW_CURSOR = `${ESC}[?25h`;
|
|
8
|
+
const CLEAR_LINE = `${ESC}[2K`;
|
|
9
|
+
const BOLD = `${ESC}[1m`;
|
|
10
|
+
const CYAN = `${ESC}[36m`;
|
|
11
|
+
const GREY = `${ESC}[90m`;
|
|
12
|
+
const RESET = `${ESC}[0m`;
|
|
13
|
+
/** The widest the bar is drawn, and the narrowest before the brand is dropped. */
|
|
14
|
+
const BAR_WIDTH = 24;
|
|
15
|
+
const BAR_MIN = 8;
|
|
16
|
+
/** The shortest label worth keeping whole before the bar shrinks to make room for it. */
|
|
17
|
+
const LABEL_WISH = 20;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The bar as text: `width` cells, the first `round(fraction * width)` filled.
|
|
21
|
+
* @param {number} fraction Share done, 0 to 1 (clamped; NaN counts as 0).
|
|
22
|
+
* @param {number} width Cells.
|
|
23
|
+
* @returns {{ filled: string, empty: string }} The filled and the empty part.
|
|
24
|
+
*/
|
|
25
|
+
export function barParts(fraction, width) {
|
|
26
|
+
const share = Number.isFinite(fraction) ? Math.min(1, Math.max(0, fraction)) : 0;
|
|
27
|
+
const cells = Math.max(0, Math.floor(width));
|
|
28
|
+
const count = Math.round(share * cells);
|
|
29
|
+
return { filled: FILLED.repeat(count), empty: EMPTY.repeat(cells - count) };
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The overall share of the work: completed steps plus the part of the current one.
|
|
33
|
+
* @param {number} done Steps completed.
|
|
34
|
+
* @param {number} total Steps in all (0 or less gives 0).
|
|
35
|
+
* @param {number} [within] Share of the current step done, 0 to 1 (clamped to just under 1, so a step is only complete when `done` says so).
|
|
36
|
+
* @returns {number} 0 to 1.
|
|
37
|
+
*/
|
|
38
|
+
export function overallFraction(done, total, within = 0) {
|
|
39
|
+
if (!(total > 0)) return 0;
|
|
40
|
+
const part = Number.isFinite(within) ? Math.min(0.999, Math.max(0, within)) : 0;
|
|
41
|
+
return Math.min(1, (Math.max(0, done) + (done >= total ? 0 : part)) / total);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* A size in binary megabytes with one decimal (`6.5 MB`), or kilobytes below one megabyte.
|
|
45
|
+
* @param {number} bytes Size in bytes.
|
|
46
|
+
* @returns {string} The text.
|
|
47
|
+
*/
|
|
48
|
+
export function formatSize(bytes) {
|
|
49
|
+
return bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* How far a download is, as `3.1/6.5 MB` (both in megabytes), or `512/900 KB` when the whole is under a megabyte.
|
|
53
|
+
* @param {number} done Bytes received.
|
|
54
|
+
* @param {number} total Bytes expected.
|
|
55
|
+
* @returns {string} The text.
|
|
56
|
+
*/
|
|
57
|
+
export function formatTransfer(done, total) {
|
|
58
|
+
if (total >= 1024 * 1024) return `${(done / 1024 / 1024).toFixed(1)}/${formatSize(total)}`;
|
|
59
|
+
return `${Math.round(done / 1024)}/${formatSize(total)}`;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Cut a text to `width` characters with an ellipsis, never wrapping.
|
|
63
|
+
* @param {string} text The text.
|
|
64
|
+
* @param {number} width Characters allowed.
|
|
65
|
+
* @returns {string} The text itself when it fits, else its start and `…` (empty when the width is 0 or less).
|
|
66
|
+
*/
|
|
67
|
+
export function truncate(text, width) {
|
|
68
|
+
const chars = Array.from(text);
|
|
69
|
+
if (chars.length <= width) return text;
|
|
70
|
+
return width <= 0 ? "" : `${chars.slice(0, width - 1).join("")}…`;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* One line of the bar, for a terminal `columns` wide: `TokenHub ━━━━────── 4/7 label`. It is never longer than `columns - 1`, so
|
|
74
|
+
* the terminal never wraps it: the label is cut first, then the bar shrinks, then the brand goes.
|
|
75
|
+
*
|
|
76
|
+
* @param {object} state
|
|
77
|
+
* @param {number} state.done Steps completed.
|
|
78
|
+
* @param {number} state.total Steps in all.
|
|
79
|
+
* @param {number} [state.within] Share of the current step done, 0 to 1.
|
|
80
|
+
* @param {string} state.label What is happening.
|
|
81
|
+
* @param {number} state.columns Width of the terminal.
|
|
82
|
+
* @param {boolean} [state.color] Colour the brand and the bar.
|
|
83
|
+
* @param {string} [state.brand] The name drawn first.
|
|
84
|
+
* @returns {string} The line, without a line break.
|
|
85
|
+
*/
|
|
86
|
+
export function renderLine({ done, total, within = 0, label, columns, color = false, brand = "TokenHub" }) {
|
|
87
|
+
const limit = Math.max(1, columns - 1);
|
|
88
|
+
const count = `${done}/${total}`;
|
|
89
|
+
const room = (barWidth, withBrand) => limit - ((withBrand ? brand.length + 2 : 0) + barWidth + 2 + count.length + 2);
|
|
90
|
+
let barWidth = BAR_WIDTH;
|
|
91
|
+
let withBrand = true;
|
|
92
|
+
const wish = Math.min(Array.from(label).length, LABEL_WISH);
|
|
93
|
+
while (room(barWidth, withBrand) < wish && barWidth > BAR_MIN) barWidth -= 1;
|
|
94
|
+
if (room(barWidth, withBrand) < wish) withBrand = false;
|
|
95
|
+
while (room(barWidth, withBrand) < wish && barWidth > 1) barWidth -= 1;
|
|
96
|
+
const text = truncate(label, Math.max(0, room(barWidth, withBrand)));
|
|
97
|
+
const { filled, empty } = barParts(overallFraction(done, total, within), barWidth);
|
|
98
|
+
const bar = color ? `${CYAN}${filled}${GREY}${empty}${RESET}` : `${filled}${empty}`;
|
|
99
|
+
const head = withBrand ? `${color ? `${BOLD}${brand}${RESET}` : brand} ` : "";
|
|
100
|
+
return `${head}${bar} ${count}${text ? ` ${text}` : ""}`;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Whether the bar can be drawn in place on a stream: a terminal that understands VT sequences, with colour not turned off.
|
|
104
|
+
* `NO_COLOR`, `TERM=dumb` and `CI` mean plain lines; on Windows a console Node cannot write VT sequences to counts as no terminal.
|
|
105
|
+
* @param {{ isTTY?: boolean, hasColors?: (count?: number) => boolean }} stream The output stream.
|
|
106
|
+
* @param {Record<string, string | undefined>} [env] Environment.
|
|
107
|
+
* @returns {boolean} True to draw the bar.
|
|
108
|
+
*/
|
|
109
|
+
export function canDraw(stream, env = process.env) {
|
|
110
|
+
if (!stream?.isTTY) return false;
|
|
111
|
+
if (env.NO_COLOR || env.CI || env.TERM === "dumb") return false;
|
|
112
|
+
return typeof stream.hasColors === "function" ? stream.hasColors() : true;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* One overall progress bar that redraws in place on a terminal, or plain step lines when it cannot.
|
|
117
|
+
*
|
|
118
|
+
* On a terminal one line is redrawn (`\r`, clear, text) as steps finish and as `update` moves the current one; the cursor is
|
|
119
|
+
* hidden while it draws and shown again by `pause`, `finish`, `close` and, as a last resort, when the process exits. Anything the
|
|
120
|
+
* user has to read or answer is printed after `pause()`, which leaves the bar line as it is and moves to a new line; the next
|
|
121
|
+
* `begin`, `update` or `complete` draws the bar again on a fresh line. In plain mode each finished step is one line,
|
|
122
|
+
* `[4/7] text`, without escape sequences, and nothing else is drawn.
|
|
123
|
+
*
|
|
124
|
+
* @param {object} [options]
|
|
125
|
+
* @param {{ write: (text: string) => unknown, isTTY?: boolean, columns?: number, hasColors?: () => boolean }} [options.stream] Where to write (stdout).
|
|
126
|
+
* @param {(line: string) => void} [options.log] Where a plain step line goes (the stream's own `write` by default).
|
|
127
|
+
* @param {Record<string, string | undefined>} [options.env] Environment (`NO_COLOR`, `TERM`, `CI`).
|
|
128
|
+
* @param {boolean} [options.plain] Force plain lines (`--plain`, `--verbose`).
|
|
129
|
+
* @param {number} [options.total] Steps in all.
|
|
130
|
+
* @param {() => number} [options.now] Clock in milliseconds (tests).
|
|
131
|
+
* @param {number} [options.minInterval] Shortest time between two redraws caused by `update`, in milliseconds.
|
|
132
|
+
* @param {string} [options.brand] The name drawn first.
|
|
133
|
+
* @returns {Progress} The bar.
|
|
134
|
+
*/
|
|
135
|
+
export function createProgress({ stream = process.stdout, log, env = process.env, plain = false, total = 1, now = Date.now, minInterval = 50, brand = "TokenHub" } = {}) {
|
|
136
|
+
const live = !plain && canDraw(stream, env);
|
|
137
|
+
const color = live;
|
|
138
|
+
let done = 0;
|
|
139
|
+
let steps = total;
|
|
140
|
+
let label = "";
|
|
141
|
+
let within = 0;
|
|
142
|
+
/** A bar line is on screen with no line break after it. */
|
|
143
|
+
let lineOpen = false;
|
|
144
|
+
let cursorHidden = false;
|
|
145
|
+
let hooked = false;
|
|
146
|
+
let lastDraw = Number.NEGATIVE_INFINITY;
|
|
147
|
+
let closed = false;
|
|
148
|
+
const restore = () => {
|
|
149
|
+
if (cursorHidden) {
|
|
150
|
+
stream.write(SHOW_CURSOR);
|
|
151
|
+
cursorHidden = false;
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
/** @param {boolean} force Draw even if one was drawn a moment ago. */
|
|
155
|
+
const draw = (force) => {
|
|
156
|
+
if (!live || closed) return;
|
|
157
|
+
const time = now();
|
|
158
|
+
if (!force && time - lastDraw < minInterval) return;
|
|
159
|
+
lastDraw = time;
|
|
160
|
+
if (!cursorHidden) {
|
|
161
|
+
stream.write(HIDE_CURSOR);
|
|
162
|
+
cursorHidden = true;
|
|
163
|
+
if (!hooked) {
|
|
164
|
+
hooked = true;
|
|
165
|
+
process.once("exit", restore);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
stream.write(`\r${CLEAR_LINE}${renderLine({ done, total: steps, within, label, columns: stream.columns || 80, color, brand })}`);
|
|
169
|
+
lineOpen = true;
|
|
170
|
+
};
|
|
171
|
+
return {
|
|
172
|
+
live,
|
|
173
|
+
begin(text) {
|
|
174
|
+
label = text;
|
|
175
|
+
within = 0;
|
|
176
|
+
draw(true);
|
|
177
|
+
},
|
|
178
|
+
update(change) {
|
|
179
|
+
if (change.label !== undefined) label = change.label;
|
|
180
|
+
if (change.within !== undefined) within = change.within;
|
|
181
|
+
draw(false);
|
|
182
|
+
},
|
|
183
|
+
complete(text) {
|
|
184
|
+
done = Math.min(steps, done + 1);
|
|
185
|
+
within = 0;
|
|
186
|
+
if (live) {
|
|
187
|
+
label = text;
|
|
188
|
+
draw(true);
|
|
189
|
+
} else {
|
|
190
|
+
(log ?? ((line) => stream.write(`${line}\n`)))(`[${done}/${steps}] ${text}`);
|
|
191
|
+
}
|
|
192
|
+
},
|
|
193
|
+
setTotal(count) {
|
|
194
|
+
steps = Math.max(done, count);
|
|
195
|
+
},
|
|
196
|
+
pause() {
|
|
197
|
+
if (!live || closed) return;
|
|
198
|
+
if (lineOpen) {
|
|
199
|
+
stream.write("\n");
|
|
200
|
+
lineOpen = false;
|
|
201
|
+
}
|
|
202
|
+
restore();
|
|
203
|
+
},
|
|
204
|
+
finish(text) {
|
|
205
|
+
if (!live || closed) return;
|
|
206
|
+
done = steps;
|
|
207
|
+
within = 0;
|
|
208
|
+
label = text;
|
|
209
|
+
draw(true);
|
|
210
|
+
stream.write("\n");
|
|
211
|
+
lineOpen = false;
|
|
212
|
+
restore();
|
|
213
|
+
},
|
|
214
|
+
close() {
|
|
215
|
+
if (closed) return;
|
|
216
|
+
if (lineOpen) {
|
|
217
|
+
stream.write("\n");
|
|
218
|
+
lineOpen = false;
|
|
219
|
+
}
|
|
220
|
+
restore();
|
|
221
|
+
closed = true;
|
|
222
|
+
process.off("exit", restore);
|
|
223
|
+
},
|
|
224
|
+
get done() {
|
|
225
|
+
return done;
|
|
226
|
+
},
|
|
227
|
+
get total() {
|
|
228
|
+
return steps;
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
}
|
package/lib/remote-download.d.ts
CHANGED
|
@@ -15,6 +15,9 @@ export function parseManifest(json: unknown): Manifest;
|
|
|
15
15
|
export function pickPlatform(manifest: Manifest, platform: string, arch: string): { key: string; files: ManifestFile[] };
|
|
16
16
|
export function compareVersions(a: string, b: string): number;
|
|
17
17
|
export function readCurrent(root: string): { version: string; dir: string } | undefined;
|
|
18
|
+
export function pruneVersions(root: string, keep: string): void;
|
|
19
|
+
export function stableHookPath(root: string): string;
|
|
20
|
+
export function syncStableHook(root: string, source: string): { path: string; changed: boolean };
|
|
18
21
|
export function fetchManifest(pool: string, options?: { fetchImpl?: typeof fetch; signal?: AbortSignal }): Promise<Manifest>;
|
|
19
22
|
export function downloadRemote(options: {
|
|
20
23
|
pool: string;
|
|
@@ -26,4 +29,5 @@ export function downloadRemote(options: {
|
|
|
26
29
|
signal?: AbortSignal;
|
|
27
30
|
run?: Runner;
|
|
28
31
|
manifest?: Manifest;
|
|
32
|
+
onProgress?: (progress: { version: string; done: number; total: number | undefined }) => void;
|
|
29
33
|
}): Promise<{ version: string; dir: string; action: "installed" | "updated" | "repaired" | "kept"; previous?: string; platformKey: string }>;
|
package/lib/remote-download.js
CHANGED
|
@@ -119,14 +119,28 @@ export async function fetchManifest(pool, { fetchImpl = fetch, signal } = {}) {
|
|
|
119
119
|
* Fetch one file and check it against the manifest before it is kept.
|
|
120
120
|
* @param {string} url File address.
|
|
121
121
|
* @param {{ name: string, sha256: string, size?: number }} file Its manifest entry.
|
|
122
|
-
* @param {{ fetchImpl: typeof fetch, signal?: AbortSignal }} io `fetch
|
|
122
|
+
* @param {{ fetchImpl: typeof fetch, signal?: AbortSignal, onBytes?: (count: number) => void }} io `fetch`, cancel signal, and a callback told how many bytes each chunk brought.
|
|
123
123
|
* @returns {Promise<Buffer>} The bytes, whose SHA-256 (and size, when the manifest has one) match.
|
|
124
124
|
* @throws {Error} On a failed download or a mismatch (the bytes are never returned then).
|
|
125
125
|
*/
|
|
126
|
-
async function fetchVerified(url, file, { fetchImpl, signal }) {
|
|
126
|
+
async function fetchVerified(url, file, { fetchImpl, signal, onBytes }) {
|
|
127
127
|
const res = await fetchImpl(url, { signal: signal ?? AbortSignal.timeout(FILE_TIMEOUT_MS) });
|
|
128
128
|
if (!res.ok) throw new Error(`Downloading ${file.name} failed (HTTP ${res.status}).`);
|
|
129
|
-
|
|
129
|
+
let bytes;
|
|
130
|
+
if (onBytes && res.body?.getReader) {
|
|
131
|
+
const reader = res.body.getReader();
|
|
132
|
+
const chunks = [];
|
|
133
|
+
for (;;) {
|
|
134
|
+
const { done, value } = await reader.read();
|
|
135
|
+
if (done) break;
|
|
136
|
+
chunks.push(value);
|
|
137
|
+
onBytes(value.length);
|
|
138
|
+
}
|
|
139
|
+
bytes = Buffer.concat(chunks);
|
|
140
|
+
} else {
|
|
141
|
+
bytes = Buffer.from(await res.arrayBuffer());
|
|
142
|
+
onBytes?.(bytes.length);
|
|
143
|
+
}
|
|
130
144
|
if (file.size !== undefined && bytes.length !== file.size) throw new Error(`${file.name} did not download completely (${bytes.length} of ${file.size} bytes). Nothing was installed.`);
|
|
131
145
|
if (sha256Hex(bytes) !== file.sha256) throw new Error(`${file.name} does not match the SHA-256 in the download list. Nothing was installed.`);
|
|
132
146
|
return bytes;
|
|
@@ -162,10 +176,12 @@ function installedOk(dir, files, verify) {
|
|
|
162
176
|
* @param {AbortSignal} [options.signal] Cancels the downloads.
|
|
163
177
|
* @param {import("./run.js").Runner} [options.run] Runs `xattr` on macOS (tests replace it).
|
|
164
178
|
* @param {ReturnType<typeof parseManifest>} [options.manifest] A manifest already fetched.
|
|
179
|
+
* @param {(progress: { version: string, done: number, total: number | undefined }) => void} [options.onProgress] Told the version to be installed before the first byte, then the bytes received so far of
|
|
180
|
+
* the total (undefined when a file's size is not in the manifest). Not called when the installed version is kept.
|
|
165
181
|
* @returns {Promise<{ version: string, dir: string, action: "installed" | "updated" | "repaired" | "kept", previous?: string, platformKey: string }>} What was done.
|
|
166
182
|
* @throws {Error} On any download, verification or write failure; nothing is switched over then.
|
|
167
183
|
*/
|
|
168
|
-
export async function downloadRemote({ pool, root, platform = process.platform, arch = process.arch, log = () => {}, fetchImpl = fetch, signal, run = defaultRun, manifest }) {
|
|
184
|
+
export async function downloadRemote({ pool, root, platform = process.platform, arch = process.arch, log = () => {}, fetchImpl = fetch, signal, run = defaultRun, manifest, onProgress }) {
|
|
169
185
|
const parsed = manifest ?? (await fetchManifest(pool, { fetchImpl, signal }));
|
|
170
186
|
const { key, files } = pickPlatform(parsed, platform, arch);
|
|
171
187
|
const current = readCurrent(root);
|
|
@@ -180,9 +196,16 @@ export async function downloadRemote({ pool, root, platform = process.platform,
|
|
|
180
196
|
const stage = join(root, `.stage-${randomBytes(4).toString("hex")}`);
|
|
181
197
|
try {
|
|
182
198
|
mkdirSync(stage);
|
|
199
|
+
const total = files.every((file) => file.size !== undefined) ? files.reduce((sum, file) => sum + file.size, 0) : undefined;
|
|
200
|
+
let received = 0;
|
|
201
|
+
onProgress?.({ version: parsed.version, done: 0, total });
|
|
183
202
|
for (const file of files) {
|
|
184
203
|
log(` ${file.name}${file.size ? ` (${(file.size / 1024 / 1024).toFixed(1)} MB)` : ""}`);
|
|
185
|
-
const
|
|
204
|
+
const onBytes = (count) => {
|
|
205
|
+
received += count;
|
|
206
|
+
onProgress?.({ version: parsed.version, done: received, total });
|
|
207
|
+
};
|
|
208
|
+
const bytes = await fetchVerified(`${pool}${REMOTE_DOWNLOADS}/${key}/${file.name}`, file, { fetchImpl, signal, onBytes });
|
|
186
209
|
writeFileSync(join(stage, file.name), bytes);
|
|
187
210
|
}
|
|
188
211
|
if (existsSync(target)) {
|
|
@@ -205,7 +228,7 @@ export async function downloadRemote({ pool, root, platform = process.platform,
|
|
|
205
228
|
}
|
|
206
229
|
const previous = current?.version;
|
|
207
230
|
writeCurrent(root, parsed.version, target);
|
|
208
|
-
|
|
231
|
+
pruneVersions(root, parsed.version);
|
|
209
232
|
const action = previous === undefined ? "installed" : previous === parsed.version ? "repaired" : "updated";
|
|
210
233
|
return { version: parsed.version, dir: target, action, previous, platformKey: key };
|
|
211
234
|
}
|
|
@@ -222,6 +245,43 @@ function writeCurrent(root, version, dir) {
|
|
|
222
245
|
writeFileSync(temp, `${JSON.stringify({ version, dir }, null, 2)}\n`);
|
|
223
246
|
renameSync(temp, file);
|
|
224
247
|
}
|
|
248
|
+
/**
|
|
249
|
+
* Where the hook script that Claude Code's `settings.json` points at lives: `<root>/current/tf-remote-hook.mjs`. It is a copy of the installed
|
|
250
|
+
* version's script that `syncStableHook` refreshes on every install, so the path in `settings.json` never changes with the version and an update
|
|
251
|
+
* does not rewrite it. (A copy, not a link: a Windows junction or symlink can fail or need rights, and the script is one self-contained file.)
|
|
252
|
+
* @param {string} root The Remote folder.
|
|
253
|
+
* @returns {string} The path.
|
|
254
|
+
*/
|
|
255
|
+
export function stableHookPath(root) {
|
|
256
|
+
return join(root, "current", HOOK_FILE);
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Make the stable hook script the same as the installed version's: written next to it and renamed over it, and left alone when its bytes already match.
|
|
260
|
+
* @param {string} root The Remote folder.
|
|
261
|
+
* @param {string} source The installed version's hook script.
|
|
262
|
+
* @returns {{ path: string, changed: boolean }} The stable path and whether it was written.
|
|
263
|
+
* @throws {Error} When the source cannot be read or the copy cannot be written.
|
|
264
|
+
*/
|
|
265
|
+
export function syncStableHook(root, source) {
|
|
266
|
+
const path = stableHookPath(root);
|
|
267
|
+
const bytes = readFileSync(source);
|
|
268
|
+
try {
|
|
269
|
+
if (readFileSync(path).equals(bytes)) return { path, changed: false };
|
|
270
|
+
} catch {
|
|
271
|
+
// missing: written below
|
|
272
|
+
}
|
|
273
|
+
mkdirSync(join(root, "current"), { recursive: true });
|
|
274
|
+
const temp = `${path}.${randomBytes(3).toString("hex")}.tmp`;
|
|
275
|
+
writeFileSync(temp, bytes);
|
|
276
|
+
try {
|
|
277
|
+
renameSync(temp, path);
|
|
278
|
+
} catch {
|
|
279
|
+
// a running hook has the file open (Windows): write over it instead
|
|
280
|
+
writeFileSync(path, bytes);
|
|
281
|
+
rmSync(temp, { force: true });
|
|
282
|
+
}
|
|
283
|
+
return { path, changed: true };
|
|
284
|
+
}
|
|
225
285
|
/**
|
|
226
286
|
* Delete the version folders (and leftover staging folders) other than `keep`; one that cannot be deleted (a running daemon holds it)
|
|
227
287
|
* stays until the next run.
|
|
@@ -229,7 +289,7 @@ function writeCurrent(root, version, dir) {
|
|
|
229
289
|
* @param {string} keep The version to keep.
|
|
230
290
|
* @returns {void}
|
|
231
291
|
*/
|
|
232
|
-
function
|
|
292
|
+
export function pruneVersions(root, keep) {
|
|
233
293
|
for (const entry of readdirSync(root, { withFileTypes: true })) {
|
|
234
294
|
if (!entry.isDirectory() || entry.name === keep) continue;
|
|
235
295
|
if (!VERSION.test(entry.name) && !entry.name.startsWith(".stage-")) continue;
|
package/lib/remote-install.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { InstallUi } from "./install-ui.js";
|
|
1
2
|
import type { Runner } from "./run.js";
|
|
2
3
|
import type { UserPath } from "./user-path.js";
|
|
3
4
|
import type { WinSystem } from "./launcher-precedence.js";
|
|
@@ -34,6 +35,7 @@ export function installRemote(options: {
|
|
|
34
35
|
settingsFile: string;
|
|
35
36
|
lang?: "en" | "vi";
|
|
36
37
|
log?: (line: string) => void;
|
|
38
|
+
ui?: InstallUi;
|
|
37
39
|
open: (url: string) => void;
|
|
38
40
|
signal?: AbortSignal;
|
|
39
41
|
ask: (question: string, defaultYes?: boolean) => Promise<boolean>;
|
|
@@ -47,10 +49,11 @@ export function installRemote(options: {
|
|
|
47
49
|
node?: string;
|
|
48
50
|
fetchImpl?: typeof fetch;
|
|
49
51
|
run?: Runner;
|
|
52
|
+
proc?: Proc;
|
|
50
53
|
userPath?: UserPath;
|
|
51
54
|
pickPort?: typeof pickHookPort;
|
|
52
55
|
launcherSys?: WinSystem;
|
|
53
|
-
}): Promise<{ ok: true; version: string; shim: boolean; launcher?: string } | { ok: false; code: number }>;
|
|
56
|
+
}): Promise<{ ok: true; version: string; shim: boolean; launcher?: string; summary: string[] } | { ok: false; code: number }>;
|
|
54
57
|
export function realProc(platform: string, run: Runner): Proc;
|
|
55
58
|
export function daemonState(options: { appDir: string; root: string; platform: string; proc: Proc }): Promise<{ state: "running" | "other" | "stopped"; pid?: number }>;
|
|
56
59
|
export function stopDaemon(options: {
|
package/lib/remote-install.js
CHANGED
|
@@ -4,9 +4,12 @@ import { createServer } from "node:net";
|
|
|
4
4
|
import { hostname } from "node:os";
|
|
5
5
|
import { basename, dirname, join } from "node:path";
|
|
6
6
|
import { findOnPath, findRealClaude, normalizeDir } from "./claude-shim.js";
|
|
7
|
+
import { createInstallUi } from "./install-ui.js";
|
|
8
|
+
import { installLogPath } from "./install-log.js";
|
|
7
9
|
import { ensureLauncher, hasPsBlock, launcherWins, realWindowsSystem, removeLauncher } from "./launcher-precedence.js";
|
|
8
10
|
import { pairRemote, checkRemoteToken, revokeRemoteToken } from "./remote.js";
|
|
9
|
-
import { downloadRemote, HOOK_FILE, readCurrent } from "./remote-download.js";
|
|
11
|
+
import { compareVersions, downloadRemote, HOOK_FILE, pruneVersions, readCurrent, stableHookPath, syncStableHook } from "./remote-download.js";
|
|
12
|
+
import { formatTransfer } from "./progress.js";
|
|
10
13
|
import { appConfigDir, exeName, legacyConfigDir, remoteDir, shimDir } from "./remote-paths.js";
|
|
11
14
|
import { installShimFiles, removeShimFiles, shimInstalled, shimPresent } from "./remote-shim.js";
|
|
12
15
|
import { detectLang, text } from "./remote-text.js";
|
|
@@ -154,20 +157,66 @@ async function runHookScript(verb, { script, claudeDir, node, run }) {
|
|
|
154
157
|
const lines = (result.code === 0 ? result.stdout : result.stderr || result.stdout).split(/\r?\n/).filter((line) => line.trim() !== "");
|
|
155
158
|
return { ok: result.code === 0, output: lines };
|
|
156
159
|
}
|
|
160
|
+
/**
|
|
161
|
+
* The `version` the running host wrote into `host.json` (empty from a host older than 0.1.5, which wrote none).
|
|
162
|
+
* @param {string} appDir The app config folder.
|
|
163
|
+
* @returns {string} The version, or "" when there is none or the file is unreadable.
|
|
164
|
+
*/
|
|
165
|
+
function hostVersion(appDir) {
|
|
166
|
+
try {
|
|
167
|
+
const version = JSON.parse(readFileSync(join(appDir, "host.json"), "utf8")).version;
|
|
168
|
+
return typeof version === "string" ? version : "";
|
|
169
|
+
} catch {
|
|
170
|
+
return "";
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* After an update: a Remote daemon of an older version that is still running would keep serving the old code, so it is stopped when it
|
|
175
|
+
* hosts no sessions (the next `claude` starts the new one), and the user is told to close their Claude windows when it does. A daemon that
|
|
176
|
+
* is not ours, or is as new as the installed version, is left alone.
|
|
177
|
+
*
|
|
178
|
+
* @param {object} options
|
|
179
|
+
* @param {string} options.appDir The app config folder (`host.json`).
|
|
180
|
+
* @param {string} options.root The Remote folder.
|
|
181
|
+
* @param {string} options.version The version just installed.
|
|
182
|
+
* @param {string} options.platform Node platform name.
|
|
183
|
+
* @param {Record<string, string | undefined>} options.env Environment for `tfc`.
|
|
184
|
+
* @param {Proc} options.proc Process facts.
|
|
185
|
+
* @param {import("./run.js").Runner} options.run Runs `tfc ls`.
|
|
186
|
+
* @param {import("./install-ui.js").InstallUi} options.ui Output.
|
|
187
|
+
* @param {Record<string, any>} options.t The messages.
|
|
188
|
+
* @returns {Promise<void>}
|
|
189
|
+
*/
|
|
190
|
+
async function retireOldDaemon({ appDir, root, version, platform, env, proc, run, ui, t }) {
|
|
191
|
+
const state = await daemonState({ appDir, root, platform, proc });
|
|
192
|
+
if (state.state !== "running") return;
|
|
193
|
+
const running = hostVersion(appDir);
|
|
194
|
+
if (running && compareVersions(running, version) >= 0) return;
|
|
195
|
+
const stopped = await stopDaemon({ appDir, root, platform, force: false, env, proc, run });
|
|
196
|
+
if (stopped.status === "stopped") {
|
|
197
|
+
ui.detail(t.oldDaemonStopped(running || t.versionUnknown, version));
|
|
198
|
+
pruneVersions(root, version);
|
|
199
|
+
} else if (stopped.status === "busy") {
|
|
200
|
+
ui.say(t.closeWindows(version));
|
|
201
|
+
}
|
|
202
|
+
}
|
|
157
203
|
/**
|
|
158
204
|
* Set up TokenHub Remote on this computer (the step `connect` offers after the settings are written).
|
|
159
205
|
*
|
|
160
|
-
*
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
*
|
|
206
|
+
* Four steps, shown on the progress bar (see `createInstallUi`): download the daemon (verified, nothing in place before it checks out;
|
|
207
|
+
* an older daemon that still runs is stopped when it hosts no sessions); pair this computer with the `remote` kind, or keep the token it
|
|
208
|
+
* already has when the pool still accepts it, and write `relay.json`; install the Claude Code hooks and `/tf-remote` by running the hook script's own
|
|
209
|
+
* `install` on the stable copy `<remote>/current/tf-remote-hook.mjs` (so `settings.json` never names a version); and, after asking, the
|
|
210
|
+
* `claude` launcher and its PATH entry. The download comes first so a failed download does not leave a pairing behind. What was done is
|
|
211
|
+
* recorded in `<remote>/install.json` as it goes. Sizes, paths, diffs and hook output go to `<remote>/install.log`, and are printed only with `--verbose`.
|
|
164
212
|
*
|
|
165
213
|
* @param {object} options
|
|
166
214
|
* @param {string} options.pool Pool address from `resolvePoolUrl`.
|
|
167
215
|
* @param {string} [options.baseUrl] Address the key was issued by (the public origin); defaults to `pool`.
|
|
168
216
|
* @param {string} options.settingsFile Claude Code's `settings.json`; its folder gets the hooks and `/tf-remote`.
|
|
169
217
|
* @param {"en" | "vi"} [options.lang] Message language.
|
|
170
|
-
* @param {(line: string) => void} [options.log] Output sink.
|
|
218
|
+
* @param {(line: string) => void} [options.log] Output sink for the default `ui` (plain step lines, no bar).
|
|
219
|
+
* @param {import("./install-ui.js").InstallUi} [options.ui] The caller's output (bar, plain lines, log). Without it the installer makes its own plain one, finishes it and prints the summary; with it the summary is returned for the caller to print after `finish`.
|
|
171
220
|
* @param {(url: string) => void} options.open Browser opener.
|
|
172
221
|
* @param {AbortSignal} [options.signal] Aborts the flow (Ctrl+C).
|
|
173
222
|
* @param {(question: string, defaultYes?: boolean) => Promise<boolean>} options.ask Yes/no prompt (false without a terminal).
|
|
@@ -181,10 +230,11 @@ async function runHookScript(verb, { script, claudeDir, node, run }) {
|
|
|
181
230
|
* @param {string} [options.node] Node program that runs the hook script (this one by default).
|
|
182
231
|
* @param {typeof fetch} [options.fetchImpl] `fetch` override for tests.
|
|
183
232
|
* @param {import("./run.js").Runner} [options.run] Process runner for `xattr`, `icacls` and the hook script (tests replace it).
|
|
233
|
+
* @param {Proc} [options.proc] Process facts for the old-daemon check (tests replace them).
|
|
184
234
|
* @param {ReturnType<typeof windowsUserPath>} [options.userPath] Registry access for the PATH edit (tests replace it).
|
|
185
235
|
* @param {typeof pickHookPort} [options.pickPort] Chooses the hook port when `relay.json` has none (tests replace it).
|
|
186
236
|
* @param {import("./launcher-precedence.js").WinSystem} [options.launcherSys] Windows access for the launcher check: Machine Path, PowerShell profiles and policies, elevation (tests replace it).
|
|
187
|
-
* @returns {Promise<{ ok: true, version: string, shim: boolean, launcher?: string } | { ok: false, code: number }>} The outcome (`launcher`: what makes `claude` start it on Windows, see `ensureLauncher`); on failure the exit code.
|
|
237
|
+
* @returns {Promise<{ ok: true, version: string, shim: boolean, launcher?: string, summary: string[] } | { ok: false, code: number }>} The outcome (`launcher`: what makes `claude` start it on Windows, see `ensureLauncher`; `summary`: the closing lines); on failure the exit code.
|
|
188
238
|
*/
|
|
189
239
|
export async function installRemote({
|
|
190
240
|
pool,
|
|
@@ -192,9 +242,10 @@ export async function installRemote({
|
|
|
192
242
|
settingsFile,
|
|
193
243
|
lang = detectLang(),
|
|
194
244
|
log = console.log,
|
|
245
|
+
ui: given,
|
|
195
246
|
open,
|
|
196
247
|
signal,
|
|
197
|
-
ask,
|
|
248
|
+
ask: rawAsk,
|
|
198
249
|
shim,
|
|
199
250
|
deviceName = hostname(),
|
|
200
251
|
intervalOverrideMs,
|
|
@@ -205,13 +256,16 @@ export async function installRemote({
|
|
|
205
256
|
node = process.execPath,
|
|
206
257
|
fetchImpl = fetch,
|
|
207
258
|
run = defaultRun,
|
|
259
|
+
proc,
|
|
208
260
|
userPath,
|
|
209
261
|
pickPort = pickHookPort,
|
|
210
262
|
launcherSys,
|
|
211
263
|
}) {
|
|
212
264
|
const t = text(lang);
|
|
265
|
+
const ui = given ?? createInstallUi({ log, env, plain: true, total: 4 });
|
|
266
|
+
const ask = ui.ask(rawAsk);
|
|
213
267
|
if (platform !== "win32" && platform !== "darwin") {
|
|
214
|
-
|
|
268
|
+
ui.say(t.unsupported(platform));
|
|
215
269
|
return { ok: false, code: 1 };
|
|
216
270
|
}
|
|
217
271
|
const root = remoteDir(env, home);
|
|
@@ -219,21 +273,44 @@ export async function installRemote({
|
|
|
219
273
|
const relayFile = join(appConfigDir(env, home), "relay.json");
|
|
220
274
|
const legacyFile = join(legacyConfigDir(env, home), "relay.json");
|
|
221
275
|
const claudeDir = dirname(settingsFile);
|
|
276
|
+
const logFile = installLogPath(root);
|
|
222
277
|
let origin = baseUrl ?? pool;
|
|
278
|
+
ui.useLog(logFile, "tokenhub connect --remote");
|
|
279
|
+
/** An error the user must see, with where the details are. @param {string} message What went wrong. @returns {{ ok: false, code: number }} */
|
|
280
|
+
const fail = (message, code = 1) => {
|
|
281
|
+
ui.say(message);
|
|
282
|
+
ui.say(t.seeLog(logFile));
|
|
283
|
+
return { ok: false, code };
|
|
284
|
+
};
|
|
223
285
|
|
|
224
|
-
|
|
225
|
-
|
|
286
|
+
// Step 4: download (or keep) the daemon.
|
|
287
|
+
ui.begin(t.stepCheck);
|
|
226
288
|
let download;
|
|
227
289
|
try {
|
|
228
|
-
download = await downloadRemote({
|
|
290
|
+
download = await downloadRemote({
|
|
291
|
+
pool,
|
|
292
|
+
root,
|
|
293
|
+
platform,
|
|
294
|
+
arch,
|
|
295
|
+
log: (line) => ui.detail(line.trim()),
|
|
296
|
+
fetchImpl,
|
|
297
|
+
signal,
|
|
298
|
+
run,
|
|
299
|
+
onProgress: ({ version, done, total }) => ui.update({ label: t.stepDownload(version, total ? formatTransfer(done, total) : ""), within: total ? done / total : 0 }),
|
|
300
|
+
});
|
|
229
301
|
} catch (error) {
|
|
230
|
-
|
|
231
|
-
|
|
302
|
+
if (signal?.aborted) {
|
|
303
|
+
ui.say("Cancelled.");
|
|
304
|
+
return { ok: false, code: 130 };
|
|
305
|
+
}
|
|
306
|
+
return fail(t.failed(error.message));
|
|
232
307
|
}
|
|
233
|
-
log(download.action === "updated" ? t.updated(download.version, download.previous) : download.action === "repaired" ? t.repaired(download.version) : download.action === "kept" ? t.kept(download.version) : t.installed(download.version));
|
|
234
308
|
saveRecord(root, { version: download.version });
|
|
309
|
+
await retireOldDaemon({ appDir: dirname(relayFile), root, version: download.version, platform, env, proc: proc ?? realProc(platform, run), run, ui, t });
|
|
310
|
+
ui.complete(download.action === "updated" ? t.doneDownload.updated(download.version, download.previous) : t.doneDownload[download.action](download.version));
|
|
235
311
|
|
|
236
|
-
//
|
|
312
|
+
// Step 5: pair this computer (keep the token it already has unless the pool says it was revoked, or it is for another pool).
|
|
313
|
+
ui.begin(t.stepPair);
|
|
237
314
|
const record = readRecord(root);
|
|
238
315
|
let existing = readRelayJson(relayFile);
|
|
239
316
|
// Version 0.1.0 wrote relay.json into TicketFlow's config folder. When that file is ours, its token carries over and the file goes
|
|
@@ -250,22 +327,21 @@ export async function installRemote({
|
|
|
250
327
|
let token;
|
|
251
328
|
let name = deviceName;
|
|
252
329
|
let relayOrigin;
|
|
330
|
+
let pairedBefore = false;
|
|
253
331
|
if (existing?.deviceToken && record?.pool === origin && record.tokenSha256 === sha256(existing.deviceToken)) {
|
|
254
332
|
const check = await checkRemoteToken({ pool: origin, token: existing.deviceToken, signal, fetchImpl });
|
|
255
333
|
if (check.status !== "revoked") {
|
|
256
334
|
token = existing.deviceToken;
|
|
257
335
|
name = check.status === "valid" ? check.deviceName : (existing.name ?? deviceName);
|
|
258
336
|
relayOrigin = check.status === "valid" ? check.relayOrigin : undefined;
|
|
259
|
-
|
|
337
|
+
pairedBefore = true;
|
|
338
|
+
ui.detail(t.keepingToken(name));
|
|
260
339
|
}
|
|
261
340
|
}
|
|
262
341
|
if (!token) {
|
|
263
|
-
|
|
264
|
-
const paired = await pairRemote({ pool, deviceName, log, open, signal, intervalOverrideMs, fetchImpl });
|
|
265
|
-
if (!paired.ok) {
|
|
266
|
-
log(t.pairingFailed);
|
|
267
|
-
return { ok: false, code: paired.code };
|
|
268
|
-
}
|
|
342
|
+
ui.say(t.pairing);
|
|
343
|
+
const paired = await pairRemote({ pool, deviceName, log: ui.say, open, signal, intervalOverrideMs, fetchImpl });
|
|
344
|
+
if (!paired.ok) return paired.code === 130 ? { ok: false, code: 130 } : fail(t.pairingFailed, paired.code);
|
|
269
345
|
token = paired.token;
|
|
270
346
|
origin = paired.baseUrl;
|
|
271
347
|
const check = await checkRemoteToken({ pool: origin, token, signal, fetchImpl });
|
|
@@ -276,38 +352,53 @@ export async function installRemote({
|
|
|
276
352
|
// Keep other keys of an existing relay.json (a hook port, say); the three the daemon needs are ours. A new file gets a free hook port.
|
|
277
353
|
const hookPort = existing?.hookPort ?? (await pickPort());
|
|
278
354
|
const restricted = await writeRelayJson(relayFile, { ...existing, relayUrl, deviceToken: token, name, ...(hookPort ? { hookPort } : {}) }, { platform, env, run });
|
|
279
|
-
if (!restricted)
|
|
355
|
+
if (!restricted) ui.say(`(could not restrict access to ${relayFile}; the folder's own permissions apply)`);
|
|
280
356
|
if (legacy) {
|
|
281
357
|
rmSync(legacyFile, { force: true });
|
|
282
|
-
|
|
358
|
+
ui.detail(t.movedConfig(legacyFile, relayFile));
|
|
283
359
|
}
|
|
284
360
|
saveRecord(root, { pool: origin, deviceName: name, tokenSha256: sha256(token), relayFile });
|
|
361
|
+
ui.complete(pairedBefore ? t.donePairedKept(name) : t.donePaired(name));
|
|
285
362
|
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
363
|
+
// Step 6: the hooks and /tf-remote. Settings name the stable copy of the script, so an update leaves settings.json alone.
|
|
364
|
+
ui.begin(t.stepHooks);
|
|
365
|
+
let hooks;
|
|
366
|
+
try {
|
|
367
|
+
const stable = syncStableHook(root, join(download.dir, HOOK_FILE));
|
|
368
|
+
ui.detail(`hook script: ${stable.path} (${stable.changed ? "updated" : "unchanged"})`);
|
|
369
|
+
hooks = await runHookScript("install", { script: stable.path, claudeDir, node, run });
|
|
370
|
+
} catch (error) {
|
|
371
|
+
hooks = { ok: false, output: [String(error.message ?? error)] };
|
|
292
372
|
}
|
|
373
|
+
for (const line of hooks.output) ui.detail(line);
|
|
374
|
+
if (!hooks.ok) return fail(t.hooksFailed(hooks.output.at(-1) ?? "?"));
|
|
293
375
|
saveRecord(root, { claudeDir });
|
|
376
|
+
ui.complete(t.doneHooks);
|
|
294
377
|
|
|
378
|
+
// Step 7: the launcher.
|
|
379
|
+
ui.begin(t.stepLauncher);
|
|
295
380
|
const registry = userPath ?? windowsUserPath({ run });
|
|
296
|
-
const
|
|
381
|
+
const shimBefore = shimInstalled(binDir, platform);
|
|
382
|
+
const shimOn = await offerShim({ shim, ask, ui, t, binDir, platform, env, home, run, userPath: registry, root });
|
|
297
383
|
// Windows: the user Path is only half of what a new process gets (the Machine Path comes first), so check that `claude` would win.
|
|
298
|
-
|
|
384
|
+
const launcher = shimOn && platform === "win32" ? await ensureLauncher({ binDir, env, userPath: registry, sys: launcherSys ?? realWindowsSystem({ run }), ask, log: ui.say, t, previous: record?.launcher }) : undefined;
|
|
299
385
|
if (launcher) saveRecord(root, { launcher: launcher.record });
|
|
386
|
+
ui.complete(t.doneLauncher(!shimOn ? "skipped" : shimBefore ? "kept" : "on"));
|
|
387
|
+
|
|
300
388
|
const tfc = join(download.dir, exeName("tfc", platform));
|
|
301
389
|
const claudeCmd = join(binDir, "claude.cmd");
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
390
|
+
const summary = [
|
|
391
|
+
t.ready(download.version, name),
|
|
392
|
+
!shimOn ? t.nextNoShim(tfc) : launcher?.how === "profile" ? t.nextPowerShell : launcher?.how === "none" ? t.nextByHand(claudeCmd) : t.nextNew,
|
|
393
|
+
...(launcher?.how === "profile" ? [t.noteShells] : []),
|
|
394
|
+
t.manage(`${origin}/member/remote`),
|
|
395
|
+
t.details(logFile),
|
|
396
|
+
];
|
|
397
|
+
if (!given) {
|
|
398
|
+
ui.finish(t.finished);
|
|
399
|
+
for (const line of summary) ui.say(line);
|
|
400
|
+
}
|
|
401
|
+
return { ok: true, version: download.version, shim: shimOn, launcher: launcher?.how, summary };
|
|
311
402
|
}
|
|
312
403
|
/** @param {Record<string, any> | undefined} existing An existing `relay.json`. @returns {string | undefined} The origin its `relayUrl` was made from. */
|
|
313
404
|
function relayOriginFromFile(existing) {
|
|
@@ -321,32 +412,33 @@ function relayOriginFromFile(existing) {
|
|
|
321
412
|
/**
|
|
322
413
|
* The launcher step: explain it, ask (unless a flag or an earlier install already decided), write the shim, edit PATH.
|
|
323
414
|
*
|
|
324
|
-
* @param {object} options What `installRemote` has: `shim`, `ask
|
|
415
|
+
* @param {object} options What `installRemote` has: `shim`, `ask` (already wrapped by the ui), `ui`, `t`, `binDir`, `platform`, `env`, `home`, `run`, `userPath`, `root`.
|
|
325
416
|
* @returns {Promise<boolean>} Whether the launcher is installed afterwards.
|
|
326
417
|
*/
|
|
327
|
-
async function offerShim({ shim, ask,
|
|
418
|
+
async function offerShim({ shim, ask, ui, t, binDir, platform, env, home, run, userPath, root }) {
|
|
328
419
|
const already = shimInstalled(binDir, platform);
|
|
329
420
|
let want = shim ?? already;
|
|
330
421
|
if (shim === undefined && !already) {
|
|
331
|
-
for (const line of t.shimIntro(binDir, platform === "win32" ? t.wherePath : t.whereProfile))
|
|
422
|
+
for (const line of t.shimIntro(binDir, platform === "win32" ? t.wherePath : t.whereProfile)) ui.say(line);
|
|
332
423
|
want = await ask(t.askShim, true);
|
|
333
424
|
}
|
|
334
425
|
if (!want) {
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
426
|
+
ui.detail(t.shimSkipped);
|
|
427
|
+
ui.detail(` ${join(readCurrent(root)?.dir ?? "", exeName("tfc", platform))}`);
|
|
428
|
+
ui.detail(t.shimSkippedHint);
|
|
338
429
|
return false;
|
|
339
430
|
}
|
|
340
431
|
const realClaude = findRealClaude({ pathValue: env.PATH ?? env.Path ?? "", shimDirs: [binDir], env, platform, home });
|
|
341
|
-
if (!realClaude)
|
|
432
|
+
if (!realClaude) ui.say(t.shimNoClaude);
|
|
342
433
|
installShimFiles({ binDir, platform, realClaude });
|
|
343
|
-
|
|
434
|
+
ui.detail(t.shimOn(binDir));
|
|
344
435
|
try {
|
|
345
436
|
const edited = await addBinToPath({ dir: binDir, platform, home, userPath: userPath ?? windowsUserPath({ run }) });
|
|
346
437
|
saveRecord(root, { shim: { binDir, targets: edited.targets } });
|
|
438
|
+
for (const target of edited.targets) ui.detail(`PATH: ${target.kind}${target.file ? ` ${target.file}` : ""}`);
|
|
347
439
|
} catch (error) {
|
|
348
440
|
saveRecord(root, { shim: { binDir, targets: [] } });
|
|
349
|
-
|
|
441
|
+
ui.say(t.shimPathFailed(error.message));
|
|
350
442
|
}
|
|
351
443
|
return true;
|
|
352
444
|
}
|
|
@@ -503,8 +595,8 @@ export async function disconnectRemote({ settingsFile, lang = detectLang(), log
|
|
|
503
595
|
|
|
504
596
|
const claudeDir = record?.claudeDir ?? dirname(settingsFile);
|
|
505
597
|
const current = readCurrent(root);
|
|
506
|
-
const script = current ? join(current.dir, HOOK_FILE) : undefined;
|
|
507
|
-
if (script
|
|
598
|
+
const script = [stableHookPath(root), current ? join(current.dir, HOOK_FILE) : undefined].find((file) => file && existsSync(file));
|
|
599
|
+
if (script) {
|
|
508
600
|
const hooks = await runHookScript("uninstall", { script, claudeDir, node, run });
|
|
509
601
|
if (hooks.ok) log(t.hooksRemoved);
|
|
510
602
|
else log(t.hooksStay(claudeDir));
|
package/lib/remote-text.js
CHANGED
|
@@ -71,6 +71,35 @@ const TEXT = {
|
|
|
71
71
|
lineShim: (on) => ` Launcher: ${on ? "on: `claude` starts through Remote" : "off"}`,
|
|
72
72
|
next: "Next: open a NEW terminal, run `claude`, type /tf-remote and scan the QR code with your phone.",
|
|
73
73
|
nextNoShim: (tfc) => `Next: run \`${tfc}\` instead of \`claude\`, type /tf-remote and scan the QR code with your phone.`,
|
|
74
|
+
// the bar: what is happening (shown while it runs), and what a finished step says (the plain line)
|
|
75
|
+
stepKey: "Pairing with your gateway…",
|
|
76
|
+
stepStatusLine: "Setting up the status line…",
|
|
77
|
+
stepPicker: "Setting up the model picker…",
|
|
78
|
+
stepCheck: "Checking TokenHub Remote…",
|
|
79
|
+
stepDownload: (version, transfer) => `Downloading Remote ${version}${transfer ? ` · ${transfer}` : ""}`,
|
|
80
|
+
stepPair: "Pairing this computer…",
|
|
81
|
+
stepHooks: "Adding hooks and /tf-remote…",
|
|
82
|
+
stepLauncher: "Setting up the launcher…",
|
|
83
|
+
doneKey: "Gateway key saved",
|
|
84
|
+
doneStatusLine: (result) => ({ installed: "Status line added", updated: "Status line refreshed", kept: "Status line left as it was" })[result] ?? "Status line skipped",
|
|
85
|
+
donePicker: (installed) => (installed ? "Model picker installed" : "Model picker skipped"),
|
|
86
|
+
doneDownload: { installed: (v) => `Remote ${v} downloaded`, updated: (v, previous) => `Remote updated to ${v} (was ${previous})`, repaired: (v) => `Remote ${v} reinstalled`, kept: (v) => `Remote ${v} already installed` },
|
|
87
|
+
donePaired: (name) => `Computer paired as ${name}`,
|
|
88
|
+
donePairedKept: (name) => `Computer already paired as ${name}`,
|
|
89
|
+
doneHooks: "Hooks and /tf-remote ready",
|
|
90
|
+
doneLauncher: (how) => ({ on: "Launcher installed", kept: "Launcher already in place", skipped: "Launcher skipped" })[how] ?? "Launcher skipped",
|
|
91
|
+
finished: "Done",
|
|
92
|
+
// the summary
|
|
93
|
+
ready: (version, name) => `TokenHub Remote ${version} is ready on ${name}.`,
|
|
94
|
+
nextNew: "Next: open a new terminal, run `claude`, type /tf-remote and scan the QR.",
|
|
95
|
+
nextPowerShell: "Next: open a new PowerShell window, run `claude`, type /tf-remote and scan the QR.",
|
|
96
|
+
noteShells: "cmd and Git Bash still start Claude without Remote: run `tokenhub connect --remote` again to cover them.",
|
|
97
|
+
manage: (url) => `Manage your computers: ${url}`,
|
|
98
|
+
details: (file) => `(details: ${file})`,
|
|
99
|
+
seeLog: (file) => `Details: ${file}`,
|
|
100
|
+
closeWindows: (version) => `Close your open Claude windows to start using Remote ${version}`,
|
|
101
|
+
versionUnknown: "unknown",
|
|
102
|
+
oldDaemonStopped: (previous, version) => `Stopped the Remote daemon of version ${previous}; the next claude starts ${version}.`,
|
|
74
103
|
// disconnect
|
|
75
104
|
busy: (n) => `${n === undefined ? "Hosted Claude sessions" : `${n} hosted Claude session(s)`} may be running through TokenHub Remote. Close them (or run \`tokenhub disconnect --force\` to stop them) and run this again. Nothing was changed.`,
|
|
76
105
|
stopped: "Stopped the Remote daemon.",
|
|
@@ -160,6 +189,34 @@ const TEXT = {
|
|
|
160
189
|
lineShim: (on) => ` Khởi chạy: ${on ? "bật: `claude` mở qua Remote" : "tắt"}`,
|
|
161
190
|
next: "Tiếp theo: mở cửa sổ terminal MỚI, chạy `claude`, gõ /tf-remote rồi quét mã QR bằng điện thoại.",
|
|
162
191
|
nextNoShim: (tfc) => `Tiếp theo: chạy \`${tfc}\` thay cho \`claude\`, gõ /tf-remote rồi quét mã QR bằng điện thoại.`,
|
|
192
|
+
// thanh tiến trình: việc đang làm (hiện khi chạy), và dòng của một bước đã xong (chế độ chữ thường)
|
|
193
|
+
stepKey: "Đang ghép với gateway…",
|
|
194
|
+
stepStatusLine: "Đang cài dòng trạng thái…",
|
|
195
|
+
stepPicker: "Đang cài bộ chọn model…",
|
|
196
|
+
stepCheck: "Đang kiểm tra TokenHub Remote…",
|
|
197
|
+
stepDownload: (version, transfer) => `Đang tải Remote ${version}${transfer ? ` · ${transfer}` : ""}`,
|
|
198
|
+
stepPair: "Đang ghép máy này…",
|
|
199
|
+
stepHooks: "Đang thêm hook và /tf-remote…",
|
|
200
|
+
stepLauncher: "Đang cài trình khởi chạy…",
|
|
201
|
+
doneKey: "Đã lưu khóa gateway",
|
|
202
|
+
doneStatusLine: (result) => ({ installed: "Đã thêm dòng trạng thái", updated: "Đã làm mới dòng trạng thái", kept: "Giữ nguyên dòng trạng thái cũ" })[result] ?? "Bỏ qua dòng trạng thái",
|
|
203
|
+
donePicker: (installed) => (installed ? "Đã cài bộ chọn model" : "Bỏ qua bộ chọn model"),
|
|
204
|
+
doneDownload: { installed: (v) => `Đã tải Remote ${v}`, updated: (v, previous) => `Đã cập nhật Remote lên ${v} (trước đó ${previous})`, repaired: (v) => `Đã cài lại Remote ${v}`, kept: (v) => `Remote ${v} đã được cài` },
|
|
205
|
+
donePaired: (name) => `Đã ghép máy với tên ${name}`,
|
|
206
|
+
donePairedKept: (name) => `Máy đã được ghép với tên ${name}`,
|
|
207
|
+
doneHooks: "Hook và /tf-remote đã sẵn sàng",
|
|
208
|
+
doneLauncher: (how) => ({ on: "Đã cài trình khởi chạy", kept: "Trình khởi chạy đã có sẵn", skipped: "Bỏ qua trình khởi chạy" })[how] ?? "Bỏ qua trình khởi chạy",
|
|
209
|
+
finished: "Xong",
|
|
210
|
+
ready: (version, name) => `TokenHub Remote ${version} đã sẵn sàng trên ${name}.`,
|
|
211
|
+
nextNew: "Tiếp theo: mở terminal mới, chạy `claude`, gõ /tf-remote rồi quét mã QR.",
|
|
212
|
+
nextPowerShell: "Tiếp theo: mở cửa sổ PowerShell mới, chạy `claude`, gõ /tf-remote rồi quét mã QR.",
|
|
213
|
+
noteShells: "cmd và Git Bash vẫn mở Claude không có Remote: chạy lại `tokenhub connect --remote` để áp dụng cho chúng.",
|
|
214
|
+
manage: (url) => `Quản lý các máy của bạn: ${url}`,
|
|
215
|
+
details: (file) => `(chi tiết: ${file})`,
|
|
216
|
+
seeLog: (file) => `Chi tiết: ${file}`,
|
|
217
|
+
closeWindows: (version) => `Hãy đóng các cửa sổ Claude đang mở để dùng Remote ${version}`,
|
|
218
|
+
versionUnknown: "không rõ",
|
|
219
|
+
oldDaemonStopped: (previous, version) => `Đã dừng daemon Remote phiên bản ${previous}; lần chạy claude kế tiếp sẽ dùng ${version}.`,
|
|
163
220
|
busy: (n) => `${n === undefined ? "Có thể còn phiên Claude" : `Còn ${n} phiên Claude`} đang chạy qua TokenHub Remote. Hãy đóng chúng (hoặc chạy \`tokenhub disconnect --force\` để dừng) rồi chạy lại. Chưa có gì bị thay đổi.`,
|
|
164
221
|
stopped: "Đã dừng daemon Remote.",
|
|
165
222
|
revoked: "Đã thu hồi token Remote của máy này trên pool.",
|