@emesoft/tokenhub 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -56,6 +56,8 @@ Prefer not to install? Use `npx @emesoft/tokenhub connect <your tenant name>` in
56
56
  | `--no-statusline` | `connect` | Don't add the spend status line to Claude Code. |
57
57
  | `--no-model-picker` | `connect` | Don't offer to install the TokenHub model picker. |
58
58
  | `--remote` / `--no-remote` | `connect` | Set up TokenHub Remote without asking / skip its question. |
59
+ | `--plain` | `connect` | One plain line per finished step instead of the progress bar (also used without a terminal or with `NO_COLOR`). |
60
+ | `--verbose` | `connect` | Also print what is otherwise only kept in `~/.tokenhub/remote/install.log` (download sizes, backup paths, the settings diff, PATH details). |
59
61
  | `--force` | `disconnect` | Stop the Remote daemon even while it hosts Claude sessions (they end). |
60
62
  | `--admin` | `connect`, `disconnect` | Pair (or forget) this machine as an admin device. See [For admins](#for-admins). |
61
63
  | `--json` | `usage` | Print the raw report. |
package/bin/tokenhub.js CHANGED
@@ -17,7 +17,7 @@ import { fetchUsage, formatUsage, resolveCredentials } from "../lib/usage.js";
17
17
  const HELP = `tokenhub - pair Claude Code with your TokenHub tenant
18
18
 
19
19
  Usage:
20
- tokenhub connect [tenant] [--no-statusline] [--no-model-picker] [--remote | --no-remote]
20
+ tokenhub connect [tenant] [--no-statusline] [--no-model-picker] [--remote | --no-remote] [--plain] [--verbose]
21
21
  Pair this machine and write ~/.claude/settings.json, including the status line
22
22
  (today's spend under the prompt) unless --no-statusline. Then offers to install the
23
23
  TokenHub model picker (a bare /model in Claude Code lists TokenHub models) unless
@@ -27,7 +27,9 @@ Usage:
27
27
  the daemon, pairs this computer (one more approval in the browser), adds the /tf-remote
28
28
  command to Claude Code and, if you agree, a launcher that makes claude use it, first on your PATH
29
29
  tenant is your tenant name (acme = https://acme.${TENANT_DOMAIN}) or a full URL;
30
- it is asked for when left out
30
+ it is asked for when left out. One progress bar shows the steps; --plain prints one
31
+ line per finished step instead (also used without a terminal or with NO_COLOR) and
32
+ --verbose prints what is otherwise only kept in ~/.tokenhub/remote/install.log
31
33
  tokenhub connect [tenant] --admin
32
34
  Pair this machine as an admin device (for the desktop overlay's pool view): the admin
33
35
  confirms in the console, the token is saved to ~/.tokenhub/admin.json
@@ -94,6 +96,8 @@ async function main(argv) {
94
96
  adminFile: adminConfigPath(),
95
97
  modelPicker: !flags.includes("--no-model-picker"),
96
98
  remote: flags.includes("--remote") ? true : flags.includes("--no-remote") ? false : undefined,
99
+ plain: flags.includes("--plain"),
100
+ verbose: flags.includes("--verbose"),
97
101
  });
98
102
  }
99
103
  if (command === "desktop") {
@@ -0,0 +1,2 @@
1
+ export function installLogPath(root: string): string;
2
+ export function openInstallLog(options: { file: string; title?: string; now?: () => Date }): { file: string; write(line: string): void };
@@ -0,0 +1,46 @@
1
+ import { appendFileSync, mkdirSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+
4
+ /**
5
+ * Where the installer's log goes: `<remote dir>/install.log`.
6
+ * @param {string} root The Remote folder (`remoteDir()`).
7
+ * @returns {string} Absolute path.
8
+ */
9
+ export function installLogPath(root) {
10
+ return join(root, "install.log");
11
+ }
12
+ /**
13
+ * The installer's log: a file that every run appends to, each run under a header with its time. It holds what a quiet install
14
+ * does not print (download sizes, backup paths, the settings diff, the hook script's output, PATH and launcher details) and what
15
+ * it printed. Writing never throws: a log that cannot be written must not stop an install.
16
+ *
17
+ * @param {object} options
18
+ * @param {string} options.file Path of the log (created with its folder).
19
+ * @param {string} [options.title] What the run is, for the header (`tokenhub connect --remote`).
20
+ * @param {() => Date} [options.now] Clock (tests).
21
+ * @returns {{ file: string, write: (line: string) => void }} The log. The header is written with the first line.
22
+ */
23
+ export function openInstallLog({ file, title = "tokenhub connect", now = () => new Date() }) {
24
+ let started = false;
25
+ let broken = false;
26
+ /** @param {string} text Text to append. */
27
+ const append = (text) => {
28
+ if (broken) return;
29
+ try {
30
+ mkdirSync(dirname(file), { recursive: true });
31
+ appendFileSync(file, text);
32
+ } catch {
33
+ broken = true;
34
+ }
35
+ };
36
+ return {
37
+ file,
38
+ write(line) {
39
+ if (!started) {
40
+ started = true;
41
+ append(`\n=== ${now().toISOString()} ${title} ===\n`);
42
+ }
43
+ append(`${line}\n`);
44
+ },
45
+ };
46
+ }
@@ -0,0 +1,27 @@
1
+ import type { Progress, ProgressStream } from "./progress.js";
2
+
3
+ export interface InstallUi {
4
+ readonly progress: Progress;
5
+ /** Path of the log once `useLog` has been called. */
6
+ readonly logFile: string | undefined;
7
+ useLog(file: string, title?: string): void;
8
+ say(line: string): void;
9
+ detail(line: string): void;
10
+ ask(question: (text: string, defaultYes?: boolean) => Promise<boolean>): (text: string, defaultYes?: boolean) => Promise<boolean>;
11
+ begin(label: string): void;
12
+ update(change: { label?: string; within?: number }): void;
13
+ complete(text: string): void;
14
+ addSteps(count: number): void;
15
+ finish(label: string): void;
16
+ close(): void;
17
+ }
18
+ export interface InstallUiOptions {
19
+ log?: (line: string) => void;
20
+ stream?: ProgressStream;
21
+ env?: Record<string, string | undefined>;
22
+ plain?: boolean;
23
+ verbose?: boolean;
24
+ total?: number;
25
+ now?: () => Date;
26
+ }
27
+ export function createInstallUi(options?: InstallUiOptions): InstallUi;
@@ -0,0 +1,66 @@
1
+ import { openInstallLog } from "./install-log.js";
2
+ import { createProgress } from "./progress.js";
3
+
4
+ /**
5
+ * What `tokenhub connect` shows while it works: the progress bar, plain lines for what the user must read, and a log file for the rest.
6
+ *
7
+ * - `say(line)` is for what the user must read or act on (a code, a question's text, a warning, an error): the bar is paused first,
8
+ * so the line is printed plainly below it and the bar is drawn again on a fresh line by the next step.
9
+ * - `detail(line)` is for what a quiet install keeps to itself (sizes, paths, diffs, hook output): it goes to the log file, and is printed
10
+ * only with `verbose` (which also turns the bar into plain step lines, so the output reads in order).
11
+ * - `ask(fn)` wraps a yes/no prompt so the bar is paused before it is shown.
12
+ * - the step methods (`begin`, `update`, `complete`, `finish`, `addSteps`) drive the bar.
13
+ *
14
+ * @param {object} options
15
+ * @param {(line: string) => void} [options.log] Where plain lines go (console.log).
16
+ * @param {import("./progress.js").ProgressStream} [options.stream] Where the bar is drawn (stdout).
17
+ * @param {Record<string, string | undefined>} [options.env] Environment (NO_COLOR, TERM, CI).
18
+ * @param {boolean} [options.plain] `--plain`: plain step lines, no bar.
19
+ * @param {boolean} [options.verbose] `--verbose`: print the details too (and no bar).
20
+ * @param {number} [options.total] Steps in all.
21
+ * @param {() => Date} [options.now] Clock for the log's headers (tests).
22
+ * @returns {InstallUi} The interface.
23
+ */
24
+ export function createInstallUi({ log = console.log, stream = process.stdout, env = process.env, plain = false, verbose = false, total = 1, now } = {}) {
25
+ const progress = createProgress({ stream, log, env, plain: plain || verbose, total });
26
+ /** @type {{ file: string, write: (line: string) => void } | undefined} */
27
+ let logFile;
28
+ return {
29
+ progress,
30
+ get logFile() {
31
+ return logFile?.file;
32
+ },
33
+ useLog(file, title) {
34
+ logFile = openInstallLog({ file, title, now });
35
+ },
36
+ say(line) {
37
+ progress.pause();
38
+ logFile?.write(line);
39
+ log(line);
40
+ },
41
+ detail(line) {
42
+ logFile?.write(line);
43
+ if (verbose) {
44
+ progress.pause();
45
+ log(` ${line}`);
46
+ }
47
+ },
48
+ ask(question) {
49
+ return async (text, defaultYes) => {
50
+ progress.pause();
51
+ const answer = await question(text, defaultYes);
52
+ logFile?.write(`? ${text} ${answer ? "yes" : "no"}`);
53
+ return answer;
54
+ };
55
+ },
56
+ begin: (label) => progress.begin(label),
57
+ update: (change) => progress.update(change),
58
+ complete(text) {
59
+ logFile?.write(`step ${progress.done + 1}/${progress.total}: ${text}`);
60
+ progress.complete(text);
61
+ },
62
+ addSteps: (count) => progress.setTotal(progress.total + count),
63
+ finish: (label) => progress.finish(label),
64
+ close: () => progress.close(),
65
+ };
66
+ }
@@ -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
+ }