@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.
@@ -4,8 +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";
9
+ import { ensureLauncher, hasPsBlock, launcherWins, realWindowsSystem, removeLauncher } from "./launcher-precedence.js";
7
10
  import { pairRemote, checkRemoteToken, revokeRemoteToken } from "./remote.js";
8
- 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";
9
13
  import { appConfigDir, exeName, legacyConfigDir, remoteDir, shimDir } from "./remote-paths.js";
10
14
  import { installShimFiles, removeShimFiles, shimInstalled, shimPresent } from "./remote-shim.js";
11
15
  import { detectLang, text } from "./remote-text.js";
@@ -36,6 +40,7 @@ function sha256(value) {
36
40
  * @property {string} relayFile Path of the `relay.json` written.
37
41
  * @property {string} [claudeDir] Claude Code's config folder the hooks went into.
38
42
  * @property {{ binDir: string, targets: Array<{ kind: string, file?: string }> }} [shim] The launcher and where PATH was edited.
43
+ * @property {import("./launcher-precedence.js").LauncherRecord} [launcher] What was done to make `claude` start the launcher on Windows (profiles, execution policy, Machine Path).
39
44
  */
40
45
  /**
41
46
  * @param {string} root The Remote folder.
@@ -152,20 +157,66 @@ async function runHookScript(verb, { script, claudeDir, node, run }) {
152
157
  const lines = (result.code === 0 ? result.stdout : result.stderr || result.stdout).split(/\r?\n/).filter((line) => line.trim() !== "");
153
158
  return { ok: result.code === 0, output: lines };
154
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
+ }
155
203
  /**
156
204
  * Set up TokenHub Remote on this computer (the step `connect` offers after the settings are written).
157
205
  *
158
- * In order: download the daemon (verified, nothing in place before it checks out); pair this computer with the `remote` kind, or keep
159
- * the token it already has when the pool still accepts it; write `relay.json` for the daemon; install the Claude Code hooks and
160
- * `/tf-remote` by running the hook script's own `install`; and, after asking, the `claude` launcher and its PATH entry. The download
161
- * comes first so a failed download does not leave a pairing behind. What was done is recorded in `<remote>/install.json` as it goes.
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`.
162
212
  *
163
213
  * @param {object} options
164
214
  * @param {string} options.pool Pool address from `resolvePoolUrl`.
165
215
  * @param {string} [options.baseUrl] Address the key was issued by (the public origin); defaults to `pool`.
166
216
  * @param {string} options.settingsFile Claude Code's `settings.json`; its folder gets the hooks and `/tf-remote`.
167
217
  * @param {"en" | "vi"} [options.lang] Message language.
168
- * @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`.
169
220
  * @param {(url: string) => void} options.open Browser opener.
170
221
  * @param {AbortSignal} [options.signal] Aborts the flow (Ctrl+C).
171
222
  * @param {(question: string, defaultYes?: boolean) => Promise<boolean>} options.ask Yes/no prompt (false without a terminal).
@@ -179,9 +230,11 @@ async function runHookScript(verb, { script, claudeDir, node, run }) {
179
230
  * @param {string} [options.node] Node program that runs the hook script (this one by default).
180
231
  * @param {typeof fetch} [options.fetchImpl] `fetch` override for tests.
181
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).
182
234
  * @param {ReturnType<typeof windowsUserPath>} [options.userPath] Registry access for the PATH edit (tests replace it).
183
235
  * @param {typeof pickHookPort} [options.pickPort] Chooses the hook port when `relay.json` has none (tests replace it).
184
- * @returns {Promise<{ ok: true, version: string, shim: boolean } | { ok: false, code: number }>} The outcome; on failure the exit code.
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).
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.
185
238
  */
186
239
  export async function installRemote({
187
240
  pool,
@@ -189,9 +242,10 @@ export async function installRemote({
189
242
  settingsFile,
190
243
  lang = detectLang(),
191
244
  log = console.log,
245
+ ui: given,
192
246
  open,
193
247
  signal,
194
- ask,
248
+ ask: rawAsk,
195
249
  shim,
196
250
  deviceName = hostname(),
197
251
  intervalOverrideMs,
@@ -202,12 +256,16 @@ export async function installRemote({
202
256
  node = process.execPath,
203
257
  fetchImpl = fetch,
204
258
  run = defaultRun,
259
+ proc,
205
260
  userPath,
206
261
  pickPort = pickHookPort,
262
+ launcherSys,
207
263
  }) {
208
264
  const t = text(lang);
265
+ const ui = given ?? createInstallUi({ log, env, plain: true, total: 4 });
266
+ const ask = ui.ask(rawAsk);
209
267
  if (platform !== "win32" && platform !== "darwin") {
210
- log(t.unsupported(platform));
268
+ ui.say(t.unsupported(platform));
211
269
  return { ok: false, code: 1 };
212
270
  }
213
271
  const root = remoteDir(env, home);
@@ -215,21 +273,44 @@ export async function installRemote({
215
273
  const relayFile = join(appConfigDir(env, home), "relay.json");
216
274
  const legacyFile = join(legacyConfigDir(env, home), "relay.json");
217
275
  const claudeDir = dirname(settingsFile);
276
+ const logFile = installLogPath(root);
218
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
+ };
219
285
 
220
- log("");
221
- log(t.downloading);
286
+ // Step 4: download (or keep) the daemon.
287
+ ui.begin(t.stepCheck);
222
288
  let download;
223
289
  try {
224
- download = await downloadRemote({ pool, root, platform, arch, log, fetchImpl, signal, run });
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
+ });
225
301
  } catch (error) {
226
- log(t.failed(error.message));
227
- return { ok: false, code: 1 };
302
+ if (signal?.aborted) {
303
+ ui.say("Cancelled.");
304
+ return { ok: false, code: 130 };
305
+ }
306
+ return fail(t.failed(error.message));
228
307
  }
229
- 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));
230
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));
231
311
 
232
- // Keep the token this computer already has unless the pool says it was revoked (or it is for another pool).
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);
233
314
  const record = readRecord(root);
234
315
  let existing = readRelayJson(relayFile);
235
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
@@ -246,22 +327,21 @@ export async function installRemote({
246
327
  let token;
247
328
  let name = deviceName;
248
329
  let relayOrigin;
330
+ let pairedBefore = false;
249
331
  if (existing?.deviceToken && record?.pool === origin && record.tokenSha256 === sha256(existing.deviceToken)) {
250
332
  const check = await checkRemoteToken({ pool: origin, token: existing.deviceToken, signal, fetchImpl });
251
333
  if (check.status !== "revoked") {
252
334
  token = existing.deviceToken;
253
335
  name = check.status === "valid" ? check.deviceName : (existing.name ?? deviceName);
254
336
  relayOrigin = check.status === "valid" ? check.relayOrigin : undefined;
255
- log(t.keepingToken(name));
337
+ pairedBefore = true;
338
+ ui.detail(t.keepingToken(name));
256
339
  }
257
340
  }
258
341
  if (!token) {
259
- log(t.pairing);
260
- const paired = await pairRemote({ pool, deviceName, log, open, signal, intervalOverrideMs, fetchImpl });
261
- if (!paired.ok) {
262
- log(t.pairingFailed);
263
- return { ok: false, code: paired.code };
264
- }
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);
265
345
  token = paired.token;
266
346
  origin = paired.baseUrl;
267
347
  const check = await checkRemoteToken({ pool: origin, token, signal, fetchImpl });
@@ -272,33 +352,53 @@ export async function installRemote({
272
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.
273
353
  const hookPort = existing?.hookPort ?? (await pickPort());
274
354
  const restricted = await writeRelayJson(relayFile, { ...existing, relayUrl, deviceToken: token, name, ...(hookPort ? { hookPort } : {}) }, { platform, env, run });
275
- if (!restricted) log(`(could not restrict access to ${relayFile}; the folder's own permissions apply)`);
355
+ if (!restricted) ui.say(`(could not restrict access to ${relayFile}; the folder's own permissions apply)`);
276
356
  if (legacy) {
277
357
  rmSync(legacyFile, { force: true });
278
- log(t.movedConfig(legacyFile, relayFile));
358
+ ui.detail(t.movedConfig(legacyFile, relayFile));
279
359
  }
280
360
  saveRecord(root, { pool: origin, deviceName: name, tokenSha256: sha256(token), relayFile });
361
+ ui.complete(pairedBefore ? t.donePairedKept(name) : t.donePaired(name));
281
362
 
282
- log(t.hooks);
283
- const hooks = await runHookScript("install", { script: join(download.dir, HOOK_FILE), claudeDir, node, run });
284
- for (const line of hooks.output) log(` ${line}`);
285
- if (!hooks.ok) {
286
- log(t.hooksFailed(hooks.output.at(-1) ?? "?"));
287
- return { ok: false, code: 1 };
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)] };
288
372
  }
373
+ for (const line of hooks.output) ui.detail(line);
374
+ if (!hooks.ok) return fail(t.hooksFailed(hooks.output.at(-1) ?? "?"));
289
375
  saveRecord(root, { claudeDir });
376
+ ui.complete(t.doneHooks);
290
377
 
291
- const shimOn = await offerShim({ shim, ask, log, t, binDir, platform, env, home, node, run, userPath, root });
292
- const tfc = join(download.dir, exeName("tfc", platform));
378
+ // Step 7: the launcher.
379
+ ui.begin(t.stepLauncher);
380
+ const registry = userPath ?? windowsUserPath({ run });
381
+ const shimBefore = shimInstalled(binDir, platform);
382
+ const shimOn = await offerShim({ shim, ask, ui, t, binDir, platform, env, home, run, userPath: registry, root });
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.
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;
385
+ if (launcher) saveRecord(root, { launcher: launcher.record });
386
+ ui.complete(t.doneLauncher(!shimOn ? "skipped" : shimBefore ? "kept" : "on"));
293
387
 
294
- log("");
295
- log(t.done(download.version));
296
- log(t.lineComputer(name));
297
- log(t.linePage(`${origin}/member/remote`));
298
- log(t.lineHooks(claudeDir));
299
- log(t.lineShim(shimOn));
300
- log(shimOn ? t.next : t.nextNoShim(tfc));
301
- return { ok: true, version: download.version, shim: shimOn };
388
+ const tfc = join(download.dir, exeName("tfc", platform));
389
+ const claudeCmd = join(binDir, "claude.cmd");
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 };
302
402
  }
303
403
  /** @param {Record<string, any> | undefined} existing An existing `relay.json`. @returns {string | undefined} The origin its `relayUrl` was made from. */
304
404
  function relayOriginFromFile(existing) {
@@ -312,32 +412,33 @@ function relayOriginFromFile(existing) {
312
412
  /**
313
413
  * The launcher step: explain it, ask (unless a flag or an earlier install already decided), write the shim, edit PATH.
314
414
  *
315
- * @param {object} options What `installRemote` has: `shim`, `ask`, `log`, `t`, `binDir`, `platform`, `env`, `home`, `run`, `userPath`, `root`.
415
+ * @param {object} options What `installRemote` has: `shim`, `ask` (already wrapped by the ui), `ui`, `t`, `binDir`, `platform`, `env`, `home`, `run`, `userPath`, `root`.
316
416
  * @returns {Promise<boolean>} Whether the launcher is installed afterwards.
317
417
  */
318
- async function offerShim({ shim, ask, log, t, binDir, platform, env, home, run, userPath, root }) {
418
+ async function offerShim({ shim, ask, ui, t, binDir, platform, env, home, run, userPath, root }) {
319
419
  const already = shimInstalled(binDir, platform);
320
420
  let want = shim ?? already;
321
421
  if (shim === undefined && !already) {
322
- for (const line of t.shimIntro(binDir, platform === "win32" ? t.wherePath : t.whereProfile)) log(line);
422
+ for (const line of t.shimIntro(binDir, platform === "win32" ? t.wherePath : t.whereProfile)) ui.say(line);
323
423
  want = await ask(t.askShim, true);
324
424
  }
325
425
  if (!want) {
326
- log(t.shimSkipped);
327
- log(` ${join(readCurrent(root)?.dir ?? "", exeName("tfc", platform))}`);
328
- log(t.shimSkippedHint);
426
+ ui.detail(t.shimSkipped);
427
+ ui.detail(` ${join(readCurrent(root)?.dir ?? "", exeName("tfc", platform))}`);
428
+ ui.detail(t.shimSkippedHint);
329
429
  return false;
330
430
  }
331
431
  const realClaude = findRealClaude({ pathValue: env.PATH ?? env.Path ?? "", shimDirs: [binDir], env, platform, home });
332
- if (!realClaude) log(t.shimNoClaude);
432
+ if (!realClaude) ui.say(t.shimNoClaude);
333
433
  installShimFiles({ binDir, platform, realClaude });
334
- log(t.shimOn(binDir));
434
+ ui.detail(t.shimOn(binDir));
335
435
  try {
336
436
  const edited = await addBinToPath({ dir: binDir, platform, home, userPath: userPath ?? windowsUserPath({ run }) });
337
437
  saveRecord(root, { shim: { binDir, targets: edited.targets } });
438
+ for (const target of edited.targets) ui.detail(`PATH: ${target.kind}${target.file ? ` ${target.file}` : ""}`);
338
439
  } catch (error) {
339
440
  saveRecord(root, { shim: { binDir, targets: [] } });
340
- log(t.shimPathFailed(error.message));
441
+ ui.say(t.shimPathFailed(error.message));
341
442
  }
342
443
  return true;
343
444
  }
@@ -465,9 +566,10 @@ export async function stopDaemon({ appDir, root, platform, force = false, env, p
465
566
  * @param {import("./run.js").Runner} [options.run] Process runner.
466
567
  * @param {Proc} [options.proc] Process facts (tests replace them).
467
568
  * @param {ReturnType<typeof windowsUserPath>} [options.userPath] Registry access (tests replace it).
569
+ * @param {import("./launcher-precedence.js").WinSystem} [options.launcherSys] Windows access for undoing the launcher fix (tests replace it).
468
570
  * @returns {Promise<{ found: boolean, blocked: boolean }>} `found`: there was something of Remote to remove. `blocked`: it was not removed because sessions run.
469
571
  */
470
- export async function disconnectRemote({ settingsFile, lang = detectLang(), log = console.log, force = false, env = process.env, home, platform = process.platform, node = process.execPath, fetchImpl = fetch, run = defaultRun, proc, userPath }) {
572
+ export async function disconnectRemote({ settingsFile, lang = detectLang(), log = console.log, force = false, env = process.env, home, platform = process.platform, node = process.execPath, fetchImpl = fetch, run = defaultRun, proc, userPath, launcherSys }) {
471
573
  const t = text(lang);
472
574
  const root = remoteDir(env, home);
473
575
  const binDir = shimDir(env, home);
@@ -493,8 +595,8 @@ export async function disconnectRemote({ settingsFile, lang = detectLang(), log
493
595
 
494
596
  const claudeDir = record?.claudeDir ?? dirname(settingsFile);
495
597
  const current = readCurrent(root);
496
- const script = current ? join(current.dir, HOOK_FILE) : undefined;
497
- if (script && existsSync(script)) {
598
+ const script = [stableHookPath(root), current ? join(current.dir, HOOK_FILE) : undefined].find((file) => file && existsSync(file));
599
+ if (script) {
498
600
  const hooks = await runHookScript("uninstall", { script, claudeDir, node, run });
499
601
  if (hooks.ok) log(t.hooksRemoved);
500
602
  else log(t.hooksStay(claudeDir));
@@ -502,6 +604,7 @@ export async function disconnectRemote({ settingsFile, lang = detectLang(), log
502
604
  log(t.hooksStay(claudeDir));
503
605
  }
504
606
 
607
+ if (platform === "win32" && record?.launcher) await removeLauncher({ record: record.launcher, sys: launcherSys ?? realWindowsSystem({ run }), log, t });
505
608
  if (record?.shim || shimPresent(binDir, platform) || profileHasBlock) {
506
609
  const wasInRegistry = platform === "win32" && Boolean(record?.shim?.targets?.some((target) => target.kind === "registry"));
507
610
  if (platform === "darwin" || wasInRegistry) {
@@ -524,6 +627,21 @@ export async function disconnectRemote({ settingsFile, lang = detectLang(), log
524
627
  }
525
628
  return { found: true, blocked: false };
526
629
  }
630
+ /**
631
+ * What a NEW terminal on Windows would do with `claude`, when this terminal's own PATH does not reach the launcher: read the Machine and User Path
632
+ * from the registry (the way a new process builds its Path), and look for our PowerShell profile function.
633
+ * @param {object} options `binDir`, `env`, `record` (install.json), `userPath` (registry User Path), `sys` (Machine Path).
634
+ * @returns {Promise<"new-terminals" | "powershell-only" | "installed">} The first when the launcher wins by PATH (this terminal started earlier), the second when only the profile function does.
635
+ */
636
+ async function windowsLauncherState({ binDir, env, record, userPath, sys }) {
637
+ try {
638
+ const [machine, user] = await Promise.all([sys.machinePath(), userPath.get()]);
639
+ if (launcherWins({ machine: machine.value, user: user.value, env, binDir }).ours) return "new-terminals";
640
+ } catch {
641
+ // Unreadable: fall through to what the record says.
642
+ }
643
+ return record?.launcher?.profiles?.some((profile) => hasPsBlock(profile.file)) ? "powershell-only" : "installed";
644
+ }
527
645
  /** @param {string} file Path of a settings file. @returns {boolean} Whether it mentions the hook script (entries of ours that could not be removed). */
528
646
  function settingsMentionsHook(file) {
529
647
  try {
@@ -545,9 +663,11 @@ function settingsMentionsHook(file) {
545
663
  * @param {string} [options.platform] Node platform name.
546
664
  * @param {import("./run.js").Runner} [options.run] Process runner.
547
665
  * @param {Proc} [options.proc] Process facts.
666
+ * @param {ReturnType<typeof windowsUserPath>} [options.userPath] Registry access (tests replace it).
667
+ * @param {import("./launcher-precedence.js").WinSystem} [options.launcherSys] Windows access (tests replace it).
548
668
  * @returns {Promise<number>} 0 when installed, 1 when not.
549
669
  */
550
- export async function remoteStatus({ settingsFile, lang = detectLang(), log = console.log, env = process.env, home, platform = process.platform, run = defaultRun, proc }) {
670
+ export async function remoteStatus({ settingsFile, lang = detectLang(), log = console.log, env = process.env, home, platform = process.platform, run = defaultRun, proc, userPath, launcherSys }) {
551
671
  const t = text(lang);
552
672
  const root = remoteDir(env, home);
553
673
  const binDir = shimDir(env, home);
@@ -573,6 +693,7 @@ export async function remoteStatus({ settingsFile, lang = detectLang(), log = co
573
693
  if (shimInstalled(binDir, platform)) {
574
694
  const first = findOnPath(platform === "win32" ? ["claude.exe", "claude.cmd"] : ["claude"], env.PATH ?? env.Path ?? "", { platform });
575
695
  shimState = first && normalizeDir(dirname(first), platform) === normalizeDir(binDir, platform) ? "active" : "installed";
696
+ if (shimState === "installed" && platform === "win32") shimState = await windowsLauncherState({ binDir, env, record, userPath: userPath ?? windowsUserPath({ run }), sys: launcherSys ?? realWindowsSystem({ run }) });
576
697
  }
577
698
  log(t.statusShim(shimState));
578
699
  const claudeDir = record?.claudeDir ?? dirname(settingsFile);
@@ -38,6 +38,32 @@ const TEXT = {
38
38
  shimNoClaude: "Claude Code was not found on PATH. The launcher will find it once it is installed.",
39
39
  shimSkipped: "Launcher skipped. Start Claude through Remote with:",
40
40
  shimSkippedHint: "Run `tokenhub connect --remote` again in a terminal to add the launcher.",
41
+ // making the launcher win on Windows (launcher-precedence.js)
42
+ launcherUnchecked: (why) => `Could not check whether \`claude\` will start the launcher (${why}).`,
43
+ launcherShadowed: (winner) => `Another claude (${winner}) comes before the launcher on this computer's PATH, so typing \`claude\` would start it without Remote.`,
44
+ profileIntro: ["", "Option 1, no administrator needed: add a `claude` command to your PowerShell profile that starts the launcher (PowerShell only; cmd.exe and Git Bash follow PATH)."],
45
+ askProfile: "Add it to your PowerShell profile?",
46
+ policyIntro: (shell, effective) => [`PowerShell's execution policy (${effective} in ${shell}) stops your profile from running.`, "TokenHub can allow your own profile to run, for your user only (Set-ExecutionPolicy RemoteSigned, scope CurrentUser). `tokenhub disconnect` puts it back."],
47
+ askPolicy: "Allow your PowerShell profile to run?",
48
+ policyLocked: (shell, source) => `${shell}: the execution policy comes from ${source}, which TokenHub cannot override. Skipped.`,
49
+ policyFailed: (shell) => `${shell}: the execution policy was not changed.`,
50
+ profileAdded: (shell, file) => `Added a \`claude\` function to the ${shell} profile: ${file}`,
51
+ profileSkipped: (file, why) => `Left ${file} alone (${why}).`,
52
+ profileFailed: (file, why) => `Could not write ${file} (${why}).`,
53
+ machineIntro: ["", "Option 2, one administrator prompt: put the launcher before the real claude in the system PATH. This covers cmd.exe and Git Bash too."],
54
+ askMachine: "Change the system PATH (Windows will ask for permission)?",
55
+ machineDone: "The launcher is now first in the system PATH.",
56
+ machineFailed: "The system PATH was not changed (the permission prompt was declined, or it failed).",
57
+ machineNotEnough: "The system PATH was changed, but `claude` still would not start the launcher.",
58
+ startByHand: (cmd) => `\`claude\` will not start TokenHub Remote yet. To start a session that works with your phone, run:\n & "${cmd}"\nRun \`tokenhub connect --remote\` again to choose one of the fixes.`,
59
+ noteProfile: " In PowerShell `claude` now starts through Remote. cmd.exe and Git Bash follow PATH, where another claude comes first: run `tokenhub connect --remote` again and choose the system PATH to cover them.",
60
+ nextProfile: "Next: open a NEW PowerShell window, run `claude`, type /tf-remote and scan the QR code with your phone.",
61
+ nextByHand: (cmd) => `Next: run \`& "${cmd}"\`, type /tf-remote and scan the QR code with your phone.`,
62
+ profileRemoved: (file) => `Removed the claude function from ${file}.`,
63
+ profileRemoveFailed: (file, why) => `Could not clean ${file} (${why}). Remove the block marked "tokenhub remote" yourself.`,
64
+ machineRemoved: "Removed the launcher from the system PATH.",
65
+ machineRemoveFailed: (entry) => `Could not take ${entry} out of the system PATH. Remove it yourself (System Properties, Environment Variables).`,
66
+ policyRestored: (shell, previous) => `Put the ${shell} execution policy for your user back to ${previous}.`,
41
67
  done: (version) => `TokenHub Remote ${version} is set up.`,
42
68
  lineComputer: (name) => ` Computer: ${name}`,
43
69
  linePage: (url) => ` Manage: ${url} (your computers; revoke any time)`,
@@ -45,6 +71,35 @@ const TEXT = {
45
71
  lineShim: (on) => ` Launcher: ${on ? "on: `claude` starts through Remote" : "off"}`,
46
72
  next: "Next: open a NEW terminal, run `claude`, type /tf-remote and scan the QR code with your phone.",
47
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}.`,
48
103
  // disconnect
49
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.`,
50
105
  stopped: "Stopped the Remote daemon.",
@@ -66,7 +121,7 @@ const TEXT = {
66
121
  statusRelay: (url) => `Relay: ${url} (the daemon does not report its connection; this is its configuration)`,
67
122
  statusNoRelay: "Relay: not configured (relay.json is missing): run `tokenhub connect --remote`",
68
123
  statusDevice: (name) => `Computer: ${name}`,
69
- statusShim: (state) => `Launcher: ${state === "active" ? "on: `claude` in this terminal starts through Remote" : state === "installed" ? "installed, but `claude` in this terminal does not use it (open a new terminal, or another claude comes first on PATH)" : "off"}`,
124
+ statusShim: (state) => `Launcher: ${{ active: "on: `claude` in this terminal starts through Remote", "new-terminals": "on in new terminals (this terminal started before it was set up: open a new one)", "powershell-only": "on in PowerShell only (a profile function); cmd.exe and Git Bash follow PATH, where another claude comes first", installed: "installed, but another claude comes before it on PATH, so `claude` does not start through Remote (run `tokenhub connect --remote` to fix it)" }[state] ?? "off"}`,
70
125
  statusHooks: (on) => `Hooks: ${on ? "installed (/tf-remote)" : "missing: run `tokenhub connect --remote`"}`,
71
126
  statusPage: (url) => `Manage: ${url}`,
72
127
  },
@@ -101,6 +156,32 @@ const TEXT = {
101
156
  shimNoClaude: "Không thấy Claude Code trong PATH. Trình khởi chạy sẽ tự tìm thấy nó khi bạn cài xong.",
102
157
  shimSkipped: "Bỏ qua trình khởi chạy. Hãy mở Claude qua Remote bằng lệnh:",
103
158
  shimSkippedHint: "Chạy lại `tokenhub connect --remote` trong terminal để thêm trình khởi chạy.",
159
+ // making the launcher win on Windows (launcher-precedence.js)
160
+ launcherUnchecked: (why) => `Không kiểm tra được lệnh \`claude\` có mở trình khởi chạy không (${why}).`,
161
+ launcherShadowed: (winner) => `Một claude khác (${winner}) đứng trước trình khởi chạy trong PATH của máy này, nên gõ \`claude\` sẽ mở nó mà không có Remote.`,
162
+ profileIntro: ["", "Cách 1, không cần quyền quản trị: thêm lệnh `claude` vào profile PowerShell để mở trình khởi chạy (chỉ cho PowerShell; cmd.exe và Git Bash theo PATH)."],
163
+ askProfile: "Thêm vào profile PowerShell của bạn?",
164
+ policyIntro: (shell, effective) => [`Chính sách thực thi của PowerShell (${effective} trong ${shell}) không cho profile chạy.`, "TokenHub có thể cho phép profile của riêng bạn chạy, chỉ cho tài khoản của bạn (Set-ExecutionPolicy RemoteSigned, phạm vi CurrentUser). `tokenhub disconnect` sẽ trả lại như cũ."],
165
+ askPolicy: "Cho phép profile PowerShell của bạn chạy?",
166
+ policyLocked: (shell, source) => `${shell}: chính sách thực thi đến từ ${source}, TokenHub không thể ghi đè. Bỏ qua.`,
167
+ policyFailed: (shell) => `${shell}: chưa đổi được chính sách thực thi.`,
168
+ profileAdded: (shell, file) => `Đã thêm hàm \`claude\` vào profile ${shell}: ${file}`,
169
+ profileSkipped: (file, why) => `Giữ nguyên ${file} (${why}).`,
170
+ profileFailed: (file, why) => `Không ghi được ${file} (${why}).`,
171
+ machineIntro: ["", "Cách 2, một lần hỏi quyền quản trị: đặt trình khởi chạy trước claude thật trong PATH hệ thống. Cách này áp dụng cả cmd.exe và Git Bash."],
172
+ askMachine: "Đổi PATH hệ thống (Windows sẽ hỏi quyền)?",
173
+ machineDone: "Trình khởi chạy đã đứng đầu PATH hệ thống.",
174
+ machineFailed: "Chưa đổi PATH hệ thống (bạn từ chối hộp thoại cấp quyền, hoặc có lỗi).",
175
+ machineNotEnough: "Đã đổi PATH hệ thống, nhưng `claude` vẫn chưa mở trình khởi chạy.",
176
+ startByHand: (cmd) => `\`claude\` chưa mở TokenHub Remote. Để mở phiên dùng được với điện thoại, hãy chạy:\n & "${cmd}"\nChạy lại \`tokenhub connect --remote\` để chọn một cách sửa.`,
177
+ noteProfile: " Trong PowerShell, `claude` giờ mở qua Remote. cmd.exe và Git Bash theo PATH, nơi một claude khác đứng trước: chạy lại `tokenhub connect --remote` và chọn PATH hệ thống để áp dụng cho chúng.",
178
+ nextProfile: "Tiếp theo: mở cửa sổ PowerShell MỚI, chạy `claude`, gõ /tf-remote rồi quét mã QR bằng điện thoại.",
179
+ nextByHand: (cmd) => `Tiếp theo: chạy \`& "${cmd}"\`, gõ /tf-remote rồi quét mã QR bằng điện thoại.`,
180
+ profileRemoved: (file) => `Đã gỡ hàm claude khỏi ${file}.`,
181
+ profileRemoveFailed: (file, why) => `Không dọn được ${file} (${why}). Hãy tự xoá khối đánh dấu "tokenhub remote".`,
182
+ machineRemoved: "Đã gỡ trình khởi chạy khỏi PATH hệ thống.",
183
+ machineRemoveFailed: (entry) => `Không gỡ được ${entry} khỏi PATH hệ thống. Hãy tự xoá (System Properties, Environment Variables).`,
184
+ policyRestored: (shell, previous) => `Đã trả chính sách thực thi ${shell} của bạn về ${previous}.`,
104
185
  done: (version) => `TokenHub Remote ${version} đã sẵn sàng.`,
105
186
  lineComputer: (name) => ` Máy tính: ${name}`,
106
187
  linePage: (url) => ` Quản lý: ${url} (các máy của bạn; thu hồi bất cứ lúc nào)`,
@@ -108,6 +189,34 @@ const TEXT = {
108
189
  lineShim: (on) => ` Khởi chạy: ${on ? "bật: `claude` mở qua Remote" : "tắt"}`,
109
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.",
110
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}.`,
111
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.`,
112
221
  stopped: "Đã dừng daemon Remote.",
113
222
  revoked: "Đã thu hồi token Remote của máy này trên pool.",
@@ -127,7 +236,7 @@ const TEXT = {
127
236
  statusRelay: (url) => `Relay: ${url} (daemon không báo trạng thái kết nối; đây là cấu hình của nó)`,
128
237
  statusNoRelay: "Relay: chưa cấu hình (thiếu relay.json): chạy `tokenhub connect --remote`",
129
238
  statusDevice: (name) => `Máy tính: ${name}`,
130
- statusShim: (state) => `Khởi chạy: ${state === "active" ? "bật: `claude` trong terminal này mở qua Remote" : state === "installed" ? "đã cài, nhưng `claude` trong terminal này chưa dùng nó (mở terminal mới, hoặc có claude khác đứng trước trong PATH)" : "tắt"}`,
239
+ statusShim: (state) => `Khởi chạy: ${{ active: "bật: `claude` trong terminal này mở qua Remote", "new-terminals": "bật trong terminal mới (terminal này mở trước khi cài: hãy mở cửa sổ mới)", "powershell-only": "chỉ bật trong PowerShell (hàm trong profile); cmd.exe và Git Bash theo PATH, nơi một claude khác đứng trước", installed: "đã cài, nhưng một claude khác đứng trước trong PATH nên `claude` không mở qua Remote (chạy `tokenhub connect --remote` để sửa)" }[state] ?? "tắt"}`,
131
240
  statusHooks: (on) => `Hook: ${on ? "đã cài (/tf-remote)" : "thiếu: chạy `tokenhub connect --remote`"}`,
132
241
  statusPage: (url) => `Quản lý: ${url}`,
133
242
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emesoft/tokenhub",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
4
4
  "description": "Connect Claude Code to a TokenHub pool in one command, and track your spend from the terminal",
5
5
  "keywords": [
6
6
  "claude",