@yanzc/claude-pro 0.5.8 → 0.6.0

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/src/host.js ADDED
@@ -0,0 +1,1031 @@
1
+ // The computer service (`claude-pro host`): one background process per computer (per CONFIG_DIR) that keeps
2
+ // this computer on the gateway's 远程控制 page, so that the page can open a new session here: it lists the
3
+ // directories to choose from, and opens a terminal window with claude-pro in the one chosen, online at once with
4
+ // the id the gateway gave it. Like a session it only connects out to the gateway, with the API key of /login.
5
+ //
6
+ // Protocol (Bearer = the gateway API key; ARCHITECTURE.md 3.1.5):
7
+ // POST /v1/remote/hosts {id, machine, host, platform, version, home, terminal} -> {id, ok}
8
+ // GET /v1/remote/hosts/:id/commands (SSE): online while it is open; {cid, type: 'list'|'open', body}
9
+ // POST /v1/remote/hosts/:id/results {cid, ok: true, ...} | {cid, ok: false, error}
10
+ // DELETE /v1/remote/hosts/:id: off the page's list (`host stop`, a logout, another account)
11
+ //
12
+ // It runs in the foreground with `claude-pro host`, in the background (detached, no window, logging to
13
+ // CONFIG_DIR/host.log) with `host start`; an interactive session logged in to the gateway starts one when none
14
+ // runs (CLAUDE_PRO_HOST=0: not), and `host install` starts one at logon. CONFIG_DIR/host.json keeps its id (for
15
+ // good) and, while it runs, its pid and a heartbeat; host.lock keeps a second one from running. It follows the
16
+ // login in gateway.json (waits without one, registers again with another key), and a background one starts the
17
+ // new version of the program when its files change (an update, an edit of the source).
18
+
19
+ import fs from 'node:fs';
20
+ import fsp from 'node:fs/promises';
21
+ import os from 'node:os';
22
+ import path from 'node:path';
23
+ import crypto from 'node:crypto';
24
+ import { spawn, spawnSync } from 'node:child_process';
25
+ import { CONFIG_DIR, INSTALL_DIR, VERSION, GATEWAY_DEFAULT_URL, loadConfig } from './config.js';
26
+ import { readGatewayLogin, normalizeGatewayUrl } from './gateway.js';
27
+ import { machineName, cleanName } from './peers.js';
28
+ import { ENV_SUPERVISED, ENV_RESTART_FILE, ENV_RESTARTED } from './supervisor.js';
29
+
30
+ export const ENTRY = path.join(INSTALL_DIR, 'bin', 'claude-pro.js');
31
+ const ID = /^[A-Za-z0-9_-]{8,64}$/;
32
+ const BEAT_MS = 20_000; // host.json is written this often while it runs ...
33
+ const STALE_MS = 90_000; // ... and one whose heartbeat is older than this is not running (its pid may be another program's now)
34
+ const LOGIN_CHECK_MS = 5_000;
35
+ const CODE_CHECK_MS = 60_000;
36
+ const REQUEST_TIMEOUT_MS = 15_000;
37
+ const STREAM_SILENCE_MS = 50_000; // the gateway pings every 15 s
38
+ const MAX_ENTRIES = 1000;
39
+ const MAX_RECENT = 15;
40
+ const LOG_BYTES = 1_000_000;
41
+ const SESSION_ONLY = [ENV_SUPERVISED, ENV_RESTART_FILE, ENV_RESTARTED]; // a session's own: not for the service, nor the sessions it opens
42
+
43
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
44
+
45
+ // Whether sessions start the service by themselves (CLAUDE_PRO_HOST=0: only `claude-pro host start` does).
46
+ export const hostEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(env.CLAUDE_PRO_HOST || '');
47
+
48
+ const configDir = () => process.env.CLAUDE_PRO_CONFIG_DIR || CONFIG_DIR;
49
+ export const hostFiles = () => {
50
+ const dir = configDir();
51
+ return { dir, state: path.join(dir, 'host.json'), lock: path.join(dir, 'host.lock'), log: path.join(dir, 'host.log'), launch: path.join(dir, 'launch') };
52
+ };
53
+
54
+ // ---------------------------------------------------------------- host.json, the lock
55
+
56
+ export function readHostState() {
57
+ try {
58
+ const state = JSON.parse(fs.readFileSync(hostFiles().state, 'utf8'));
59
+ return state && typeof state === 'object' ? state : {};
60
+ } catch {
61
+ return {};
62
+ }
63
+ }
64
+
65
+ // Merges `change` into host.json (an undefined value removes the key).
66
+ function updateHostState(change) {
67
+ const next = { ...readHostState(), ...change };
68
+ for (const k of Object.keys(next)) if (next[k] === undefined) delete next[k];
69
+ const file = hostFiles().state;
70
+ try {
71
+ fs.mkdirSync(path.dirname(file), { recursive: true });
72
+ const tmp = `${file}.${process.pid}.tmp`;
73
+ fs.writeFileSync(tmp, JSON.stringify(next, null, 2));
74
+ fs.renameSync(tmp, file);
75
+ } catch { /* best effort: the next heartbeat writes it again */ }
76
+ return next;
77
+ }
78
+
79
+ export function pidAlive(pid) {
80
+ if (!Number.isInteger(pid) || pid <= 0) return false;
81
+ try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
82
+ }
83
+
84
+ export function hostRunning(state = readHostState(), now = Date.now()) {
85
+ return Boolean(state.pid && pidAlive(state.pid) && now - (Number(state.beat) || 0) < STALE_MS);
86
+ }
87
+
88
+ // This computer's id at the gateway: made once, then kept in host.json.
89
+ function hostId() {
90
+ const state = readHostState();
91
+ if (ID.test(state.id || '')) return state.id;
92
+ const id = crypto.randomBytes(9).toString('base64url');
93
+ updateHostState({ id });
94
+ return id;
95
+ }
96
+
97
+ // One service per CONFIG_DIR: host.lock holds the pid of the one that runs. A lock is taken over when its process
98
+ // is gone, or when it is old and no heartbeat says it runs (its pid may be another program's now).
99
+ function takeLock() {
100
+ const { lock } = hostFiles();
101
+ fs.mkdirSync(path.dirname(lock), { recursive: true });
102
+ for (let i = 0; i < 2; i++) {
103
+ try {
104
+ fs.writeFileSync(lock, String(process.pid), { flag: 'wx' });
105
+ return true;
106
+ } catch (e) {
107
+ if (e.code !== 'EEXIST') throw e;
108
+ }
109
+ let holder = 0;
110
+ let age = Infinity;
111
+ try { holder = Number(fs.readFileSync(lock, 'utf8')); age = Date.now() - fs.statSync(lock).mtimeMs; } catch { continue; }
112
+ const state = readHostState();
113
+ if (holder !== process.pid && pidAlive(holder) && (age < STALE_MS || (state.pid === holder && Date.now() - (Number(state.beat) || 0) < STALE_MS))) return false;
114
+ try { fs.rmSync(lock, { force: true }); } catch { /* taken again below, or not */ }
115
+ }
116
+ return false;
117
+ }
118
+
119
+ function releaseLock(pid = process.pid) {
120
+ const { lock } = hostFiles();
121
+ try { if (Number(fs.readFileSync(lock, 'utf8')) === pid) fs.rmSync(lock, { force: true }); } catch { /* not ours, or gone */ }
122
+ }
123
+
124
+ // ---------------------------------------------------------------- logging
125
+
126
+ function fileLogger() {
127
+ const file = hostFiles().log;
128
+ return (msg) => {
129
+ try {
130
+ fs.mkdirSync(path.dirname(file), { recursive: true });
131
+ try { if (fs.statSync(file).size > LOG_BYTES) fs.renameSync(file, `${file}.1`); } catch { /* none yet */ }
132
+ fs.appendFileSync(file, `[${new Date().toISOString()}] ${msg}\n`);
133
+ } catch { /* nowhere to say it */ }
134
+ };
135
+ }
136
+
137
+ const consoleLogger = () => (msg) => process.stdout.write(`[${new Date().toLocaleTimeString()}] ${msg}\n`);
138
+
139
+ // ---------------------------------------------------------------- starting it from elsewhere
140
+
141
+ function serviceEnv(env = process.env) {
142
+ const out = { ...env };
143
+ for (const k of SESSION_ONLY) delete out[k];
144
+ return out;
145
+ }
146
+
147
+ // A service in the background: detached (it outlives the session or terminal that started it), without a window.
148
+ export function startHostInBackground({ env = process.env } = {}) {
149
+ const child = spawn(process.execPath, [ENTRY, 'host', 'run', '--background'], { detached: true, stdio: 'ignore', windowsHide: true, cwd: os.homedir(), env: serviceEnv(env) });
150
+ child.on('error', () => { /* the next session tries again */ });
151
+ child.unref();
152
+ return child.pid;
153
+ }
154
+
155
+ // For a session that starts (see App.ensureHost): a service, unless one runs, `claude-pro host stop` stopped it, or
156
+ // one was started a moment ago (by another session starting at the same time). Returns the pid of a new one.
157
+ export function ensureHost({ env = process.env } = {}) {
158
+ const state = readHostState();
159
+ if (hostRunning(state) || state.disabled) return null;
160
+ if (Date.now() - (Number(state.spawnedAt) || 0) < 30_000) return null;
161
+ updateHostState({ spawnedAt: Date.now() });
162
+ return startHostInBackground({ env });
163
+ }
164
+
165
+ // What /status says about it.
166
+ export function describeHost(env = process.env) {
167
+ const state = readHostState();
168
+ if (hostRunning(state)) return `running (pid ${state.pid})${state.online ? ' · the web page can open sessions on this computer' : ' · not connected to the gateway now'}`;
169
+ if (state.disabled) return 'stopped with `claude-pro host stop` (`claude-pro host start` starts it again)';
170
+ return hostEnabled(env) ? 'not running (a session starts it once this computer is logged in to the gateway; or `claude-pro host start`)' : 'not running (CLAUDE_PRO_HOST=0: `claude-pro host start` starts it)';
171
+ }
172
+
173
+ // ---------------------------------------------------------------- directories (the list command)
174
+
175
+ // `input` as an absolute directory of this computer: "" (or ~) is the home directory, "D:" is the root of D:, and
176
+ // forward slashes do on Windows too. null when it is not absolute.
177
+ export function normalizeDir(input, { platform = process.platform, home = os.homedir() } = {}) {
178
+ const p = platform === 'win32' ? path.win32 : path.posix;
179
+ let s = String(input ?? '').trim();
180
+ if (!s || s === '~') return home;
181
+ if (s.startsWith('~/') || s.startsWith('~\\')) s = p.join(home, s.slice(2));
182
+ if (platform === 'win32') {
183
+ s = s.replace(/\//g, '\\');
184
+ if (/^[A-Za-z]:$/.test(s)) s += '\\';
185
+ if (!/^([A-Za-z]:\\|\\\\[^\\]+\\[^\\]+)/.test(s)) return null;
186
+ s = s.replace(/^[a-z]:/, (d) => d.toUpperCase());
187
+ } else if (!s.startsWith('/')) {
188
+ return null;
189
+ }
190
+ return p.resolve(s);
191
+ }
192
+
193
+ const describeFsError = (e, dir) => (e.code === 'ENOENT' || e.code === 'ENOTDIR' ? `目录不存在:${dir}`
194
+ : e.code === 'EACCES' || e.code === 'EPERM' ? `没有权限读取:${dir}`
195
+ : `读取 ${dir} 失败:${e.message}`);
196
+
197
+ let rootsCache = { at: 0, roots: [] };
198
+ async function roots(platform = process.platform) {
199
+ if (platform !== 'win32') return ['/'];
200
+ if (Date.now() - rootsCache.at < 30_000) return rootsCache.roots;
201
+ // a disconnected network drive can take long to answer: 1.5 seconds each, all at once
202
+ const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
203
+ const found = await Promise.all(letters.map((l) => Promise.race([
204
+ fsp.access(`${l}:\\`).then(() => `${l}:\\`, () => null),
205
+ sleep(1500).then(() => null),
206
+ ])));
207
+ rootsCache = { at: Date.now(), roots: found.filter(Boolean) };
208
+ return rootsCache.roots;
209
+ }
210
+
211
+ // The directories in `input` (only directories, links to them included), for the page to choose from.
212
+ export async function listDirectory(input, { home = os.homedir(), recent = () => [] } = {}) {
213
+ const dir = normalizeDir(input, { home });
214
+ if (!dir) throw new Error(`不是绝对路径:${input}`);
215
+ let st;
216
+ try { st = await fsp.stat(dir); } catch (e) { throw new Error(describeFsError(e, dir)); }
217
+ if (!st.isDirectory()) throw new Error(`不是目录:${dir}`);
218
+ let dirents;
219
+ try { dirents = await fsp.readdir(dir, { withFileTypes: true }); } catch (e) { throw new Error(describeFsError(e, dir)); }
220
+ const entries = [];
221
+ for (const d of dirents) {
222
+ const full = path.join(dir, d.name);
223
+ let isDir = d.isDirectory();
224
+ if (!isDir && d.isSymbolicLink()) {
225
+ // a link to a directory counts, unless it cannot be opened (Windows' old junctions in the profile:
226
+ // "My Documents", "Application Data" ... refuse to be listed)
227
+ try { isDir = (await fsp.stat(full)).isDirectory(); } catch { isDir = false; }
228
+ if (isDir) {
229
+ let handle = null;
230
+ try {
231
+ handle = await fsp.opendir(full);
232
+ await handle.read(); // Windows checks the access at the first read, not at the opening
233
+ } catch {
234
+ isDir = false;
235
+ } finally {
236
+ await handle?.close().catch(() => {});
237
+ }
238
+ }
239
+ // ... and the profile's other compatibility junctions ("Application Data", "Recent", the Start Menu in the
240
+ // system's language ...), which Explorer hides: all lead into AppData
241
+ if (isDir && process.platform === 'win32' && dir.toLowerCase() === path.resolve(home).toLowerCase()) {
242
+ try {
243
+ if ((await fsp.realpath(full)).toLowerCase().startsWith(`${path.join(home, 'AppData').toLowerCase()}\\`)) isDir = false;
244
+ } catch { isDir = false; }
245
+ }
246
+ }
247
+ if (isDir) entries.push({ name: d.name, path: full });
248
+ }
249
+ const hidden = (name) => (name.startsWith('.') ? 1 : 0);
250
+ entries.sort((a, b) => hidden(a.name) - hidden(b.name) || a.name.localeCompare(b.name, undefined, { sensitivity: 'accent', numeric: true }));
251
+ const parent = path.dirname(dir);
252
+ return {
253
+ path: dir,
254
+ parent: parent === dir ? null : parent,
255
+ sep: path.sep,
256
+ entries: entries.slice(0, MAX_ENTRIES),
257
+ truncated: entries.length > MAX_ENTRIES,
258
+ home,
259
+ roots: await roots(),
260
+ recent: recent(),
261
+ };
262
+ }
263
+
264
+ // The first line of a session file is {type: 'meta', cwd, ...} (see SessionStore.append).
265
+ function sessionCwd(file) {
266
+ let fd = null;
267
+ try {
268
+ fd = fs.openSync(file, 'r');
269
+ const buf = Buffer.alloc(16 * 1024);
270
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
271
+ const line = buf.subarray(0, n).toString('utf8').split('\n')[0];
272
+ const meta = JSON.parse(line);
273
+ return meta?.type === 'meta' && typeof meta.cwd === 'string' ? meta.cwd : null;
274
+ } catch {
275
+ return null;
276
+ } finally {
277
+ if (fd !== null) fs.closeSync(fd);
278
+ }
279
+ }
280
+
281
+ // Where claude-pro sessions ran lately on this computer, newest first: [{path, at}] of the directories that are
282
+ // still there. One line read per project (its newest session's first line).
283
+ export function recentDirectories({ projects = path.join(configDir(), 'projects'), max = MAX_RECENT } = {}) {
284
+ let dirs = [];
285
+ try { dirs = fs.readdirSync(projects, { withFileTypes: true }).filter((d) => d.isDirectory()); } catch { return []; }
286
+ const found = [];
287
+ for (const d of dirs) {
288
+ const sub = path.join(projects, d.name);
289
+ let newest = null;
290
+ try {
291
+ for (const f of fs.readdirSync(sub)) {
292
+ if (!f.endsWith('.jsonl')) continue;
293
+ const m = fs.statSync(path.join(sub, f)).mtimeMs;
294
+ if (!newest || m > newest.m) newest = { f, m };
295
+ }
296
+ } catch { continue; }
297
+ if (!newest) continue;
298
+ const cwd = sessionCwd(path.join(sub, newest.f));
299
+ if (cwd) found.push({ path: path.resolve(cwd), at: newest.m });
300
+ }
301
+ found.sort((a, b) => b.at - a.at);
302
+ const seen = new Set();
303
+ const out = [];
304
+ for (const r of found) {
305
+ const key = process.platform === 'win32' ? r.path.toLowerCase() : r.path;
306
+ if (seen.has(key)) continue;
307
+ seen.add(key);
308
+ try { if (!fs.statSync(r.path).isDirectory()) continue; } catch { continue; }
309
+ out.push({ path: r.path, at: new Date(r.at).toISOString() });
310
+ if (out.length >= max) break;
311
+ }
312
+ return out;
313
+ }
314
+
315
+ // ---------------------------------------------------------------- terminals (the open command)
316
+
317
+ // A program on the PATH. Windows Terminal's wt.exe is an "app execution alias" that only lstat sees.
318
+ export function findCommand(name, { env = process.env, platform = process.platform } = {}) {
319
+ const p = platform === 'win32' ? path.win32 : path.posix;
320
+ const dirs = String(env.PATH ?? env.Path ?? '').split(platform === 'win32' ? ';' : ':').filter(Boolean);
321
+ const exts = platform === 'win32' && !p.extname(name) ? String(env.PATHEXT || '.EXE;.CMD;.BAT').split(';') : [''];
322
+ const extra = platform === 'win32' && env.LOCALAPPDATA ? [p.join(env.LOCALAPPDATA, 'Microsoft', 'WindowsApps')] : [];
323
+ for (const dir of [...dirs, ...extra]) {
324
+ for (const ext of exts) {
325
+ const file = p.join(dir, name + ext);
326
+ try {
327
+ const st = fs.lstatSync(file);
328
+ if (st.isFile() || st.isSymbolicLink()) return file;
329
+ } catch { /* not here */ }
330
+ }
331
+ }
332
+ return null;
333
+ }
334
+
335
+ // What opens a terminal window on this computer: {kind, name, path}, or null when nothing here can.
336
+ export function terminalFor({ platform = process.platform, env = process.env, find = (name) => findCommand(name, { env, platform }) } = {}) {
337
+ if (platform === 'win32') {
338
+ const wt = find('wt.exe');
339
+ return wt ? { kind: 'wt', name: 'Windows Terminal', path: wt } : { kind: 'console', name: 'Windows console', path: 'powershell.exe' };
340
+ }
341
+ if (platform === 'darwin') {
342
+ const osa = find('osascript');
343
+ return osa ? { kind: 'osascript', name: 'Terminal.app', path: osa } : null;
344
+ }
345
+ if (env.DISPLAY || env.WAYLAND_DISPLAY) {
346
+ for (const cmd of ['x-terminal-emulator', 'gnome-terminal', 'konsole', 'xterm']) {
347
+ const found = find(cmd);
348
+ if (found) return { kind: cmd, name: cmd, path: found };
349
+ }
350
+ }
351
+ const tmux = find('tmux');
352
+ return tmux ? { kind: 'tmux', name: 'tmux', path: tmux } : null;
353
+ }
354
+
355
+ // One argument of a Windows command line, quoted as the C runtime reads it back.
356
+ export function quoteWindowsArg(arg) {
357
+ const s = String(arg);
358
+ if (s && !/[\s"]/.test(s)) return s;
359
+ let out = '"';
360
+ let slashes = 0;
361
+ for (const ch of s) {
362
+ if (ch === '\\') { slashes++; continue; }
363
+ out += ch === '"' ? `${'\\'.repeat(slashes * 2 + 1)}"` : `${'\\'.repeat(slashes)}${ch}`;
364
+ slashes = 0;
365
+ }
366
+ return `${out}${'\\'.repeat(slashes * 2)}"`;
367
+ }
368
+
369
+ const shQuote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
370
+
371
+ // The settings of this service's environment that a session it opens needs too (the config directory, the
372
+ // gateway's address, the computer's name ...): Windows Terminal starts the program with its own environment, and
373
+ // tmux and a desktop's terminal with theirs. Not the secrets: those stay where they were set.
374
+ const PASS_ENV = /^(CLAUDE_PRO_|ANTHROPIC_|CLAUDE_CODE_|CLAUDE_CONFIG_DIR$)/;
375
+ const SECRET = /TOKEN|KEY|SECRET|PASSWORD|HEADERS/i;
376
+ export function passedEnv(env = process.env) {
377
+ const out = {};
378
+ for (const [k, v] of Object.entries(env)) {
379
+ if (!PASS_ENV.test(k) || SECRET.test(k) || SESSION_ONLY.includes(k) || /^CLAUDE_PRO_LAUNCH_/.test(k) || v == null || /[\r\n\0]/.test(String(v))) continue;
380
+ out[k] = String(v);
381
+ }
382
+ return out;
383
+ }
384
+
385
+ // For Windows: the variables as a file for `node --env-file` (whose single and back quotes keep backslashes as they
386
+ // are). Files of launches more than 10 minutes old are removed.
387
+ function writeEnvFile(sessionId, vars) {
388
+ const entries = Object.entries(vars);
389
+ if (!entries.length) return null;
390
+ const dir = hostFiles().launch;
391
+ fs.mkdirSync(dir, { recursive: true });
392
+ try {
393
+ for (const f of fs.readdirSync(dir)) {
394
+ const file = path.join(dir, f);
395
+ if (Date.now() - fs.statSync(file).mtimeMs > 10 * 60_000) fs.rmSync(file, { force: true });
396
+ }
397
+ } catch { /* the next launch cleans up */ }
398
+ const quote = (v) => (!v.includes("'") ? `'${v}'` : !v.includes('`') ? `\`${v}\`` : null);
399
+ const lines = entries.map(([k, v]) => (quote(v) ? `${k}=${quote(v)}` : null)).filter(Boolean);
400
+ const file = path.join(dir, `${sessionId}.env`);
401
+ fs.writeFileSync(file, `${lines.join('\n')}\n`, { mode: 0o600 });
402
+ return file;
403
+ }
404
+
405
+ // How `term` opens a window that runs `node entry ...args` in `cwd`: {cmd, args, options, wait}. `wait`: 'exit'
406
+ // when the command ends once the window is open (its exit code says whether it worked), 'spawn' when it is the
407
+ // terminal itself.
408
+ export function launchCommand(term, { cwd, node = process.execPath, entry = ENTRY, args = [], env = {}, envFile = null, sessionId = '' }) {
409
+ const program = [node, ...(envFile ? [`--env-file=${envFile}`] : []), entry, ...args];
410
+ const pairs = Object.entries(env).map(([k, v]) => `${k}=${v}`);
411
+ const posix = [...(pairs.length ? ['env', ...pairs] : []), node, entry, ...args];
412
+ const line = posix.map(shQuote).join(' ');
413
+ switch (term.kind) {
414
+ case 'wt': // a new window; wt reads ; as the start of another command
415
+ return { cmd: term.path, args: ['-w', 'new', '-d', cwd, ...program].map((a) => a.replace(/;/g, '\\;')), options: { windowsHide: false }, wait: 'exit' };
416
+ case 'console': { // a console window of its own; Start-Process takes the command line as it is
417
+ // what went wrong: only its message, in UTF-8 (PowerShell writes errors as CLIXML in the system's code page)
418
+ const script = [
419
+ "$ProgressPreference = 'SilentlyContinue'",
420
+ '[Console]::OutputEncoding = [Text.Encoding]::UTF8',
421
+ 'try { Start-Process -ErrorAction Stop -FilePath $env:CLAUDE_PRO_LAUNCH_FILE -ArgumentList $env:CLAUDE_PRO_LAUNCH_ARGS -WorkingDirectory $env:CLAUDE_PRO_LAUNCH_DIR; exit 0 }',
422
+ 'catch { [Console]::Out.Write($_.Exception.Message); exit 1 }',
423
+ ].join('\n');
424
+ return {
425
+ cmd: term.path,
426
+ args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-OutputFormat', 'Text', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
427
+ // not detached: a detached (console-less) PowerShell ends at once without doing anything; hidden, its
428
+ // console does not show
429
+ options: { windowsHide: true, detached: false, env: { ...process.env, CLAUDE_PRO_LAUNCH_FILE: program[0], CLAUDE_PRO_LAUNCH_ARGS: program.slice(1).map(quoteWindowsArg).join(' '), CLAUDE_PRO_LAUNCH_DIR: cwd } },
430
+ wait: 'exit',
431
+ };
432
+ }
433
+ case 'osascript': {
434
+ const as = (s) => `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
435
+ return { cmd: term.path, args: ['-e', `tell application "Terminal" to do script ${as(`cd ${shQuote(cwd)} && exec ${line}`)}`, '-e', 'tell application "Terminal" to activate'], options: {}, wait: 'exit' };
436
+ }
437
+ case 'tmux': // no desktop: a tmux session (`tmux attach -t claude-pro-<id>` shows it here; the web page works anyway)
438
+ return { cmd: term.path, args: ['new-session', '-d', '-s', `claude-pro-${sessionId}`, '-c', cwd, `exec ${line}`], options: { cwd }, wait: 'exit' };
439
+ default: { // a desktop's terminal: sh goes to `cwd` first, as not every terminal starts where it was started
440
+ const inDir = ['sh', '-c', 'cd "$0" && exec "$@"', cwd, ...posix];
441
+ const head = term.kind === 'gnome-terminal' ? [`--working-directory=${cwd}`, '--'] : term.kind === 'konsole' ? ['--workdir', cwd, '-e'] : ['-e'];
442
+ return { cmd: term.path, args: [...head, ...inDir], options: { cwd }, wait: 'spawn' };
443
+ }
444
+ }
445
+ }
446
+
447
+ // Runs what launchCommand made: resolves once the window is open, rejects with what went wrong.
448
+ export function runLaunch(spec, { timeoutMs = 20_000 } = {}) {
449
+ return new Promise((resolve, reject) => {
450
+ const exits = spec.wait === 'exit';
451
+ let child;
452
+ // a terminal that runs on must not write into a closed pipe: only a command that ends tells its error
453
+ const out = exits ? 'pipe' : 'ignore';
454
+ try { child = spawn(spec.cmd, spec.args, { detached: true, stdio: ['ignore', out, out], ...spec.options }); } catch (e) { reject(e); return; }
455
+ let err = '';
456
+ const keep = (d) => { if (err.length < 4000) err += d; };
457
+ child.stdout?.on('data', keep);
458
+ child.stderr?.on('data', keep);
459
+ let settled = false;
460
+ const done = (e) => {
461
+ if (settled) return;
462
+ settled = true;
463
+ clearTimeout(timer);
464
+ child.unref();
465
+ if (e) reject(e); else resolve();
466
+ };
467
+ const timer = setTimeout(() => done(exits ? new Error('打开终端超时') : null), exits ? timeoutMs : 1500);
468
+ child.on('error', (e) => done(e));
469
+ child.on('exit', (code) => done(code === 0 ? null : new Error(err.trim().split(/\r?\n/).filter(Boolean).pop() || `退出码 ${code}`)));
470
+ });
471
+ }
472
+
473
+ // ---------------------------------------------------------------- the service
474
+
475
+ export class HostService {
476
+ // `readLogin`, `loadConfig`, `launch`, `terminal`, `home`: what the tests give it instead of this computer's.
477
+ constructor({ id, log = () => {}, fetchImpl = globalThis.fetch, background = false, terminal, launch = runLaunch, home = os.homedir(), readLogin, loadConfig: load } = {}) {
478
+ this.id = id;
479
+ this.log = log;
480
+ this.fetch = fetchImpl;
481
+ this.background = background;
482
+ this.terminal = terminal === undefined ? terminalFor() : terminal;
483
+ this.launch = launch;
484
+ this.home = home;
485
+ this.loadConfig = load || (() => loadConfig({ cwd: home }));
486
+ this.readLogin = readLogin || (() => readGatewayLogin(this.cfg().gatewayUrl));
487
+ this.config = null;
488
+ this.configAt = 0;
489
+ this.login = null; // {url, apiKey, account} of gateway.json
490
+ this.registered = false;
491
+ this.online = false;
492
+ this.stopped = false;
493
+ this.reloading = false;
494
+ this.inflight = 0;
495
+ this.streamAbort = null;
496
+ this.wake = null;
497
+ this.timers = [];
498
+ this.refusedKey = null;
499
+ this.lastNote = '';
500
+ this.recent = { at: 0, list: [] };
501
+ }
502
+
503
+ cfg() {
504
+ if (!this.config || Date.now() - this.configAt > 60_000) {
505
+ try { this.config = this.loadConfig(); } catch { this.config ??= { env: process.env, gatewayUrl: GATEWAY_DEFAULT_URL }; }
506
+ this.configAt = Date.now();
507
+ }
508
+ return this.config;
509
+ }
510
+
511
+ base(login = this.login) { return normalizeGatewayUrl(login?.url || this.cfg().gatewayUrl); }
512
+
513
+ // Logged once until something else happens (a gateway that is down is retried every 30 seconds).
514
+ note(msg) {
515
+ if (msg === this.lastNote) return;
516
+ this.lastNote = msg;
517
+ this.log(msg);
518
+ }
519
+
520
+ async request(method, route, body, { timeout = REQUEST_TIMEOUT_MS, login = this.login } = {}) {
521
+ const res = await this.fetch(`${this.base(login)}${route}`, {
522
+ method,
523
+ headers: { authorization: `Bearer ${login.apiKey}`, 'content-type': 'application/json' },
524
+ body: body === undefined ? undefined : JSON.stringify(body),
525
+ signal: AbortSignal.timeout(timeout),
526
+ });
527
+ const data = await res.json().catch(() => ({}));
528
+ if (!res.ok) throw Object.assign(new Error(data?.error?.message || (typeof data?.error === 'string' ? data.error : `HTTP ${res.status}`)), { status: res.status });
529
+ return data;
530
+ }
531
+
532
+ // What the page shows of this computer. `machine` is the name its sessions register with, so that the page puts
533
+ // them together.
534
+ info() {
535
+ return { id: this.id, machine: machineName(this.cfg().env), host: os.hostname(), platform: process.platform, version: VERSION, home: this.home, terminal: this.terminal?.name || '' };
536
+ }
537
+
538
+ async register() {
539
+ try {
540
+ await this.request('POST', '/v1/remote/hosts', this.info());
541
+ } catch (e) {
542
+ if (e.status === 404) e.noHosts = true; // a gateway without computers (yet): not the one that forgot this one
543
+ throw e;
544
+ }
545
+ this.registered = true;
546
+ this.note(`registered at ${this.base()} as ${this.info().machine} (${this.id})`);
547
+ }
548
+
549
+ // Follows gateway.json: logged out, the computer leaves the page's list and the service waits for a login; with
550
+ // another account it leaves the old one's list and joins the new one's.
551
+ checkLogin() {
552
+ let login = null;
553
+ try { login = this.readLogin(); } catch { /* none */ }
554
+ const key = (l) => (l?.apiKey ? `${this.base(l)}\n${l.apiKey}` : '');
555
+ if (key(login) === key(this.login)) return;
556
+ const old = this.login;
557
+ this.login = login?.apiKey ? login : null;
558
+ this.registered = false;
559
+ if (old) {
560
+ this.log(this.login ? 'the gateway login changed: registering with the new one' : 'logged out of the gateway: waiting for /login');
561
+ this.request('DELETE', `/v1/remote/hosts/${encodeURIComponent(this.id)}`, undefined, { login: old, timeout: 5000 }).catch(() => {});
562
+ } else if (this.login) {
563
+ this.log(`logged in to the gateway ${this.base()}`);
564
+ }
565
+ this.streamAbort?.abort();
566
+ this.wakeUp();
567
+ }
568
+
569
+ sleep(ms) {
570
+ return new Promise((resolve) => {
571
+ let timer = null;
572
+ const done = () => { clearTimeout(timer); if (this.wake === done) this.wake = null; resolve(); };
573
+ timer = setTimeout(done, ms);
574
+ this.wake = done;
575
+ });
576
+ }
577
+
578
+ wakeUp() { this.wake?.(); }
579
+
580
+ setOnline(online) {
581
+ if (online === this.online) return;
582
+ this.online = online;
583
+ if (online) this.lastNote = '';
584
+ this.log(online ? 'online: the web page can open sessions on this computer' : 'offline');
585
+ this.beat();
586
+ }
587
+
588
+ beat() {
589
+ if (this.stopped) return;
590
+ updateHostState({
591
+ id: this.id,
592
+ pid: process.pid,
593
+ version: VERSION,
594
+ startedAt: this.startedAt,
595
+ beat: Date.now(),
596
+ online: this.online,
597
+ gateway: this.login ? this.base() : null,
598
+ account: this.login?.account?.email || this.login?.account?.name || null,
599
+ machine: this.info().machine,
600
+ terminal: this.terminal?.name || '',
601
+ background: this.background,
602
+ disabled: undefined,
603
+ spawnedAt: undefined,
604
+ });
605
+ }
606
+
607
+ // Until stop(): resolves when the service has stopped (or stops to start its new version: `reloading`).
608
+ async run() {
609
+ this.startedAt = new Date().toISOString();
610
+ this.code = codeFingerprint();
611
+ this.checkLogin();
612
+ if (!this.login) this.log(`not logged in to the gateway ${this.base()}: waiting for /login`);
613
+ this.beat();
614
+ this.timers.push(
615
+ setInterval(() => this.beat(), BEAT_MS),
616
+ setInterval(() => this.checkLogin(), LOGIN_CHECK_MS),
617
+ setInterval(() => this.checkCode(), CODE_CHECK_MS),
618
+ );
619
+ try { await this.loop(); } finally { for (const t of this.timers) clearInterval(t); }
620
+ }
621
+
622
+ async loop() {
623
+ let wait = 1000;
624
+ while (!this.stopped) {
625
+ // without a login, or with a key the gateway refused (tried again every 10 minutes): a new login helps
626
+ const refused = this.login && this.refusedKey === this.login.apiKey && Date.now() - this.refusedAt < 10 * 60_000;
627
+ if (!this.login || refused) {
628
+ this.setOnline(false);
629
+ await this.sleep(this.login ? 60_000 : 30_000);
630
+ continue;
631
+ }
632
+ try {
633
+ if (!this.registered) await this.register();
634
+ await this.listen();
635
+ wait = 1000;
636
+ } catch (e) {
637
+ if (e.noHosts) { this.note(`the gateway ${this.base()} does not take computers (yet): trying again every 5 minutes`); wait = 5 * 60_000; }
638
+ else if (e.status === 404) this.registered = false; // the gateway forgot this computer (it restarted): register again
639
+ else if (e.status === 401 || e.status === 403) {
640
+ this.refusedKey = this.login?.apiKey;
641
+ this.refusedAt = Date.now();
642
+ this.registered = false;
643
+ this.note(`the gateway refused this computer's key (${e.message}): waiting for /login`);
644
+ }
645
+ else if (!this.stopped && e.name !== 'AbortError') this.note(`cannot reach the gateway ${this.base()}: ${e.message}`);
646
+ }
647
+ this.setOnline(false);
648
+ if (this.stopped) break;
649
+ await this.sleep(wait);
650
+ wait = Math.min(wait * 2, 30_000);
651
+ }
652
+ }
653
+
654
+ // The command stream, open until the gateway ends it, it stays silent too long, or abort().
655
+ async listen() {
656
+ const abort = new AbortController();
657
+ this.streamAbort = abort;
658
+ const res = await this.fetch(`${this.base()}/v1/remote/hosts/${encodeURIComponent(this.id)}/commands`, {
659
+ headers: { authorization: `Bearer ${this.login.apiKey}`, accept: 'text/event-stream' },
660
+ signal: abort.signal,
661
+ });
662
+ if (!res.ok) {
663
+ res.body?.cancel().catch(() => {});
664
+ throw Object.assign(new Error(`HTTP ${res.status}`), { status: res.status });
665
+ }
666
+ this.setOnline(true);
667
+ let last = Date.now();
668
+ const watchdog = setInterval(() => { if (Date.now() - last > STREAM_SILENCE_MS) abort.abort(); }, 5000);
669
+ try {
670
+ const decoder = new TextDecoder();
671
+ let buf = '';
672
+ for await (const chunk of res.body) {
673
+ last = Date.now();
674
+ buf += decoder.decode(chunk, { stream: true });
675
+ let i;
676
+ while ((i = buf.search(/\r?\n\r?\n/)) >= 0) {
677
+ const block = buf.slice(0, i);
678
+ buf = buf.slice(i).replace(/^\r?\n\r?\n/, '');
679
+ const data = block.split(/\r?\n/).filter((l) => l.startsWith('data:')).map((l) => l.slice(5).replace(/^ /, '')).join('\n');
680
+ if (!data) continue;
681
+ let cmd;
682
+ try { cmd = JSON.parse(data); } catch { continue; }
683
+ this.command(cmd);
684
+ }
685
+ }
686
+ } catch (e) {
687
+ if (!abort.signal.aborted) throw e;
688
+ } finally {
689
+ clearInterval(watchdog);
690
+ if (this.streamAbort === abort) this.streamAbort = null;
691
+ }
692
+ }
693
+
694
+ async command(cmd) {
695
+ if (!cmd || typeof cmd.cid !== 'string' || !cmd.cid) return;
696
+ const login = this.login;
697
+ this.inflight++;
698
+ let result;
699
+ try {
700
+ const body = cmd.body && typeof cmd.body === 'object' ? cmd.body : {};
701
+ let r;
702
+ if (cmd.type === 'list') r = await this.list(body);
703
+ else if (cmd.type === 'open') r = await this.open(body);
704
+ else throw new Error(`这台电脑上的 claude-pro ${VERSION} 不认识命令 ${cmd.type},请升级`);
705
+ result = { cid: cmd.cid, ok: true, ...r };
706
+ } catch (e) {
707
+ result = { cid: cmd.cid, ok: false, error: e.message };
708
+ } finally {
709
+ this.inflight--;
710
+ }
711
+ if (login) {
712
+ try {
713
+ await this.request('POST', `/v1/remote/hosts/${encodeURIComponent(this.id)}/results`, result, { login });
714
+ } catch (e) {
715
+ this.note(`could not send the result of ${cmd.type}: ${e.message}`);
716
+ }
717
+ }
718
+ if (this.reloadWanted && !this.inflight) this.reload();
719
+ }
720
+
721
+ list(body) {
722
+ return listDirectory(typeof body.path === 'string' ? body.path : '', {
723
+ home: this.home,
724
+ recent: () => {
725
+ if (Date.now() - this.recent.at > 30_000) this.recent = { at: Date.now(), list: recentDirectories() };
726
+ return this.recent.list;
727
+ },
728
+ });
729
+ }
730
+
731
+ // A new terminal window with an interactive claude-pro in `cwd`, online at once as `sessionId` (and named `name`).
732
+ async open({ sessionId, cwd, create, name } = {}) {
733
+ if (typeof sessionId !== 'string' || !ID.test(sessionId)) throw new Error('会话 id 不对');
734
+ const dir = typeof cwd === 'string' ? normalizeDir(cwd, { home: this.home }) : null;
735
+ if (!dir || !String(cwd).trim()) throw new Error(`请选择一个绝对路径的目录:${cwd ?? ''}`);
736
+ let st = null;
737
+ try { st = await fsp.stat(dir); } catch (e) {
738
+ if (e.code !== 'ENOENT') throw new Error(describeFsError(e, dir));
739
+ }
740
+ if (!st) {
741
+ if (create !== true) throw new Error(`目录不存在:${dir}`);
742
+ try { await fsp.mkdir(dir, { recursive: true }); } catch (e) { throw new Error(`创建目录失败:${dir}(${e.message})`); }
743
+ } else if (!st.isDirectory()) {
744
+ throw new Error(`不是目录:${dir}`);
745
+ }
746
+ const term = this.terminal;
747
+ if (!term) throw new Error('这台电脑上找不到能打开的终端(Windows Terminal、Terminal.app、x-terminal-emulator、gnome-terminal、konsole、xterm 或 tmux)');
748
+ const label = typeof name === 'string' && name.trim() ? cleanName(name) : '';
749
+ const args = ['--remote-id', sessionId, ...(label ? ['--name', label] : [])];
750
+ const env = passedEnv();
751
+ const envFile = process.platform === 'win32' && term.kind === 'wt' ? writeEnvFile(sessionId, env) : null;
752
+ try {
753
+ await this.launch(launchCommand(term, { cwd: dir, args, env, envFile, sessionId }));
754
+ } catch (e) {
755
+ throw new Error(`无法用 ${term.name} 打开终端:${e.message}`);
756
+ }
757
+ this.log(`opened ${term.name} in ${dir} for the session ${sessionId}${label ? ` (${label})` : ''}`);
758
+ return { terminal: term.name };
759
+ }
760
+
761
+ // The program's files changed (an update, an edit of the source): a background service starts its new version
762
+ // once the files have stayed the same for a check and no command is being answered.
763
+ checkCode() {
764
+ const now = codeFingerprint();
765
+ if (now === this.code) { this.pendingCode = null; return; }
766
+ if (!this.background) {
767
+ if (!this.toldCode) this.log("claude-pro's files changed: restart `claude-pro host` to run the new version");
768
+ this.toldCode = true;
769
+ return;
770
+ }
771
+ if (now !== this.pendingCode) { this.pendingCode = now; return; }
772
+ this.reloadWanted = true;
773
+ if (!this.inflight) this.reload();
774
+ }
775
+
776
+ reload() {
777
+ this.reloading = true;
778
+ this.stop();
779
+ }
780
+
781
+ stop() {
782
+ if (this.stopped) return;
783
+ this.stopped = true;
784
+ for (const t of this.timers) clearInterval(t);
785
+ this.streamAbort?.abort();
786
+ this.wakeUp();
787
+ }
788
+ }
789
+
790
+ // The program's files as they are now (names, sizes, times): another value means another version.
791
+ export function codeFingerprint(root = INSTALL_DIR) {
792
+ const hash = crypto.createHash('sha1');
793
+ for (const dir of ['bin', 'src']) {
794
+ let names = [];
795
+ try { names = fs.readdirSync(path.join(root, dir), { recursive: true }).map(String).filter((n) => /\.(m?js|json)$/i.test(n)).sort(); } catch { /* none */ }
796
+ for (const n of names) {
797
+ try {
798
+ const st = fs.statSync(path.join(root, dir, n));
799
+ hash.update(`${dir}/${n}:${st.size}:${st.mtimeMs}\n`);
800
+ } catch { /* gone meanwhile */ }
801
+ }
802
+ }
803
+ try { hash.update(fs.readFileSync(path.join(root, 'package.json'))); } catch { /* none */ }
804
+ return hash.digest('base64');
805
+ }
806
+
807
+ // `claude-pro host run [--background]`: the service, until it is stopped. Returns the exit code.
808
+ export async function runHost({ background = false } = {}) {
809
+ for (const k of SESSION_ONLY) delete process.env[k];
810
+ const log = background ? fileLogger() : consoleLogger();
811
+ if (!takeLock()) {
812
+ log(`claude-pro host runs already (pid ${readHostState().pid || '?'}): this one stops`);
813
+ return background ? 0 : 1;
814
+ }
815
+ const service = new HostService({ id: hostId(), log, background });
816
+ const stop = () => service.stop();
817
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, stop);
818
+ log(`claude-pro host ${VERSION} started (pid ${process.pid}${background ? ', in the background' : ''}; terminal: ${service.terminal?.name || 'none found'})`);
819
+ try {
820
+ await service.run();
821
+ } finally {
822
+ releaseLock();
823
+ if (readHostState().pid === process.pid) updateHostState({ pid: undefined, beat: undefined, online: false });
824
+ }
825
+ if (service.reloading) {
826
+ log('the program changed: starting its new version');
827
+ startHostInBackground();
828
+ } else {
829
+ log('stopped');
830
+ }
831
+ return 0;
832
+ }
833
+
834
+ // ---------------------------------------------------------------- start, stop, status
835
+
836
+ async function gatewayRequest(method, route) {
837
+ const cfg = loadConfig({ cwd: os.homedir() });
838
+ const login = readGatewayLogin(cfg.gatewayUrl);
839
+ if (!login) return false;
840
+ const res = await fetch(`${normalizeGatewayUrl(login.url || cfg.gatewayUrl)}${route}`, { method, headers: { authorization: `Bearer ${login.apiKey}` }, signal: AbortSignal.timeout(8000) });
841
+ return res.ok || res.status === 404;
842
+ }
843
+
844
+ async function startCommand() {
845
+ const state = readHostState();
846
+ if (hostRunning(state)) {
847
+ console.log(`claude-pro host is running already (pid ${state.pid}).`);
848
+ return 0;
849
+ }
850
+ updateHostState({ disabled: undefined, spawnedAt: Date.now() });
851
+ const pid = startHostInBackground();
852
+ for (let i = 0; i < 30; i++) {
853
+ await sleep(200);
854
+ const now = readHostState();
855
+ if (hostRunning(now)) {
856
+ const cfg = loadConfig({ cwd: os.homedir() });
857
+ const login = readGatewayLogin(cfg.gatewayUrl);
858
+ console.log(`claude-pro host started in the background (pid ${now.pid}). Log: ${hostFiles().log}`);
859
+ if (!login) console.log(`This computer is not logged in to the gateway ${cfg.gatewayUrl}: it waits until /login in a session.`);
860
+ return 0;
861
+ }
862
+ }
863
+ console.log(`claude-pro host was started (pid ${pid}) but has not reported yet: see ${hostFiles().log}`);
864
+ return 1;
865
+ }
866
+
867
+ async function stopCommand() {
868
+ const state = readHostState();
869
+ const running = hostRunning(state);
870
+ updateHostState({ disabled: true });
871
+ if (running) {
872
+ try { process.kill(state.pid); } catch { /* gone already */ }
873
+ for (let i = 0; i < 25 && pidAlive(state.pid); i++) await sleep(200);
874
+ releaseLock(state.pid);
875
+ }
876
+ // again: a heartbeat between the first write and the end of the process clears it
877
+ updateHostState({ disabled: true, pid: undefined, beat: undefined, online: false });
878
+ let removed = false;
879
+ if (state.id) removed = await gatewayRequest('DELETE', `/v1/remote/hosts/${encodeURIComponent(state.id)}`).catch(() => false);
880
+ console.log(`${running ? `Stopped claude-pro host (pid ${state.pid}).` : 'claude-pro host was not running.'}${removed ? ' This computer is off the gateway\'s list.' : ''}`);
881
+ console.log('Sessions no longer start it by themselves: `claude-pro host start` does.');
882
+ return 0;
883
+ }
884
+
885
+ function statusCommand() {
886
+ const state = readHostState();
887
+ const running = hostRunning(state);
888
+ const auto = installedAutostart();
889
+ const lines = [
890
+ `claude-pro host (lets the gateway's web page open sessions on this computer): ${running ? `running, pid ${state.pid}, since ${state.startedAt || '?'}` : state.disabled ? 'stopped (claude-pro host start)' : 'not running (claude-pro host start)'}`,
891
+ ];
892
+ if (running) lines.push(` gateway: ${state.gateway ? `${state.gateway}${state.account ? ` as ${state.account}` : ''} · ${state.online ? 'online' : 'not connected now'}` : 'not logged in (it waits for /login)'}`);
893
+ if (state.id) lines.push(` id: ${state.id}${state.machine ? ` · computer: ${state.machine}` : ''}${state.terminal ? ` · opens: ${state.terminal}` : ''}${state.version ? ` · version ${state.version}` : ''}`);
894
+ lines.push(` log: ${hostFiles().log}`);
895
+ lines.push(` at logon: ${auto ? `starts (${auto}; claude-pro host uninstall stops that)` : 'no (claude-pro host install)'}`);
896
+ console.log(lines.join('\n'));
897
+ return 0;
898
+ }
899
+
900
+ // ---------------------------------------------------------------- starting at logon
901
+
902
+ const suffix = () => (process.env.CLAUDE_PRO_CONFIG_DIR ? `-${crypto.createHash('sha1').update(path.resolve(process.env.CLAUDE_PRO_CONFIG_DIR)).digest('hex').slice(0, 8)}` : '');
903
+
904
+ // Where `host install` puts what starts it at logon, by platform (two kinds on Linux: a desktop's autostart, else a
905
+ // systemd user service).
906
+ export function autostartFiles({ platform = process.platform, env = process.env, home = os.homedir() } = {}) {
907
+ const s = suffix();
908
+ if (platform === 'win32') return [path.join(env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', `claude-pro-host${s}.vbs`)];
909
+ if (platform === 'darwin') return [path.join(home, 'Library', 'LaunchAgents', `com.claude-pro.host${s}.plist`)];
910
+ const config = env.XDG_CONFIG_HOME || path.join(home, '.config');
911
+ return [path.join(config, 'autostart', `claude-pro-host${s}.desktop`), path.join(config, 'systemd', 'user', `claude-pro-host${s}.service`)];
912
+ }
913
+
914
+ function installedAutostart() {
915
+ return autostartFiles().find((f) => fs.existsSync(f)) || null;
916
+ }
917
+
918
+ // What runs at logon: `claude-pro host start`, with the config directory when it is not the default one.
919
+ function startCommandLine() {
920
+ const env = process.env.CLAUDE_PRO_CONFIG_DIR ? { CLAUDE_PRO_CONFIG_DIR: path.resolve(process.env.CLAUDE_PRO_CONFIG_DIR) } : {};
921
+ return { program: [process.execPath, ENTRY, 'host', 'start'], env };
922
+ }
923
+
924
+ const xml = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
925
+
926
+ async function installCommand() {
927
+ const { program, env } = startCommandLine();
928
+ const [desktop, service] = autostartFiles();
929
+ let file;
930
+ let note = '';
931
+ if (process.platform === 'win32') {
932
+ file = desktop;
933
+ const vbs = (s) => `"${String(s).replace(/"/g, '""')}"`;
934
+ const text = [
935
+ "' claude-pro: starts its computer service (claude-pro host) at logon, without a window.",
936
+ "' `claude-pro host uninstall` removes this file.",
937
+ 'Set shell = CreateObject("WScript.Shell")',
938
+ ...Object.entries(env).map(([k, v]) => `shell.Environment("PROCESS")(${vbs(k)}) = ${vbs(v)}`),
939
+ `shell.Run ${vbs(program.map(quoteWindowsArg).join(' '))}, 0, False`,
940
+ '',
941
+ ].join('\r\n');
942
+ fs.mkdirSync(path.dirname(file), { recursive: true });
943
+ fs.writeFileSync(file, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(text, 'utf16le')])); // UTF-16: any user name
944
+ } else if (process.platform === 'darwin') {
945
+ file = desktop;
946
+ const label = path.basename(file, '.plist');
947
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
948
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
949
+ <plist version="1.0">
950
+ <dict>
951
+ <key>Label</key><string>${xml(label)}</string>
952
+ <key>ProgramArguments</key>
953
+ <array>${program.map((a) => `<string>${xml(a)}</string>`).join('')}</array>
954
+ <key>RunAtLoad</key><true/>
955
+ <key>AbandonProcessGroup</key><true/>
956
+ <key>EnvironmentVariables</key>
957
+ <dict>${Object.entries({ PATH: process.env.PATH || '', ...env }).map(([k, v]) => `<key>${xml(k)}</key><string>${xml(v)}</string>`).join('')}</dict>
958
+ </dict>
959
+ </plist>
960
+ `;
961
+ fs.mkdirSync(path.dirname(file), { recursive: true });
962
+ fs.writeFileSync(file, plist);
963
+ spawnSync('launchctl', ['unload', file], { stdio: 'ignore' });
964
+ spawnSync('launchctl', ['load', '-w', file], { stdio: 'ignore' });
965
+ } else if (process.env.DISPLAY || process.env.WAYLAND_DISPLAY) {
966
+ file = desktop;
967
+ const q = (s) => `"${String(s).replace(/(["`$\\])/g, '\\$1')}"`;
968
+ const exec = [...(Object.keys(env).length ? ['env', ...Object.entries(env).map(([k, v]) => `${k}=${v}`)] : []), ...program].map(q).join(' ');
969
+ fs.mkdirSync(path.dirname(file), { recursive: true });
970
+ fs.writeFileSync(file, `[Desktop Entry]\nType=Application\nName=claude-pro host\nComment=Lets the gateway's web page open claude-pro sessions on this computer\nExec=${exec}\nNoDisplay=true\nX-GNOME-Autostart-enabled=true\n`);
971
+ } else {
972
+ file = service;
973
+ const q = (s) => `"${String(s).replace(/(["\\])/g, '\\$1')}"`;
974
+ fs.mkdirSync(path.dirname(file), { recursive: true });
975
+ fs.writeFileSync(file, `[Unit]\nDescription=claude-pro host: lets the gateway's web page open claude-pro sessions on this computer\n\n[Service]\nType=oneshot\nRemainAfterExit=yes\nExecStart=${program.map(q).join(' ')}\n${Object.entries(env).map(([k, v]) => `Environment=${q(`${k}=${v}`)}\n`).join('')}\n[Install]\nWantedBy=default.target\n`);
976
+ const daemon = spawnSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'ignore' });
977
+ const enabled = spawnSync('systemctl', ['--user', 'enable', path.basename(file)], { stdio: 'ignore' });
978
+ note = daemon.status === 0 && enabled.status === 0
979
+ ? ` (systemd user service; \`loginctl enable-linger ${os.userInfo().username}\` keeps it running without a login)`
980
+ : ' (systemctl --user did not take it: enable it by hand)';
981
+ }
982
+ console.log(`claude-pro host starts at logon now: ${file}${note}`);
983
+ return startCommand();
984
+ }
985
+
986
+ function uninstallCommand() {
987
+ let removed = 0;
988
+ for (const file of autostartFiles()) {
989
+ if (!fs.existsSync(file)) continue;
990
+ if (process.platform === 'darwin') spawnSync('launchctl', ['unload', '-w', file], { stdio: 'ignore' });
991
+ if (file.endsWith('.service')) spawnSync('systemctl', ['--user', 'disable', path.basename(file)], { stdio: 'ignore' });
992
+ fs.rmSync(file, { force: true });
993
+ console.log(`Removed ${file}`);
994
+ removed++;
995
+ }
996
+ if (!removed) console.log('claude-pro host was not set to start at logon.');
997
+ if (hostRunning()) console.log('It is still running now: `claude-pro host stop` stops it.');
998
+ return 0;
999
+ }
1000
+
1001
+ const USAGE = `Usage: claude-pro host [run | start | stop | status | install | uninstall]
1002
+
1003
+ The computer service: it keeps this computer on the gateway's 远程控制 page, so that the page can open a new
1004
+ claude-pro session here (in a terminal window, in the directory chosen there). It uses the gateway login of
1005
+ /login, and only connects out to the gateway. A session logged in to the gateway starts it by itself
1006
+ (CLAUDE_PRO_HOST=0: not).
1007
+
1008
+ claude-pro host Run it here, in the foreground (Ctrl+C stops it)
1009
+ claude-pro host start Run it in the background (log: ~/.claude-pro/host.log)
1010
+ claude-pro host stop Stop it and take this computer off the gateway's list (sessions then no longer start it)
1011
+ claude-pro host status Whether it runs, its id, its log
1012
+ claude-pro host install Start it at logon too (Windows: a script in the Startup folder; macOS: a LaunchAgent;
1013
+ Linux: a desktop autostart entry, else a systemd user service)
1014
+ claude-pro host uninstall Not at logon any more
1015
+ `;
1016
+
1017
+ // `claude-pro host ...`: returns the exit code (`run` ends the process itself once the service has stopped).
1018
+ export async function hostCommand(args = []) {
1019
+ const [sub = 'run', ...rest] = args;
1020
+ switch (sub) {
1021
+ case 'run': process.exit(await runHost({ background: rest.includes('--background') })); break;
1022
+ case 'start': return startCommand();
1023
+ case 'stop': return stopCommand();
1024
+ case 'status': return statusCommand();
1025
+ case 'install': return installCommand();
1026
+ case 'uninstall': return uninstallCommand();
1027
+ case 'help': case '-h': case '--help': process.stdout.write(USAGE); return 0;
1028
+ default: process.stderr.write(`Unknown host command: ${sub}\n\n${USAGE}`); return 2;
1029
+ }
1030
+ return 0;
1031
+ }