@yanzc/claude-pro 0.5.9 → 0.7.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,1410 @@
1
+ // The computer service (`claude-pro host`): one background process per computer (per CONFIG_DIR) that makes this
2
+ // computer one the gateway's web page (远程控制) runs sessions on: it lists the directories to choose from, opens
3
+ // sessions in the one chosen (in the background without a window, see background.js, or in a terminal window),
4
+ // online at once with the id the gateway gave them, ends and restarts them, reopens kept conversations (history),
5
+ // gives logs, updates claude-pro, and reports the sessions and how busy the computer is. Like a session it only
6
+ // connects out to the gateway, with the API key of /login or claude-pro connect.
7
+ //
8
+ // Protocol (Bearer = the gateway API key; ARCHITECTURE.md 3.1.5):
9
+ // POST /v1/remote/hosts {id, machine, host, platform, version, home, terminal, autostart, sessions, stats}
10
+ // GET /v1/remote/hosts/:id/commands (SSE): online while it is open; {cid, type, body}: list, open, stop,
11
+ // restart, logs, history, update
12
+ // POST /v1/remote/hosts/:id/results {cid, ok: true, ...} | {cid, ok: false, error}
13
+ // POST /v1/remote/hosts/:id/state {sessions, stats}: on a change of the sessions, and every minute
14
+ // DELETE /v1/remote/hosts/:id: off the page's list (`host stop`, a logout, another account)
15
+ //
16
+ // It runs in the foreground with `claude-pro host`, in the background (detached, no window, logging to
17
+ // CONFIG_DIR/host.log) with `host start`; an interactive session logged in to the gateway starts one when none
18
+ // runs (CLAUDE_PRO_HOST=0: not), and `host install` starts one at logon. CONFIG_DIR/host.json keeps its id (for
19
+ // good) and, while it runs, its pid and a heartbeat; host.lock keeps a second one from running. It follows the
20
+ // login in gateway.json (waits without one, registers again with another key), and a background one starts the
21
+ // new version of the program when its files change (an update, an edit of the source).
22
+
23
+ import fs from 'node:fs';
24
+ import fsp from 'node:fs/promises';
25
+ import os from 'node:os';
26
+ import path from 'node:path';
27
+ import crypto from 'node:crypto';
28
+ import { spawn, spawnSync } from 'node:child_process';
29
+ import { CONFIG_DIR, INSTALL_DIR, VERSION, GATEWAY_DEFAULT_URL, loadConfig } from './config.js';
30
+ import { readGatewayLogin, normalizeGatewayUrl } from './gateway.js';
31
+ import { machineName, cleanName, listPeers } from './peers.js';
32
+ import { BackgroundSessions, markEnded, tailFile } from './background.js';
33
+ import { listConversations } from './history.js';
34
+ import { checkForUpdate, installUpdate } from './updater.js';
35
+ import { ENV_SUPERVISED, ENV_RESTART_FILE, ENV_RESTARTED } from './supervisor.js';
36
+
37
+ export const ENTRY = path.join(INSTALL_DIR, 'bin', 'claude-pro.js');
38
+ const ID = /^[A-Za-z0-9_-]{8,64}$/;
39
+ // (CLAUDE_PRO_HOST_TICK_MS, for the tests: the heartbeat and the check of the program's files that often)
40
+ const TICK = Number(process.env.CLAUDE_PRO_HOST_TICK_MS) || 0;
41
+ const BEAT_MS = TICK || 20_000; // host.json is written this often while it runs ...
42
+ const STALE_MS = 90_000; // ... and one whose heartbeat is older than this is not running (its pid may be another program's now)
43
+ const LOGIN_CHECK_MS = 5_000;
44
+ const CODE_CHECK_MS = TICK || 60_000;
45
+ const REQUEST_TIMEOUT_MS = 15_000;
46
+ const STREAM_SILENCE_MS = 50_000; // the gateway pings every 15 s
47
+ const MAX_ENTRIES = 1000;
48
+ const MAX_RECENT = 15;
49
+ const LOG_BYTES = 1_000_000;
50
+ const STATE_MS = 60_000; // the state goes to the gateway at least this often (the numbers of Stats)
51
+ // A session's own (its supervisor's, and those of one command of its Bash tool, see utils/shell.js: `claude-pro host
52
+ // start` may be run there): not for the service, nor for the sessions it opens.
53
+ const SESSION_ONLY = [ENV_SUPERVISED, ENV_RESTART_FILE, ENV_RESTARTED, 'CLAUDE_PRO_CWD_FILE', 'CLAUDE_PRO_PID_FILE', 'CLAUDE_PRO_COMMAND'];
54
+
55
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
56
+
57
+ // Whether sessions start the service by themselves (CLAUDE_PRO_HOST=0: only `claude-pro host start` does).
58
+ export const hostEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(env.CLAUDE_PRO_HOST || '');
59
+
60
+ const configDir = () => process.env.CLAUDE_PRO_CONFIG_DIR || CONFIG_DIR;
61
+ export const hostFiles = () => {
62
+ const dir = configDir();
63
+ 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') };
64
+ };
65
+
66
+ // ---------------------------------------------------------------- host.json, the lock
67
+
68
+ export function readHostState() {
69
+ try {
70
+ const state = JSON.parse(fs.readFileSync(hostFiles().state, 'utf8'));
71
+ return state && typeof state === 'object' ? state : {};
72
+ } catch {
73
+ return {};
74
+ }
75
+ }
76
+
77
+ // Merges `change` into host.json (an undefined value removes the key).
78
+ export function updateHostState(change) {
79
+ const next = { ...readHostState(), ...change };
80
+ for (const k of Object.keys(next)) if (next[k] === undefined) delete next[k];
81
+ const file = hostFiles().state;
82
+ try {
83
+ fs.mkdirSync(path.dirname(file), { recursive: true });
84
+ const tmp = `${file}.${process.pid}.tmp`;
85
+ fs.writeFileSync(tmp, JSON.stringify(next, null, 2));
86
+ fs.renameSync(tmp, file);
87
+ } catch { /* best effort: the next heartbeat writes it again */ }
88
+ return next;
89
+ }
90
+
91
+ export function pidAlive(pid) {
92
+ if (!Number.isInteger(pid) || pid <= 0) return false;
93
+ try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
94
+ }
95
+
96
+ export function hostRunning(state = readHostState(), now = Date.now()) {
97
+ return Boolean(state.pid && pidAlive(state.pid) && now - (Number(state.beat) || 0) < STALE_MS);
98
+ }
99
+
100
+ // This computer's id at the gateway: made once, then kept in host.json. The sessions register with it too
101
+ // (computerId), so that the page puts a computer's service and its sessions together.
102
+ function hostId() {
103
+ const state = readHostState();
104
+ if (ID.test(state.id || '')) return state.id;
105
+ const id = crypto.randomBytes(9).toString('base64url');
106
+ updateHostState({ id });
107
+ return id;
108
+ }
109
+
110
+ let knownId = null;
111
+ export function computerId() {
112
+ if (knownId && knownId.dir === configDir()) return knownId.id;
113
+ knownId = { dir: configDir(), id: hostId() };
114
+ return knownId.id;
115
+ }
116
+
117
+ // The id the gateway gave this computer when it was paired (claude-pro connect), when it is not the one it had.
118
+ export function setComputerId(id) {
119
+ if (!ID.test(String(id || ''))) return;
120
+ updateHostState({ id });
121
+ knownId = null;
122
+ }
123
+
124
+ // A background session ended for good (/exit): the service does not open it again (see background.js).
125
+ export function markBackgroundEnded(sessionId) { markEnded(configDir(), sessionId); }
126
+
127
+ // One service per CONFIG_DIR: host.lock holds the pid of the one that runs. A lock is taken over when its process
128
+ // is gone, or when it is old and no heartbeat says it runs (its pid may be another program's now).
129
+ function takeLock() {
130
+ const { lock } = hostFiles();
131
+ fs.mkdirSync(path.dirname(lock), { recursive: true });
132
+ for (let i = 0; i < 2; i++) {
133
+ try {
134
+ fs.writeFileSync(lock, String(process.pid), { flag: 'wx' });
135
+ return true;
136
+ } catch (e) {
137
+ if (e.code !== 'EEXIST') throw e;
138
+ }
139
+ let holder = 0;
140
+ let age = Infinity;
141
+ try { holder = Number(fs.readFileSync(lock, 'utf8')); age = Date.now() - fs.statSync(lock).mtimeMs; } catch { continue; }
142
+ const state = readHostState();
143
+ if (holder !== process.pid && pidAlive(holder) && (age < STALE_MS || (state.pid === holder && Date.now() - (Number(state.beat) || 0) < STALE_MS))) return false;
144
+ try { fs.rmSync(lock, { force: true }); } catch { /* taken again below, or not */ }
145
+ }
146
+ return false;
147
+ }
148
+
149
+ function releaseLock(pid = process.pid) {
150
+ const { lock } = hostFiles();
151
+ try { if (Number(fs.readFileSync(lock, 'utf8')) === pid) fs.rmSync(lock, { force: true }); } catch { /* not ours, or gone */ }
152
+ }
153
+
154
+ // ---------------------------------------------------------------- logging
155
+
156
+ function fileLogger() {
157
+ const file = hostFiles().log;
158
+ return (msg) => {
159
+ try {
160
+ fs.mkdirSync(path.dirname(file), { recursive: true });
161
+ try { if (fs.statSync(file).size > LOG_BYTES) fs.renameSync(file, `${file}.1`); } catch { /* none yet */ }
162
+ fs.appendFileSync(file, `[${new Date().toISOString()}] ${msg}\n`);
163
+ } catch { /* nowhere to say it */ }
164
+ };
165
+ }
166
+
167
+ const consoleLogger = () => (msg) => process.stdout.write(`[${new Date().toLocaleTimeString()}] ${msg}\n`);
168
+
169
+ // ---------------------------------------------------------------- starting it from elsewhere
170
+
171
+ function serviceEnv(env = process.env) {
172
+ const out = { ...env };
173
+ for (const k of SESSION_ONLY) delete out[k];
174
+ return out;
175
+ }
176
+
177
+ // A service in the background: detached (it outlives the session or terminal that started it), without a window.
178
+ // What it prints on its own (a crash) goes to its log too.
179
+ export function startHostInBackground({ env = process.env } = {}) {
180
+ let fd = 'ignore';
181
+ try {
182
+ fs.mkdirSync(hostFiles().dir, { recursive: true });
183
+ fd = fs.openSync(hostFiles().log, 'a');
184
+ } catch { /* nowhere: ignored */ }
185
+ try {
186
+ const child = spawn(process.execPath, [ENTRY, 'host', 'run', '--background'], { detached: true, stdio: ['ignore', fd, fd], windowsHide: true, cwd: os.homedir(), env: serviceEnv(env) });
187
+ child.on('error', () => { /* the next session tries again */ });
188
+ child.unref();
189
+ return child.pid;
190
+ } finally {
191
+ if (typeof fd === 'number') try { fs.closeSync(fd); } catch { /* closed */ }
192
+ }
193
+ }
194
+
195
+ // For a session that starts (see App.ensureHost): a service, unless one runs, `claude-pro host stop` stopped it, or
196
+ // one was started a moment ago (by another session starting at the same time). Returns the pid of a new one.
197
+ export function ensureHost({ env = process.env } = {}) {
198
+ const state = readHostState();
199
+ if (hostRunning(state) || state.disabled) return null;
200
+ if (Date.now() - (Number(state.spawnedAt) || 0) < 30_000) return null;
201
+ updateHostState({ spawnedAt: Date.now() });
202
+ return startHostInBackground({ env });
203
+ }
204
+
205
+ // What /status says about it.
206
+ export function describeHost(env = process.env) {
207
+ const state = readHostState();
208
+ 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'}`;
209
+ if (state.disabled) return 'stopped with `claude-pro host stop` (`claude-pro host start` starts it again)';
210
+ 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)';
211
+ }
212
+
213
+ // ---------------------------------------------------------------- directories (the list command)
214
+
215
+ // `input` as an absolute directory of this computer: "" (or ~) is the home directory, "D:" is the root of D:, and
216
+ // forward slashes do on Windows too. null when it is not absolute.
217
+ export function normalizeDir(input, { platform = process.platform, home = os.homedir() } = {}) {
218
+ const p = platform === 'win32' ? path.win32 : path.posix;
219
+ let s = String(input ?? '').trim();
220
+ if (!s || s === '~') return home;
221
+ if (s.startsWith('~/') || s.startsWith('~\\')) s = p.join(home, s.slice(2));
222
+ if (platform === 'win32') {
223
+ s = s.replace(/\//g, '\\');
224
+ if (/^[A-Za-z]:$/.test(s)) s += '\\';
225
+ if (!/^([A-Za-z]:\\|\\\\[^\\]+\\[^\\]+)/.test(s)) return null;
226
+ s = s.replace(/^[a-z]:/, (d) => d.toUpperCase());
227
+ } else if (!s.startsWith('/')) {
228
+ return null;
229
+ }
230
+ return p.resolve(s);
231
+ }
232
+
233
+ const describeFsError = (e, dir) => (e.code === 'ENOENT' || e.code === 'ENOTDIR' ? `目录不存在:${dir}`
234
+ : e.code === 'EACCES' || e.code === 'EPERM' ? `没有权限读取:${dir}`
235
+ : `读取 ${dir} 失败:${e.message}`);
236
+
237
+ let rootsCache = { at: 0, roots: [] };
238
+ async function roots(platform = process.platform) {
239
+ if (platform !== 'win32') return ['/'];
240
+ if (Date.now() - rootsCache.at < 30_000) return rootsCache.roots;
241
+ // a disconnected network drive can take long to answer: 1.5 seconds each, all at once
242
+ const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
243
+ const found = await Promise.all(letters.map((l) => Promise.race([
244
+ fsp.access(`${l}:\\`).then(() => `${l}:\\`, () => null),
245
+ sleep(1500).then(() => null),
246
+ ])));
247
+ rootsCache = { at: Date.now(), roots: found.filter(Boolean) };
248
+ return rootsCache.roots;
249
+ }
250
+
251
+ // The directories in `input` (only directories, links to them included), for the page to choose from.
252
+ export async function listDirectory(input, { home = os.homedir(), recent = () => [] } = {}) {
253
+ const dir = normalizeDir(input, { home });
254
+ if (!dir) throw new Error(`不是绝对路径:${input}`);
255
+ let st;
256
+ try { st = await fsp.stat(dir); } catch (e) { throw new Error(describeFsError(e, dir)); }
257
+ if (!st.isDirectory()) throw new Error(`不是目录:${dir}`);
258
+ let dirents;
259
+ try { dirents = await fsp.readdir(dir, { withFileTypes: true }); } catch (e) { throw new Error(describeFsError(e, dir)); }
260
+ const entries = [];
261
+ for (const d of dirents) {
262
+ const full = path.join(dir, d.name);
263
+ let isDir = d.isDirectory();
264
+ if (!isDir && d.isSymbolicLink()) {
265
+ // a link to a directory counts, unless it cannot be opened (Windows' old junctions in the profile:
266
+ // "My Documents", "Application Data" ... refuse to be listed)
267
+ try { isDir = (await fsp.stat(full)).isDirectory(); } catch { isDir = false; }
268
+ if (isDir) {
269
+ let handle = null;
270
+ try {
271
+ handle = await fsp.opendir(full);
272
+ await handle.read(); // Windows checks the access at the first read, not at the opening
273
+ } catch {
274
+ isDir = false;
275
+ } finally {
276
+ await handle?.close().catch(() => {});
277
+ }
278
+ }
279
+ // ... and the profile's other compatibility junctions ("Application Data", "Recent", the Start Menu in the
280
+ // system's language ...), which Explorer hides: all lead into AppData
281
+ if (isDir && process.platform === 'win32' && dir.toLowerCase() === path.resolve(home).toLowerCase()) {
282
+ try {
283
+ if ((await fsp.realpath(full)).toLowerCase().startsWith(`${path.join(home, 'AppData').toLowerCase()}\\`)) isDir = false;
284
+ } catch { isDir = false; }
285
+ }
286
+ }
287
+ if (isDir) entries.push({ name: d.name, path: full });
288
+ }
289
+ const hidden = (name) => (name.startsWith('.') ? 1 : 0);
290
+ entries.sort((a, b) => hidden(a.name) - hidden(b.name) || a.name.localeCompare(b.name, undefined, { sensitivity: 'accent', numeric: true }));
291
+ const parent = path.dirname(dir);
292
+ return {
293
+ path: dir,
294
+ parent: parent === dir ? null : parent,
295
+ sep: path.sep,
296
+ entries: entries.slice(0, MAX_ENTRIES),
297
+ truncated: entries.length > MAX_ENTRIES,
298
+ home,
299
+ roots: await roots(),
300
+ recent: recent(),
301
+ };
302
+ }
303
+
304
+ // The first line of a session file is {type: 'meta', cwd, ...} (see SessionStore.append).
305
+ function sessionCwd(file) {
306
+ let fd = null;
307
+ try {
308
+ fd = fs.openSync(file, 'r');
309
+ const buf = Buffer.alloc(16 * 1024);
310
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
311
+ const line = buf.subarray(0, n).toString('utf8').split('\n')[0];
312
+ const meta = JSON.parse(line);
313
+ return meta?.type === 'meta' && typeof meta.cwd === 'string' ? meta.cwd : null;
314
+ } catch {
315
+ return null;
316
+ } finally {
317
+ if (fd !== null) fs.closeSync(fd);
318
+ }
319
+ }
320
+
321
+ // Where claude-pro sessions ran lately on this computer, newest first: [{path, at}] of the directories that are
322
+ // still there. One line read per project (its newest session's first line).
323
+ export function recentDirectories({ projects = path.join(configDir(), 'projects'), max = MAX_RECENT } = {}) {
324
+ let dirs = [];
325
+ try { dirs = fs.readdirSync(projects, { withFileTypes: true }).filter((d) => d.isDirectory()); } catch { return []; }
326
+ const found = [];
327
+ for (const d of dirs) {
328
+ const sub = path.join(projects, d.name);
329
+ let newest = null;
330
+ try {
331
+ for (const f of fs.readdirSync(sub)) {
332
+ if (!f.endsWith('.jsonl')) continue;
333
+ const m = fs.statSync(path.join(sub, f)).mtimeMs;
334
+ if (!newest || m > newest.m) newest = { f, m };
335
+ }
336
+ } catch { continue; }
337
+ if (!newest) continue;
338
+ const cwd = sessionCwd(path.join(sub, newest.f));
339
+ if (cwd) found.push({ path: path.resolve(cwd), at: newest.m });
340
+ }
341
+ found.sort((a, b) => b.at - a.at);
342
+ const seen = new Set();
343
+ const out = [];
344
+ for (const r of found) {
345
+ const key = process.platform === 'win32' ? r.path.toLowerCase() : r.path;
346
+ if (seen.has(key)) continue;
347
+ seen.add(key);
348
+ try { if (!fs.statSync(r.path).isDirectory()) continue; } catch { continue; }
349
+ out.push({ path: r.path, at: new Date(r.at).toISOString() });
350
+ if (out.length >= max) break;
351
+ }
352
+ return out;
353
+ }
354
+
355
+ // ---------------------------------------------------------------- terminals (the open command)
356
+
357
+ // A program on the PATH. Windows Terminal's wt.exe is an "app execution alias" that only lstat sees.
358
+ export function findCommand(name, { env = process.env, platform = process.platform } = {}) {
359
+ const p = platform === 'win32' ? path.win32 : path.posix;
360
+ const dirs = String(env.PATH ?? env.Path ?? '').split(platform === 'win32' ? ';' : ':').filter(Boolean);
361
+ const exts = platform === 'win32' && !p.extname(name) ? String(env.PATHEXT || '.EXE;.CMD;.BAT').split(';') : [''];
362
+ const extra = platform === 'win32' && env.LOCALAPPDATA ? [p.join(env.LOCALAPPDATA, 'Microsoft', 'WindowsApps')] : [];
363
+ for (const dir of [...dirs, ...extra]) {
364
+ for (const ext of exts) {
365
+ const file = p.join(dir, name + ext);
366
+ try {
367
+ const st = fs.lstatSync(file);
368
+ if (st.isFile() || st.isSymbolicLink()) return file;
369
+ } catch { /* not here */ }
370
+ }
371
+ }
372
+ return null;
373
+ }
374
+
375
+ // What opens a terminal window on this computer: {kind, name, path}, or null when nothing here can.
376
+ export function terminalFor({ platform = process.platform, env = process.env, find = (name) => findCommand(name, { env, platform }) } = {}) {
377
+ if (platform === 'win32') {
378
+ const wt = find('wt.exe');
379
+ return wt ? { kind: 'wt', name: 'Windows Terminal', path: wt } : { kind: 'console', name: 'Windows console', path: 'powershell.exe' };
380
+ }
381
+ if (platform === 'darwin') {
382
+ const osa = find('osascript');
383
+ return osa ? { kind: 'osascript', name: 'Terminal.app', path: osa } : null;
384
+ }
385
+ if (env.DISPLAY || env.WAYLAND_DISPLAY) {
386
+ for (const cmd of ['x-terminal-emulator', 'gnome-terminal', 'konsole', 'xterm']) {
387
+ const found = find(cmd);
388
+ if (found) return { kind: cmd, name: cmd, path: found };
389
+ }
390
+ }
391
+ const tmux = find('tmux');
392
+ return tmux ? { kind: 'tmux', name: 'tmux', path: tmux } : null;
393
+ }
394
+
395
+ // One argument of a Windows command line, quoted as the C runtime reads it back.
396
+ export function quoteWindowsArg(arg) {
397
+ const s = String(arg);
398
+ if (s && !/[\s"]/.test(s)) return s;
399
+ let out = '"';
400
+ let slashes = 0;
401
+ for (const ch of s) {
402
+ if (ch === '\\') { slashes++; continue; }
403
+ out += ch === '"' ? `${'\\'.repeat(slashes * 2 + 1)}"` : `${'\\'.repeat(slashes)}${ch}`;
404
+ slashes = 0;
405
+ }
406
+ return `${out}${'\\'.repeat(slashes * 2)}"`;
407
+ }
408
+
409
+ const shQuote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
410
+
411
+ // The settings of this service's environment that a session it opens needs too (the config directory, the
412
+ // gateway's address, the computer's name ...): Windows Terminal starts the program with its own environment, and
413
+ // tmux and a desktop's terminal with theirs. Not the secrets: those stay where they were set.
414
+ const PASS_ENV = /^(CLAUDE_PRO_|ANTHROPIC_|CLAUDE_CODE_|CLAUDE_CONFIG_DIR$)/;
415
+ const SECRET = /TOKEN|KEY|SECRET|PASSWORD|HEADERS/i;
416
+ export function passedEnv(env = process.env) {
417
+ const out = {};
418
+ for (const [k, v] of Object.entries(env)) {
419
+ 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;
420
+ out[k] = String(v);
421
+ }
422
+ return out;
423
+ }
424
+
425
+ // For Windows: the variables as a file for `node --env-file` (whose single and back quotes keep backslashes as they
426
+ // are). Files of launches more than 10 minutes old are removed.
427
+ function writeEnvFile(sessionId, vars) {
428
+ const entries = Object.entries(vars);
429
+ if (!entries.length) return null;
430
+ const dir = hostFiles().launch;
431
+ fs.mkdirSync(dir, { recursive: true });
432
+ try {
433
+ for (const f of fs.readdirSync(dir)) {
434
+ const file = path.join(dir, f);
435
+ if (Date.now() - fs.statSync(file).mtimeMs > 10 * 60_000) fs.rmSync(file, { force: true });
436
+ }
437
+ } catch { /* the next launch cleans up */ }
438
+ const quote = (v) => (!v.includes("'") ? `'${v}'` : !v.includes('`') ? `\`${v}\`` : null);
439
+ const lines = entries.map(([k, v]) => (quote(v) ? `${k}=${quote(v)}` : null)).filter(Boolean);
440
+ const file = path.join(dir, `${sessionId}.env`);
441
+ fs.writeFileSync(file, `${lines.join('\n')}\n`, { mode: 0o600 });
442
+ return file;
443
+ }
444
+
445
+ // How `term` opens a window that runs `node entry ...args` in `cwd`: {cmd, args, options, wait}. `wait`: 'exit'
446
+ // when the command ends once the window is open (its exit code says whether it worked), 'spawn' when it is the
447
+ // terminal itself.
448
+ export function launchCommand(term, { cwd, node = process.execPath, entry = ENTRY, args = [], env = {}, envFile = null, sessionId = '' }) {
449
+ const program = [node, ...(envFile ? [`--env-file=${envFile}`] : []), entry, ...args];
450
+ const pairs = Object.entries(env).map(([k, v]) => `${k}=${v}`);
451
+ const posix = [...(pairs.length ? ['env', ...pairs] : []), node, entry, ...args];
452
+ const line = posix.map(shQuote).join(' ');
453
+ switch (term.kind) {
454
+ case 'wt': // a new window; wt reads ; as the start of another command
455
+ return { cmd: term.path, args: ['-w', 'new', '-d', cwd, ...program].map((a) => a.replace(/;/g, '\\;')), options: { windowsHide: false }, wait: 'exit' };
456
+ case 'console': { // a console window of its own; Start-Process takes the command line as it is
457
+ // what went wrong: only its message, in UTF-8 (PowerShell writes errors as CLIXML in the system's code page)
458
+ const script = [
459
+ "$ProgressPreference = 'SilentlyContinue'",
460
+ '[Console]::OutputEncoding = [Text.Encoding]::UTF8',
461
+ '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 }',
462
+ 'catch { [Console]::Out.Write($_.Exception.Message); exit 1 }',
463
+ ].join('\n');
464
+ return {
465
+ cmd: term.path,
466
+ args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-OutputFormat', 'Text', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
467
+ // not detached: a detached (console-less) PowerShell ends at once without doing anything; hidden, its
468
+ // console does not show
469
+ 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 } },
470
+ wait: 'exit',
471
+ };
472
+ }
473
+ case 'osascript': {
474
+ const as = (s) => `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
475
+ 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' };
476
+ }
477
+ case 'tmux': // no desktop: a tmux session (`tmux attach -t claude-pro-<id>` shows it here; the web page works anyway)
478
+ return { cmd: term.path, args: ['new-session', '-d', '-s', `claude-pro-${sessionId}`, '-c', cwd, `exec ${line}`], options: { cwd }, wait: 'exit' };
479
+ default: { // a desktop's terminal: sh goes to `cwd` first, as not every terminal starts where it was started
480
+ const inDir = ['sh', '-c', 'cd "$0" && exec "$@"', cwd, ...posix];
481
+ const head = term.kind === 'gnome-terminal' ? [`--working-directory=${cwd}`, '--'] : term.kind === 'konsole' ? ['--workdir', cwd, '-e'] : ['-e'];
482
+ return { cmd: term.path, args: [...head, ...inDir], options: { cwd }, wait: 'spawn' };
483
+ }
484
+ }
485
+ }
486
+
487
+ // Runs what launchCommand made: resolves once the window is open, rejects with what went wrong.
488
+ export function runLaunch(spec, { timeoutMs = 20_000 } = {}) {
489
+ return new Promise((resolve, reject) => {
490
+ const exits = spec.wait === 'exit';
491
+ let child;
492
+ // a terminal that runs on must not write into a closed pipe: only a command that ends tells its error
493
+ const out = exits ? 'pipe' : 'ignore';
494
+ try { child = spawn(spec.cmd, spec.args, { detached: true, stdio: ['ignore', out, out], ...spec.options }); } catch (e) { reject(e); return; }
495
+ let err = '';
496
+ const keep = (d) => { if (err.length < 4000) err += d; };
497
+ child.stdout?.on('data', keep);
498
+ child.stderr?.on('data', keep);
499
+ let settled = false;
500
+ const done = (e) => {
501
+ if (settled) return;
502
+ settled = true;
503
+ clearTimeout(timer);
504
+ child.unref();
505
+ if (e) reject(e); else resolve();
506
+ };
507
+ const timer = setTimeout(() => done(exits ? new Error('打开终端超时') : null), exits ? timeoutMs : 1500);
508
+ child.on('error', (e) => done(e));
509
+ child.on('exit', (code) => done(code === 0 ? null : new Error(err.trim().split(/\r?\n/).filter(Boolean).pop() || `退出码 ${code}`)));
510
+ });
511
+ }
512
+
513
+ // ---------------------------------------------------------------- the service
514
+
515
+ export class HostService {
516
+ // `readLogin`, `loadConfig`, `launch`, `terminal`, `home`: what the tests give it instead of this computer's.
517
+ // `sessions`: the background sessions it runs (see background.js), null when it runs none (the tests).
518
+ constructor({ id, log = () => {}, fetchImpl = globalThis.fetch, background = false, terminal, launch = runLaunch, home = os.homedir(), readLogin, loadConfig: load, sessions = null } = {}) {
519
+ this.id = id;
520
+ this.log = log;
521
+ this.fetch = fetchImpl;
522
+ this.background = background;
523
+ this.sessions = sessions;
524
+ this.stats = new Stats(home);
525
+ this.stateTimer = null;
526
+ this.terminal = terminal === undefined ? terminalFor() : terminal;
527
+ this.launch = launch;
528
+ this.home = home;
529
+ this.loadConfig = load || (() => loadConfig({ cwd: home }));
530
+ this.readLogin = readLogin || (() => readGatewayLogin(this.cfg().gatewayUrl));
531
+ this.config = null;
532
+ this.configAt = 0;
533
+ this.login = null; // {url, apiKey, account} of gateway.json
534
+ this.registered = false;
535
+ this.online = false;
536
+ this.stopped = false;
537
+ this.reloading = false;
538
+ this.inflight = 0;
539
+ this.streamAbort = null;
540
+ this.wake = null;
541
+ this.timers = [];
542
+ this.refusedKey = null;
543
+ this.lastNote = '';
544
+ this.recent = { at: 0, list: [] };
545
+ }
546
+
547
+ cfg() {
548
+ if (!this.config || Date.now() - this.configAt > 60_000) {
549
+ try { this.config = this.loadConfig(); } catch { this.config ??= { env: process.env, gatewayUrl: GATEWAY_DEFAULT_URL }; }
550
+ this.configAt = Date.now();
551
+ }
552
+ return this.config;
553
+ }
554
+
555
+ base(login = this.login) { return normalizeGatewayUrl(login?.url || this.cfg().gatewayUrl); }
556
+
557
+ // Logged once until something else happens (a gateway that is down is retried every 30 seconds).
558
+ note(msg) {
559
+ if (msg === this.lastNote) return;
560
+ this.lastNote = msg;
561
+ this.log(msg);
562
+ }
563
+
564
+ async request(method, route, body, { timeout = REQUEST_TIMEOUT_MS, login = this.login } = {}) {
565
+ const res = await this.fetch(`${this.base(login)}${route}`, {
566
+ method,
567
+ headers: { authorization: `Bearer ${login.apiKey}`, 'content-type': 'application/json' },
568
+ body: body === undefined ? undefined : JSON.stringify(body),
569
+ signal: AbortSignal.timeout(timeout),
570
+ });
571
+ const data = await res.json().catch(() => ({}));
572
+ if (!res.ok) throw Object.assign(new Error(data?.error?.message || (typeof data?.error === 'string' ? data.error : `HTTP ${res.status}`)), { status: res.status });
573
+ return data;
574
+ }
575
+
576
+ // What the page shows of this computer. `machine` is the name its sessions register with, so that the page puts
577
+ // them together.
578
+ info() {
579
+ return { id: this.id, machine: machineName(this.cfg().env), host: os.hostname(), platform: process.platform, version: VERSION, home: this.home, terminal: this.terminal?.name || '' };
580
+ }
581
+
582
+ // What the page shows of this computer now: its background sessions and how busy it is.
583
+ state() {
584
+ return { sessions: this.sessions?.list() || [], stats: this.stats.now() };
585
+ }
586
+
587
+ // The state to the gateway: soon after a change of the sessions (several changes in a row go as one), and every
588
+ // minute for the numbers.
589
+ reportState({ soon = true } = {}) {
590
+ if (soon) {
591
+ if (this.stateTimer) return;
592
+ this.stateTimer = setTimeout(() => { this.stateTimer = null; this.reportState({ soon: false }); }, 300);
593
+ this.stateTimer.unref?.();
594
+ return;
595
+ }
596
+ if (!this.registered || !this.login || this.stopped) return;
597
+ this.request('POST', `/v1/remote/hosts/${encodeURIComponent(this.id)}/state`, this.state()).catch((e) => {
598
+ if (e.status === 404) { this.registered = false; this.streamAbort?.abort(); } // forgotten: registered again
599
+ });
600
+ }
601
+
602
+ async register() {
603
+ try {
604
+ await this.request('POST', '/v1/remote/hosts', { ...this.info(), autostart: autostartKind(), ...this.state() });
605
+ } catch (e) {
606
+ if (e.status === 404) e.noHosts = true; // a gateway without computers (yet): not the one that forgot this one
607
+ throw e;
608
+ }
609
+ this.registered = true;
610
+ this.note(`registered at ${this.base()} as ${this.info().machine} (${this.id})`);
611
+ }
612
+
613
+ // Follows gateway.json: logged out, the computer leaves the page's list and the service waits for a login; with
614
+ // another account it leaves the old one's list and joins the new one's.
615
+ checkLogin() {
616
+ let login = null;
617
+ try { login = this.readLogin(); } catch { /* none */ }
618
+ const key = (l) => (l?.apiKey ? `${this.base(l)}\n${l.apiKey}` : '');
619
+ if (key(login) === key(this.login)) return;
620
+ const old = this.login;
621
+ this.login = login?.apiKey ? login : null;
622
+ this.registered = false;
623
+ if (old) {
624
+ this.log(this.login ? 'the gateway login changed: registering with the new one' : 'logged out of the gateway: waiting for /login');
625
+ this.request('DELETE', `/v1/remote/hosts/${encodeURIComponent(this.id)}`, undefined, { login: old, timeout: 5000 }).catch(() => {});
626
+ } else if (this.login) {
627
+ this.log(`logged in to the gateway ${this.base()}`);
628
+ }
629
+ // the background sessions are the account's: gone with the login, back with a login
630
+ if (!this.login) this.sessions?.suspendAll();
631
+ else this.sessions?.resumeAll();
632
+ this.streamAbort?.abort();
633
+ this.wakeUp();
634
+ }
635
+
636
+ sleep(ms) {
637
+ return new Promise((resolve) => {
638
+ let timer = null;
639
+ const done = () => { clearTimeout(timer); if (this.wake === done) this.wake = null; resolve(); };
640
+ timer = setTimeout(done, ms);
641
+ this.wake = done;
642
+ });
643
+ }
644
+
645
+ wakeUp() { this.wake?.(); }
646
+
647
+ setOnline(online) {
648
+ if (online === this.online) return;
649
+ this.online = online;
650
+ if (online) this.lastNote = '';
651
+ this.log(online ? 'online: the web page can open sessions on this computer' : 'offline');
652
+ this.beat();
653
+ }
654
+
655
+ beat() {
656
+ if (this.stopped) return;
657
+ updateHostState({
658
+ id: this.id,
659
+ pid: process.pid,
660
+ version: VERSION,
661
+ startedAt: this.startedAt,
662
+ beat: Date.now(),
663
+ online: this.online,
664
+ gateway: this.login ? this.base() : null,
665
+ account: this.login?.account?.email || this.login?.account?.name || null,
666
+ machine: this.info().machine,
667
+ terminal: this.terminal?.name || '',
668
+ background: this.background,
669
+ disabled: undefined,
670
+ spawnedAt: undefined,
671
+ });
672
+ }
673
+
674
+ // Until stop(): resolves when the service has stopped (or stops to start its new version: `reloading`).
675
+ async run() {
676
+ this.startedAt = new Date().toISOString();
677
+ this.code = codeFingerprint();
678
+ this.checkLogin();
679
+ if (!this.login) this.log(`not logged in to the gateway ${this.base()}: waiting for /login`);
680
+ this.beat();
681
+ this.timers.push(
682
+ setInterval(() => this.beat(), BEAT_MS),
683
+ setInterval(() => this.checkLogin(), LOGIN_CHECK_MS),
684
+ setInterval(() => this.checkCode(), CODE_CHECK_MS),
685
+ setInterval(() => this.reportState({ soon: false }), STATE_MS),
686
+ setInterval(() => this.stats.sample(), 5000),
687
+ );
688
+ for (const t of this.timers) t.unref?.();
689
+ try { await this.loop(); } finally { for (const t of this.timers) clearInterval(t); clearTimeout(this.stateTimer); }
690
+ }
691
+
692
+ async loop() {
693
+ let wait = 1000;
694
+ while (!this.stopped) {
695
+ // without a login, or with a key the gateway refused (tried again every 10 minutes): a new login helps
696
+ const refused = this.login && this.refusedKey === this.login.apiKey && Date.now() - this.refusedAt < 10 * 60_000;
697
+ if (!this.login || refused) {
698
+ this.setOnline(false);
699
+ await this.sleep(this.login ? 60_000 : 30_000);
700
+ continue;
701
+ }
702
+ try {
703
+ if (!this.registered) await this.register();
704
+ await this.listen();
705
+ wait = 1000;
706
+ } catch (e) {
707
+ if (e.noHosts) { this.note(`the gateway ${this.base()} does not take computers (yet): trying again every 5 minutes`); wait = 5 * 60_000; }
708
+ else if (e.status === 404) this.registered = false; // the gateway forgot this computer (it restarted): register again
709
+ else if (e.status === 401 || e.status === 403) {
710
+ this.refusedKey = this.login?.apiKey;
711
+ this.refusedAt = Date.now();
712
+ this.registered = false;
713
+ // removed on the web page, or its key revoked: its background sessions end (kept to be opened again)
714
+ this.note(`这台电脑已从网页上移除 (the gateway refused this computer's key: ${e.message}); waiting for /login or claude-pro connect`);
715
+ this.sessions?.suspendAll();
716
+ }
717
+ else if (!this.stopped && e.name !== 'AbortError') this.note(`cannot reach the gateway ${this.base()}: ${e.message}`);
718
+ }
719
+ this.setOnline(false);
720
+ if (this.stopped) break;
721
+ await this.sleep(wait);
722
+ wait = Math.min(wait * 2, 30_000);
723
+ }
724
+ }
725
+
726
+ // The command stream, open until the gateway ends it, it stays silent too long, or abort().
727
+ async listen() {
728
+ const abort = new AbortController();
729
+ this.streamAbort = abort;
730
+ const res = await this.fetch(`${this.base()}/v1/remote/hosts/${encodeURIComponent(this.id)}/commands`, {
731
+ headers: { authorization: `Bearer ${this.login.apiKey}`, accept: 'text/event-stream' },
732
+ signal: abort.signal,
733
+ });
734
+ if (!res.ok) {
735
+ res.body?.cancel().catch(() => {});
736
+ throw Object.assign(new Error(`HTTP ${res.status}`), { status: res.status });
737
+ }
738
+ this.setOnline(true);
739
+ let last = Date.now();
740
+ const watchdog = setInterval(() => { if (Date.now() - last > STREAM_SILENCE_MS) abort.abort(); }, 5000);
741
+ try {
742
+ const decoder = new TextDecoder();
743
+ let buf = '';
744
+ for await (const chunk of res.body) {
745
+ last = Date.now();
746
+ buf += decoder.decode(chunk, { stream: true });
747
+ let i;
748
+ while ((i = buf.search(/\r?\n\r?\n/)) >= 0) {
749
+ const block = buf.slice(0, i);
750
+ buf = buf.slice(i).replace(/^\r?\n\r?\n/, '');
751
+ const data = block.split(/\r?\n/).filter((l) => l.startsWith('data:')).map((l) => l.slice(5).replace(/^ /, '')).join('\n');
752
+ if (!data) continue;
753
+ let cmd;
754
+ try { cmd = JSON.parse(data); } catch { continue; }
755
+ this.command(cmd);
756
+ }
757
+ }
758
+ } catch (e) {
759
+ if (!abort.signal.aborted) throw e;
760
+ } finally {
761
+ clearInterval(watchdog);
762
+ if (this.streamAbort === abort) this.streamAbort = null;
763
+ }
764
+ }
765
+
766
+ async command(cmd) {
767
+ if (!cmd || typeof cmd.cid !== 'string' || !cmd.cid) return;
768
+ const login = this.login;
769
+ this.inflight++;
770
+ let result;
771
+ try {
772
+ const body = cmd.body && typeof cmd.body === 'object' ? cmd.body : {};
773
+ let r;
774
+ if (cmd.type === 'list') r = await this.list(body);
775
+ else if (cmd.type === 'open') r = await this.open(body);
776
+ else if (cmd.type === 'stop') r = await this.needSessions().stop(String(body.sessionId || ''));
777
+ else if (cmd.type === 'restart') r = await this.needSessions().restart(String(body.sessionId || ''));
778
+ else if (cmd.type === 'logs') r = this.logs(body);
779
+ else if (cmd.type === 'history') r = this.history(body);
780
+ else if (cmd.type === 'update') r = await this.update();
781
+ else throw new Error(`这台电脑上的 claude-pro ${VERSION} 不认识命令 ${cmd.type},请升级`);
782
+ result = { cid: cmd.cid, ok: true, ...r };
783
+ } catch (e) {
784
+ result = { cid: cmd.cid, ok: false, error: e.message };
785
+ } finally {
786
+ this.inflight--;
787
+ }
788
+ if (login) {
789
+ try {
790
+ await this.request('POST', `/v1/remote/hosts/${encodeURIComponent(this.id)}/results`, result, { login });
791
+ } catch (e) {
792
+ this.note(`could not send the result of ${cmd.type}: ${e.message}`);
793
+ }
794
+ }
795
+ if (this.reloadWanted && !this.inflight) this.reload();
796
+ }
797
+
798
+ list(body) {
799
+ return listDirectory(typeof body.path === 'string' ? body.path : '', {
800
+ home: this.home,
801
+ recent: () => {
802
+ if (Date.now() - this.recent.at > 30_000) this.recent = { at: Date.now(), list: recentDirectories() };
803
+ return this.recent.list;
804
+ },
805
+ });
806
+ }
807
+
808
+ // The conversations kept on this computer (see history.js), with the session each one is open in.
809
+ history({ query, cwd, limit, before } = {}) {
810
+ if (before != null && Number.isNaN(Date.parse(before))) throw new Error('before 不是时间');
811
+ if (cwd != null && (typeof cwd !== 'string' || !normalizeDir(cwd, { home: this.home }))) throw new Error(`不是绝对路径:${cwd}`);
812
+ const open = new Map(listPeers().filter((p) => p.conversationId && p.remoteId).map((p) => [p.conversationId, p.remoteId]));
813
+ return listConversations({
814
+ projects: path.join(configDir(), 'projects'),
815
+ query: typeof query === 'string' ? query : '',
816
+ cwd: cwd ? normalizeDir(cwd, { home: this.home }) : null,
817
+ limit,
818
+ before,
819
+ open,
820
+ });
821
+ }
822
+
823
+ // update: a newer claude-pro from npm now (as /update). An install takes a while: it goes on after the answer,
824
+ // and its result goes to the log. The service and the sessions pick the new version up by themselves.
825
+ async update() {
826
+ const found = await checkForUpdate({ force: true });
827
+ if (found.status === 'dev') return { version: VERSION, message: `这台电脑运行的是源码目录里的 claude-pro ${VERSION}(${INSTALL_DIR}),不从 npm 更新` };
828
+ if (found.status === 'current') return { version: VERSION, message: `已是最新 ${VERSION}` };
829
+ if (found.status === 'installed') return { version: found.version, message: `已安装 ${found.version},空闲后重启` };
830
+ if (found.status !== 'available') throw new Error(`检查更新失败(${found.status})`);
831
+ this.updating ??= installUpdate(found.version).then((r) => {
832
+ if (r.status === 'updated' || r.status === 'installed') this.log(`installed claude-pro ${r.version}`);
833
+ else this.log(`could not install claude-pro ${found.version}: ${r.status}${r.error ? ` (${r.error})` : ''}`);
834
+ }, (e) => this.log(`could not install claude-pro ${found.version}: ${e.message}`)).finally(() => { this.updating = null; });
835
+ return { version: found.version, message: `正在安装 ${found.version},装好后空闲时自动重启` };
836
+ }
837
+
838
+ needSessions() {
839
+ if (!this.sessions) throw new Error('这台电脑的 claude-pro 服务不运行后台会话');
840
+ return this.sessions;
841
+ }
842
+
843
+ // The end of a log: a background session's, or the service's own. {text}
844
+ logs({ sessionId, lines } = {}) {
845
+ const n = Math.max(1, Math.min(2000, Number(lines) || 200));
846
+ if (sessionId) {
847
+ if (!ID.test(String(sessionId))) throw new Error('会话 id 不对');
848
+ const file = this.needSessions().logFile(sessionId);
849
+ if (!fs.existsSync(file) && !fs.existsSync(`${file}.1`)) throw new Error('这个会话没有日志');
850
+ return { text: tailFile(file, n) };
851
+ }
852
+ return { text: tailFile(hostFiles().log, n) };
853
+ }
854
+
855
+ // A new session in `cwd`, online at once as `sessionId` (and named `name`): in the background (no window, see
856
+ // background.js), or with `window` in a terminal window. `resume`: a conversation of this computer, opened again
857
+ // (where it is already open, that session is the answer: {existing: its id at the gateway}). `model`: to start with.
858
+ async open({ sessionId, cwd, create, name, window = true, resume = null, model = null } = {}) {
859
+ if (typeof sessionId !== 'string' || !ID.test(sessionId)) throw new Error('会话 id 不对');
860
+ if (resume != null && (typeof resume !== 'string' || !/^[0-9a-f-]{8,}$/i.test(resume))) throw new Error('对话 id 不对');
861
+ if (model != null && (typeof model !== 'string' || !/^[\w.:/[\]-]{1,100}$/.test(model))) throw new Error('模型名不对');
862
+ if (resume) {
863
+ const open = listPeers().find((p) => p.conversationId === resume);
864
+ if (open?.remoteId) return { existing: open.remoteId };
865
+ if (open) throw new Error(`这段对话已经在这台电脑的会话 &${open.name} 里打开了(它没有连上网关)`);
866
+ }
867
+ const dir = typeof cwd === 'string' ? normalizeDir(cwd, { home: this.home }) : null;
868
+ if (!dir || !String(cwd).trim()) throw new Error(`请选择一个绝对路径的目录:${cwd ?? ''}`);
869
+ let st = null;
870
+ try { st = await fsp.stat(dir); } catch (e) {
871
+ if (e.code !== 'ENOENT') throw new Error(describeFsError(e, dir));
872
+ }
873
+ if (!st) {
874
+ if (create !== true) throw new Error(`目录不存在:${dir}`);
875
+ try { await fsp.mkdir(dir, { recursive: true }); } catch (e) { throw new Error(`创建目录失败:${dir}(${e.message})`); }
876
+ } else if (!st.isDirectory()) {
877
+ throw new Error(`不是目录:${dir}`);
878
+ }
879
+ const label = typeof name === 'string' && name.trim() ? cleanName(name) : '';
880
+ if (window === false) {
881
+ const r = this.needSessions().open({ sessionId, cwd: dir, name: label, resume, model });
882
+ this.log(`opened a background session in ${dir} for ${sessionId}${label ? ` (${label})` : ''}${resume ? `, resuming ${resume}` : ''}`);
883
+ return { pid: r.pid };
884
+ }
885
+ const term = this.terminal;
886
+ if (!term) throw new Error('这台电脑上找不到能打开的终端(Windows Terminal、Terminal.app、x-terminal-emulator、gnome-terminal、konsole、xterm 或 tmux)');
887
+ const args = ['--remote-id', sessionId, ...(label ? ['--name', label] : []), ...(resume ? ['--resume', resume] : []), ...(model ? ['--model', model] : [])];
888
+ const env = passedEnv();
889
+ const envFile = process.platform === 'win32' && term.kind === 'wt' ? writeEnvFile(sessionId, env) : null;
890
+ try {
891
+ await this.launch(launchCommand(term, { cwd: dir, args, env, envFile, sessionId }));
892
+ } catch (e) {
893
+ throw new Error(`无法用 ${term.name} 打开终端:${e.message}`);
894
+ }
895
+ this.log(`opened ${term.name} in ${dir} for the session ${sessionId}${label ? ` (${label})` : ''}`);
896
+ return { terminal: term.name };
897
+ }
898
+
899
+ // The program's files changed (an update, an edit of the source): a background service starts its new version
900
+ // once the files have stayed the same for a check and no command is being answered.
901
+ checkCode() {
902
+ const now = codeFingerprint();
903
+ if (now === this.code) { this.pendingCode = null; return; }
904
+ if (!this.background) {
905
+ if (!this.toldCode) this.log("claude-pro's files changed: restart `claude-pro host` to run the new version");
906
+ this.toldCode = true;
907
+ return;
908
+ }
909
+ if (now !== this.pendingCode) { this.pendingCode = now; return; }
910
+ this.reloadWanted = true;
911
+ if (!this.inflight) this.reload();
912
+ }
913
+
914
+ reload() {
915
+ this.reloading = true;
916
+ this.stop();
917
+ }
918
+
919
+ stop() {
920
+ if (this.stopped) return;
921
+ this.stopped = true;
922
+ for (const t of this.timers) clearInterval(t);
923
+ this.streamAbort?.abort();
924
+ this.wakeUp();
925
+ }
926
+ }
927
+
928
+ // The program's files as they are now (names, sizes, times): another value means another version.
929
+ export function codeFingerprint(root = INSTALL_DIR) {
930
+ const hash = crypto.createHash('sha1');
931
+ for (const dir of ['bin', 'src']) {
932
+ let names = [];
933
+ try { names = fs.readdirSync(path.join(root, dir), { recursive: true }).map(String).filter((n) => /\.(m?js|json)$/i.test(n)).sort(); } catch { /* none */ }
934
+ for (const n of names) {
935
+ try {
936
+ const st = fs.statSync(path.join(root, dir, n));
937
+ hash.update(`${dir}/${n}:${st.size}:${st.mtimeMs}\n`);
938
+ } catch { /* gone meanwhile */ }
939
+ }
940
+ }
941
+ try { hash.update(fs.readFileSync(path.join(root, 'package.json'))); } catch { /* none */ }
942
+ return hash.digest('base64');
943
+ }
944
+
945
+ // How busy this computer is, for the page: {cpu (percent, the last minute, all cores), memUsed, memTotal, diskFree,
946
+ // diskTotal (bytes; the disk of the home directory), uptime (seconds)}. The CPU is sampled every 5 seconds.
947
+ export class Stats {
948
+ constructor(home = os.homedir()) {
949
+ this.home = home;
950
+ this.samples = [];
951
+ this.sample();
952
+ }
953
+
954
+ sample() {
955
+ let idle = 0;
956
+ let total = 0;
957
+ for (const c of os.cpus()) {
958
+ idle += c.times.idle;
959
+ total += c.times.user + c.times.nice + c.times.sys + c.times.idle + c.times.irq;
960
+ }
961
+ this.samples.push({ at: Date.now(), idle, total });
962
+ while (this.samples.length > 2 && Date.now() - this.samples[1].at >= 60_000) this.samples.shift();
963
+ }
964
+
965
+ now() {
966
+ const first = this.samples[0];
967
+ const last = this.samples[this.samples.length - 1];
968
+ const busy = last && first && last.total > first.total ? 1 - (last.idle - first.idle) / (last.total - first.total) : 0;
969
+ let diskFree = null;
970
+ let diskTotal = null;
971
+ try {
972
+ const s = fs.statfsSync(this.home);
973
+ diskFree = s.bavail * s.bsize;
974
+ diskTotal = s.blocks * s.bsize;
975
+ } catch { /* unknown */ }
976
+ return {
977
+ cpu: Math.round(Math.max(0, Math.min(1, busy)) * 1000) / 10,
978
+ memUsed: os.totalmem() - os.freemem(),
979
+ memTotal: os.totalmem(),
980
+ diskFree,
981
+ diskTotal,
982
+ uptime: Math.round(os.uptime()),
983
+ };
984
+ }
985
+ }
986
+
987
+ // `claude-pro host check`: the code of this version loads (the service's, and a session's). A service that runs
988
+ // asks this before it hands over to a new version (see runHost).
989
+ export async function checkCommand() {
990
+ await import('./background.js');
991
+ await import('./ui/repl.js');
992
+ await import('./main.js');
993
+ process.stdout.write(`claude-pro ${VERSION} loads\n`);
994
+ return 0;
995
+ }
996
+
997
+ // Whether the code now on disk starts: `host check` in a process of its own. null, or what went wrong.
998
+ function newVersionFails() {
999
+ const r = spawnSync(process.execPath, [ENTRY, 'host', 'check'], { cwd: os.homedir(), env: serviceEnv(), windowsHide: true, encoding: 'utf8', timeout: 60_000 });
1000
+ if (r.status === 0) return null;
1001
+ const said = `${r.stderr || ''}${r.stdout || ''}`.trim().split(/\r?\n/).filter(Boolean).slice(-6).join(' | ');
1002
+ return said || r.error?.message || `exit code ${r.status}`;
1003
+ }
1004
+
1005
+ // `claude-pro host run [--background]`: the service, until it is stopped. Returns the exit code.
1006
+ //
1007
+ // When the program's files change (an update, an edit of the source), a background service hands over to the new
1008
+ // version, carefully: this machine must not lose the web page's control. The new code is checked first (`host
1009
+ // check`); when it does not load, this one goes on (and says why in the log) until the files change again. When it
1010
+ // does, the new service is started and this one leaves once it runs; when it does not come up, this one takes over
1011
+ // again. The background sessions run on through it all (each is a process of its own, taken over by the next one).
1012
+ export async function runHost({ background = false } = {}) {
1013
+ for (const k of SESSION_ONLY) delete process.env[k];
1014
+ // its log: host.log (where the web page reads it, see logs), and in the foreground the terminal too
1015
+ const toFile = fileLogger();
1016
+ const toTerminal = background ? null : consoleLogger();
1017
+ const log = (msg) => { toFile(msg); toTerminal?.(msg); };
1018
+ if (!takeLock()) {
1019
+ (toTerminal || toFile)(`claude-pro host runs already (pid ${readHostState().pid || '?'}): this one stops`);
1020
+ return background ? 0 : 1;
1021
+ }
1022
+ const sessions = new BackgroundSessions({ dir: configDir(), entry: ENTRY, env: serviceEnv(), log });
1023
+ let service = null;
1024
+ const stop = () => service?.stop();
1025
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, stop);
1026
+ sessions.start();
1027
+ for (;;) {
1028
+ service = new HostService({ id: hostId(), log, background, sessions });
1029
+ sessions.onChange = () => service.reportState();
1030
+ log(`claude-pro host ${VERSION} started (pid ${process.pid}${background ? ', in the background' : ''}; terminal: ${service.terminal?.name || 'none found'})`);
1031
+ try {
1032
+ await service.run();
1033
+ } catch (e) {
1034
+ log(`the service stopped on an error: ${e.stack || e.message}`);
1035
+ }
1036
+ if (!service.reloading) break;
1037
+ const failure = newVersionFails();
1038
+ if (failure) {
1039
+ log(`the new version does not start, this one goes on: ${failure}`);
1040
+ continue;
1041
+ }
1042
+ log('the program changed: starting its new version');
1043
+ sessions.close();
1044
+ releaseLock();
1045
+ if (readHostState().pid === process.pid) updateHostState({ pid: undefined, beat: undefined, online: false });
1046
+ const pid = startHostInBackground();
1047
+ let handedOver = false;
1048
+ for (let t = 0; t < 30_000 && !handedOver; t += 500) {
1049
+ await sleep(500);
1050
+ const s = readHostState();
1051
+ handedOver = Boolean(pid && s.pid === pid && hostRunning(s));
1052
+ }
1053
+ if (handedOver) { log(`the new version runs (pid ${pid}): this one leaves`); return 0; }
1054
+ if (!takeLock()) { log('the new version has the lock but did not report yet: this one leaves'); return 0; }
1055
+ log(`the new version did not come up (pid ${pid}), this one goes on; see the lines above`);
1056
+ sessions.start();
1057
+ }
1058
+ sessions.close();
1059
+ releaseLock();
1060
+ if (readHostState().pid === process.pid) updateHostState({ pid: undefined, beat: undefined, online: false });
1061
+ log('stopped');
1062
+ return 0;
1063
+ }
1064
+
1065
+ // ---------------------------------------------------------------- start, stop, status
1066
+
1067
+ async function gatewayRequest(method, route) {
1068
+ const cfg = loadConfig({ cwd: os.homedir() });
1069
+ const login = readGatewayLogin(cfg.gatewayUrl);
1070
+ if (!login) return false;
1071
+ const res = await fetch(`${normalizeGatewayUrl(login.url || cfg.gatewayUrl)}${route}`, { method, headers: { authorization: `Bearer ${login.apiKey}` }, signal: AbortSignal.timeout(8000) });
1072
+ return res.ok || res.status === 404;
1073
+ }
1074
+
1075
+ async function startCommand() {
1076
+ const state = readHostState();
1077
+ if (hostRunning(state)) {
1078
+ console.log(`claude-pro host is running already (pid ${state.pid}).`);
1079
+ return 0;
1080
+ }
1081
+ updateHostState({ disabled: undefined, spawnedAt: Date.now() });
1082
+ const pid = startHostInBackground();
1083
+ for (let i = 0; i < 30; i++) {
1084
+ await sleep(200);
1085
+ const now = readHostState();
1086
+ if (hostRunning(now)) {
1087
+ const cfg = loadConfig({ cwd: os.homedir() });
1088
+ const login = readGatewayLogin(cfg.gatewayUrl);
1089
+ console.log(`claude-pro host started in the background (pid ${now.pid}). Log: ${hostFiles().log}`);
1090
+ if (!login) console.log(`This computer is not logged in to the gateway ${cfg.gatewayUrl}: it waits until /login in a session.`);
1091
+ return 0;
1092
+ }
1093
+ }
1094
+ console.log(`claude-pro host was started (pid ${pid}) but has not reported yet: see ${hostFiles().log}`);
1095
+ return 1;
1096
+ }
1097
+
1098
+ async function stopCommand() {
1099
+ const state = readHostState();
1100
+ const running = hostRunning(state);
1101
+ updateHostState({ disabled: true });
1102
+ if (running) {
1103
+ try { process.kill(state.pid); } catch { /* gone already */ }
1104
+ for (let i = 0; i < 25 && pidAlive(state.pid); i++) await sleep(200);
1105
+ releaseLock(state.pid);
1106
+ }
1107
+ // again: a heartbeat between the first write and the end of the process clears it
1108
+ updateHostState({ disabled: true, pid: undefined, beat: undefined, online: false });
1109
+ let removed = false;
1110
+ if (state.id) removed = await gatewayRequest('DELETE', `/v1/remote/hosts/${encodeURIComponent(state.id)}`).catch(() => false);
1111
+ 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.' : ''}`);
1112
+ console.log('Sessions no longer start it by themselves: `claude-pro host start` does.');
1113
+ return 0;
1114
+ }
1115
+
1116
+ function statusCommand() {
1117
+ const state = readHostState();
1118
+ const running = hostRunning(state);
1119
+ const auto = installedAutostart();
1120
+ const boot = bootAutostartInstalled();
1121
+ const lines = [
1122
+ `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)'}`,
1123
+ ];
1124
+ 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)'}`);
1125
+ if (state.id) lines.push(` id: ${state.id}${state.machine ? ` · computer: ${state.machine}` : ''}${state.terminal ? ` · opens: ${state.terminal}` : ''}${state.version ? ` · version ${state.version}` : ''}`);
1126
+ lines.push(` log: ${hostFiles().log}`);
1127
+ lines.push(` starts by itself: ${boot ? `at boot, before anyone logs in (${process.platform === 'win32' ? `scheduled task "${bootTaskName()}"` : 'systemd user service, lingering'})` : auto ? `at logon (${auto})` : 'no (claude-pro host install; --at-boot: before anyone logs in)'}${boot || auto ? ' · claude-pro host uninstall stops that' : ''}`);
1128
+ console.log(lines.join('\n'));
1129
+ return 0;
1130
+ }
1131
+
1132
+ // ---------------------------------------------------------------- starting by itself: at logon, at boot
1133
+ //
1134
+ // By default the service starts when the user logs in (Windows: a script in the Startup folder, without a window;
1135
+ // macOS: a LaunchAgent; Linux: a desktop autostart entry, else a systemd user service). `host install --at-boot`:
1136
+ // already when the computer starts, before anyone logs in (Windows: a scheduled task "at startup" that runs as the
1137
+ // user whether logged on or not, S4U: no password kept, no network shares; Linux: the systemd user service with
1138
+ // lingering; macOS: not without root, so at logon). A session logged in to the gateway, /login and `claude-pro
1139
+ // connect` set up the start at logon by themselves (ensureAutostart), unless `host uninstall` said no.
1140
+
1141
+ 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)}` : '');
1142
+
1143
+ // Where `host install` puts what starts it at logon, by platform (two kinds on Linux: a desktop's autostart, else a
1144
+ // systemd user service).
1145
+ export function autostartFiles({ platform = process.platform, env = process.env, home = os.homedir() } = {}) {
1146
+ const s = suffix();
1147
+ if (platform === 'win32') return [path.join(env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', `claude-pro-host${s}.vbs`)];
1148
+ if (platform === 'darwin') return [path.join(home, 'Library', 'LaunchAgents', `com.claude-pro.host${s}.plist`)];
1149
+ const config = env.XDG_CONFIG_HOME || path.join(home, '.config');
1150
+ return [path.join(config, 'autostart', `claude-pro-host${s}.desktop`), path.join(config, 'systemd', 'user', `claude-pro-host${s}.service`)];
1151
+ }
1152
+
1153
+ export const bootTaskName = () => `claude-pro host${suffix()}`;
1154
+
1155
+ // How the service starts by itself: 'boot' (before anyone logs in, host install --at-boot), 'logon', or ''.
1156
+ export function autostartKind() {
1157
+ if (bootAutostartInstalled()) return 'boot';
1158
+ return installedAutostart() ? 'logon' : '';
1159
+ }
1160
+
1161
+ let bootKnown = { at: 0, value: false };
1162
+ function bootAutostartInstalled() {
1163
+ if (Date.now() - bootKnown.at < 60_000) return bootKnown.value;
1164
+ let value = false;
1165
+ if (process.platform === 'win32') {
1166
+ value = spawnSync('schtasks', ['/Query', '/TN', bootTaskName()], { windowsHide: true, stdio: 'ignore' }).status === 0;
1167
+ } else if (process.platform === 'linux') {
1168
+ const unit = autostartFiles()[1];
1169
+ const linger = spawnSync('loginctl', ['show-user', os.userInfo().username, '-p', 'Linger'], { encoding: 'utf8' });
1170
+ value = fs.existsSync(unit) && /Linger=yes/.test(linger.stdout || '');
1171
+ }
1172
+ bootKnown = { at: Date.now(), value };
1173
+ return value;
1174
+ }
1175
+
1176
+ function installedAutostart() {
1177
+ return autostartFiles().find((f) => fs.existsSync(f)) || null;
1178
+ }
1179
+
1180
+ // What runs at logon: `claude-pro host start`, with the config directory when it is not the default one.
1181
+ function startCommandLine(sub = ['host', 'start']) {
1182
+ const env = process.env.CLAUDE_PRO_CONFIG_DIR ? { CLAUDE_PRO_CONFIG_DIR: path.resolve(process.env.CLAUDE_PRO_CONFIG_DIR) } : {};
1183
+ return { program: [process.execPath, ENTRY, ...sub], env };
1184
+ }
1185
+
1186
+ const xml = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
1187
+
1188
+ // The start at logon, set up: {file, note}.
1189
+ export function installLogonAutostart() {
1190
+ const { program, env } = startCommandLine();
1191
+ const [desktop, service] = autostartFiles();
1192
+ let file;
1193
+ let note = '';
1194
+ if (process.platform === 'win32') {
1195
+ file = desktop;
1196
+ const vbs = (s) => `"${String(s).replace(/"/g, '""')}"`;
1197
+ const text = [
1198
+ "' claude-pro: starts its computer service (claude-pro host) at logon, without a window.",
1199
+ "' `claude-pro host uninstall` removes this file.",
1200
+ 'Set shell = CreateObject("WScript.Shell")',
1201
+ ...Object.entries(env).map(([k, v]) => `shell.Environment("PROCESS")(${vbs(k)}) = ${vbs(v)}`),
1202
+ `shell.Run ${vbs(program.map(quoteWindowsArg).join(' '))}, 0, False`,
1203
+ '',
1204
+ ].join('\r\n');
1205
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1206
+ fs.writeFileSync(file, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(text, 'utf16le')])); // UTF-16: any user name
1207
+ } else if (process.platform === 'darwin') {
1208
+ file = desktop;
1209
+ const label = path.basename(file, '.plist');
1210
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
1211
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1212
+ <plist version="1.0">
1213
+ <dict>
1214
+ <key>Label</key><string>${xml(label)}</string>
1215
+ <key>ProgramArguments</key>
1216
+ <array>${program.map((a) => `<string>${xml(a)}</string>`).join('')}</array>
1217
+ <key>RunAtLoad</key><true/>
1218
+ <key>AbandonProcessGroup</key><true/>
1219
+ <key>EnvironmentVariables</key>
1220
+ <dict>${Object.entries({ PATH: process.env.PATH || '', ...env }).map(([k, v]) => `<key>${xml(k)}</key><string>${xml(v)}</string>`).join('')}</dict>
1221
+ </dict>
1222
+ </plist>
1223
+ `;
1224
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1225
+ fs.writeFileSync(file, plist);
1226
+ spawnSync('launchctl', ['unload', file], { stdio: 'ignore' });
1227
+ spawnSync('launchctl', ['load', '-w', file], { stdio: 'ignore' });
1228
+ } else if (process.env.DISPLAY || process.env.WAYLAND_DISPLAY) {
1229
+ file = desktop;
1230
+ const q = (s) => `"${String(s).replace(/(["`$\\])/g, '\\$1')}"`;
1231
+ const exec = [...(Object.keys(env).length ? ['env', ...Object.entries(env).map(([k, v]) => `${k}=${v}`)] : []), ...program].map(q).join(' ');
1232
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1233
+ 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`);
1234
+ } else {
1235
+ file = service;
1236
+ note = writeSystemdUnit(service);
1237
+ }
1238
+ bootKnown.at = 0;
1239
+ return { file, note };
1240
+ }
1241
+
1242
+ // Linux: the systemd user service (Type=oneshot + RemainAfterExit: the service's process stays in its cgroup).
1243
+ function writeSystemdUnit(file) {
1244
+ const { program, env } = startCommandLine();
1245
+ const q = (s) => `"${String(s).replace(/(["\\])/g, '\\$1')}"`;
1246
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1247
+ 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`);
1248
+ const daemon = spawnSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'ignore' });
1249
+ const enabled = spawnSync('systemctl', ['--user', 'enable', path.basename(file)], { stdio: 'ignore' });
1250
+ return daemon.status === 0 && enabled.status === 0 ? ' (systemd user service)' : ' (systemctl --user did not take it: enable it by hand)';
1251
+ }
1252
+
1253
+ // Windows: the scheduled task that starts the service at boot, as this user, logged on or not (S4U).
1254
+ export function bootTaskXml({ user = `${process.env.USERDOMAIN || os.hostname()}\\${os.userInfo().username}`, home = os.homedir() } = {}) {
1255
+ const { program, env } = startCommandLine(['host', 'run', '--background']);
1256
+ let command = program[0];
1257
+ let args = program.slice(1).map(quoteWindowsArg).join(' ');
1258
+ if (Object.keys(env).length) { // a task cannot set variables: cmd does
1259
+ command = process.env.ComSpec || 'cmd.exe';
1260
+ args = `/d /c "${Object.entries(env).map(([k, v]) => `set "${k}=${v}"&& `).join('')}${program.map(quoteWindowsArg).join(' ')}"`;
1261
+ }
1262
+ return `<?xml version="1.0" encoding="UTF-16"?>
1263
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
1264
+ <RegistrationInfo><Description>claude-pro host: lets the gateway's web page use this computer (claude-pro host uninstall removes it)</Description></RegistrationInfo>
1265
+ <Triggers><BootTrigger><Enabled>true</Enabled></BootTrigger></Triggers>
1266
+ <Principals><Principal id="Author"><UserId>${xml(user)}</UserId><LogonType>S4U</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
1267
+ <Settings>
1268
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
1269
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
1270
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
1271
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
1272
+ <StartWhenAvailable>true</StartWhenAvailable>
1273
+ <RestartOnFailure><Interval>PT1M</Interval><Count>3</Count></RestartOnFailure>
1274
+ <Hidden>true</Hidden>
1275
+ <Enabled>true</Enabled>
1276
+ </Settings>
1277
+ <Actions Context="Author"><Exec><Command>${xml(command)}</Command><Arguments>${xml(args)}</Arguments><WorkingDirectory>${xml(home)}</WorkingDirectory></Exec></Actions>
1278
+ </Task>
1279
+ `;
1280
+ }
1281
+
1282
+ // The start at boot, set up: a line saying how. Throws what to do when it cannot be (no administrator rights).
1283
+ export function installBootAutostart() {
1284
+ bootKnown.at = 0;
1285
+ if (process.platform === 'win32') {
1286
+ const file = path.join(os.tmpdir(), `claude-pro-boot-task-${process.pid}.xml`);
1287
+ fs.writeFileSync(file, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(bootTaskXml(), 'utf16le')]));
1288
+ try {
1289
+ const r = spawnSync('schtasks', ['/Create', '/TN', bootTaskName(), '/XML', file, '/F'], { windowsHide: true, encoding: 'latin1' });
1290
+ if (r.status !== 0) {
1291
+ throw new Error(`Windows did not create the scheduled task (schtasks exit code ${r.status}). It takes an administrator: run \`claude-pro host install --at-boot\` again in a terminal started with "Run as administrator". (Without a password kept, the service cannot use network shares; it does not need them.)`);
1292
+ }
1293
+ } finally {
1294
+ fs.rmSync(file, { force: true });
1295
+ }
1296
+ return `a scheduled task "${bootTaskName()}" starts it when Windows starts, as ${os.userInfo().username}, logged on or not`;
1297
+ }
1298
+ if (process.platform === 'linux') {
1299
+ const note = writeSystemdUnit(autostartFiles()[1]);
1300
+ const user = os.userInfo().username;
1301
+ const linger = spawnSync('loginctl', ['enable-linger', user], { stdio: 'ignore' });
1302
+ if (linger.status !== 0) throw new Error(`The systemd user service is set up${note}, but lingering is not on, so it starts only once ${user} logs in: run \`sudo loginctl enable-linger ${user}\`.`);
1303
+ return `the systemd user service starts it at boot (lingering is on for ${user})`;
1304
+ }
1305
+ throw new Error('On macOS a program starts before anyone logs in only as a LaunchDaemon, which takes root: claude-pro starts at logon instead (a LaunchAgent). Turn on automatic login in System Settings to have it after a restart.');
1306
+ }
1307
+
1308
+ function removeBootAutostart() {
1309
+ bootKnown.at = 0;
1310
+ if (process.platform === 'win32') {
1311
+ if (spawnSync('schtasks', ['/Query', '/TN', bootTaskName()], { windowsHide: true, stdio: 'ignore' }).status !== 0) return null;
1312
+ const r = spawnSync('schtasks', ['/Delete', '/TN', bootTaskName(), '/F'], { windowsHide: true, stdio: 'ignore' });
1313
+ return r.status === 0 ? `the scheduled task "${bootTaskName()}"` : `(the scheduled task "${bootTaskName()}" could not be removed: as administrator, schtasks /Delete /TN "${bootTaskName()}" /F)`;
1314
+ }
1315
+ return null; // Linux: the unit goes with the files below; lingering may serve other services, it stays
1316
+ }
1317
+
1318
+ // For a session logged in to the gateway, /login (`force`) and `claude-pro connect`: the start at logon, set up once,
1319
+ // unless the user said no (`host uninstall`) or turned the service off (CLAUDE_PRO_HOST=0).
1320
+ export function ensureAutostart({ force = false, env = process.env } = {}) {
1321
+ if (!hostEnabled(env)) return null;
1322
+ const state = readHostState();
1323
+ if (state.autostartDeclined || (state.autostartAuto && !force)) return null;
1324
+ if (installedAutostart() || bootAutostartInstalled()) { updateHostState({ autostartAuto: new Date().toISOString() }); return null; }
1325
+ try {
1326
+ const r = installLogonAutostart();
1327
+ updateHostState({ autostartAuto: new Date().toISOString() });
1328
+ return r;
1329
+ } catch {
1330
+ return null;
1331
+ }
1332
+ }
1333
+
1334
+ async function installCommand(args = []) {
1335
+ updateHostState({ autostartDeclined: undefined, autostartAuto: new Date().toISOString() });
1336
+ if (args.includes('--at-boot')) {
1337
+ try {
1338
+ console.log(`claude-pro host starts at boot now: ${installBootAutostart()}.`);
1339
+ } catch (e) {
1340
+ console.log(e.message);
1341
+ if (process.platform !== 'darwin') return 1;
1342
+ }
1343
+ }
1344
+ if (!args.includes('--at-boot') || process.platform === 'darwin') {
1345
+ const { file, note } = installLogonAutostart();
1346
+ console.log(`claude-pro host starts at logon now: ${file}${note}`);
1347
+ }
1348
+ return startCommand();
1349
+ }
1350
+
1351
+ function uninstallCommand() {
1352
+ const removed = [];
1353
+ const task = removeBootAutostart();
1354
+ if (task) removed.push(task);
1355
+ for (const file of autostartFiles()) {
1356
+ if (!fs.existsSync(file)) continue;
1357
+ if (process.platform === 'darwin') spawnSync('launchctl', ['unload', '-w', file], { stdio: 'ignore' });
1358
+ if (file.endsWith('.service')) spawnSync('systemctl', ['--user', 'disable', path.basename(file)], { stdio: 'ignore' });
1359
+ fs.rmSync(file, { force: true });
1360
+ removed.push(file);
1361
+ }
1362
+ bootKnown.at = 0;
1363
+ updateHostState({ autostartDeclined: true }); // sessions and /login do not set it up again
1364
+ console.log(removed.length ? `Removed ${removed.join(', ')}` : 'claude-pro host was not set to start by itself.');
1365
+ if (hostRunning()) console.log('It is still running now: `claude-pro host stop` stops it.');
1366
+ return 0;
1367
+ }
1368
+
1369
+ const USAGE = `Usage: claude-pro host [run | start | stop | status | install | uninstall]
1370
+
1371
+ The computer service: it makes this computer one the gateway's web page (远程控制) runs sessions on. From the
1372
+ page: new sessions here, in the directory chosen there, in the background without a window (or, when asked, in
1373
+ a terminal window); ending and restarting them; opening a conversation kept here again (history); their logs and
1374
+ its own; updating claude-pro. A background session that crashes is opened again, and after a restart of the
1375
+ computer the service opens again those that ran (the conversation, not the task that was running).
1376
+ \`claude-pro attach\` shows a background session in a terminal here.
1377
+
1378
+ It uses the gateway login of /login or claude-pro connect, and only connects out to the gateway. A session
1379
+ logged in to the gateway starts it by itself, and /login and connect set it up to start at logon
1380
+ (CLAUDE_PRO_HOST=0: neither).
1381
+
1382
+ claude-pro host Run it here, in the foreground (Ctrl+C stops it)
1383
+ claude-pro host start Run it in the background (log: ~/.claude-pro/host.log)
1384
+ claude-pro host stop Stop it and take this computer off the gateway's list (sessions then no longer start it)
1385
+ claude-pro host status Whether it runs, its id, its log
1386
+ claude-pro host install Start it at logon (Windows: a script in the Startup folder; macOS: a LaunchAgent;
1387
+ Linux: a desktop autostart entry, else a systemd user service). /login and
1388
+ claude-pro connect do this by themselves
1389
+ claude-pro host install --at-boot
1390
+ Start it when the computer starts, before anyone logs in (Windows: a scheduled
1391
+ task, as administrator; Linux: lingering; macOS: not possible, at logon instead)
1392
+ claude-pro host uninstall Not by itself any more (sessions and /login do not set it up again)
1393
+ `;
1394
+
1395
+ // `claude-pro host ...`: returns the exit code (`run` ends the process itself once the service has stopped).
1396
+ export async function hostCommand(args = []) {
1397
+ const [sub = 'run', ...rest] = args;
1398
+ switch (sub) {
1399
+ case 'run': process.exit(await runHost({ background: rest.includes('--background') })); break;
1400
+ case 'check': return checkCommand();
1401
+ case 'start': return startCommand();
1402
+ case 'stop': return stopCommand();
1403
+ case 'status': return statusCommand();
1404
+ case 'install': return installCommand(rest);
1405
+ case 'uninstall': return uninstallCommand();
1406
+ case 'help': case '-h': case '--help': process.stdout.write(USAGE); return 0;
1407
+ default: process.stderr.write(`Unknown host command: ${sub}\n\n${USAGE}`); return 2;
1408
+ }
1409
+ return 0;
1410
+ }