@emesoft/tokenhub 0.9.0 → 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/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
- log(`Connected. Claude Code settings updated: ${settingsFile}`);
348
- if (statusResult === "installed") log("Status line added: today's spend and credit show under the Claude Code prompt.");
349
- if (statusResult === "updated") log("Status line refreshed with your new key.");
350
- if (statusResult === "kept") log("Your existing statusLine was left as is. The setup guide on the pool site has the TokenHub one if you want it.");
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
- log(`Warning: ${overriding.join(", ")} set in your shell overrides settings.json. Unset it to use the pool.`);
389
+ notes.push(`Warning: ${overriding.join(", ")} set in your shell overrides settings.json. Unset it to use the pool.`);
354
390
  }
355
- if (modelPicker && (await ask("Install the TokenHub model picker for Claude Code (/model lists TokenHub models)?"))) {
356
- try {
357
- installModelPicker(settingsFile, pickerDir);
358
- log("Model picker installed. Restart Claude Code, then type /model to pick a TokenHub model.");
359
- // Claude Code reports the mouse only in its fullscreen layout (#766): offer it, never force it.
360
- if (layoutUnset(settingsFile) && (await ask("Turn on Claude Code's fullscreen layout so the picker takes the mouse?", false))) {
361
- enableFullscreen(settingsFile);
362
- log('Fullscreen layout on ("tui": "fullscreen"). Switch back any time with /tui default.');
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
- const lang = detectLang(env);
369
- if (remote ?? (await ask(text(lang).askRemote, false))) {
370
- const installed = await installRemoteFn({ pool, baseUrl, settingsFile, lang, log, open, signal, ask, deviceName, intervalOverrideMs, env, home });
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
- log("Cancelled.");
377
- return 130;
419
+ ui.say("Cancelled.");
420
+ return end(130);
378
421
  }
379
- log(`Error: ${error.message}`);
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;
@@ -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
+ }
@@ -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 }>;
@@ -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` and cancel signal.
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
- const bytes = Buffer.from(await res.arrayBuffer());
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 bytes = await fetchVerified(`${pool}${REMOTE_DOWNLOADS}/${key}/${file.name}`, file, { fetchImpl, signal });
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
- removeOtherVersions(root, parsed.version);
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 removeOtherVersions(root, keep) {
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;
@@ -1,5 +1,7 @@
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";
4
+ import type { WinSystem } from "./launcher-precedence.js";
3
5
  export const DEFAULT_RELAY_ORIGIN: string;
4
6
  export interface InstallRecord {
5
7
  pool: string;
@@ -9,6 +11,7 @@ export interface InstallRecord {
9
11
  relayFile: string;
10
12
  claudeDir?: string;
11
13
  shim?: { binDir: string; targets: Array<{ kind: string; file?: string }> };
14
+ launcher?: import("./launcher-precedence.js").LauncherRecord;
12
15
  }
13
16
  export interface Proc {
14
17
  isAlive(pid: number): boolean;
@@ -32,6 +35,7 @@ export function installRemote(options: {
32
35
  settingsFile: string;
33
36
  lang?: "en" | "vi";
34
37
  log?: (line: string) => void;
38
+ ui?: InstallUi;
35
39
  open: (url: string) => void;
36
40
  signal?: AbortSignal;
37
41
  ask: (question: string, defaultYes?: boolean) => Promise<boolean>;
@@ -45,9 +49,11 @@ export function installRemote(options: {
45
49
  node?: string;
46
50
  fetchImpl?: typeof fetch;
47
51
  run?: Runner;
52
+ proc?: Proc;
48
53
  userPath?: UserPath;
49
54
  pickPort?: typeof pickHookPort;
50
- }): Promise<{ ok: true; version: string; shim: boolean } | { ok: false; code: number }>;
55
+ launcherSys?: WinSystem;
56
+ }): Promise<{ ok: true; version: string; shim: boolean; launcher?: string; summary: string[] } | { ok: false; code: number }>;
51
57
  export function realProc(platform: string, run: Runner): Proc;
52
58
  export function daemonState(options: { appDir: string; root: string; platform: string; proc: Proc }): Promise<{ state: "running" | "other" | "stopped"; pid?: number }>;
53
59
  export function stopDaemon(options: {
@@ -72,6 +78,7 @@ export function disconnectRemote(options: {
72
78
  run?: Runner;
73
79
  proc?: Proc;
74
80
  userPath?: UserPath;
81
+ launcherSys?: WinSystem;
75
82
  }): Promise<{ found: boolean; blocked: boolean }>;
76
83
  export function remoteStatus(options: {
77
84
  settingsFile: string;
@@ -81,5 +88,7 @@ export function remoteStatus(options: {
81
88
  home: string;
82
89
  platform?: string;
83
90
  run?: Runner;
91
+ userPath?: UserPath;
92
+ launcherSys?: WinSystem;
84
93
  proc?: Proc;
85
94
  }): Promise<number>;