@yanzc/claude-pro 0.6.0 → 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/README.md +375 -370
- package/package.json +1 -1
- package/src/attach.js +132 -0
- package/src/background.js +424 -0
- package/src/commands.js +75 -35
- package/src/connect.js +79 -0
- package/src/history.js +94 -0
- package/src/host.js +444 -65
- package/src/main.js +35 -6
- package/src/peers.js +290 -215
- package/src/remote.js +50 -15
- package/src/session.js +24 -0
- package/src/supervisor.js +6 -3
- package/src/tools/bash.js +2 -2
- package/src/ui/dialogs.js +48 -0
- package/src/ui/render.js +10 -0
- package/src/ui/repl.js +308 -38
- package/src/ui/vterm.js +62 -0
package/src/host.js
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
|
-
// The computer service (`claude-pro host`): one background process per computer (per CONFIG_DIR) that
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// the id the gateway gave
|
|
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.
|
|
5
7
|
//
|
|
6
8
|
// Protocol (Bearer = the gateway API key; ARCHITECTURE.md 3.1.5):
|
|
7
|
-
// POST /v1/remote/hosts {id, machine, host, platform, version, home, terminal
|
|
8
|
-
// GET /v1/remote/hosts/:id/commands (SSE): online while it is open; {cid, type:
|
|
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
|
|
9
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
|
|
10
14
|
// DELETE /v1/remote/hosts/:id: off the page's list (`host stop`, a logout, another account)
|
|
11
15
|
//
|
|
12
16
|
// It runs in the foreground with `claude-pro host`, in the background (detached, no window, logging to
|
|
@@ -24,21 +28,29 @@ import crypto from 'node:crypto';
|
|
|
24
28
|
import { spawn, spawnSync } from 'node:child_process';
|
|
25
29
|
import { CONFIG_DIR, INSTALL_DIR, VERSION, GATEWAY_DEFAULT_URL, loadConfig } from './config.js';
|
|
26
30
|
import { readGatewayLogin, normalizeGatewayUrl } from './gateway.js';
|
|
27
|
-
import { machineName, cleanName } from './peers.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';
|
|
28
35
|
import { ENV_SUPERVISED, ENV_RESTART_FILE, ENV_RESTARTED } from './supervisor.js';
|
|
29
36
|
|
|
30
37
|
export const ENTRY = path.join(INSTALL_DIR, 'bin', 'claude-pro.js');
|
|
31
38
|
const ID = /^[A-Za-z0-9_-]{8,64}$/;
|
|
32
|
-
|
|
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 ...
|
|
33
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)
|
|
34
43
|
const LOGIN_CHECK_MS = 5_000;
|
|
35
|
-
const CODE_CHECK_MS = 60_000;
|
|
44
|
+
const CODE_CHECK_MS = TICK || 60_000;
|
|
36
45
|
const REQUEST_TIMEOUT_MS = 15_000;
|
|
37
46
|
const STREAM_SILENCE_MS = 50_000; // the gateway pings every 15 s
|
|
38
47
|
const MAX_ENTRIES = 1000;
|
|
39
48
|
const MAX_RECENT = 15;
|
|
40
49
|
const LOG_BYTES = 1_000_000;
|
|
41
|
-
const
|
|
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'];
|
|
42
54
|
|
|
43
55
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
44
56
|
|
|
@@ -63,7 +75,7 @@ export function readHostState() {
|
|
|
63
75
|
}
|
|
64
76
|
|
|
65
77
|
// Merges `change` into host.json (an undefined value removes the key).
|
|
66
|
-
function updateHostState(change) {
|
|
78
|
+
export function updateHostState(change) {
|
|
67
79
|
const next = { ...readHostState(), ...change };
|
|
68
80
|
for (const k of Object.keys(next)) if (next[k] === undefined) delete next[k];
|
|
69
81
|
const file = hostFiles().state;
|
|
@@ -85,7 +97,8 @@ export function hostRunning(state = readHostState(), now = Date.now()) {
|
|
|
85
97
|
return Boolean(state.pid && pidAlive(state.pid) && now - (Number(state.beat) || 0) < STALE_MS);
|
|
86
98
|
}
|
|
87
99
|
|
|
88
|
-
// This computer's id at the gateway: made once, then kept in host.json.
|
|
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.
|
|
89
102
|
function hostId() {
|
|
90
103
|
const state = readHostState();
|
|
91
104
|
if (ID.test(state.id || '')) return state.id;
|
|
@@ -94,6 +107,23 @@ function hostId() {
|
|
|
94
107
|
return id;
|
|
95
108
|
}
|
|
96
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
|
+
|
|
97
127
|
// One service per CONFIG_DIR: host.lock holds the pid of the one that runs. A lock is taken over when its process
|
|
98
128
|
// is gone, or when it is old and no heartbeat says it runs (its pid may be another program's now).
|
|
99
129
|
function takeLock() {
|
|
@@ -145,11 +175,21 @@ function serviceEnv(env = process.env) {
|
|
|
145
175
|
}
|
|
146
176
|
|
|
147
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.
|
|
148
179
|
export function startHostInBackground({ env = process.env } = {}) {
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
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
|
+
}
|
|
153
193
|
}
|
|
154
194
|
|
|
155
195
|
// For a session that starts (see App.ensureHost): a service, unless one runs, `claude-pro host stop` stopped it, or
|
|
@@ -474,11 +514,15 @@ export function runLaunch(spec, { timeoutMs = 20_000 } = {}) {
|
|
|
474
514
|
|
|
475
515
|
export class HostService {
|
|
476
516
|
// `readLogin`, `loadConfig`, `launch`, `terminal`, `home`: what the tests give it instead of this computer's.
|
|
477
|
-
|
|
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 } = {}) {
|
|
478
519
|
this.id = id;
|
|
479
520
|
this.log = log;
|
|
480
521
|
this.fetch = fetchImpl;
|
|
481
522
|
this.background = background;
|
|
523
|
+
this.sessions = sessions;
|
|
524
|
+
this.stats = new Stats(home);
|
|
525
|
+
this.stateTimer = null;
|
|
482
526
|
this.terminal = terminal === undefined ? terminalFor() : terminal;
|
|
483
527
|
this.launch = launch;
|
|
484
528
|
this.home = home;
|
|
@@ -535,9 +579,29 @@ export class HostService {
|
|
|
535
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 || '' };
|
|
536
580
|
}
|
|
537
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
|
+
|
|
538
602
|
async register() {
|
|
539
603
|
try {
|
|
540
|
-
await this.request('POST', '/v1/remote/hosts', this.info());
|
|
604
|
+
await this.request('POST', '/v1/remote/hosts', { ...this.info(), autostart: autostartKind(), ...this.state() });
|
|
541
605
|
} catch (e) {
|
|
542
606
|
if (e.status === 404) e.noHosts = true; // a gateway without computers (yet): not the one that forgot this one
|
|
543
607
|
throw e;
|
|
@@ -562,6 +626,9 @@ export class HostService {
|
|
|
562
626
|
} else if (this.login) {
|
|
563
627
|
this.log(`logged in to the gateway ${this.base()}`);
|
|
564
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();
|
|
565
632
|
this.streamAbort?.abort();
|
|
566
633
|
this.wakeUp();
|
|
567
634
|
}
|
|
@@ -615,8 +682,11 @@ export class HostService {
|
|
|
615
682
|
setInterval(() => this.beat(), BEAT_MS),
|
|
616
683
|
setInterval(() => this.checkLogin(), LOGIN_CHECK_MS),
|
|
617
684
|
setInterval(() => this.checkCode(), CODE_CHECK_MS),
|
|
685
|
+
setInterval(() => this.reportState({ soon: false }), STATE_MS),
|
|
686
|
+
setInterval(() => this.stats.sample(), 5000),
|
|
618
687
|
);
|
|
619
|
-
|
|
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); }
|
|
620
690
|
}
|
|
621
691
|
|
|
622
692
|
async loop() {
|
|
@@ -640,7 +710,9 @@ export class HostService {
|
|
|
640
710
|
this.refusedKey = this.login?.apiKey;
|
|
641
711
|
this.refusedAt = Date.now();
|
|
642
712
|
this.registered = false;
|
|
643
|
-
|
|
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();
|
|
644
716
|
}
|
|
645
717
|
else if (!this.stopped && e.name !== 'AbortError') this.note(`cannot reach the gateway ${this.base()}: ${e.message}`);
|
|
646
718
|
}
|
|
@@ -701,6 +773,11 @@ export class HostService {
|
|
|
701
773
|
let r;
|
|
702
774
|
if (cmd.type === 'list') r = await this.list(body);
|
|
703
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();
|
|
704
781
|
else throw new Error(`这台电脑上的 claude-pro ${VERSION} 不认识命令 ${cmd.type},请升级`);
|
|
705
782
|
result = { cid: cmd.cid, ok: true, ...r };
|
|
706
783
|
} catch (e) {
|
|
@@ -728,9 +805,65 @@ export class HostService {
|
|
|
728
805
|
});
|
|
729
806
|
}
|
|
730
807
|
|
|
731
|
-
//
|
|
732
|
-
|
|
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 } = {}) {
|
|
733
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
|
+
}
|
|
734
867
|
const dir = typeof cwd === 'string' ? normalizeDir(cwd, { home: this.home }) : null;
|
|
735
868
|
if (!dir || !String(cwd).trim()) throw new Error(`请选择一个绝对路径的目录:${cwd ?? ''}`);
|
|
736
869
|
let st = null;
|
|
@@ -743,10 +876,15 @@ export class HostService {
|
|
|
743
876
|
} else if (!st.isDirectory()) {
|
|
744
877
|
throw new Error(`不是目录:${dir}`);
|
|
745
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
|
+
}
|
|
746
885
|
const term = this.terminal;
|
|
747
886
|
if (!term) throw new Error('这台电脑上找不到能打开的终端(Windows Terminal、Terminal.app、x-terminal-emulator、gnome-terminal、konsole、xterm 或 tmux)');
|
|
748
|
-
const
|
|
749
|
-
const args = ['--remote-id', sessionId, ...(label ? ['--name', label] : [])];
|
|
887
|
+
const args = ['--remote-id', sessionId, ...(label ? ['--name', label] : []), ...(resume ? ['--resume', resume] : []), ...(model ? ['--model', model] : [])];
|
|
750
888
|
const env = passedEnv();
|
|
751
889
|
const envFile = process.platform === 'win32' && term.kind === 'wt' ? writeEnvFile(sessionId, env) : null;
|
|
752
890
|
try {
|
|
@@ -804,30 +942,123 @@ export function codeFingerprint(root = INSTALL_DIR) {
|
|
|
804
942
|
return hash.digest('base64');
|
|
805
943
|
}
|
|
806
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
|
+
|
|
807
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).
|
|
808
1012
|
export async function runHost({ background = false } = {}) {
|
|
809
1013
|
for (const k of SESSION_ONLY) delete process.env[k];
|
|
810
|
-
|
|
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); };
|
|
811
1018
|
if (!takeLock()) {
|
|
812
|
-
|
|
1019
|
+
(toTerminal || toFile)(`claude-pro host runs already (pid ${readHostState().pid || '?'}): this one stops`);
|
|
813
1020
|
return background ? 0 : 1;
|
|
814
1021
|
}
|
|
815
|
-
const
|
|
816
|
-
|
|
1022
|
+
const sessions = new BackgroundSessions({ dir: configDir(), entry: ENTRY, env: serviceEnv(), log });
|
|
1023
|
+
let service = null;
|
|
1024
|
+
const stop = () => service?.stop();
|
|
817
1025
|
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, stop);
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
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();
|
|
822
1044
|
releaseLock();
|
|
823
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();
|
|
824
1057
|
}
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
log('stopped');
|
|
830
|
-
}
|
|
1058
|
+
sessions.close();
|
|
1059
|
+
releaseLock();
|
|
1060
|
+
if (readHostState().pid === process.pid) updateHostState({ pid: undefined, beat: undefined, online: false });
|
|
1061
|
+
log('stopped');
|
|
831
1062
|
return 0;
|
|
832
1063
|
}
|
|
833
1064
|
|
|
@@ -886,18 +1117,26 @@ function statusCommand() {
|
|
|
886
1117
|
const state = readHostState();
|
|
887
1118
|
const running = hostRunning(state);
|
|
888
1119
|
const auto = installedAutostart();
|
|
1120
|
+
const boot = bootAutostartInstalled();
|
|
889
1121
|
const lines = [
|
|
890
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)'}`,
|
|
891
1123
|
];
|
|
892
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)'}`);
|
|
893
1125
|
if (state.id) lines.push(` id: ${state.id}${state.machine ? ` · computer: ${state.machine}` : ''}${state.terminal ? ` · opens: ${state.terminal}` : ''}${state.version ? ` · version ${state.version}` : ''}`);
|
|
894
1126
|
lines.push(` log: ${hostFiles().log}`);
|
|
895
|
-
lines.push(`
|
|
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' : ''}`);
|
|
896
1128
|
console.log(lines.join('\n'));
|
|
897
1129
|
return 0;
|
|
898
1130
|
}
|
|
899
1131
|
|
|
900
|
-
// ---------------------------------------------------------------- starting at logon
|
|
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.
|
|
901
1140
|
|
|
902
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)}` : '');
|
|
903
1142
|
|
|
@@ -911,19 +1150,43 @@ export function autostartFiles({ platform = process.platform, env = process.env,
|
|
|
911
1150
|
return [path.join(config, 'autostart', `claude-pro-host${s}.desktop`), path.join(config, 'systemd', 'user', `claude-pro-host${s}.service`)];
|
|
912
1151
|
}
|
|
913
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
|
+
|
|
914
1176
|
function installedAutostart() {
|
|
915
1177
|
return autostartFiles().find((f) => fs.existsSync(f)) || null;
|
|
916
1178
|
}
|
|
917
1179
|
|
|
918
1180
|
// What runs at logon: `claude-pro host start`, with the config directory when it is not the default one.
|
|
919
|
-
function startCommandLine() {
|
|
1181
|
+
function startCommandLine(sub = ['host', 'start']) {
|
|
920
1182
|
const env = process.env.CLAUDE_PRO_CONFIG_DIR ? { CLAUDE_PRO_CONFIG_DIR: path.resolve(process.env.CLAUDE_PRO_CONFIG_DIR) } : {};
|
|
921
|
-
return { program: [process.execPath, ENTRY,
|
|
1183
|
+
return { program: [process.execPath, ENTRY, ...sub], env };
|
|
922
1184
|
}
|
|
923
1185
|
|
|
924
|
-
const xml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
1186
|
+
const xml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
925
1187
|
|
|
926
|
-
|
|
1188
|
+
// The start at logon, set up: {file, note}.
|
|
1189
|
+
export function installLogonAutostart() {
|
|
927
1190
|
const { program, env } = startCommandLine();
|
|
928
1191
|
const [desktop, service] = autostartFiles();
|
|
929
1192
|
let file;
|
|
@@ -970,48 +1233,163 @@ async function installCommand() {
|
|
|
970
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`);
|
|
971
1234
|
} else {
|
|
972
1235
|
file = service;
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
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}`);
|
|
981
1347
|
}
|
|
982
|
-
console.log(`claude-pro host starts at logon now: ${file}${note}`);
|
|
983
1348
|
return startCommand();
|
|
984
1349
|
}
|
|
985
1350
|
|
|
986
1351
|
function uninstallCommand() {
|
|
987
|
-
|
|
1352
|
+
const removed = [];
|
|
1353
|
+
const task = removeBootAutostart();
|
|
1354
|
+
if (task) removed.push(task);
|
|
988
1355
|
for (const file of autostartFiles()) {
|
|
989
1356
|
if (!fs.existsSync(file)) continue;
|
|
990
1357
|
if (process.platform === 'darwin') spawnSync('launchctl', ['unload', '-w', file], { stdio: 'ignore' });
|
|
991
1358
|
if (file.endsWith('.service')) spawnSync('systemctl', ['--user', 'disable', path.basename(file)], { stdio: 'ignore' });
|
|
992
1359
|
fs.rmSync(file, { force: true });
|
|
993
|
-
|
|
994
|
-
removed++;
|
|
1360
|
+
removed.push(file);
|
|
995
1361
|
}
|
|
996
|
-
|
|
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.');
|
|
997
1365
|
if (hostRunning()) console.log('It is still running now: `claude-pro host stop` stops it.');
|
|
998
1366
|
return 0;
|
|
999
1367
|
}
|
|
1000
1368
|
|
|
1001
1369
|
const USAGE = `Usage: claude-pro host [run | start | stop | status | install | uninstall]
|
|
1002
1370
|
|
|
1003
|
-
The computer service: it
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
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).
|
|
1007
1381
|
|
|
1008
1382
|
claude-pro host Run it here, in the foreground (Ctrl+C stops it)
|
|
1009
1383
|
claude-pro host start Run it in the background (log: ~/.claude-pro/host.log)
|
|
1010
1384
|
claude-pro host stop Stop it and take this computer off the gateway's list (sessions then no longer start it)
|
|
1011
1385
|
claude-pro host status Whether it runs, its id, its log
|
|
1012
|
-
claude-pro host install Start it at logon
|
|
1013
|
-
Linux: a desktop autostart entry, else a systemd user service)
|
|
1014
|
-
|
|
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)
|
|
1015
1393
|
`;
|
|
1016
1394
|
|
|
1017
1395
|
// `claude-pro host ...`: returns the exit code (`run` ends the process itself once the service has stopped).
|
|
@@ -1019,10 +1397,11 @@ export async function hostCommand(args = []) {
|
|
|
1019
1397
|
const [sub = 'run', ...rest] = args;
|
|
1020
1398
|
switch (sub) {
|
|
1021
1399
|
case 'run': process.exit(await runHost({ background: rest.includes('--background') })); break;
|
|
1400
|
+
case 'check': return checkCommand();
|
|
1022
1401
|
case 'start': return startCommand();
|
|
1023
1402
|
case 'stop': return stopCommand();
|
|
1024
1403
|
case 'status': return statusCommand();
|
|
1025
|
-
case 'install': return installCommand();
|
|
1404
|
+
case 'install': return installCommand(rest);
|
|
1026
1405
|
case 'uninstall': return uninstallCommand();
|
|
1027
1406
|
case 'help': case '-h': case '--help': process.stdout.write(USAGE); return 0;
|
|
1028
1407
|
default: process.stderr.write(`Unknown host command: ${sub}\n\n${USAGE}`); return 2;
|