@yanzc/claude-pro 0.7.8 → 0.9.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/README.md +37 -58
- package/package.json +1 -1
- package/src/agent.js +127 -25
- package/src/cache.js +18 -0
- package/src/commands.js +24 -28
- package/src/config.js +8 -2
- package/src/filestate.js +1 -1
- package/src/keepalive.js +129 -0
- package/src/main.js +12 -39
- package/src/mcp.js +58 -13
- package/src/peers.js +6 -75
- package/src/prompts.js +3 -3
- package/src/remote.js +77 -33
- package/src/runtime.js +3 -0
- package/src/session.js +48 -15
- package/src/supervisor.js +4 -6
- package/src/tools/bash.js +30 -14
- package/src/tools/files.js +366 -62
- package/src/tools/index.js +3 -1
- package/src/tools/search.js +14 -10
- package/src/tools/web.js +14 -6
- package/src/ui/ansi.js +24 -9
- package/src/ui/repl.js +314 -305
- package/src/ui/screen.js +38 -11
- package/src/updater.js +7 -3
- package/src/utils/clipboard.js +16 -75
- package/src/utils/diff.js +21 -3
- package/src/utils/dirs.js +136 -0
- package/src/utils/encoding.js +187 -0
- package/src/utils/paths.js +46 -5
- package/src/utils/shell.js +90 -19
- package/src/attach.js +0 -146
- package/src/background.js +0 -514
- package/src/connect.js +0 -79
- package/src/history.js +0 -163
- package/src/host.js +0 -1474
- package/src/ui/vterm.js +0 -62
package/src/host.js
DELETED
|
@@ -1,1474 +0,0 @@
|
|
|
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, window, logs, history, delete, 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 { gatewayLogin, normalizeGatewayUrl } from './gateway.js';
|
|
31
|
-
import { machineName, cleanName, listPeers } from './peers.js';
|
|
32
|
-
import { BackgroundSessions, markEnded, tailFile } from './background.js';
|
|
33
|
-
import { listConversations, deleteConversation, CONVERSATION_ID } 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_|CLAUDE_CODE_)/;
|
|
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. `title`: the tab's first title, where the terminal takes one (Windows Terminal).
|
|
448
|
-
export function launchCommand(term, { cwd, node = process.execPath, entry = ENTRY, args = [], env = {}, envFile = null, sessionId = '', title = '' }) {
|
|
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', ...(title ? ['--title', title] : []), '-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 || (() => {
|
|
531
|
-
const cfg = this.cfg();
|
|
532
|
-
return gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
|
|
533
|
-
});
|
|
534
|
-
this.config = null;
|
|
535
|
-
this.configAt = 0;
|
|
536
|
-
this.login = null; // {url, apiKey, account} of gateway.json
|
|
537
|
-
this.registered = false;
|
|
538
|
-
this.online = false;
|
|
539
|
-
this.stopped = false;
|
|
540
|
-
this.reloading = false;
|
|
541
|
-
this.inflight = 0;
|
|
542
|
-
this.streamAbort = null;
|
|
543
|
-
this.wake = null;
|
|
544
|
-
this.timers = [];
|
|
545
|
-
this.refusedKey = null;
|
|
546
|
-
this.lastNote = '';
|
|
547
|
-
this.recent = { at: 0, list: [] };
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
cfg() {
|
|
551
|
-
if (!this.config || Date.now() - this.configAt > 60_000) {
|
|
552
|
-
try { this.config = this.loadConfig(); } catch { this.config ??= { env: process.env, gatewayUrl: GATEWAY_DEFAULT_URL }; }
|
|
553
|
-
this.configAt = Date.now();
|
|
554
|
-
}
|
|
555
|
-
return this.config;
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
base(login = this.login) { return normalizeGatewayUrl(login?.url || this.cfg().gatewayUrl); }
|
|
559
|
-
|
|
560
|
-
// Logged once until something else happens (a gateway that is down is retried every 30 seconds).
|
|
561
|
-
note(msg) {
|
|
562
|
-
if (msg === this.lastNote) return;
|
|
563
|
-
this.lastNote = msg;
|
|
564
|
-
this.log(msg);
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
async request(method, route, body, { timeout = REQUEST_TIMEOUT_MS, login = this.login } = {}) {
|
|
568
|
-
const res = await this.fetch(`${this.base(login)}${route}`, {
|
|
569
|
-
method,
|
|
570
|
-
headers: { authorization: `Bearer ${login.apiKey}`, 'content-type': 'application/json' },
|
|
571
|
-
body: body === undefined ? undefined : JSON.stringify(body),
|
|
572
|
-
signal: AbortSignal.timeout(timeout),
|
|
573
|
-
});
|
|
574
|
-
const data = await res.json().catch(() => ({}));
|
|
575
|
-
if (!res.ok) throw Object.assign(new Error(data?.error?.message || (typeof data?.error === 'string' ? data.error : `HTTP ${res.status}`)), { status: res.status });
|
|
576
|
-
return data;
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
// What the page shows of this computer. `machine` is the name its sessions register with, so that the page puts
|
|
580
|
-
// them together.
|
|
581
|
-
info() {
|
|
582
|
-
return { id: this.id, machine: machineName(this.cfg().env), host: os.hostname(), platform: process.platform, version: VERSION, home: this.home, terminal: this.terminal?.name || '' };
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
// What the page shows of this computer now: its background sessions and how busy it is.
|
|
586
|
-
state() {
|
|
587
|
-
return { sessions: this.sessions?.list() || [], stats: this.stats.now() };
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
// The state to the gateway: soon after a change of the sessions (several changes in a row go as one), and every
|
|
591
|
-
// minute for the numbers.
|
|
592
|
-
reportState({ soon = true } = {}) {
|
|
593
|
-
if (soon) {
|
|
594
|
-
if (this.stateTimer) return;
|
|
595
|
-
this.stateTimer = setTimeout(() => { this.stateTimer = null; this.reportState({ soon: false }); }, 300);
|
|
596
|
-
this.stateTimer.unref?.();
|
|
597
|
-
return;
|
|
598
|
-
}
|
|
599
|
-
if (!this.registered || !this.login || this.stopped) return;
|
|
600
|
-
this.request('POST', `/v1/remote/hosts/${encodeURIComponent(this.id)}/state`, this.state()).catch((e) => {
|
|
601
|
-
if (e.status === 404) { this.registered = false; this.streamAbort?.abort(); } // forgotten: registered again
|
|
602
|
-
});
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
async register() {
|
|
606
|
-
try {
|
|
607
|
-
await this.request('POST', '/v1/remote/hosts', { ...this.info(), autostart: autostartKind(), ...this.state() });
|
|
608
|
-
} catch (e) {
|
|
609
|
-
if (e.status === 404) e.noHosts = true; // a gateway without computers (yet): not the one that forgot this one
|
|
610
|
-
throw e;
|
|
611
|
-
}
|
|
612
|
-
this.registered = true;
|
|
613
|
-
this.note(`registered at ${this.base()} as ${this.info().machine} (${this.id})`);
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
// Follows gateway.json: logged out, the computer leaves the page's list and the service waits for a login; with
|
|
617
|
-
// another account it leaves the old one's list and joins the new one's.
|
|
618
|
-
checkLogin() {
|
|
619
|
-
let login = null;
|
|
620
|
-
try { login = this.readLogin(); } catch { /* none */ }
|
|
621
|
-
const key = (l) => (l?.apiKey ? `${this.base(l)}\n${l.apiKey}` : '');
|
|
622
|
-
if (key(login) === key(this.login)) return;
|
|
623
|
-
const old = this.login;
|
|
624
|
-
this.login = login?.apiKey ? login : null;
|
|
625
|
-
this.registered = false;
|
|
626
|
-
if (old) {
|
|
627
|
-
this.log(this.login ? 'the gateway login changed: registering with the new one' : 'logged out of the gateway: waiting for /login');
|
|
628
|
-
this.request('DELETE', `/v1/remote/hosts/${encodeURIComponent(this.id)}`, undefined, { login: old, timeout: 5000 }).catch(() => {});
|
|
629
|
-
} else if (this.login) {
|
|
630
|
-
this.log(`logged in to the gateway ${this.base()}`);
|
|
631
|
-
}
|
|
632
|
-
// the background sessions are the account's: gone with the login, back with a login
|
|
633
|
-
if (!this.login) this.sessions?.suspendAll();
|
|
634
|
-
else this.sessions?.resumeAll();
|
|
635
|
-
this.streamAbort?.abort();
|
|
636
|
-
this.wakeUp();
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
sleep(ms) {
|
|
640
|
-
return new Promise((resolve) => {
|
|
641
|
-
let timer = null;
|
|
642
|
-
const done = () => { clearTimeout(timer); if (this.wake === done) this.wake = null; resolve(); };
|
|
643
|
-
timer = setTimeout(done, ms);
|
|
644
|
-
this.wake = done;
|
|
645
|
-
});
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
wakeUp() { this.wake?.(); }
|
|
649
|
-
|
|
650
|
-
setOnline(online) {
|
|
651
|
-
if (online === this.online) return;
|
|
652
|
-
this.online = online;
|
|
653
|
-
if (online) this.lastNote = '';
|
|
654
|
-
this.log(online ? 'online: the web page can open sessions on this computer' : 'offline');
|
|
655
|
-
this.beat();
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
beat() {
|
|
659
|
-
if (this.stopped) return;
|
|
660
|
-
updateHostState({
|
|
661
|
-
id: this.id,
|
|
662
|
-
pid: process.pid,
|
|
663
|
-
version: VERSION,
|
|
664
|
-
startedAt: this.startedAt,
|
|
665
|
-
beat: Date.now(),
|
|
666
|
-
online: this.online,
|
|
667
|
-
gateway: this.login ? this.base() : null,
|
|
668
|
-
account: this.login?.account?.email || this.login?.account?.name || null,
|
|
669
|
-
machine: this.info().machine,
|
|
670
|
-
terminal: this.terminal?.name || '',
|
|
671
|
-
background: this.background,
|
|
672
|
-
disabled: undefined,
|
|
673
|
-
spawnedAt: undefined,
|
|
674
|
-
});
|
|
675
|
-
}
|
|
676
|
-
|
|
677
|
-
// Until stop(): resolves when the service has stopped (or stops to start its new version: `reloading`).
|
|
678
|
-
async run() {
|
|
679
|
-
this.startedAt = new Date().toISOString();
|
|
680
|
-
this.code = codeFingerprint();
|
|
681
|
-
this.checkLogin();
|
|
682
|
-
if (!this.login) this.log(`not logged in to the gateway ${this.base()}: waiting for /login`);
|
|
683
|
-
this.beat();
|
|
684
|
-
this.timers.push(
|
|
685
|
-
setInterval(() => this.beat(), BEAT_MS),
|
|
686
|
-
setInterval(() => this.checkLogin(), LOGIN_CHECK_MS),
|
|
687
|
-
setInterval(() => this.checkCode(), CODE_CHECK_MS),
|
|
688
|
-
setInterval(() => this.reportState({ soon: false }), STATE_MS),
|
|
689
|
-
setInterval(() => this.stats.sample(), 5000),
|
|
690
|
-
);
|
|
691
|
-
for (const t of this.timers) t.unref?.();
|
|
692
|
-
try { await this.loop(); } finally { for (const t of this.timers) clearInterval(t); clearTimeout(this.stateTimer); }
|
|
693
|
-
}
|
|
694
|
-
|
|
695
|
-
async loop() {
|
|
696
|
-
let wait = 1000;
|
|
697
|
-
while (!this.stopped) {
|
|
698
|
-
// without a login, or with a key the gateway refused (tried again every 10 minutes): a new login helps
|
|
699
|
-
const refused = this.login && this.refusedKey === this.login.apiKey && Date.now() - this.refusedAt < 10 * 60_000;
|
|
700
|
-
if (!this.login || refused) {
|
|
701
|
-
this.setOnline(false);
|
|
702
|
-
await this.sleep(this.login ? 60_000 : 30_000);
|
|
703
|
-
continue;
|
|
704
|
-
}
|
|
705
|
-
try {
|
|
706
|
-
if (!this.registered) await this.register();
|
|
707
|
-
await this.listen();
|
|
708
|
-
wait = 1000;
|
|
709
|
-
} catch (e) {
|
|
710
|
-
if (e.noHosts) { this.note(`the gateway ${this.base()} does not take computers (yet): trying again every 5 minutes`); wait = 5 * 60_000; }
|
|
711
|
-
else if (e.status === 404) this.registered = false; // the gateway forgot this computer (it restarted): register again
|
|
712
|
-
else if (e.status === 401 || e.status === 403) {
|
|
713
|
-
this.refusedKey = this.login?.apiKey;
|
|
714
|
-
this.refusedAt = Date.now();
|
|
715
|
-
this.registered = false;
|
|
716
|
-
// removed on the web page, or its key revoked: its background sessions end (kept to be opened again)
|
|
717
|
-
this.note(`这台电脑已从网页上移除 (the gateway refused this computer's key: ${e.message}); waiting for /login or claude-pro connect`);
|
|
718
|
-
this.sessions?.suspendAll();
|
|
719
|
-
}
|
|
720
|
-
else if (!this.stopped && e.name !== 'AbortError') this.note(`cannot reach the gateway ${this.base()}: ${e.message}`);
|
|
721
|
-
}
|
|
722
|
-
this.setOnline(false);
|
|
723
|
-
if (this.stopped) break;
|
|
724
|
-
await this.sleep(wait);
|
|
725
|
-
wait = Math.min(wait * 2, 30_000);
|
|
726
|
-
}
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
// The command stream, open until the gateway ends it, it stays silent too long, or abort().
|
|
730
|
-
async listen() {
|
|
731
|
-
const abort = new AbortController();
|
|
732
|
-
this.streamAbort = abort;
|
|
733
|
-
const res = await this.fetch(`${this.base()}/v1/remote/hosts/${encodeURIComponent(this.id)}/commands`, {
|
|
734
|
-
headers: { authorization: `Bearer ${this.login.apiKey}`, accept: 'text/event-stream' },
|
|
735
|
-
signal: abort.signal,
|
|
736
|
-
});
|
|
737
|
-
if (!res.ok) {
|
|
738
|
-
res.body?.cancel().catch(() => {});
|
|
739
|
-
throw Object.assign(new Error(`HTTP ${res.status}`), { status: res.status });
|
|
740
|
-
}
|
|
741
|
-
this.setOnline(true);
|
|
742
|
-
let last = Date.now();
|
|
743
|
-
const watchdog = setInterval(() => { if (Date.now() - last > STREAM_SILENCE_MS) abort.abort(); }, 5000);
|
|
744
|
-
try {
|
|
745
|
-
const decoder = new TextDecoder();
|
|
746
|
-
let buf = '';
|
|
747
|
-
for await (const chunk of res.body) {
|
|
748
|
-
last = Date.now();
|
|
749
|
-
buf += decoder.decode(chunk, { stream: true });
|
|
750
|
-
let i;
|
|
751
|
-
while ((i = buf.search(/\r?\n\r?\n/)) >= 0) {
|
|
752
|
-
const block = buf.slice(0, i);
|
|
753
|
-
buf = buf.slice(i).replace(/^\r?\n\r?\n/, '');
|
|
754
|
-
const data = block.split(/\r?\n/).filter((l) => l.startsWith('data:')).map((l) => l.slice(5).replace(/^ /, '')).join('\n');
|
|
755
|
-
if (!data) continue;
|
|
756
|
-
let cmd;
|
|
757
|
-
try { cmd = JSON.parse(data); } catch { continue; }
|
|
758
|
-
this.command(cmd);
|
|
759
|
-
}
|
|
760
|
-
}
|
|
761
|
-
} catch (e) {
|
|
762
|
-
if (!abort.signal.aborted) throw e;
|
|
763
|
-
} finally {
|
|
764
|
-
clearInterval(watchdog);
|
|
765
|
-
if (this.streamAbort === abort) this.streamAbort = null;
|
|
766
|
-
}
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
async command(cmd) {
|
|
770
|
-
if (!cmd || typeof cmd.cid !== 'string' || !cmd.cid) return;
|
|
771
|
-
const login = this.login;
|
|
772
|
-
this.inflight++;
|
|
773
|
-
let result;
|
|
774
|
-
try {
|
|
775
|
-
const body = cmd.body && typeof cmd.body === 'object' ? cmd.body : {};
|
|
776
|
-
let r;
|
|
777
|
-
if (cmd.type === 'list') r = await this.list(body);
|
|
778
|
-
else if (cmd.type === 'open') r = await this.open(body);
|
|
779
|
-
else if (cmd.type === 'stop') r = await this.needSessions().stop(String(body.sessionId || ''));
|
|
780
|
-
else if (cmd.type === 'restart') r = await this.needSessions().restart(String(body.sessionId || ''));
|
|
781
|
-
else if (cmd.type === 'logs') r = this.logs(body);
|
|
782
|
-
else if (cmd.type === 'history') r = this.history(body);
|
|
783
|
-
else if (cmd.type === 'update') r = await this.update();
|
|
784
|
-
else if (cmd.type === 'window') r = await this.window(body);
|
|
785
|
-
else if (cmd.type === 'delete') r = await this.deleteConversation(body);
|
|
786
|
-
else throw new Error(`这台电脑上的 claude-pro ${VERSION} 不认识命令 ${cmd.type},请升级`);
|
|
787
|
-
result = { cid: cmd.cid, ok: true, ...r };
|
|
788
|
-
} catch (e) {
|
|
789
|
-
result = { cid: cmd.cid, ok: false, error: e.message };
|
|
790
|
-
} finally {
|
|
791
|
-
this.inflight--;
|
|
792
|
-
}
|
|
793
|
-
if (login) {
|
|
794
|
-
try {
|
|
795
|
-
await this.request('POST', `/v1/remote/hosts/${encodeURIComponent(this.id)}/results`, result, { login });
|
|
796
|
-
} catch (e) {
|
|
797
|
-
this.note(`could not send the result of ${cmd.type}: ${e.message}`);
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
if (this.reloadWanted && !this.inflight) this.reload();
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
list(body) {
|
|
804
|
-
return listDirectory(typeof body.path === 'string' ? body.path : '', {
|
|
805
|
-
home: this.home,
|
|
806
|
-
recent: () => {
|
|
807
|
-
if (Date.now() - this.recent.at > 30_000) this.recent = { at: Date.now(), list: recentDirectories() };
|
|
808
|
-
return this.recent.list;
|
|
809
|
-
},
|
|
810
|
-
});
|
|
811
|
-
}
|
|
812
|
-
|
|
813
|
-
// window: a background session brought to the front in a terminal window of this computer, `claude-pro attach` in
|
|
814
|
-
// it (chosen as open's terminal window is). A turn that runs goes on and shows there as it goes; the session stays
|
|
815
|
-
// the service's. Closing the window (its X included: the attach process ends) only detaches it. Each call opens
|
|
816
|
-
// another window. Without a desktop, a tmux session to attach to (`tmux attach -t claude-pro-<id>-…`).
|
|
817
|
-
async window({ sessionId } = {}) {
|
|
818
|
-
if (typeof sessionId !== 'string' || !ID.test(sessionId)) throw new Error('会话 id 不对');
|
|
819
|
-
const rec = this.sessions?.sessions.get(sessionId);
|
|
820
|
-
if (!rec) {
|
|
821
|
-
if (this.sessions?.ended.some((e) => e.sessionId === sessionId)) throw new Error('会话没有在运行');
|
|
822
|
-
throw new Error('这个会话不是这台电脑上的后台会话');
|
|
823
|
-
}
|
|
824
|
-
if (rec.state !== 'running' || !this.sessions.alive(rec)) throw new Error('会话没有在运行');
|
|
825
|
-
const label = rec.name || sessionId;
|
|
826
|
-
const term = this.terminal;
|
|
827
|
-
if (!term) throw new Error(`这台电脑没有可以打开窗口的桌面(可以在终端里运行 claude-pro attach ${label})`);
|
|
828
|
-
let cwd = rec.cwd;
|
|
829
|
-
try { if (!fs.statSync(cwd).isDirectory()) cwd = this.home; } catch { cwd = this.home; }
|
|
830
|
-
const env = passedEnv();
|
|
831
|
-
const key = `${sessionId}-w${Date.now().toString(36)}`; // its own env file and tmux session: one window more each time
|
|
832
|
-
const envFile = process.platform === 'win32' && term.kind === 'wt' ? writeEnvFile(key, env) : null;
|
|
833
|
-
try {
|
|
834
|
-
await this.launch(launchCommand(term, { cwd, args: ['attach', sessionId, '--keep-open'], env, envFile, sessionId: key, title: `${label} · claude-pro` }));
|
|
835
|
-
} catch (e) {
|
|
836
|
-
throw new Error(`无法用 ${term.name} 打开终端:${e.message}`);
|
|
837
|
-
}
|
|
838
|
-
this.log(`opened ${term.name} attached to the background session ${sessionId} (${label})`);
|
|
839
|
-
return { terminal: term.name };
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
// delete: what this computer keeps of a conversation (see history.js), for good. Open in a background session of this
|
|
843
|
-
// service, that session is ended first with `stop` (as the stop command does), else it is refused; open in a terminal,
|
|
844
|
-
// it is refused: a terminal the user works in is not closed for them. {files, bytes}
|
|
845
|
-
async deleteConversation({ conversationId, stop = false } = {}) {
|
|
846
|
-
const id = conversationId;
|
|
847
|
-
if (typeof id !== 'string' || !CONVERSATION_ID.test(id)) throw new Error('对话 id 不对');
|
|
848
|
-
const open = listPeers().filter((p) => p.conversationId === id);
|
|
849
|
-
const ours = (p) => p.kind === 'background' && this.sessions?.sessions.has(p.remoteId);
|
|
850
|
-
const terminal = open.find((p) => !ours(p) && p.kind !== 'background');
|
|
851
|
-
if (terminal) throw new Error(`这段对话正开在终端里的会话 &${terminal.name} 里:请先在那台电脑上结束它(/exit)`);
|
|
852
|
-
const other = open.find((p) => !ours(p));
|
|
853
|
-
if (other) throw new Error(`这段对话正开在会话 &${other.name} 里:先结束它`);
|
|
854
|
-
// the service's own sessions with it: those in the registry, and those starting or restarting
|
|
855
|
-
const running = [...(this.sessions?.sessions.values() || [])].filter((r) => (r.conversationId === id || open.some((p) => p.remoteId === r.sessionId)) && this.sessions.alive(r));
|
|
856
|
-
if (running.length && stop !== true) {
|
|
857
|
-
// the name it has in the registry: its record learns it only at the next tick (see BackgroundSessions.tick)
|
|
858
|
-
const name = open.find((p) => p.remoteId === running[0].sessionId)?.name || running[0].name || running[0].sessionId;
|
|
859
|
-
throw new Error(`这段对话正开在会话 &${name} 里:先结束它`);
|
|
860
|
-
}
|
|
861
|
-
// what the registry says it has open, before its record learns it at the next tick: ended with it, the session's
|
|
862
|
-
// log goes with the conversation
|
|
863
|
-
for (const r of running) r.conversationId = id;
|
|
864
|
-
for (const r of running) await this.sessions.stop(r.sessionId);
|
|
865
|
-
const logs = this.sessions ? this.sessions.forgetConversation(id) : [];
|
|
866
|
-
const r = deleteConversation({ projects: path.join(configDir(), 'projects'), id, extra: logs });
|
|
867
|
-
this.log(`deleted the conversation ${id}: ${r.files} files, ${r.bytes} bytes${running.length ? ` (its session ${running.map((x) => x.sessionId).join(', ')} ended first)` : ''}`);
|
|
868
|
-
return { files: r.files, bytes: r.bytes };
|
|
869
|
-
}
|
|
870
|
-
|
|
871
|
-
// The conversations kept on this computer (see history.js), with the session each one is open in.
|
|
872
|
-
history({ query, cwd, limit, before } = {}) {
|
|
873
|
-
if (before != null && Number.isNaN(Date.parse(before))) throw new Error('before 不是时间');
|
|
874
|
-
if (cwd != null && (typeof cwd !== 'string' || !normalizeDir(cwd, { home: this.home }))) throw new Error(`不是绝对路径:${cwd}`);
|
|
875
|
-
const open = new Map(listPeers().filter((p) => p.conversationId && p.remoteId).map((p) => [p.conversationId, p.remoteId]));
|
|
876
|
-
return listConversations({
|
|
877
|
-
projects: path.join(configDir(), 'projects'),
|
|
878
|
-
query: typeof query === 'string' ? query : '',
|
|
879
|
-
cwd: cwd ? normalizeDir(cwd, { home: this.home }) : null,
|
|
880
|
-
limit,
|
|
881
|
-
before,
|
|
882
|
-
open,
|
|
883
|
-
});
|
|
884
|
-
}
|
|
885
|
-
|
|
886
|
-
// update: a newer claude-pro from npm now (as /update). An install takes a while: it goes on after the answer,
|
|
887
|
-
// and its result goes to the log. The service and the sessions pick the new version up by themselves.
|
|
888
|
-
async update() {
|
|
889
|
-
const found = await checkForUpdate({ force: true });
|
|
890
|
-
if (found.status === 'dev') return { version: VERSION, message: `这台电脑运行的是源码目录里的 claude-pro ${VERSION}(${INSTALL_DIR}),不从 npm 更新` };
|
|
891
|
-
if (found.status === 'current') return { version: VERSION, message: `已是最新 ${VERSION}` };
|
|
892
|
-
if (found.status === 'installed') return { version: found.version, message: `已安装 ${found.version},空闲后重启` };
|
|
893
|
-
if (found.status !== 'available') throw new Error(`检查更新失败(${found.status})`);
|
|
894
|
-
this.updating ??= installUpdate(found.version).then((r) => {
|
|
895
|
-
if (r.status === 'updated' || r.status === 'installed') this.log(`installed claude-pro ${r.version}`);
|
|
896
|
-
else this.log(`could not install claude-pro ${found.version}: ${r.status}${r.error ? ` (${r.error})` : ''}`);
|
|
897
|
-
}, (e) => this.log(`could not install claude-pro ${found.version}: ${e.message}`)).finally(() => { this.updating = null; });
|
|
898
|
-
return { version: found.version, message: `正在安装 ${found.version},装好后空闲时自动重启` };
|
|
899
|
-
}
|
|
900
|
-
|
|
901
|
-
needSessions() {
|
|
902
|
-
if (!this.sessions) throw new Error('这台电脑的 claude-pro 服务不运行后台会话');
|
|
903
|
-
return this.sessions;
|
|
904
|
-
}
|
|
905
|
-
|
|
906
|
-
// The end of a log: a background session's, or the service's own. {text}
|
|
907
|
-
logs({ sessionId, lines } = {}) {
|
|
908
|
-
const n = Math.max(1, Math.min(2000, Number(lines) || 200));
|
|
909
|
-
if (sessionId) {
|
|
910
|
-
if (!ID.test(String(sessionId))) throw new Error('会话 id 不对');
|
|
911
|
-
const file = this.needSessions().logFile(sessionId);
|
|
912
|
-
if (!fs.existsSync(file) && !fs.existsSync(`${file}.1`)) throw new Error('这个会话没有日志');
|
|
913
|
-
return { text: tailFile(file, n) };
|
|
914
|
-
}
|
|
915
|
-
return { text: tailFile(hostFiles().log, n) };
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
// A new session in `cwd`, online at once as `sessionId` (and named `name`): in the background (no window, see
|
|
919
|
-
// background.js), or with `window` in a terminal window. `resume`: a conversation of this computer, opened again
|
|
920
|
-
// (where it is already open, that session is the answer: {existing: its id at the gateway}). `model`: to start with.
|
|
921
|
-
async open({ sessionId, cwd, create, name, window = true, resume = null, model = null } = {}) {
|
|
922
|
-
if (typeof sessionId !== 'string' || !ID.test(sessionId)) throw new Error('会话 id 不对');
|
|
923
|
-
if (resume != null && (typeof resume !== 'string' || !/^[0-9a-f-]{8,}$/i.test(resume))) throw new Error('对话 id 不对');
|
|
924
|
-
if (model != null && (typeof model !== 'string' || !/^[\w.:/[\]-]{1,100}$/.test(model))) throw new Error('模型名不对');
|
|
925
|
-
if (resume) {
|
|
926
|
-
const open = listPeers().find((p) => p.conversationId === resume);
|
|
927
|
-
if (open?.remoteId) return { existing: open.remoteId };
|
|
928
|
-
if (open) throw new Error(`这段对话已经在这台电脑的会话 &${open.name} 里打开了(它没有连上网关)`);
|
|
929
|
-
}
|
|
930
|
-
const dir = typeof cwd === 'string' ? normalizeDir(cwd, { home: this.home }) : null;
|
|
931
|
-
if (!dir || !String(cwd).trim()) throw new Error(`请选择一个绝对路径的目录:${cwd ?? ''}`);
|
|
932
|
-
let st = null;
|
|
933
|
-
try { st = await fsp.stat(dir); } catch (e) {
|
|
934
|
-
if (e.code !== 'ENOENT') throw new Error(describeFsError(e, dir));
|
|
935
|
-
}
|
|
936
|
-
if (!st) {
|
|
937
|
-
if (create !== true) throw new Error(`目录不存在:${dir}`);
|
|
938
|
-
try { await fsp.mkdir(dir, { recursive: true }); } catch (e) { throw new Error(`创建目录失败:${dir}(${e.message})`); }
|
|
939
|
-
} else if (!st.isDirectory()) {
|
|
940
|
-
throw new Error(`不是目录:${dir}`);
|
|
941
|
-
}
|
|
942
|
-
const label = typeof name === 'string' && name.trim() ? cleanName(name) : '';
|
|
943
|
-
if (window === false) {
|
|
944
|
-
const r = this.needSessions().open({ sessionId, cwd: dir, name: label, resume, model });
|
|
945
|
-
this.log(`opened a background session in ${dir} for ${sessionId}${label ? ` (${label})` : ''}${resume ? `, resuming ${resume}` : ''}`);
|
|
946
|
-
return { pid: r.pid };
|
|
947
|
-
}
|
|
948
|
-
const term = this.terminal;
|
|
949
|
-
if (!term) throw new Error('这台电脑上找不到能打开的终端(Windows Terminal、Terminal.app、x-terminal-emulator、gnome-terminal、konsole、xterm 或 tmux)');
|
|
950
|
-
const args = ['--remote-id', sessionId, ...(label ? ['--name', label] : []), ...(resume ? ['--resume', resume] : []), ...(model ? ['--model', model] : [])];
|
|
951
|
-
const env = passedEnv();
|
|
952
|
-
const envFile = process.platform === 'win32' && term.kind === 'wt' ? writeEnvFile(sessionId, env) : null;
|
|
953
|
-
try {
|
|
954
|
-
await this.launch(launchCommand(term, { cwd: dir, args, env, envFile, sessionId }));
|
|
955
|
-
} catch (e) {
|
|
956
|
-
throw new Error(`无法用 ${term.name} 打开终端:${e.message}`);
|
|
957
|
-
}
|
|
958
|
-
this.log(`opened ${term.name} in ${dir} for the session ${sessionId}${label ? ` (${label})` : ''}`);
|
|
959
|
-
return { terminal: term.name };
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
// The program's files changed (an update, an edit of the source): a background service starts its new version
|
|
963
|
-
// once the files have stayed the same for a check and no command is being answered.
|
|
964
|
-
checkCode() {
|
|
965
|
-
const now = codeFingerprint();
|
|
966
|
-
if (now === this.code) { this.pendingCode = null; return; }
|
|
967
|
-
if (!this.background) {
|
|
968
|
-
if (!this.toldCode) this.log("claude-pro's files changed: restart `claude-pro host` to run the new version");
|
|
969
|
-
this.toldCode = true;
|
|
970
|
-
return;
|
|
971
|
-
}
|
|
972
|
-
if (now !== this.pendingCode) { this.pendingCode = now; return; }
|
|
973
|
-
this.reloadWanted = true;
|
|
974
|
-
if (!this.inflight) this.reload();
|
|
975
|
-
}
|
|
976
|
-
|
|
977
|
-
reload() {
|
|
978
|
-
this.reloading = true;
|
|
979
|
-
this.stop();
|
|
980
|
-
}
|
|
981
|
-
|
|
982
|
-
stop() {
|
|
983
|
-
if (this.stopped) return;
|
|
984
|
-
this.stopped = true;
|
|
985
|
-
for (const t of this.timers) clearInterval(t);
|
|
986
|
-
this.streamAbort?.abort();
|
|
987
|
-
this.wakeUp();
|
|
988
|
-
}
|
|
989
|
-
}
|
|
990
|
-
|
|
991
|
-
// The program's files as they are now (names, sizes, times): another value means another version.
|
|
992
|
-
export function codeFingerprint(root = INSTALL_DIR) {
|
|
993
|
-
const hash = crypto.createHash('sha1');
|
|
994
|
-
for (const dir of ['bin', 'src']) {
|
|
995
|
-
let names = [];
|
|
996
|
-
try { names = fs.readdirSync(path.join(root, dir), { recursive: true }).map(String).filter((n) => /\.(m?js|json)$/i.test(n)).sort(); } catch { /* none */ }
|
|
997
|
-
for (const n of names) {
|
|
998
|
-
try {
|
|
999
|
-
const st = fs.statSync(path.join(root, dir, n));
|
|
1000
|
-
hash.update(`${dir}/${n}:${st.size}:${st.mtimeMs}\n`);
|
|
1001
|
-
} catch { /* gone meanwhile */ }
|
|
1002
|
-
}
|
|
1003
|
-
}
|
|
1004
|
-
try { hash.update(fs.readFileSync(path.join(root, 'package.json'))); } catch { /* none */ }
|
|
1005
|
-
return hash.digest('base64');
|
|
1006
|
-
}
|
|
1007
|
-
|
|
1008
|
-
// How busy this computer is, for the page: {cpu (percent, the last minute, all cores), memUsed, memTotal, diskFree,
|
|
1009
|
-
// diskTotal (bytes; the disk of the home directory), uptime (seconds)}. The CPU is sampled every 5 seconds.
|
|
1010
|
-
export class Stats {
|
|
1011
|
-
constructor(home = os.homedir()) {
|
|
1012
|
-
this.home = home;
|
|
1013
|
-
this.samples = [];
|
|
1014
|
-
this.sample();
|
|
1015
|
-
}
|
|
1016
|
-
|
|
1017
|
-
sample() {
|
|
1018
|
-
let idle = 0;
|
|
1019
|
-
let total = 0;
|
|
1020
|
-
for (const c of os.cpus()) {
|
|
1021
|
-
idle += c.times.idle;
|
|
1022
|
-
total += c.times.user + c.times.nice + c.times.sys + c.times.idle + c.times.irq;
|
|
1023
|
-
}
|
|
1024
|
-
this.samples.push({ at: Date.now(), idle, total });
|
|
1025
|
-
while (this.samples.length > 2 && Date.now() - this.samples[1].at >= 60_000) this.samples.shift();
|
|
1026
|
-
}
|
|
1027
|
-
|
|
1028
|
-
now() {
|
|
1029
|
-
const first = this.samples[0];
|
|
1030
|
-
const last = this.samples[this.samples.length - 1];
|
|
1031
|
-
const busy = last && first && last.total > first.total ? 1 - (last.idle - first.idle) / (last.total - first.total) : 0;
|
|
1032
|
-
let diskFree = null;
|
|
1033
|
-
let diskTotal = null;
|
|
1034
|
-
try {
|
|
1035
|
-
const s = fs.statfsSync(this.home);
|
|
1036
|
-
diskFree = s.bavail * s.bsize;
|
|
1037
|
-
diskTotal = s.blocks * s.bsize;
|
|
1038
|
-
} catch { /* unknown */ }
|
|
1039
|
-
return {
|
|
1040
|
-
cpu: Math.round(Math.max(0, Math.min(1, busy)) * 1000) / 10,
|
|
1041
|
-
memUsed: os.totalmem() - os.freemem(),
|
|
1042
|
-
memTotal: os.totalmem(),
|
|
1043
|
-
diskFree,
|
|
1044
|
-
diskTotal,
|
|
1045
|
-
uptime: Math.round(os.uptime()),
|
|
1046
|
-
};
|
|
1047
|
-
}
|
|
1048
|
-
}
|
|
1049
|
-
|
|
1050
|
-
// `claude-pro host check`: the code of this version loads (the service's, and a session's). A service that runs
|
|
1051
|
-
// asks this before it hands over to a new version (see runHost).
|
|
1052
|
-
export async function checkCommand() {
|
|
1053
|
-
await import('./background.js');
|
|
1054
|
-
await import('./ui/repl.js');
|
|
1055
|
-
await import('./main.js');
|
|
1056
|
-
process.stdout.write(`claude-pro ${VERSION} loads\n`);
|
|
1057
|
-
return 0;
|
|
1058
|
-
}
|
|
1059
|
-
|
|
1060
|
-
// Whether the code now on disk starts: `host check` in a process of its own. null, or what went wrong.
|
|
1061
|
-
function newVersionFails() {
|
|
1062
|
-
const r = spawnSync(process.execPath, [ENTRY, 'host', 'check'], { cwd: os.homedir(), env: serviceEnv(), windowsHide: true, encoding: 'utf8', timeout: 60_000 });
|
|
1063
|
-
if (r.status === 0) return null;
|
|
1064
|
-
const said = `${r.stderr || ''}${r.stdout || ''}`.trim().split(/\r?\n/).filter(Boolean).slice(-6).join(' | ');
|
|
1065
|
-
return said || r.error?.message || `exit code ${r.status}`;
|
|
1066
|
-
}
|
|
1067
|
-
|
|
1068
|
-
// `claude-pro host run [--background]`: the service, until it is stopped. Returns the exit code.
|
|
1069
|
-
//
|
|
1070
|
-
// When the program's files change (an update, an edit of the source), a background service hands over to the new
|
|
1071
|
-
// version, carefully: this machine must not lose the web page's control. The new code is checked first (`host
|
|
1072
|
-
// check`); when it does not load, this one goes on (and says why in the log) until the files change again. When it
|
|
1073
|
-
// does, the new service is started and this one leaves once it runs; when it does not come up, this one takes over
|
|
1074
|
-
// again. The background sessions run on through it all (each is a process of its own, taken over by the next one).
|
|
1075
|
-
export async function runHost({ background = false } = {}) {
|
|
1076
|
-
for (const k of SESSION_ONLY) delete process.env[k];
|
|
1077
|
-
// its log: host.log (where the web page reads it, see logs), and in the foreground the terminal too
|
|
1078
|
-
const toFile = fileLogger();
|
|
1079
|
-
const toTerminal = background ? null : consoleLogger();
|
|
1080
|
-
const log = (msg) => { toFile(msg); toTerminal?.(msg); };
|
|
1081
|
-
if (!takeLock()) {
|
|
1082
|
-
(toTerminal || toFile)(`claude-pro host runs already (pid ${readHostState().pid || '?'}): this one stops`);
|
|
1083
|
-
return background ? 0 : 1;
|
|
1084
|
-
}
|
|
1085
|
-
const sessions = new BackgroundSessions({ dir: configDir(), entry: ENTRY, env: serviceEnv(), log });
|
|
1086
|
-
let service = null;
|
|
1087
|
-
const stop = () => service?.stop();
|
|
1088
|
-
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, stop);
|
|
1089
|
-
sessions.start();
|
|
1090
|
-
for (;;) {
|
|
1091
|
-
service = new HostService({ id: hostId(), log, background, sessions });
|
|
1092
|
-
sessions.onChange = () => service.reportState();
|
|
1093
|
-
log(`claude-pro host ${VERSION} started (pid ${process.pid}${background ? ', in the background' : ''}; terminal: ${service.terminal?.name || 'none found'})`);
|
|
1094
|
-
try {
|
|
1095
|
-
await service.run();
|
|
1096
|
-
} catch (e) {
|
|
1097
|
-
log(`the service stopped on an error: ${e.stack || e.message}`);
|
|
1098
|
-
}
|
|
1099
|
-
if (!service.reloading) break;
|
|
1100
|
-
const failure = newVersionFails();
|
|
1101
|
-
if (failure) {
|
|
1102
|
-
log(`the new version does not start, this one goes on: ${failure}`);
|
|
1103
|
-
continue;
|
|
1104
|
-
}
|
|
1105
|
-
log('the program changed: starting its new version');
|
|
1106
|
-
sessions.close();
|
|
1107
|
-
releaseLock();
|
|
1108
|
-
if (readHostState().pid === process.pid) updateHostState({ pid: undefined, beat: undefined, online: false });
|
|
1109
|
-
const pid = startHostInBackground();
|
|
1110
|
-
let handedOver = false;
|
|
1111
|
-
for (let t = 0; t < 30_000 && !handedOver; t += 500) {
|
|
1112
|
-
await sleep(500);
|
|
1113
|
-
const s = readHostState();
|
|
1114
|
-
handedOver = Boolean(pid && s.pid === pid && hostRunning(s));
|
|
1115
|
-
}
|
|
1116
|
-
if (handedOver) { log(`the new version runs (pid ${pid}): this one leaves`); return 0; }
|
|
1117
|
-
if (!takeLock()) { log('the new version has the lock but did not report yet: this one leaves'); return 0; }
|
|
1118
|
-
log(`the new version did not come up (pid ${pid}), this one goes on; see the lines above`);
|
|
1119
|
-
sessions.start();
|
|
1120
|
-
}
|
|
1121
|
-
sessions.close();
|
|
1122
|
-
releaseLock();
|
|
1123
|
-
if (readHostState().pid === process.pid) updateHostState({ pid: undefined, beat: undefined, online: false });
|
|
1124
|
-
log('stopped');
|
|
1125
|
-
return 0;
|
|
1126
|
-
}
|
|
1127
|
-
|
|
1128
|
-
// ---------------------------------------------------------------- start, stop, status
|
|
1129
|
-
|
|
1130
|
-
async function gatewayRequest(method, route) {
|
|
1131
|
-
const cfg = loadConfig({ cwd: os.homedir() });
|
|
1132
|
-
const login = gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
|
|
1133
|
-
if (!login) return false;
|
|
1134
|
-
const res = await fetch(`${normalizeGatewayUrl(login.url || cfg.gatewayUrl)}${route}`, { method, headers: { authorization: `Bearer ${login.apiKey}` }, signal: AbortSignal.timeout(8000) });
|
|
1135
|
-
return res.ok || res.status === 404;
|
|
1136
|
-
}
|
|
1137
|
-
|
|
1138
|
-
async function startCommand() {
|
|
1139
|
-
const state = readHostState();
|
|
1140
|
-
if (hostRunning(state)) {
|
|
1141
|
-
console.log(`claude-pro host is running already (pid ${state.pid}).`);
|
|
1142
|
-
return 0;
|
|
1143
|
-
}
|
|
1144
|
-
updateHostState({ disabled: undefined, spawnedAt: Date.now() });
|
|
1145
|
-
const pid = startHostInBackground();
|
|
1146
|
-
for (let i = 0; i < 30; i++) {
|
|
1147
|
-
await sleep(200);
|
|
1148
|
-
const now = readHostState();
|
|
1149
|
-
if (hostRunning(now)) {
|
|
1150
|
-
const cfg = loadConfig({ cwd: os.homedir() });
|
|
1151
|
-
const login = gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
|
|
1152
|
-
console.log(`claude-pro host started in the background (pid ${now.pid}). Log: ${hostFiles().log}`);
|
|
1153
|
-
if (!login) console.log(`This computer is not logged in to the gateway ${cfg.gatewayUrl}: it waits until /login in a session.`);
|
|
1154
|
-
return 0;
|
|
1155
|
-
}
|
|
1156
|
-
}
|
|
1157
|
-
console.log(`claude-pro host was started (pid ${pid}) but has not reported yet: see ${hostFiles().log}`);
|
|
1158
|
-
return 1;
|
|
1159
|
-
}
|
|
1160
|
-
|
|
1161
|
-
async function stopCommand() {
|
|
1162
|
-
const state = readHostState();
|
|
1163
|
-
const running = hostRunning(state);
|
|
1164
|
-
updateHostState({ disabled: true });
|
|
1165
|
-
if (running) {
|
|
1166
|
-
try { process.kill(state.pid); } catch { /* gone already */ }
|
|
1167
|
-
for (let i = 0; i < 25 && pidAlive(state.pid); i++) await sleep(200);
|
|
1168
|
-
releaseLock(state.pid);
|
|
1169
|
-
}
|
|
1170
|
-
// again: a heartbeat between the first write and the end of the process clears it
|
|
1171
|
-
updateHostState({ disabled: true, pid: undefined, beat: undefined, online: false });
|
|
1172
|
-
let removed = false;
|
|
1173
|
-
if (state.id) removed = await gatewayRequest('DELETE', `/v1/remote/hosts/${encodeURIComponent(state.id)}`).catch(() => false);
|
|
1174
|
-
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.' : ''}`);
|
|
1175
|
-
console.log('Sessions no longer start it by themselves: `claude-pro host start` does.');
|
|
1176
|
-
return 0;
|
|
1177
|
-
}
|
|
1178
|
-
|
|
1179
|
-
function statusCommand() {
|
|
1180
|
-
const state = readHostState();
|
|
1181
|
-
const running = hostRunning(state);
|
|
1182
|
-
const auto = installedAutostart();
|
|
1183
|
-
const boot = bootAutostartInstalled();
|
|
1184
|
-
const lines = [
|
|
1185
|
-
`claude-pro host (the web page runs and manages sessions on this computer through it): ${running ? `running, pid ${state.pid}, since ${state.startedAt || '?'}` : state.disabled ? 'stopped (claude-pro host start)' : 'not running (claude-pro host start)'}`,
|
|
1186
|
-
];
|
|
1187
|
-
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)'}`);
|
|
1188
|
-
if (state.id) lines.push(` id: ${state.id}${state.machine ? ` · computer: ${state.machine}` : ''}${state.terminal ? ` · opens: ${state.terminal}` : ''}${state.version ? ` · version ${state.version}` : ''}`);
|
|
1189
|
-
lines.push(` log: ${hostFiles().log}`);
|
|
1190
|
-
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' : ''}`);
|
|
1191
|
-
console.log(lines.join('\n'));
|
|
1192
|
-
return 0;
|
|
1193
|
-
}
|
|
1194
|
-
|
|
1195
|
-
// ---------------------------------------------------------------- starting by itself: at logon, at boot
|
|
1196
|
-
//
|
|
1197
|
-
// By default the service starts when the user logs in (Windows: a script in the Startup folder, without a window;
|
|
1198
|
-
// macOS: a LaunchAgent; Linux: a desktop autostart entry, else a systemd user service). `host install --at-boot`:
|
|
1199
|
-
// already when the computer starts, before anyone logs in (Windows: a scheduled task "at startup" that runs as the
|
|
1200
|
-
// user whether logged on or not, S4U: no password kept, no network shares; Linux: the systemd user service with
|
|
1201
|
-
// lingering; macOS: not without root, so at logon). A session logged in to the gateway, /login and `claude-pro
|
|
1202
|
-
// connect` set up the start at logon by themselves (ensureAutostart), unless `host uninstall` said no.
|
|
1203
|
-
|
|
1204
|
-
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)}` : '');
|
|
1205
|
-
|
|
1206
|
-
// Where `host install` puts what starts it at logon, by platform (two kinds on Linux: a desktop's autostart, else a
|
|
1207
|
-
// systemd user service).
|
|
1208
|
-
export function autostartFiles({ platform = process.platform, env = process.env, home = os.homedir() } = {}) {
|
|
1209
|
-
const s = suffix();
|
|
1210
|
-
if (platform === 'win32') return [path.join(env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', `claude-pro-host${s}.vbs`)];
|
|
1211
|
-
if (platform === 'darwin') return [path.join(home, 'Library', 'LaunchAgents', `com.claude-pro.host${s}.plist`)];
|
|
1212
|
-
const config = env.XDG_CONFIG_HOME || path.join(home, '.config');
|
|
1213
|
-
return [path.join(config, 'autostart', `claude-pro-host${s}.desktop`), path.join(config, 'systemd', 'user', `claude-pro-host${s}.service`)];
|
|
1214
|
-
}
|
|
1215
|
-
|
|
1216
|
-
export const bootTaskName = () => `claude-pro host${suffix()}`;
|
|
1217
|
-
|
|
1218
|
-
// How the service starts by itself: 'boot' (before anyone logs in, host install --at-boot), 'logon', or ''.
|
|
1219
|
-
export function autostartKind() {
|
|
1220
|
-
if (bootAutostartInstalled()) return 'boot';
|
|
1221
|
-
return installedAutostart() ? 'logon' : '';
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
let bootKnown = { at: 0, value: false };
|
|
1225
|
-
function bootAutostartInstalled() {
|
|
1226
|
-
if (Date.now() - bootKnown.at < 60_000) return bootKnown.value;
|
|
1227
|
-
let value = false;
|
|
1228
|
-
if (process.platform === 'win32') {
|
|
1229
|
-
value = spawnSync('schtasks', ['/Query', '/TN', bootTaskName()], { windowsHide: true, stdio: 'ignore' }).status === 0;
|
|
1230
|
-
} else if (process.platform === 'linux') {
|
|
1231
|
-
const unit = autostartFiles()[1];
|
|
1232
|
-
const linger = spawnSync('loginctl', ['show-user', os.userInfo().username, '-p', 'Linger'], { encoding: 'utf8' });
|
|
1233
|
-
value = fs.existsSync(unit) && /Linger=yes/.test(linger.stdout || '');
|
|
1234
|
-
}
|
|
1235
|
-
bootKnown = { at: Date.now(), value };
|
|
1236
|
-
return value;
|
|
1237
|
-
}
|
|
1238
|
-
|
|
1239
|
-
function installedAutostart() {
|
|
1240
|
-
return autostartFiles().find((f) => fs.existsSync(f)) || null;
|
|
1241
|
-
}
|
|
1242
|
-
|
|
1243
|
-
// What runs at logon: `claude-pro host start`, with the config directory when it is not the default one.
|
|
1244
|
-
function startCommandLine(sub = ['host', 'start']) {
|
|
1245
|
-
const env = process.env.CLAUDE_PRO_CONFIG_DIR ? { CLAUDE_PRO_CONFIG_DIR: path.resolve(process.env.CLAUDE_PRO_CONFIG_DIR) } : {};
|
|
1246
|
-
return { program: [process.execPath, ENTRY, ...sub], env };
|
|
1247
|
-
}
|
|
1248
|
-
|
|
1249
|
-
const xml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
1250
|
-
|
|
1251
|
-
// The start at logon, set up: {file, note}.
|
|
1252
|
-
export function installLogonAutostart() {
|
|
1253
|
-
const { program, env } = startCommandLine();
|
|
1254
|
-
const [desktop, service] = autostartFiles();
|
|
1255
|
-
let file;
|
|
1256
|
-
let note = '';
|
|
1257
|
-
if (process.platform === 'win32') {
|
|
1258
|
-
file = desktop;
|
|
1259
|
-
const vbs = (s) => `"${String(s).replace(/"/g, '""')}"`;
|
|
1260
|
-
const text = [
|
|
1261
|
-
"' claude-pro: starts its computer service (claude-pro host) at logon, without a window.",
|
|
1262
|
-
"' `claude-pro host uninstall` removes this file.",
|
|
1263
|
-
'Set shell = CreateObject("WScript.Shell")',
|
|
1264
|
-
...Object.entries(env).map(([k, v]) => `shell.Environment("PROCESS")(${vbs(k)}) = ${vbs(v)}`),
|
|
1265
|
-
`shell.Run ${vbs(program.map(quoteWindowsArg).join(' '))}, 0, False`,
|
|
1266
|
-
'',
|
|
1267
|
-
].join('\r\n');
|
|
1268
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
1269
|
-
fs.writeFileSync(file, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(text, 'utf16le')])); // UTF-16: any user name
|
|
1270
|
-
} else if (process.platform === 'darwin') {
|
|
1271
|
-
file = desktop;
|
|
1272
|
-
const label = path.basename(file, '.plist');
|
|
1273
|
-
const plist = `<?xml version="1.0" encoding="UTF-8"?>
|
|
1274
|
-
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1275
|
-
<plist version="1.0">
|
|
1276
|
-
<dict>
|
|
1277
|
-
<key>Label</key><string>${xml(label)}</string>
|
|
1278
|
-
<key>ProgramArguments</key>
|
|
1279
|
-
<array>${program.map((a) => `<string>${xml(a)}</string>`).join('')}</array>
|
|
1280
|
-
<key>RunAtLoad</key><true/>
|
|
1281
|
-
<key>AbandonProcessGroup</key><true/>
|
|
1282
|
-
<key>EnvironmentVariables</key>
|
|
1283
|
-
<dict>${Object.entries({ PATH: process.env.PATH || '', ...env }).map(([k, v]) => `<key>${xml(k)}</key><string>${xml(v)}</string>`).join('')}</dict>
|
|
1284
|
-
</dict>
|
|
1285
|
-
</plist>
|
|
1286
|
-
`;
|
|
1287
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
1288
|
-
fs.writeFileSync(file, plist);
|
|
1289
|
-
spawnSync('launchctl', ['unload', file], { stdio: 'ignore' });
|
|
1290
|
-
spawnSync('launchctl', ['load', '-w', file], { stdio: 'ignore' });
|
|
1291
|
-
} else if (process.env.DISPLAY || process.env.WAYLAND_DISPLAY) {
|
|
1292
|
-
file = desktop;
|
|
1293
|
-
const q = (s) => `"${String(s).replace(/(["`$\\])/g, '\\$1')}"`;
|
|
1294
|
-
const exec = [...(Object.keys(env).length ? ['env', ...Object.entries(env).map(([k, v]) => `${k}=${v}`)] : []), ...program].map(q).join(' ');
|
|
1295
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
1296
|
-
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`);
|
|
1297
|
-
} else {
|
|
1298
|
-
file = service;
|
|
1299
|
-
note = writeSystemdUnit(service);
|
|
1300
|
-
}
|
|
1301
|
-
bootKnown.at = 0;
|
|
1302
|
-
return { file, note };
|
|
1303
|
-
}
|
|
1304
|
-
|
|
1305
|
-
// Linux: the systemd user service (Type=oneshot + RemainAfterExit: the service's process stays in its cgroup).
|
|
1306
|
-
function writeSystemdUnit(file) {
|
|
1307
|
-
const { program, env } = startCommandLine();
|
|
1308
|
-
const q = (s) => `"${String(s).replace(/(["\\])/g, '\\$1')}"`;
|
|
1309
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
1310
|
-
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`);
|
|
1311
|
-
const daemon = spawnSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'ignore' });
|
|
1312
|
-
const enabled = spawnSync('systemctl', ['--user', 'enable', path.basename(file)], { stdio: 'ignore' });
|
|
1313
|
-
return daemon.status === 0 && enabled.status === 0 ? ' (systemd user service)' : ' (systemctl --user did not take it: enable it by hand)';
|
|
1314
|
-
}
|
|
1315
|
-
|
|
1316
|
-
// Windows: the scheduled task that starts the service at boot, as this user, logged on or not (S4U).
|
|
1317
|
-
export function bootTaskXml({ user = `${process.env.USERDOMAIN || os.hostname()}\\${os.userInfo().username}`, home = os.homedir() } = {}) {
|
|
1318
|
-
const { program, env } = startCommandLine(['host', 'run', '--background']);
|
|
1319
|
-
let command = program[0];
|
|
1320
|
-
let args = program.slice(1).map(quoteWindowsArg).join(' ');
|
|
1321
|
-
if (Object.keys(env).length) { // a task cannot set variables: cmd does
|
|
1322
|
-
command = process.env.ComSpec || 'cmd.exe';
|
|
1323
|
-
args = `/d /c "${Object.entries(env).map(([k, v]) => `set "${k}=${v}"&& `).join('')}${program.map(quoteWindowsArg).join(' ')}"`;
|
|
1324
|
-
}
|
|
1325
|
-
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
1326
|
-
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
1327
|
-
<RegistrationInfo><Description>claude-pro host: lets the gateway's web page use this computer (claude-pro host uninstall removes it)</Description></RegistrationInfo>
|
|
1328
|
-
<Triggers><BootTrigger><Enabled>true</Enabled></BootTrigger></Triggers>
|
|
1329
|
-
<Principals><Principal id="Author"><UserId>${xml(user)}</UserId><LogonType>S4U</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
|
|
1330
|
-
<Settings>
|
|
1331
|
-
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
1332
|
-
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
1333
|
-
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
1334
|
-
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
|
1335
|
-
<StartWhenAvailable>true</StartWhenAvailable>
|
|
1336
|
-
<RestartOnFailure><Interval>PT1M</Interval><Count>3</Count></RestartOnFailure>
|
|
1337
|
-
<Hidden>true</Hidden>
|
|
1338
|
-
<Enabled>true</Enabled>
|
|
1339
|
-
</Settings>
|
|
1340
|
-
<Actions Context="Author"><Exec><Command>${xml(command)}</Command><Arguments>${xml(args)}</Arguments><WorkingDirectory>${xml(home)}</WorkingDirectory></Exec></Actions>
|
|
1341
|
-
</Task>
|
|
1342
|
-
`;
|
|
1343
|
-
}
|
|
1344
|
-
|
|
1345
|
-
// The start at boot, set up: a line saying how. Throws what to do when it cannot be (no administrator rights).
|
|
1346
|
-
export function installBootAutostart() {
|
|
1347
|
-
bootKnown.at = 0;
|
|
1348
|
-
if (process.platform === 'win32') {
|
|
1349
|
-
const file = path.join(os.tmpdir(), `claude-pro-boot-task-${process.pid}.xml`);
|
|
1350
|
-
fs.writeFileSync(file, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(bootTaskXml(), 'utf16le')]));
|
|
1351
|
-
try {
|
|
1352
|
-
const r = spawnSync('schtasks', ['/Create', '/TN', bootTaskName(), '/XML', file, '/F'], { windowsHide: true, encoding: 'latin1' });
|
|
1353
|
-
if (r.status !== 0) {
|
|
1354
|
-
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.)`);
|
|
1355
|
-
}
|
|
1356
|
-
} finally {
|
|
1357
|
-
fs.rmSync(file, { force: true });
|
|
1358
|
-
}
|
|
1359
|
-
return `a scheduled task "${bootTaskName()}" starts it when Windows starts, as ${os.userInfo().username}, logged on or not`;
|
|
1360
|
-
}
|
|
1361
|
-
if (process.platform === 'linux') {
|
|
1362
|
-
const note = writeSystemdUnit(autostartFiles()[1]);
|
|
1363
|
-
const user = os.userInfo().username;
|
|
1364
|
-
const linger = spawnSync('loginctl', ['enable-linger', user], { stdio: 'ignore' });
|
|
1365
|
-
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}\`.`);
|
|
1366
|
-
return `the systemd user service starts it at boot (lingering is on for ${user})`;
|
|
1367
|
-
}
|
|
1368
|
-
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.');
|
|
1369
|
-
}
|
|
1370
|
-
|
|
1371
|
-
function removeBootAutostart() {
|
|
1372
|
-
bootKnown.at = 0;
|
|
1373
|
-
if (process.platform === 'win32') {
|
|
1374
|
-
if (spawnSync('schtasks', ['/Query', '/TN', bootTaskName()], { windowsHide: true, stdio: 'ignore' }).status !== 0) return null;
|
|
1375
|
-
const r = spawnSync('schtasks', ['/Delete', '/TN', bootTaskName(), '/F'], { windowsHide: true, stdio: 'ignore' });
|
|
1376
|
-
return r.status === 0 ? `the scheduled task "${bootTaskName()}"` : `(the scheduled task "${bootTaskName()}" could not be removed: as administrator, schtasks /Delete /TN "${bootTaskName()}" /F)`;
|
|
1377
|
-
}
|
|
1378
|
-
return null; // Linux: the unit goes with the files below; lingering may serve other services, it stays
|
|
1379
|
-
}
|
|
1380
|
-
|
|
1381
|
-
// For a session logged in to the gateway, /login (`force`) and `claude-pro connect`: the start at logon, set up once,
|
|
1382
|
-
// unless the user said no (`host uninstall`) or turned the service off (CLAUDE_PRO_HOST=0).
|
|
1383
|
-
export function ensureAutostart({ force = false, env = process.env } = {}) {
|
|
1384
|
-
if (!hostEnabled(env)) return null;
|
|
1385
|
-
const state = readHostState();
|
|
1386
|
-
if (state.autostartDeclined || (state.autostartAuto && !force)) return null;
|
|
1387
|
-
if (installedAutostart() || bootAutostartInstalled()) { updateHostState({ autostartAuto: new Date().toISOString() }); return null; }
|
|
1388
|
-
try {
|
|
1389
|
-
const r = installLogonAutostart();
|
|
1390
|
-
updateHostState({ autostartAuto: new Date().toISOString() });
|
|
1391
|
-
return r;
|
|
1392
|
-
} catch {
|
|
1393
|
-
return null;
|
|
1394
|
-
}
|
|
1395
|
-
}
|
|
1396
|
-
|
|
1397
|
-
async function installCommand(args = []) {
|
|
1398
|
-
updateHostState({ autostartDeclined: undefined, autostartAuto: new Date().toISOString() });
|
|
1399
|
-
if (args.includes('--at-boot')) {
|
|
1400
|
-
try {
|
|
1401
|
-
console.log(`claude-pro host starts at boot now: ${installBootAutostart()}.`);
|
|
1402
|
-
} catch (e) {
|
|
1403
|
-
console.log(e.message);
|
|
1404
|
-
if (process.platform !== 'darwin') return 1;
|
|
1405
|
-
}
|
|
1406
|
-
}
|
|
1407
|
-
if (!args.includes('--at-boot') || process.platform === 'darwin') {
|
|
1408
|
-
const { file, note } = installLogonAutostart();
|
|
1409
|
-
console.log(`claude-pro host starts at logon now: ${file}${note}`);
|
|
1410
|
-
}
|
|
1411
|
-
return startCommand();
|
|
1412
|
-
}
|
|
1413
|
-
|
|
1414
|
-
function uninstallCommand() {
|
|
1415
|
-
const removed = [];
|
|
1416
|
-
const task = removeBootAutostart();
|
|
1417
|
-
if (task) removed.push(task);
|
|
1418
|
-
for (const file of autostartFiles()) {
|
|
1419
|
-
if (!fs.existsSync(file)) continue;
|
|
1420
|
-
if (process.platform === 'darwin') spawnSync('launchctl', ['unload', '-w', file], { stdio: 'ignore' });
|
|
1421
|
-
if (file.endsWith('.service')) spawnSync('systemctl', ['--user', 'disable', path.basename(file)], { stdio: 'ignore' });
|
|
1422
|
-
fs.rmSync(file, { force: true });
|
|
1423
|
-
removed.push(file);
|
|
1424
|
-
}
|
|
1425
|
-
bootKnown.at = 0;
|
|
1426
|
-
updateHostState({ autostartDeclined: true }); // sessions and /login do not set it up again
|
|
1427
|
-
console.log(removed.length ? `Removed ${removed.join(', ')}` : 'claude-pro host was not set to start by itself.');
|
|
1428
|
-
if (hostRunning()) console.log('It is still running now: `claude-pro host stop` stops it.');
|
|
1429
|
-
return 0;
|
|
1430
|
-
}
|
|
1431
|
-
|
|
1432
|
-
const USAGE = `Usage: claude-pro host [run | start | stop | status | install | uninstall]
|
|
1433
|
-
|
|
1434
|
-
The computer service: it makes this computer one the gateway's web page (远程控制) runs sessions on. From the
|
|
1435
|
-
page: new sessions here, in the directory chosen there, in the background without a window (or, when asked, in
|
|
1436
|
-
a terminal window); bringing a background session to the front in a terminal window here (also while it works;
|
|
1437
|
-
closing the window sends it back); ending and restarting them; opening a conversation kept here again (history),
|
|
1438
|
-
or deleting it from this computer; their logs and its own; updating claude-pro. A background session that
|
|
1439
|
-
crashes is opened again, and after a restart of the computer the service opens again those that ran (the
|
|
1440
|
-
conversation, not the task that was running). \`claude-pro attach\` shows a background session in a terminal here.
|
|
1441
|
-
|
|
1442
|
-
It uses the gateway login of /login or claude-pro connect, and only connects out to the gateway. A session
|
|
1443
|
-
logged in to the gateway starts it by itself, and /login and connect set it up to start at logon
|
|
1444
|
-
(CLAUDE_PRO_HOST=0: neither).
|
|
1445
|
-
|
|
1446
|
-
claude-pro host Run it here, in the foreground (Ctrl+C stops it)
|
|
1447
|
-
claude-pro host start Run it in the background (log: ~/.claude-pro/host.log)
|
|
1448
|
-
claude-pro host stop Stop it and take this computer off the gateway's list (sessions then no longer start it)
|
|
1449
|
-
claude-pro host status Whether it runs, its id, its log
|
|
1450
|
-
claude-pro host install Start it at logon (Windows: a script in the Startup folder; macOS: a LaunchAgent;
|
|
1451
|
-
Linux: a desktop autostart entry, else a systemd user service). /login and
|
|
1452
|
-
claude-pro connect do this by themselves
|
|
1453
|
-
claude-pro host install --at-boot
|
|
1454
|
-
Start it when the computer starts, before anyone logs in (Windows: a scheduled
|
|
1455
|
-
task, as administrator; Linux: lingering; macOS: not possible, at logon instead)
|
|
1456
|
-
claude-pro host uninstall Not by itself any more (sessions and /login do not set it up again)
|
|
1457
|
-
`;
|
|
1458
|
-
|
|
1459
|
-
// `claude-pro host ...`: returns the exit code (`run` ends the process itself once the service has stopped).
|
|
1460
|
-
export async function hostCommand(args = []) {
|
|
1461
|
-
const [sub = 'run', ...rest] = args;
|
|
1462
|
-
switch (sub) {
|
|
1463
|
-
case 'run': process.exit(await runHost({ background: rest.includes('--background') })); break;
|
|
1464
|
-
case 'check': return checkCommand();
|
|
1465
|
-
case 'start': return startCommand();
|
|
1466
|
-
case 'stop': return stopCommand();
|
|
1467
|
-
case 'status': return statusCommand();
|
|
1468
|
-
case 'install': return installCommand(rest);
|
|
1469
|
-
case 'uninstall': return uninstallCommand();
|
|
1470
|
-
case 'help': case '-h': case '--help': process.stdout.write(USAGE); return 0;
|
|
1471
|
-
default: process.stderr.write(`Unknown host command: ${sub}\n\n${USAGE}`); return 2;
|
|
1472
|
-
}
|
|
1473
|
-
return 0;
|
|
1474
|
-
}
|