@emesoft/tokenhub 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ import type { Runner } from "./run.js";
2
+ export interface PolicyEntry {
3
+ scope: string;
4
+ policy: string;
5
+ }
6
+ export interface ShellInfo {
7
+ shell: "powershell" | "pwsh";
8
+ profile: string;
9
+ effective: string;
10
+ policies: PolicyEntry[];
11
+ }
12
+ export interface WinSystem {
13
+ machinePath(): Promise<{ value: string | null; kind: string }>;
14
+ machineSet(expected: string | null, next: string, kind: string): Promise<boolean>;
15
+ shells(): Promise<ShellInfo[]>;
16
+ setPolicy(shell: string, policy: string): Promise<boolean>;
17
+ }
18
+ export interface LauncherRecord {
19
+ profiles?: Array<{ shell: string; file: string }>;
20
+ policies?: Array<{ shell: string; previous: string }>;
21
+ machinePath?: { entry: string };
22
+ }
23
+ export function expandEnv(text: string, env: Record<string, string | undefined>): string;
24
+ export function effectiveDirs(machine: string | null, user: string | null, env: Record<string, string | undefined>): string[];
25
+ export function resolveCommand(name: string, dirs: string[], options?: { pathext?: string; exists?: (file: string) => boolean }): string | undefined;
26
+ export function launcherWins(options: { machine: string | null; user: string | null; env: Record<string, string | undefined>; binDir: string; exists?: (file: string) => boolean }): { ours: boolean; winner: string | undefined };
27
+ export function insertBefore(value: string | null, dir: string, anchor: string | undefined, env?: Record<string, string | undefined>): string;
28
+ export function psProfileBlock(binDir: string): string;
29
+ export function addPsBlock(text: string, binDir: string): string;
30
+ export function writePsProfile(file: string, binDir: string): { changed: boolean; skipped?: string };
31
+ export function removePsProfile(file: string): boolean;
32
+ export function hasPsBlock(file: string): boolean;
33
+ export function policyDecision(info: { effective: string; policies: PolicyEntry[] }): { blocked: boolean; source?: string; fixable?: boolean; previous?: string };
34
+ export function ensureLauncher(options: {
35
+ binDir: string;
36
+ env: Record<string, string | undefined>;
37
+ userPath: { get(): Promise<{ value: string | null; kind: string }> };
38
+ sys: WinSystem;
39
+ ask: (question: string, defaultYes?: boolean) => Promise<boolean>;
40
+ log: (line: string) => void;
41
+ t: Record<string, any>;
42
+ exists?: (file: string) => boolean;
43
+ previous?: LauncherRecord;
44
+ }): Promise<{ how: "path" | "profile" | "machine" | "none" | "unknown"; path: boolean; powershell: boolean; record: LauncherRecord }>;
45
+ export function removeLauncher(options: { record: LauncherRecord | undefined; sys: WinSystem; log: (line: string) => void; t: Record<string, any> }): Promise<void>;
46
+ export function realWindowsSystem(options?: { run?: Runner }): WinSystem;
@@ -0,0 +1,430 @@
1
+ // Making the `claude` launcher win on Windows (TokenHub Remote, ADR-0058).
2
+ //
3
+ // Putting `~/.tokenhub/bin` first in the USER Path is not enough: a new process gets the MACHINE Path followed by the USER Path, so a
4
+ // real `claude.exe` in a Machine Path folder still comes first. This module computes what a new process would resolve `claude` to
5
+ // (the registry's two Path values, expanded, in order, with PATHEXT), and when the launcher would not win it offers, in order:
6
+ // a. a `claude` function in the CurrentUser AllHosts profile of Windows PowerShell 5.1 and PowerShell 7 (no admin; asks before it
7
+ // allows profiles to run when the execution policy blocks them),
8
+ // b. an entry in the Machine Path before the real claude's folder (one UAC prompt),
9
+ // c. otherwise it says how to start a remote-ready session by hand.
10
+ // Everything that touches the system (registry, shells, elevation) goes through a `WinSystem`, so tests inject fakes.
11
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
12
+ import { dirname, win32 } from "node:path";
13
+ import { run as defaultRun } from "./run.js";
14
+ import { addPathEntry, hasPathEntry, PROFILE_BEGIN, PROFILE_END, removePathEntry, removeProfileBlock } from "./user-path.js";
15
+
16
+ /** The default PATHEXT of Windows, used when the environment has none. */
17
+ const DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC";
18
+ /** The execution policies that stop a profile from running. */
19
+ const BLOCKING = new Set(["restricted", "allsigned"]);
20
+ /** The scopes whose policy a change to `CurrentUser` can override (the group-policy scopes and `Process` cannot be). */
21
+ const OVERRIDABLE_SOURCES = new Set(["CurrentUser", "LocalMachine", "default"]);
22
+
23
+ /**
24
+ * `%NAME%` references replaced from an environment (names compare without case, as on Windows); unknown names stay as they are.
25
+ * @param {string} text A Path entry.
26
+ * @param {Record<string, string | undefined>} env Environment.
27
+ * @returns {string} The expanded text.
28
+ */
29
+ export function expandEnv(text, env) {
30
+ const lower = new Map(Object.entries(env).map(([name, value]) => [name.toLowerCase(), value]));
31
+ return text.replace(/%([^%]+)%/g, (whole, name) => lower.get(name.toLowerCase()) ?? whole);
32
+ }
33
+ /** @param {string} dir A folder. @returns {string} It in the form folders are compared in (absolute-looking, lower case, no trailing slash). */
34
+ function same(dir) {
35
+ return win32.normalize(dir.trim().replace(/^"(.*)"$/, "$1")).replace(/[\\/]+$/, "").toLowerCase();
36
+ }
37
+ /**
38
+ * The folders a new process searches, in order: the Machine Path, then the User Path, each entry unquoted and expanded; empty entries
39
+ * and later duplicates go.
40
+ * @param {string | null} machine The Machine `Path` as stored (may hold `%VAR%`).
41
+ * @param {string | null} user The User `Path` as stored.
42
+ * @param {Record<string, string | undefined>} env Environment to expand `%VAR%` from (USERPROFILE, SystemRoot...).
43
+ * @returns {string[]} The folders.
44
+ */
45
+ export function effectiveDirs(machine, user, env) {
46
+ const seen = new Set();
47
+ const dirs = [];
48
+ for (const raw of [...String(machine ?? "").split(";"), ...String(user ?? "").split(";")]) {
49
+ const entry = expandEnv(raw.trim().replace(/^"(.*)"$/, "$1"), env);
50
+ if (!entry || seen.has(same(entry))) continue;
51
+ seen.add(same(entry));
52
+ dirs.push(entry);
53
+ }
54
+ return dirs;
55
+ }
56
+ /**
57
+ * What `name` resolves to as a program: the first folder holding `name` with an extension of PATHEXT (in PATHEXT's order within the folder).
58
+ * cmd.exe and PowerShell (after its functions and aliases) search the same way.
59
+ * @param {string} name The command without extension.
60
+ * @param {string[]} dirs The folders, in order.
61
+ * @param {object} [options]
62
+ * @param {string} [options.pathext] PATHEXT.
63
+ * @param {(file: string) => boolean} [options.exists] File check (tests replace it).
64
+ * @returns {string | undefined} The file.
65
+ */
66
+ export function resolveCommand(name, dirs, { pathext, exists = existsSync } = {}) {
67
+ const exts = (pathext || DEFAULT_PATHEXT).split(";").map((ext) => ext.trim().toLowerCase()).filter(Boolean);
68
+ for (const dir of dirs) {
69
+ for (const ext of exts) {
70
+ const file = win32.join(dir, `${name}${ext}`);
71
+ if (exists(file)) return file;
72
+ }
73
+ }
74
+ return undefined;
75
+ }
76
+ /**
77
+ * Whether `claude` would start our launcher in a new process, from the two registry values.
78
+ * @param {object} options
79
+ * @param {string | null} options.machine The Machine `Path`.
80
+ * @param {string | null} options.user The User `Path`.
81
+ * @param {Record<string, string | undefined>} options.env Environment (expansion and PATHEXT).
82
+ * @param {string} options.binDir The launcher's folder.
83
+ * @param {(file: string) => boolean} [options.exists] File check.
84
+ * @returns {{ ours: boolean, winner: string | undefined }} `winner` is the file `claude` resolves to (undefined: none found).
85
+ */
86
+ export function launcherWins({ machine, user, env, binDir, exists }) {
87
+ const dirs = effectiveDirs(machine, user, env);
88
+ const pathext = Object.entries(env).find(([name]) => name.toUpperCase() === "PATHEXT")?.[1];
89
+ const winner = resolveCommand("claude", dirs, { pathext, exists });
90
+ return { ours: winner !== undefined && same(win32.dirname(winner)) === same(binDir), winner };
91
+ }
92
+ /**
93
+ * A Path value with `dir` inserted before the entry for `anchor` (the real claude's folder); at the front when `anchor` is not in it.
94
+ * @param {string | null} value The Path as stored.
95
+ * @param {string} dir The folder to add (any earlier copy of it goes).
96
+ * @param {string | undefined} anchor The folder it must come before (as expanded).
97
+ * @param {Record<string, string | undefined>} [env] Environment, to expand `%VAR%` entries when looking for the anchor.
98
+ * @returns {string} The new value; other entries are kept as they are.
99
+ */
100
+ export function insertBefore(value, dir, anchor, env = {}) {
101
+ const rest = removePathEntry(value, dir, "win32").split(";").filter(Boolean);
102
+ const at = anchor ? rest.findIndex((entry) => same(expandEnv(entry, env)) === same(anchor)) : -1;
103
+ if (at === -1) return addPathEntry(rest.join(";"), dir, "win32");
104
+ rest.splice(at, 0, dir);
105
+ return rest.join(";");
106
+ }
107
+
108
+ /**
109
+ * The marked block a PowerShell profile gets: a `claude` function that runs the launcher, and falls back to the real program if the
110
+ * launcher is gone (so a profile that outlives `tokenhub disconnect` does not break `claude`).
111
+ * @param {string} binDir The launcher's folder.
112
+ * @returns {string} The lines, without a final newline.
113
+ */
114
+ export function psProfileBlock(binDir) {
115
+ const launcher = `'${win32.join(binDir, "claude.cmd").replace(/'/g, "''")}'`;
116
+ const fallback = "(Get-Command claude -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source";
117
+ return [PROFILE_BEGIN, `function claude { $l = ${launcher}; if (Test-Path -LiteralPath $l) { & $l @args } else { & ${fallback} @args } }`, PROFILE_END].join("\n");
118
+ }
119
+ /**
120
+ * A profile's text with our block at the end (an earlier block is replaced, so running twice adds nothing).
121
+ * @param {string} text The profile's text.
122
+ * @param {string} binDir The launcher's folder.
123
+ * @returns {string} The new text.
124
+ */
125
+ export function addPsBlock(text, binDir) {
126
+ const clean = removeProfileBlock(text).text;
127
+ const block = psProfileBlock(binDir);
128
+ if (clean === "") return `${block}\n`;
129
+ return `${clean.endsWith("\n") ? clean : `${clean}\n`}\n${block}\n`;
130
+ }
131
+ /**
132
+ * Add our block to a PowerShell profile file.
133
+ * @param {string} file The profile path (its folder is created).
134
+ * @param {string} binDir The launcher's folder.
135
+ * @returns {{ changed: boolean, skipped?: string }} `skipped` says why the file was left alone: it holds characters outside ASCII in an encoding we cannot tell, and the block has some too.
136
+ * @sideEffect Copies an existing profile to `<file>.tokenhub.bak` once. The file keeps a UTF-8 byte-order mark it had, and gets one when it is new
137
+ * or the block has non-ASCII characters (Windows PowerShell 5.1 reads a file without one as ANSI).
138
+ */
139
+ export function writePsProfile(file, binDir) {
140
+ const exists = existsSync(file);
141
+ const bytes = exists ? readFileSync(file) : Buffer.alloc(0);
142
+ const hasBom = bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;
143
+ const before = bytes.subarray(hasBom ? 3 : 0).toString("utf8");
144
+ const after = addPsBlock(before, binDir);
145
+ if (after === before) return { changed: false };
146
+ const wide = /[^\x00-\x7f]/.test(psProfileBlock(binDir));
147
+ if (wide && !hasBom && bytes.some((byte) => byte >= 0x80)) return { changed: false, skipped: "non-ASCII text in an unknown encoding" };
148
+ mkdirSync(dirname(file), { recursive: true });
149
+ if (exists && !existsSync(`${file}.tokenhub.bak`)) copyFileSync(file, `${file}.tokenhub.bak`);
150
+ const bom = hasBom || wide || !exists ? "" : "";
151
+ writeFileSync(file, `${bom}${after}`, "utf8");
152
+ return { changed: true };
153
+ }
154
+ /**
155
+ * Take our block out of a PowerShell profile; a profile left empty (only our block was in it) is deleted.
156
+ * @param {string} file The profile path.
157
+ * @returns {boolean} Whether a block was removed.
158
+ */
159
+ export function removePsProfile(file) {
160
+ if (!existsSync(file)) return false;
161
+ const bytes = readFileSync(file);
162
+ const hasBom = bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;
163
+ const { text, removed } = removeProfileBlock(bytes.subarray(hasBom ? 3 : 0).toString("utf8"));
164
+ if (!removed) return false;
165
+ if (text.trim() === "") rmSync(file, { force: true });
166
+ else writeFileSync(file, `${hasBom ? "" : ""}${text}`, "utf8");
167
+ return true;
168
+ }
169
+ /**
170
+ * Whether a profile file holds our block.
171
+ * @param {string} file The profile path.
172
+ * @returns {boolean} True when it does.
173
+ */
174
+ export function hasPsBlock(file) {
175
+ try {
176
+ const text = readFileSync(file, "utf8");
177
+ return text.includes(PROFILE_BEGIN) && text.includes(PROFILE_END);
178
+ } catch {
179
+ return false;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * What the shell's execution policy means for a profile.
185
+ * @param {{ effective: string, policies: Array<{ scope: string, policy: string }> }} info What `Get-ExecutionPolicy` and `-List` said.
186
+ * @returns {{ blocked: boolean, source?: string, fixable?: boolean, previous?: string }} `blocked`: the profile would not run. `source`: the scope that decides.
187
+ * `fixable`: a change to the CurrentUser scope would override it (not so for a group policy or the process scope). `previous`: the CurrentUser value now.
188
+ */
189
+ export function policyDecision(info) {
190
+ const previous = info.policies.find((entry) => entry.scope === "CurrentUser")?.policy ?? "Undefined";
191
+ if (!BLOCKING.has(String(info.effective).toLowerCase())) return { blocked: false, previous };
192
+ const source = info.policies.find((entry) => entry.policy !== "Undefined")?.scope ?? "default";
193
+ return { blocked: true, source, fixable: OVERRIDABLE_SOURCES.has(source), previous };
194
+ }
195
+
196
+ /**
197
+ * What the installer needs from Windows, so tests can replace it.
198
+ * @typedef {object} WinSystem
199
+ * @property {() => Promise<{ value: string | null, kind: string }>} machinePath The Machine `Path` as stored (read-only, no elevation).
200
+ * @property {(expected: string | null, next: string, kind: string) => Promise<boolean>} machineSet Writes the Machine `Path` through an elevated
201
+ * PowerShell (one UAC prompt), only if it still equals `expected`; resolves with whether it was written.
202
+ * @property {() => Promise<Array<{ shell: "powershell" | "pwsh", profile: string, effective: string, policies: Array<{ scope: string, policy: string }> }>>} shells
203
+ * The PowerShells that are installed, with their CurrentUser AllHosts profile path and execution policies.
204
+ * @property {(shell: string, policy: string) => Promise<boolean>} setPolicy `Set-ExecutionPolicy -Scope CurrentUser` in that shell.
205
+ */
206
+ /**
207
+ * @typedef {object} LauncherRecord What was done to make the launcher win, kept in `install.json` so `disconnect` undoes exactly that.
208
+ * @property {Array<{ shell: string, file: string }>} [profiles] The profiles that got our block.
209
+ * @property {Array<{ shell: string, previous: string }>} [policies] Shells whose CurrentUser execution policy we set to RemoteSigned, and what it was.
210
+ * @property {{ entry: string }} [machinePath] The folder we put in the Machine Path.
211
+ */
212
+ /**
213
+ * Make sure `claude` starts the launcher, and when it would not, fix it with the user's consent.
214
+ *
215
+ * @param {object} options
216
+ * @param {string} options.binDir The launcher's folder (already first in the User Path).
217
+ * @param {Record<string, string | undefined>} options.env Environment (for expansion and PATHEXT).
218
+ * @param {{ get: () => Promise<{ value: string | null, kind: string }> }} options.userPath The registry's User Path.
219
+ * @param {WinSystem} options.sys Windows access.
220
+ * @param {(question: string, defaultYes?: boolean) => Promise<boolean>} options.ask Yes/no prompt (false without a terminal).
221
+ * @param {(line: string) => void} options.log Output sink.
222
+ * @param {Record<string, any>} options.t The messages (`text(lang)`).
223
+ * @param {(file: string) => boolean} [options.exists] File check for the resolution (tests replace it).
224
+ * @param {LauncherRecord} [options.previous] What an earlier run recorded: its profile blocks count (nothing is asked again) and its records are kept.
225
+ * @returns {Promise<{ how: "path" | "profile" | "machine" | "none" | "unknown", path: boolean, powershell: boolean, record: LauncherRecord }>}
226
+ * `how`: what makes `claude` start the launcher (`path`: nothing was needed). `path`: it wins in cmd.exe and Git Bash too. `powershell`: it wins in PowerShell.
227
+ * `unknown`: the registry could not be read, so nothing could be checked.
228
+ */
229
+ export async function ensureLauncher({ binDir, env, userPath, sys, ask, log, t, exists, previous }) {
230
+ /** Reads both Path values and decides. */
231
+ const check = async () => {
232
+ const [machine, user] = await Promise.all([sys.machinePath(), userPath.get()]);
233
+ return { machine, user, ...launcherWins({ machine: machine.value, user: user.value, env, binDir, exists }) };
234
+ };
235
+ let now;
236
+ try {
237
+ now = await check();
238
+ } catch (error) {
239
+ log(t.launcherUnchecked(String(error.message ?? error)));
240
+ return { how: "unknown", path: false, powershell: false, record: {} };
241
+ }
242
+ if (now.ours) return { how: "path", path: true, powershell: true, record: previous ?? {} };
243
+ // An earlier run put the function in a profile and it is still there: PowerShell is covered, and the user already chose.
244
+ if (previous?.profiles?.some((profile) => hasPsBlock(profile.file))) return { how: "profile", path: false, powershell: true, record: previous };
245
+ log(t.launcherShadowed(now.winner ?? "?"));
246
+ /** @type {LauncherRecord} */
247
+ const record = { ...previous };
248
+
249
+ // a. the PowerShell profile function
250
+ const shells = await sys.shells().catch(() => []);
251
+ let powershell = false;
252
+ if (shells.length > 0) {
253
+ for (const line of t.profileIntro) log(line);
254
+ if (await ask(t.askProfile, true)) {
255
+ for (const shell of shells) {
256
+ const decision = policyDecision(shell);
257
+ if (decision.blocked) {
258
+ if (!decision.fixable) {
259
+ log(t.policyLocked(shell.shell, decision.source));
260
+ continue;
261
+ }
262
+ for (const line of t.policyIntro(shell.shell, shell.effective)) log(line);
263
+ if (!(await ask(t.askPolicy, false))) continue;
264
+ if (!(await sys.setPolicy(shell.shell, "RemoteSigned"))) {
265
+ log(t.policyFailed(shell.shell));
266
+ continue;
267
+ }
268
+ record.policies = [...(record.policies ?? []).filter((p) => p.shell !== shell.shell), { shell: shell.shell, previous: decision.previous ?? "Undefined" }];
269
+ }
270
+ try {
271
+ const written = writePsProfile(shell.profile, binDir);
272
+ if (written.skipped) {
273
+ log(t.profileSkipped(shell.profile, written.skipped));
274
+ continue;
275
+ }
276
+ record.profiles = [...(record.profiles ?? []).filter((p) => p.file !== shell.profile), { shell: shell.shell, file: shell.profile }];
277
+ log(t.profileAdded(shell.shell, shell.profile));
278
+ powershell = true;
279
+ } catch (error) {
280
+ log(t.profileFailed(shell.profile, String(error.message ?? error)));
281
+ }
282
+ }
283
+ }
284
+ }
285
+ if (powershell) return { how: "profile", path: false, powershell: true, record };
286
+
287
+ // b. the Machine Path
288
+ for (const line of t.machineIntro) log(line);
289
+ if (await ask(t.askMachine, true)) {
290
+ const before = now.machine.value;
291
+ const next = insertBefore(before, binDir, now.winner ? win32.dirname(now.winner) : undefined, env);
292
+ const written = await sys.machineSet(before, next, now.machine.kind).catch(() => false);
293
+ const after = written ? await check().catch(() => undefined) : undefined;
294
+ if (after?.ours) {
295
+ record.machinePath = { entry: binDir };
296
+ log(t.machineDone);
297
+ return { how: "machine", path: true, powershell: true, record };
298
+ }
299
+ log(written ? t.machineNotEnough : t.machineFailed);
300
+ }
301
+
302
+ // c. by hand
303
+ log(t.startByHand(win32.join(binDir, "claude.cmd")));
304
+ return { how: "none", path: false, powershell: false, record };
305
+ }
306
+ /**
307
+ * Undo `ensureLauncher`: our profile blocks, our Machine Path entry (elevated) and the execution policy we changed, each only if it is
308
+ * still what we left.
309
+ *
310
+ * @param {object} options
311
+ * @param {LauncherRecord | undefined} options.record What `install.json` kept.
312
+ * @param {WinSystem} options.sys Windows access.
313
+ * @param {(line: string) => void} options.log Output sink.
314
+ * @param {Record<string, any>} options.t The messages.
315
+ * @returns {Promise<void>}
316
+ */
317
+ export async function removeLauncher({ record, sys, log, t }) {
318
+ if (!record) return;
319
+ for (const { file } of record.profiles ?? []) {
320
+ try {
321
+ if (removePsProfile(file)) log(t.profileRemoved(file));
322
+ } catch (error) {
323
+ log(t.profileRemoveFailed(file, String(error.message ?? error)));
324
+ }
325
+ }
326
+ if (record.machinePath) {
327
+ try {
328
+ const now = await sys.machinePath();
329
+ if (now.value !== null && hasPathEntry(now.value, record.machinePath.entry, "win32")) {
330
+ const ok = await sys.machineSet(now.value, removePathEntry(now.value, record.machinePath.entry, "win32"), now.kind);
331
+ log(ok ? t.machineRemoved : t.machineRemoveFailed(record.machinePath.entry));
332
+ }
333
+ } catch (error) {
334
+ log(t.machineRemoveFailed(record.machinePath.entry));
335
+ }
336
+ }
337
+ if (record.policies?.length) {
338
+ const shells = await sys.shells().catch(() => []);
339
+ for (const { shell, previous } of record.policies) {
340
+ const current = shells.find((s) => s.shell === shell)?.policies.find((entry) => entry.scope === "CurrentUser")?.policy;
341
+ // Only what we set, and only if nobody changed it since.
342
+ if (current === "RemoteSigned" && (await sys.setPolicy(shell, previous))) log(t.policyRestored(shell, previous));
343
+ }
344
+ }
345
+ }
346
+
347
+ /** The PowerShell that reads the Machine `Path` (read-only: no elevation). */
348
+ const MACHINE_READ_SCRIPT = `
349
+ $ErrorActionPreference = 'Stop'
350
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
351
+ $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment')
352
+ $raw = $key.GetValue('Path', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
353
+ if ($null -eq $raw) { Write-Output '{"value":null,"kind":"ExpandString"}' }
354
+ else { Write-Output (ConvertTo-Json -Compress @{ value = [string]$raw; kind = $key.GetValueKind('Path').ToString() }) }
355
+ `;
356
+ /** The PowerShell that describes one shell: its CurrentUser AllHosts profile and its execution policies. */
357
+ const SHELL_SCRIPT = `
358
+ $ErrorActionPreference = 'Stop'
359
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
360
+ $list = @(Get-ExecutionPolicy -List | ForEach-Object { [pscustomobject]@{ scope = [string]$_.Scope; policy = [string]$_.ExecutionPolicy } })
361
+ ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{ profile = [string]$PROFILE.CurrentUserAllHosts; effective = [string](Get-ExecutionPolicy); policies = $list })
362
+ `;
363
+ /**
364
+ * The script the elevated PowerShell runs: sets the Machine `Path` if it still has the value we read, and tells every window.
365
+ * @param {string | null} expected The value read before.
366
+ * @param {string} next The value to write.
367
+ * @param {string} kind `ExpandString` or `String`.
368
+ * @returns {string} PowerShell source (the values are embedded as JSON strings).
369
+ */
370
+ function machineWriteScript(expected, next, kind) {
371
+ return `
372
+ $ErrorActionPreference = 'Stop'
373
+ $expected = ConvertFrom-Json '${JSON.stringify(expected).replace(/'/g, "''")}'
374
+ $next = ConvertFrom-Json '${JSON.stringify(next).replace(/'/g, "''")}'
375
+ $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment', $true)
376
+ $raw = $key.GetValue('Path', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
377
+ if ($raw -ne $expected) { exit 3 }
378
+ $key.SetValue('Path', $next, [Microsoft.Win32.RegistryValueKind]'${kind === "String" ? "String" : "ExpandString"}')
379
+ $key.Close()
380
+ Add-Type -Namespace TokenHub -Name Native -MemberDefinition '[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint flags, uint timeout, out UIntPtr result);'
381
+ $result = [UIntPtr]::Zero
382
+ [void][TokenHub.Native]::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$result)
383
+ `;
384
+ }
385
+ /** @param {string} script PowerShell source. @returns {string} It as `-EncodedCommand` takes it. */
386
+ const encode = (script) => Buffer.from(script, "utf16le").toString("base64");
387
+ /**
388
+ * The real Windows access: Windows PowerShell for the registry and policies, `pwsh` too when it is installed, and an elevated
389
+ * PowerShell (`Start-Process -Verb RunAs`, so Windows shows its UAC prompt) for the one write that needs it.
390
+ *
391
+ * @param {object} [options]
392
+ * @param {import("./run.js").Runner} [options.run] Runs a program (tests replace it).
393
+ * @returns {WinSystem} The access.
394
+ */
395
+ export function realWindowsSystem({ run = defaultRun } = {}) {
396
+ const ps = (exe, script, timeoutMs = 60_000) => run(exe, ["-NoProfile", "-NonInteractive", "-EncodedCommand", encode(script)], { timeoutMs });
397
+ return {
398
+ async machinePath() {
399
+ const result = await ps("powershell.exe", MACHINE_READ_SCRIPT);
400
+ if (result.code !== 0) throw new Error(`could not read the Machine PATH (${result.stderr.trim().split("\n")[0] || `exit ${result.code}`})`);
401
+ const parsed = JSON.parse(result.stdout.replace(/^/, "").trim());
402
+ return { value: parsed.value ?? null, kind: parsed.kind === "String" ? "String" : "ExpandString" };
403
+ },
404
+ async machineSet(expected, next, kind) {
405
+ const inner = encode(machineWriteScript(expected, next, kind));
406
+ const outer = `$p = Start-Process -FilePath powershell.exe -Verb RunAs -Wait -PassThru -WindowStyle Hidden -ArgumentList '-NoProfile','-NonInteractive','-EncodedCommand','${inner}'; exit $p.ExitCode`;
407
+ const result = await ps("powershell.exe", outer, 180_000);
408
+ return result.code === 0;
409
+ },
410
+ async shells() {
411
+ const found = [];
412
+ for (const [shell, exe] of [["powershell", "powershell.exe"], ["pwsh", "pwsh.exe"]]) {
413
+ const result = await ps(exe, SHELL_SCRIPT).catch(() => ({ code: -1, stdout: "", stderr: "" }));
414
+ if (result.code !== 0) continue;
415
+ try {
416
+ const parsed = JSON.parse(result.stdout.replace(/^/, "").trim());
417
+ if (typeof parsed.profile === "string" && parsed.profile) found.push({ shell, profile: parsed.profile, effective: String(parsed.effective), policies: parsed.policies ?? [] });
418
+ } catch {
419
+ // Not readable: that shell is left alone.
420
+ }
421
+ }
422
+ return found;
423
+ },
424
+ async setPolicy(shell, policy) {
425
+ const exe = shell === "pwsh" ? "pwsh.exe" : "powershell.exe";
426
+ const result = await run(exe, ["-NoProfile", "-NonInteractive", "-Command", `Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy ${policy} -Force`], { timeoutMs: 60_000 });
427
+ return result.code === 0;
428
+ },
429
+ };
430
+ }
@@ -1,5 +1,6 @@
1
1
  import type { Runner } from "./run.js";
2
2
  import type { UserPath } from "./user-path.js";
3
+ import type { WinSystem } from "./launcher-precedence.js";
3
4
  export const DEFAULT_RELAY_ORIGIN: string;
4
5
  export interface InstallRecord {
5
6
  pool: string;
@@ -9,6 +10,7 @@ export interface InstallRecord {
9
10
  relayFile: string;
10
11
  claudeDir?: string;
11
12
  shim?: { binDir: string; targets: Array<{ kind: string; file?: string }> };
13
+ launcher?: import("./launcher-precedence.js").LauncherRecord;
12
14
  }
13
15
  export interface Proc {
14
16
  isAlive(pid: number): boolean;
@@ -47,7 +49,8 @@ export function installRemote(options: {
47
49
  run?: Runner;
48
50
  userPath?: UserPath;
49
51
  pickPort?: typeof pickHookPort;
50
- }): Promise<{ ok: true; version: string; shim: boolean } | { ok: false; code: number }>;
52
+ launcherSys?: WinSystem;
53
+ }): Promise<{ ok: true; version: string; shim: boolean; launcher?: string } | { ok: false; code: number }>;
51
54
  export function realProc(platform: string, run: Runner): Proc;
52
55
  export function daemonState(options: { appDir: string; root: string; platform: string; proc: Proc }): Promise<{ state: "running" | "other" | "stopped"; pid?: number }>;
53
56
  export function stopDaemon(options: {
@@ -72,6 +75,7 @@ export function disconnectRemote(options: {
72
75
  run?: Runner;
73
76
  proc?: Proc;
74
77
  userPath?: UserPath;
78
+ launcherSys?: WinSystem;
75
79
  }): Promise<{ found: boolean; blocked: boolean }>;
76
80
  export function remoteStatus(options: {
77
81
  settingsFile: string;
@@ -81,5 +85,7 @@ export function remoteStatus(options: {
81
85
  home: string;
82
86
  platform?: string;
83
87
  run?: Runner;
88
+ userPath?: UserPath;
89
+ launcherSys?: WinSystem;
84
90
  proc?: Proc;
85
91
  }): Promise<number>;
@@ -4,6 +4,7 @@ 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 { ensureLauncher, hasPsBlock, launcherWins, realWindowsSystem, removeLauncher } from "./launcher-precedence.js";
7
8
  import { pairRemote, checkRemoteToken, revokeRemoteToken } from "./remote.js";
8
9
  import { downloadRemote, HOOK_FILE, readCurrent } from "./remote-download.js";
9
10
  import { appConfigDir, exeName, legacyConfigDir, remoteDir, shimDir } from "./remote-paths.js";
@@ -36,6 +37,7 @@ function sha256(value) {
36
37
  * @property {string} relayFile Path of the `relay.json` written.
37
38
  * @property {string} [claudeDir] Claude Code's config folder the hooks went into.
38
39
  * @property {{ binDir: string, targets: Array<{ kind: string, file?: string }> }} [shim] The launcher and where PATH was edited.
40
+ * @property {import("./launcher-precedence.js").LauncherRecord} [launcher] What was done to make `claude` start the launcher on Windows (profiles, execution policy, Machine Path).
39
41
  */
40
42
  /**
41
43
  * @param {string} root The Remote folder.
@@ -181,7 +183,8 @@ async function runHookScript(verb, { script, claudeDir, node, run }) {
181
183
  * @param {import("./run.js").Runner} [options.run] Process runner for `xattr`, `icacls` and the hook script (tests replace it).
182
184
  * @param {ReturnType<typeof windowsUserPath>} [options.userPath] Registry access for the PATH edit (tests replace it).
183
185
  * @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.
186
+ * @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.
185
188
  */
186
189
  export async function installRemote({
187
190
  pool,
@@ -204,6 +207,7 @@ export async function installRemote({
204
207
  run = defaultRun,
205
208
  userPath,
206
209
  pickPort = pickHookPort,
210
+ launcherSys,
207
211
  }) {
208
212
  const t = text(lang);
209
213
  if (platform !== "win32" && platform !== "darwin") {
@@ -288,17 +292,22 @@ export async function installRemote({
288
292
  }
289
293
  saveRecord(root, { claudeDir });
290
294
 
291
- const shimOn = await offerShim({ shim, ask, log, t, binDir, platform, env, home, node, run, userPath, root });
295
+ const registry = userPath ?? windowsUserPath({ run });
296
+ const shimOn = await offerShim({ shim, ask, log, t, binDir, platform, env, home, node, run, userPath: registry, root });
297
+ // 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
+ let launcher = shimOn && platform === "win32" ? await ensureLauncher({ binDir, env, userPath: registry, sys: launcherSys ?? realWindowsSystem({ run }), ask, log, t, previous: record?.launcher }) : undefined;
299
+ if (launcher) saveRecord(root, { launcher: launcher.record });
292
300
  const tfc = join(download.dir, exeName("tfc", platform));
293
-
301
+ const claudeCmd = join(binDir, "claude.cmd");
294
302
  log("");
295
303
  log(t.done(download.version));
296
304
  log(t.lineComputer(name));
297
305
  log(t.linePage(`${origin}/member/remote`));
298
306
  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 };
307
+ log(t.lineShim(shimOn && launcher?.how !== "none"));
308
+ if (launcher?.how === "profile") log(t.noteProfile);
309
+ log(!shimOn ? t.nextNoShim(tfc) : launcher?.how === "profile" ? t.nextProfile : launcher?.how === "none" ? t.nextByHand(claudeCmd) : t.next);
310
+ return { ok: true, version: download.version, shim: shimOn, launcher: launcher?.how };
302
311
  }
303
312
  /** @param {Record<string, any> | undefined} existing An existing `relay.json`. @returns {string | undefined} The origin its `relayUrl` was made from. */
304
313
  function relayOriginFromFile(existing) {
@@ -465,9 +474,10 @@ export async function stopDaemon({ appDir, root, platform, force = false, env, p
465
474
  * @param {import("./run.js").Runner} [options.run] Process runner.
466
475
  * @param {Proc} [options.proc] Process facts (tests replace them).
467
476
  * @param {ReturnType<typeof windowsUserPath>} [options.userPath] Registry access (tests replace it).
477
+ * @param {import("./launcher-precedence.js").WinSystem} [options.launcherSys] Windows access for undoing the launcher fix (tests replace it).
468
478
  * @returns {Promise<{ found: boolean, blocked: boolean }>} `found`: there was something of Remote to remove. `blocked`: it was not removed because sessions run.
469
479
  */
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 }) {
480
+ 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
481
  const t = text(lang);
472
482
  const root = remoteDir(env, home);
473
483
  const binDir = shimDir(env, home);
@@ -502,6 +512,7 @@ export async function disconnectRemote({ settingsFile, lang = detectLang(), log
502
512
  log(t.hooksStay(claudeDir));
503
513
  }
504
514
 
515
+ if (platform === "win32" && record?.launcher) await removeLauncher({ record: record.launcher, sys: launcherSys ?? realWindowsSystem({ run }), log, t });
505
516
  if (record?.shim || shimPresent(binDir, platform) || profileHasBlock) {
506
517
  const wasInRegistry = platform === "win32" && Boolean(record?.shim?.targets?.some((target) => target.kind === "registry"));
507
518
  if (platform === "darwin" || wasInRegistry) {
@@ -524,6 +535,21 @@ export async function disconnectRemote({ settingsFile, lang = detectLang(), log
524
535
  }
525
536
  return { found: true, blocked: false };
526
537
  }
538
+ /**
539
+ * 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
540
+ * from the registry (the way a new process builds its Path), and look for our PowerShell profile function.
541
+ * @param {object} options `binDir`, `env`, `record` (install.json), `userPath` (registry User Path), `sys` (Machine Path).
542
+ * @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.
543
+ */
544
+ async function windowsLauncherState({ binDir, env, record, userPath, sys }) {
545
+ try {
546
+ const [machine, user] = await Promise.all([sys.machinePath(), userPath.get()]);
547
+ if (launcherWins({ machine: machine.value, user: user.value, env, binDir }).ours) return "new-terminals";
548
+ } catch {
549
+ // Unreadable: fall through to what the record says.
550
+ }
551
+ return record?.launcher?.profiles?.some((profile) => hasPsBlock(profile.file)) ? "powershell-only" : "installed";
552
+ }
527
553
  /** @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
554
  function settingsMentionsHook(file) {
529
555
  try {
@@ -545,9 +571,11 @@ function settingsMentionsHook(file) {
545
571
  * @param {string} [options.platform] Node platform name.
546
572
  * @param {import("./run.js").Runner} [options.run] Process runner.
547
573
  * @param {Proc} [options.proc] Process facts.
574
+ * @param {ReturnType<typeof windowsUserPath>} [options.userPath] Registry access (tests replace it).
575
+ * @param {import("./launcher-precedence.js").WinSystem} [options.launcherSys] Windows access (tests replace it).
548
576
  * @returns {Promise<number>} 0 when installed, 1 when not.
549
577
  */
550
- export async function remoteStatus({ settingsFile, lang = detectLang(), log = console.log, env = process.env, home, platform = process.platform, run = defaultRun, proc }) {
578
+ export async function remoteStatus({ settingsFile, lang = detectLang(), log = console.log, env = process.env, home, platform = process.platform, run = defaultRun, proc, userPath, launcherSys }) {
551
579
  const t = text(lang);
552
580
  const root = remoteDir(env, home);
553
581
  const binDir = shimDir(env, home);
@@ -573,6 +601,7 @@ export async function remoteStatus({ settingsFile, lang = detectLang(), log = co
573
601
  if (shimInstalled(binDir, platform)) {
574
602
  const first = findOnPath(platform === "win32" ? ["claude.exe", "claude.cmd"] : ["claude"], env.PATH ?? env.Path ?? "", { platform });
575
603
  shimState = first && normalizeDir(dirname(first), platform) === normalizeDir(binDir, platform) ? "active" : "installed";
604
+ if (shimState === "installed" && platform === "win32") shimState = await windowsLauncherState({ binDir, env, record, userPath: userPath ?? windowsUserPath({ run }), sys: launcherSys ?? realWindowsSystem({ run }) });
576
605
  }
577
606
  log(t.statusShim(shimState));
578
607
  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)`,
@@ -66,7 +92,7 @@ const TEXT = {
66
92
  statusRelay: (url) => `Relay: ${url} (the daemon does not report its connection; this is its configuration)`,
67
93
  statusNoRelay: "Relay: not configured (relay.json is missing): run `tokenhub connect --remote`",
68
94
  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"}`,
95
+ 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
96
  statusHooks: (on) => `Hooks: ${on ? "installed (/tf-remote)" : "missing: run `tokenhub connect --remote`"}`,
71
97
  statusPage: (url) => `Manage: ${url}`,
72
98
  },
@@ -101,6 +127,32 @@ const TEXT = {
101
127
  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
128
  shimSkipped: "Bỏ qua trình khởi chạy. Hãy mở Claude qua Remote bằng lệnh:",
103
129
  shimSkippedHint: "Chạy lại `tokenhub connect --remote` trong terminal để thêm trình khởi chạy.",
130
+ // making the launcher win on Windows (launcher-precedence.js)
131
+ launcherUnchecked: (why) => `Không kiểm tra được lệnh \`claude\` có mở trình khởi chạy không (${why}).`,
132
+ 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.`,
133
+ 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)."],
134
+ askProfile: "Thêm vào profile PowerShell của bạn?",
135
+ 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ũ."],
136
+ askPolicy: "Cho phép profile PowerShell của bạn chạy?",
137
+ policyLocked: (shell, source) => `${shell}: chính sách thực thi đến từ ${source}, TokenHub không thể ghi đè. Bỏ qua.`,
138
+ policyFailed: (shell) => `${shell}: chưa đổi được chính sách thực thi.`,
139
+ profileAdded: (shell, file) => `Đã thêm hàm \`claude\` vào profile ${shell}: ${file}`,
140
+ profileSkipped: (file, why) => `Giữ nguyên ${file} (${why}).`,
141
+ profileFailed: (file, why) => `Không ghi được ${file} (${why}).`,
142
+ 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."],
143
+ askMachine: "Đổi PATH hệ thống (Windows sẽ hỏi quyền)?",
144
+ machineDone: "Trình khởi chạy đã đứng đầu PATH hệ thống.",
145
+ 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).",
146
+ machineNotEnough: "Đã đổi PATH hệ thống, nhưng `claude` vẫn chưa mở trình khởi chạy.",
147
+ 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.`,
148
+ 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.",
149
+ 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.",
150
+ nextByHand: (cmd) => `Tiếp theo: chạy \`& "${cmd}"\`, gõ /tf-remote rồi quét mã QR bằng điện thoại.`,
151
+ profileRemoved: (file) => `Đã gỡ hàm claude khỏi ${file}.`,
152
+ profileRemoveFailed: (file, why) => `Không dọn được ${file} (${why}). Hãy tự xoá khối đánh dấu "tokenhub remote".`,
153
+ machineRemoved: "Đã gỡ trình khởi chạy khỏi PATH hệ thống.",
154
+ machineRemoveFailed: (entry) => `Không gỡ được ${entry} khỏi PATH hệ thống. Hãy tự xoá (System Properties, Environment Variables).`,
155
+ policyRestored: (shell, previous) => `Đã trả chính sách thực thi ${shell} của bạn về ${previous}.`,
104
156
  done: (version) => `TokenHub Remote ${version} đã sẵn sàng.`,
105
157
  lineComputer: (name) => ` Máy tính: ${name}`,
106
158
  linePage: (url) => ` Quản lý: ${url} (các máy của bạn; thu hồi bất cứ lúc nào)`,
@@ -127,7 +179,7 @@ const TEXT = {
127
179
  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
180
  statusNoRelay: "Relay: chưa cấu hình (thiếu relay.json): chạy `tokenhub connect --remote`",
129
181
  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"}`,
182
+ 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
183
  statusHooks: (on) => `Hook: ${on ? "đã cài (/tf-remote)" : "thiếu: chạy `tokenhub connect --remote`"}`,
132
184
  statusPage: (url) => `Quản lý: ${url}`,
133
185
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emesoft/tokenhub",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
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",