@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/src/background.js DELETED
@@ -1,514 +0,0 @@
1
- // The background sessions of this computer: claude-pro --headless processes that the computer service (host.js)
2
- // starts for the web page, without a window. Each one is a supervisor (bin/claude-pro.js, see supervisor.js) with
3
- // the session as its child, so that /restart, /cd, the Restart tool and updates restart it as they restart a
4
- // terminal session, under the same id. The service only watches the supervisor:
5
- //
6
- // - it ends with 0, or the session left a mark that it ended (/exit, the service's stop): exited, and off the list
7
- // of sessions to open again;
8
- // - otherwise it crashed: opened again with --resume (the same conversation, the same id at the gateway), at most
9
- // MAX_CRASHES times in CRASH_WINDOW_MS, then failed (with the end of its log as the error);
10
- // - CONFIG_DIR/host-sessions.json keeps the sessions to open again when the service starts (after a reboot, or a
11
- // new version of the service): one still running is taken over, the others are opened again with --resume. A task
12
- // that was running is not continued: the conversation is.
13
- // - Whether a session runs is told by the processes themselves (liveSessionProcesses: those started with --headless
14
- // --remote-id <id>), not by a pid kept from before: a session is never opened while a process of it runs, and
15
- // copies that should not be there (two supervisors of one id) are ended, the one the service knew kept.
16
- //
17
- // Each session's output (its log: what it printed, as plain text, and the errors of its processes) goes to
18
- // CONFIG_DIR/logs/sessions/<id>.log, cut down to LOG_BYTES (copied to .log.1 first) once a minute.
19
- //
20
- // What the service learns from a session (its directory after a /cd, its name, its conversation) comes from the
21
- // registry of this computer's sessions (peers.js), where a session also takes its orders from the service
22
- // (POST /control: exit, restart).
23
-
24
- import fs from 'node:fs';
25
- import path from 'node:path';
26
- import { spawn, spawnSync } from 'node:child_process';
27
- import { listPeers, controlPeer } from './peers.js';
28
-
29
- export const CRASH_WINDOW_MS = 10 * 60_000;
30
- export const MAX_CRASHES = 3;
31
- const KEEP_ENDED = 20;
32
- const LOG_BYTES = 1_000_000;
33
- const STOP_WAIT_MS = 10_000;
34
- const STARTING_MS = 30_000; // a session that has not shown up in the registry by then counts as running anyway
35
- const ID = /^[A-Za-z0-9_-]{8,64}$/;
36
-
37
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
38
-
39
- export function pidAlive(pid) {
40
- if (!Number.isInteger(pid) || pid <= 0) return false;
41
- try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
42
- }
43
-
44
- // The processes of background sessions running now, by their id at the gateway: Map id -> {supervisors, sessions}
45
- // ([{pid, ppid}] each): the processes started with --headless --remote-id <id> (bin/claude-pro.js runs the
46
- // supervisor, which runs the session with the same arguments). A supervisor is one whose parent is not one of them;
47
- // a session without its supervisor (killed) is in `sessions` alone. Read from the system's list of processes.
48
- export function liveSessionProcesses() {
49
- let rows = [];
50
- try {
51
- if (process.platform === 'win32') {
52
- const script = [
53
- '[Console]::OutputEncoding = [Text.Encoding]::UTF8',
54
- // a tab between the fields: "`t" in a string of double quotes
55
- "Get-CimInstance Win32_Process -Filter \"CommandLine LIKE '%--headless%'\" | ForEach-Object { \"{0}`t{1}`t{2}\" -f $_.ProcessId, $_.ParentProcessId, $_.CommandLine }",
56
- ].join('\n');
57
- const r = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], { windowsHide: true, encoding: 'utf8', timeout: 30_000 });
58
- rows = String(r.stdout || '').split(/\r?\n/).filter(Boolean).map((l) => { const [pid, ppid, ...rest] = l.split('\t'); return { pid: Number(pid), ppid: Number(ppid), args: rest.join('\t') }; });
59
- } else if (process.platform === 'linux') {
60
- for (const d of fs.readdirSync('/proc')) {
61
- if (!/^\d+$/.test(d)) continue;
62
- try {
63
- const args = fs.readFileSync(`/proc/${d}/cmdline`, 'utf8').split('\0').join(' ');
64
- if (!args.includes('--headless')) continue;
65
- const stat = fs.readFileSync(`/proc/${d}/stat`, 'utf8');
66
- rows.push({ pid: Number(d), ppid: Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]), args });
67
- } catch { /* gone meanwhile */ }
68
- }
69
- } else {
70
- const r = spawnSync('ps', ['-axo', 'pid=,ppid=,command='], { encoding: 'utf8', timeout: 30_000 });
71
- rows = String(r.stdout || '').split('\n').map((l) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(l)).filter(Boolean).map((m) => ({ pid: Number(m[1]), ppid: Number(m[2]), args: m[3] }));
72
- }
73
- } catch { /* nothing known: nothing taken for running */ }
74
- const byId = new Map();
75
- for (const row of rows) {
76
- const id = /--remote-id\s+"?([A-Za-z0-9_-]{8,64})/.exec(row.args)?.[1];
77
- if (!id || !/--headless/.test(row.args) || row.pid === process.pid) continue;
78
- if (!byId.has(id)) byId.set(id, []);
79
- byId.get(id).push({ pid: row.pid, ppid: row.ppid });
80
- }
81
- const out = new Map();
82
- for (const [id, list] of byId) {
83
- const pids = new Set(list.map((p) => p.pid));
84
- out.set(id, { supervisors: list.filter((p) => !pids.has(p.ppid)), sessions: list.filter((p) => pids.has(p.ppid)) });
85
- }
86
- return out;
87
- }
88
-
89
- // Where a background session says it ended for good (see App.exit): the service reads and removes it.
90
- export const endedMarker = (dir, id) => path.join(dir, 'background-ended', id);
91
-
92
- export function markEnded(dir, id) {
93
- if (!ID.test(String(id || ''))) return;
94
- try {
95
- fs.mkdirSync(path.dirname(endedMarker(dir, id)), { recursive: true });
96
- fs.writeFileSync(endedMarker(dir, id), new Date().toISOString());
97
- } catch { /* the service then thinks it crashed, and opens it again */ }
98
- }
99
-
100
- // The last `lines` lines of a log (and of the one before it, when that is not enough).
101
- export function tailFile(file, lines = 200) {
102
- const read = (f) => { try { return fs.readFileSync(f, 'utf8'); } catch { return ''; } };
103
- let text = read(file);
104
- if (text.split('\n').length <= lines) text = read(`${file}.1`) + text;
105
- const all = text.replace(/\n$/, '').split('\n');
106
- return all.slice(-lines).join('\n');
107
- }
108
-
109
- // End a process and what it started: the supervisor of a session, and the session under it.
110
- export function killTree(pid) {
111
- if (!pidAlive(pid)) return;
112
- if (process.platform === 'win32') {
113
- spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
114
- return;
115
- }
116
- try { process.kill(-pid, 'SIGTERM'); } catch { try { process.kill(pid, 'SIGTERM'); } catch { /* gone */ } }
117
- setTimeout(() => { try { process.kill(-pid, 'SIGKILL'); } catch { /* gone */ } }, 3000).unref?.();
118
- }
119
-
120
- export class BackgroundSessions {
121
- // dir: CONFIG_DIR. entry: bin/claude-pro.js. env: what the sessions get. onChange(): something to report.
122
- constructor({ dir, entry, env = process.env, log = () => {}, onChange = () => {}, execPath = process.execPath }) {
123
- this.dir = dir;
124
- this.entry = entry;
125
- this.env = env;
126
- this.log = log;
127
- this.onChange = onChange;
128
- this.execPath = execPath;
129
- this.sessions = new Map(); // sessionId -> record (running, starting, restarting, failed, or suspended)
130
- this.ended = []; // the public records of the sessions that ended, newest first
131
- this.timer = null;
132
- this.rotateTimer = null;
133
- this.suspended = false;
134
- }
135
-
136
- get file() { return path.join(this.dir, 'host-sessions.json'); }
137
- logFile(id) { return path.join(this.dir, 'logs', 'sessions', `${id}.log`); }
138
-
139
- // The sessions saved by the service before: taken over when they still run, opened again when not.
140
- start() {
141
- let saved = [];
142
- let live = null; // the processes of the sessions running now, read once
143
- try { saved = JSON.parse(fs.readFileSync(this.file, 'utf8')); } catch { /* none */ }
144
- for (const s of Array.isArray(saved) ? saved : []) {
145
- if (!s || !ID.test(String(s.sessionId || '')) || typeof s.cwd !== 'string') continue;
146
- const rec = this.record(s);
147
- this.sessions.set(rec.sessionId, rec);
148
- if (s.state === 'failed') { rec.state = 'failed'; rec.error = s.error || null; continue; }
149
- if (s.suspended) { rec.suspended = true; rec.state = 'exited'; continue; }
150
- live ??= liveSessionProcesses();
151
- if (this.adopt(rec, live.get(rec.sessionId), s.pid)) {
152
- rec.startedAt = s.startedAt || null;
153
- } else {
154
- this.log(`opening the background session ${rec.sessionId} again in ${rec.cwd}`);
155
- this.launch(rec, { resume: true });
156
- }
157
- }
158
- this.closed = false;
159
- this.timer = setInterval(() => this.tick(), 2000);
160
- this.timer.unref?.();
161
- this.rotateTimer = setInterval(() => this.rotateLogs(), 60_000);
162
- this.rotateTimer.unref?.();
163
- this.persist();
164
- }
165
-
166
- // The service stops watching (its sessions run on, for the next one to take over).
167
- close() {
168
- this.closed = true;
169
- clearInterval(this.timer);
170
- clearInterval(this.rotateTimer);
171
- }
172
-
173
- record(s) {
174
- return {
175
- sessionId: s.sessionId,
176
- cwd: s.cwd,
177
- name: s.name || '',
178
- conversationId: s.conversationId || null,
179
- model: s.model || null,
180
- state: 'starting',
181
- pid: null,
182
- childPid: null,
183
- child: null,
184
- startedAt: null,
185
- endedAt: null,
186
- exitCode: null,
187
- error: null,
188
- restarts: 0,
189
- crashes: [],
190
- stopping: false,
191
- restartFrom: null,
192
- suspended: false,
193
- attached: 0, // terminals attached to it (claude-pro attach, a window the page opened)
194
- };
195
- }
196
-
197
- // A new background session for the web page: {sessionId, cwd, name, conversationId (to resume), model}.
198
- open({ sessionId, cwd, name = '', resume = null, model = null }) {
199
- if (this.sessions.get(sessionId) && this.alive(this.sessions.get(sessionId))) throw new Error('这个会话已经在运行');
200
- const rec = this.record({ sessionId, cwd, name, conversationId: resume, model });
201
- this.sessions.set(sessionId, rec);
202
- this.ended = this.ended.filter((e) => e.sessionId !== sessionId);
203
- this.launch(rec, { resume: Boolean(resume), first: true });
204
- this.persist();
205
- this.onChange();
206
- return { pid: rec.pid };
207
- }
208
-
209
- // Take over the session `rec` when processes of it run (`found`: an entry of liveSessionProcesses): its supervisor,
210
- // the one with pid `prefer` when there are several (the others, copies that should not be there, are ended);
211
- // without one, the session process itself (its supervisor was killed: it ends one day, and is then opened again).
212
- // Returns whether there was one to take over.
213
- adopt(rec, found, prefer = null) {
214
- const heads = found?.supervisors?.length ? found.supervisors : found?.sessions || [];
215
- if (!heads.length) return false;
216
- const keep = heads.find((p) => p.pid === prefer) || heads.find((p) => p.pid === rec.pid) || heads[heads.length - 1];
217
- for (const p of heads) {
218
- if (p === keep) continue;
219
- this.log(`the background session ${rec.sessionId} ran twice: ended the copy with pid ${p.pid}, kept ${keep.pid}`);
220
- killTree(p.pid);
221
- }
222
- rec.pid = keep.pid;
223
- rec.child = null;
224
- rec.state = 'running';
225
- rec.suspended = false;
226
- this.log(`took over the background session ${rec.sessionId} (pid ${rec.pid}) in ${rec.cwd}`);
227
- return true;
228
- }
229
-
230
- // Start the session's processes; with `resume` (opened again: after a crash, a restart of the service, a login)
231
- // only when none of them runs (see adopt): opening it again then would make two copies of one session.
232
- launch(rec, { resume = false, first = false } = {}) {
233
- if (resume && this.adopt(rec, liveSessionProcesses().get(rec.sessionId))) {
234
- this.persist();
235
- this.onChange();
236
- return;
237
- }
238
- const args = [this.entry, '--headless', '--remote-id', rec.sessionId];
239
- if (resume && rec.conversationId) args.push('--resume', rec.conversationId);
240
- if (first && rec.name) args.push('--name', rec.name);
241
- if (first && rec.model) args.push('--model', rec.model);
242
- const log = this.logFile(rec.sessionId);
243
- let fd = null;
244
- try {
245
- fs.mkdirSync(path.dirname(log), { recursive: true });
246
- fs.appendFileSync(log, `${new Date().toISOString()} [service] starting: claude-pro ${args.slice(1).join(' ')}\n`);
247
- fd = fs.openSync(log, 'a');
248
- const child = spawn(this.execPath, args, { cwd: rec.cwd, env: this.env, detached: true, windowsHide: true, stdio: ['ignore', fd, fd] });
249
- rec.child = child;
250
- rec.pid = child.pid ?? null;
251
- rec.childPid = null;
252
- rec.state = rec.state === 'restarting' ? 'restarting' : 'starting';
253
- rec.startedAt = new Date().toISOString();
254
- rec.launchedAt = Date.now();
255
- rec.endedAt = null;
256
- rec.exitCode = null;
257
- rec.error = null;
258
- rec.stopping = false;
259
- rec.suspended = false;
260
- child.on('error', (e) => {
261
- if (rec.child !== child) return;
262
- rec.child = null;
263
- this.fail(rec, `无法启动:${e.message}`);
264
- });
265
- child.on('exit', (code, signal) => {
266
- if (rec.child !== child) return;
267
- rec.child = null;
268
- this.gone(rec, code ?? (signal ? `signal ${signal}` : null));
269
- });
270
- child.unref();
271
- } catch (e) {
272
- this.fail(rec, `无法启动:${e.message}`);
273
- } finally {
274
- if (fd !== null) try { fs.closeSync(fd); } catch { /* closed */ }
275
- }
276
- }
277
-
278
- alive(rec) { return Boolean(rec.child) || pidAlive(rec.pid); }
279
-
280
- // The supervisor of `rec` is gone: ended for good, or crashed.
281
- gone(rec, code) {
282
- if (!this.sessions.has(rec.sessionId)) return;
283
- let marked = false;
284
- try { fs.rmSync(endedMarker(this.dir, rec.sessionId)); marked = true; } catch { /* none */ }
285
- if (rec.suspended) { rec.state = 'exited'; rec.endedAt = new Date().toISOString(); this.persist(); this.onChange(); return; }
286
- if (rec.stopping || marked || code === 0) {
287
- this.finish(rec, code);
288
- return;
289
- }
290
- const now = Date.now();
291
- rec.crashes = rec.crashes.filter((t) => now - t < CRASH_WINDOW_MS);
292
- rec.crashes.push(now);
293
- if (rec.crashes.length > MAX_CRASHES) {
294
- this.fail(rec, tailFile(this.logFile(rec.sessionId), 12) || `退出码 ${code}`, code);
295
- return;
296
- }
297
- rec.restarts++;
298
- rec.state = 'restarting';
299
- rec.exitCode = code;
300
- this.log(`the background session ${rec.sessionId} stopped (${code ?? 'no exit code'}): opening it again (${rec.crashes.length}/${MAX_CRASHES} in ${CRASH_WINDOW_MS / 60_000} minutes)`);
301
- this.onChange();
302
- setTimeout(() => { if (!this.closed && this.sessions.get(rec.sessionId) === rec && rec.state === 'restarting' && !this.alive(rec)) this.launch(rec, { resume: true }); }, 1000).unref?.();
303
- }
304
-
305
- fail(rec, error, code = null) {
306
- rec.state = 'failed';
307
- rec.error = String(error || '').slice(-2000);
308
- rec.exitCode = code;
309
- rec.endedAt = new Date().toISOString();
310
- this.log(`the background session ${rec.sessionId} failed: ${rec.error.split('\n').pop()}`);
311
- this.persist();
312
- this.onChange();
313
- }
314
-
315
- // Ended for good: off the list of sessions to open again.
316
- finish(rec, code = null) {
317
- rec.state = 'exited';
318
- rec.exitCode = code;
319
- rec.endedAt = new Date().toISOString();
320
- this.sessions.delete(rec.sessionId);
321
- this.ended.unshift(this.public(rec));
322
- this.ended.length = Math.min(this.ended.length, KEEP_ENDED);
323
- this.log(`the background session ${rec.sessionId} ended`);
324
- this.persist();
325
- this.onChange();
326
- }
327
-
328
- peerOf(rec) { return listPeers().find((p) => p.remoteId === rec.sessionId && p.kind === 'background') || null; }
329
-
330
- // Every two seconds: what the sessions say about themselves in the registry, and whether they still run.
331
- tick() {
332
- let changed = false;
333
- const peers = listPeers();
334
- for (const rec of this.sessions.values()) {
335
- if (rec.state === 'failed' || rec.suspended) continue;
336
- const p = peers.find((x) => x.remoteId === rec.sessionId);
337
- if (p) {
338
- for (const [k, v] of [['cwd', p.cwd], ['name', p.name], ['conversationId', p.conversationId], ['childPid', p.pid]]) {
339
- if (v && rec[k] !== v) { rec[k] = v; changed = true; }
340
- }
341
- if (rec.state === 'starting' || (rec.state === 'restarting' && p.pid !== rec.restartFrom)) { rec.state = 'running'; rec.restartFrom = null; changed = true; }
342
- } else if (rec.state === 'starting' && Date.now() - (rec.launchedAt || 0) > STARTING_MS && this.alive(rec)) {
343
- rec.state = 'running';
344
- changed = true;
345
- }
346
- // the terminals attached to it (none while it is not in the registry: starting, restarting)
347
- const attached = Number(p?.attached) || 0;
348
- if (rec.attached !== attached) { rec.attached = attached; changed = true; }
349
- // one taken over from an earlier service has no child process here: its pid tells
350
- if (!rec.child && rec.state !== 'restarting' && !pidAlive(rec.pid)) this.gone(rec, null);
351
- }
352
- if (changed) { this.persist(); this.onChange(); }
353
- }
354
-
355
- // stop: as /exit (the session stops what it does, then ends); not ended after STOP_WAIT_MS, it is killed.
356
- async stop(sessionId) {
357
- const rec = this.sessions.get(sessionId);
358
- if (!rec) {
359
- if (this.ended.some((e) => e.sessionId === sessionId)) return {};
360
- throw new Error('这台电脑上没有这个后台会话');
361
- }
362
- if (!this.alive(rec)) { this.finish(rec, rec.exitCode); return {}; }
363
- rec.stopping = true;
364
- const peer = this.peerOf(rec);
365
- if (peer) await controlPeer(peer, { action: 'exit' }).catch(() => { /* killed below */ });
366
- for (let t = 0; t < STOP_WAIT_MS && this.alive(rec); t += 200) await sleep(200);
367
- if (this.alive(rec)) {
368
- this.log(`the background session ${sessionId} did not end in ${STOP_WAIT_MS / 1000} s: killing it`);
369
- killTree(rec.pid);
370
- for (let t = 0; t < 5000 && this.alive(rec); t += 200) await sleep(200);
371
- }
372
- if (this.sessions.get(sessionId) === rec) this.finish(rec, rec.exitCode);
373
- return {};
374
- }
375
-
376
- // restart: as /restart for one that runs (the same process tree, the conversation kept); one that failed or
377
- // ended is opened again with --resume, its count of restarts back to 0.
378
- async restart(sessionId) {
379
- let rec = this.sessions.get(sessionId);
380
- if (rec && this.alive(rec) && rec.state !== 'failed') {
381
- const peer = this.peerOf(rec);
382
- if (!peer) throw new Error('这个会话还在启动,稍后再试');
383
- rec.restartFrom = peer.pid;
384
- rec.state = 'restarting';
385
- this.onChange();
386
- try {
387
- await controlPeer(peer, { action: 'restart' });
388
- } catch (e) {
389
- rec.state = 'running';
390
- rec.restartFrom = null;
391
- this.onChange();
392
- throw new Error(`重启失败:${e.message}`);
393
- }
394
- return {};
395
- }
396
- if (!rec) {
397
- const old = this.ended.find((e) => e.sessionId === sessionId);
398
- if (!old) throw new Error('这台电脑上没有这个后台会话');
399
- rec = this.record(old);
400
- this.ended = this.ended.filter((e) => e.sessionId !== sessionId);
401
- this.sessions.set(sessionId, rec);
402
- }
403
- rec.crashes = [];
404
- rec.restarts = 0;
405
- rec.state = 'starting';
406
- this.launch(rec, { resume: true });
407
- this.persist();
408
- this.onChange();
409
- return {};
410
- }
411
-
412
- // The gateway no longer takes this computer (or it logged out): the sessions end, and are kept to be opened
413
- // again when it is back (resumeAll).
414
- async suspendAll() {
415
- if (this.suspended) return;
416
- this.suspended = true;
417
- const running = [...this.sessions.values()].filter((r) => this.alive(r));
418
- for (const rec of running) rec.suspended = true;
419
- await Promise.all(running.map(async (rec) => {
420
- const peer = this.peerOf(rec);
421
- if (peer) await controlPeer(peer, { action: 'exit' }).catch(() => {});
422
- for (let t = 0; t < STOP_WAIT_MS && this.alive(rec); t += 200) await sleep(200);
423
- if (this.alive(rec)) killTree(rec.pid);
424
- }));
425
- this.persist();
426
- this.onChange();
427
- }
428
-
429
- resumeAll() {
430
- if (!this.suspended && ![...this.sessions.values()].some((r) => r.suspended)) return;
431
- this.suspended = false;
432
- for (const rec of this.sessions.values()) {
433
- if (!rec.suspended) continue;
434
- rec.suspended = false;
435
- rec.crashes = [];
436
- this.launch(rec, { resume: true });
437
- }
438
- this.persist();
439
- this.onChange();
440
- }
441
-
442
- // The conversation `conversationId` deleted: the sessions that are not running and had it (failed, suspended,
443
- // ended) are forgotten, so that it is not opened again. Returns their logs (they hold its text), to delete too.
444
- forgetConversation(conversationId) {
445
- const logs = [];
446
- for (const rec of [...this.sessions.values()]) {
447
- if (rec.conversationId !== conversationId || this.alive(rec)) continue;
448
- this.sessions.delete(rec.sessionId);
449
- logs.push(this.logFile(rec.sessionId));
450
- }
451
- for (const e of this.ended.filter((x) => x.conversationId === conversationId)) logs.push(this.logFile(e.sessionId));
452
- this.ended = this.ended.filter((x) => x.conversationId !== conversationId);
453
- this.persist();
454
- this.onChange();
455
- return logs.flatMap((f) => [f, `${f}.1`]);
456
- }
457
-
458
- // The conversation `conversationId` already open in a session of this computer (a background one, or a terminal):
459
- // its entry in the registry.
460
- openConversation(conversationId) {
461
- if (!conversationId) return null;
462
- return listPeers().find((p) => p.conversationId === conversationId) || null;
463
- }
464
-
465
- rotateLogs() {
466
- for (const rec of this.sessions.values()) {
467
- const file = this.logFile(rec.sessionId);
468
- try {
469
- if (fs.statSync(file).size <= LOG_BYTES) continue;
470
- // copied, then emptied: the processes write to it all along (in append mode, so they go on at its end)
471
- fs.copyFileSync(file, `${file}.1`);
472
- fs.truncateSync(file, 0);
473
- } catch { /* not there yet */ }
474
- }
475
- }
476
-
477
- public(rec) {
478
- return {
479
- sessionId: rec.sessionId,
480
- cwd: rec.cwd,
481
- name: rec.name,
482
- conversationId: rec.conversationId,
483
- state: rec.state,
484
- pid: rec.pid,
485
- startedAt: rec.startedAt,
486
- endedAt: rec.endedAt,
487
- exitCode: rec.exitCode,
488
- error: rec.error,
489
- restarts: rec.restarts,
490
- attached: rec.attached || 0,
491
- };
492
- }
493
-
494
- // For the gateway: the sessions now, then those that ended (at most KEEP_ENDED).
495
- list() {
496
- return [...[...this.sessions.values()].map((r) => this.public(r)), ...this.ended];
497
- }
498
-
499
- persist() {
500
- const list = [...this.sessions.values()].map((r) => ({
501
- sessionId: r.sessionId, cwd: r.cwd, name: r.name, conversationId: r.conversationId, model: r.model,
502
- pid: r.pid, startedAt: r.startedAt, state: r.state === 'failed' ? 'failed' : undefined, error: r.state === 'failed' ? r.error : undefined,
503
- suspended: r.suspended || undefined,
504
- }));
505
- try {
506
- fs.mkdirSync(this.dir, { recursive: true });
507
- const tmp = `${this.file}.${process.pid}.tmp`;
508
- fs.writeFileSync(tmp, JSON.stringify(list, null, 2));
509
- fs.renameSync(tmp, this.file);
510
- } catch (e) {
511
- this.log(`could not save ${this.file}: ${e.message}`);
512
- }
513
- }
514
- }
package/src/connect.js DELETED
@@ -1,79 +0,0 @@
1
- // `claude-pro connect <code> [--url U]`: a new computer joins the user's gateway account with the pairing code the
2
- // web page shows (添加电脑). No login in a browser: the code stands for it. The gateway answers with an API key of
3
- // this computer's own, which is saved as /login saves one (gateway.json); then the computer service is set up to
4
- // start at logon and started, so that the page can use this computer at once and after every restart.
5
- //
6
- // POST {url}/v1/remote/pair {code, id, machine, host, platform, version, home} (no authentication)
7
- // 200 {apiKey, computerId, url, account: {name, email}} · 400 配对码无效或已过期 · 429 too many tries
8
-
9
- import os from 'node:os';
10
- import { VERSION, GATEWAY_DEFAULT_URL, loadConfig, settingsFiles, updateSettingsFile } from './config.js';
11
- import { saveGatewayLogin, normalizeGatewayUrl } from './gateway.js';
12
- import { machineName } from './peers.js';
13
- import { computerId, setComputerId, hostEnabled, ensureAutostart, startHostInBackground, hostRunning, readHostState, updateHostState } from './host.js';
14
-
15
- // The code as typed: 8 letters and digits (I, O, 0 and 1 are not used), maybe with a dash or spaces, in any case.
16
- export function normalizePairingCode(input) {
17
- const code = String(input ?? '').toUpperCase().replace(/[\s-]+/g, '');
18
- return /^[A-Z2-9]{8}$/.test(code) ? code : null;
19
- }
20
-
21
- const USAGE = `Usage: claude-pro connect <code> [--url <gateway>]
22
-
23
- Connects this computer to your gateway account with the pairing code the web page shows (远程控制 → 添加电脑),
24
- then starts the computer service and sets it to start at logon, so that the page can use this computer.
25
- --url: the gateway's address (default ${GATEWAY_DEFAULT_URL}, or CLAUDE_PRO_GATEWAY_URL).
26
- `;
27
-
28
- export async function connectCommand(args = [], { fetchImpl = globalThis.fetch, out = (s) => process.stdout.write(`${s}\n`), err = (s) => process.stderr.write(`${s}\n`), startService = true } = {}) {
29
- let url = null;
30
- const rest = [];
31
- for (let i = 0; i < args.length; i++) {
32
- if (args[i] === '--url') url = args[++i];
33
- else if (args[i].startsWith('--url=')) url = args[i].slice(6);
34
- else if (args[i] === '-h' || args[i] === '--help') { out(USAGE); return 0; }
35
- else rest.push(args[i]);
36
- }
37
- const code = normalizePairingCode(rest.join(''));
38
- if (!code) { err(`配对码应是 8 位字母和数字(例如 K7QF-M2XD),不是 "${rest.join(' ')}"\n\n${USAGE}`); return 2; }
39
- const home = os.homedir();
40
- const cfg = loadConfig({ cwd: home });
41
- const base = normalizeGatewayUrl(url || cfg.gatewayUrl);
42
- let res;
43
- let data = {};
44
- try {
45
- res = await fetchImpl(`${base}/v1/remote/pair`, {
46
- method: 'POST',
47
- headers: { 'content-type': 'application/json' },
48
- body: JSON.stringify({ code, id: computerId(), machine: machineName(cfg.env), host: os.hostname(), platform: process.platform, version: VERSION, home }),
49
- signal: AbortSignal.timeout(20_000),
50
- });
51
- data = await res.json().catch(() => ({}));
52
- } catch (e) {
53
- err(`连不上网关 ${base}:${e.message}`);
54
- return 1;
55
- }
56
- if (!res.ok || !data.apiKey) {
57
- const said = data?.error?.message || (typeof data?.error === 'string' ? data.error : '');
58
- err(res.status === 429 ? `请求太频繁,请稍后再试${said ? `(${said})` : ''}` : said || `配对失败(HTTP ${res.status})`);
59
- return 1;
60
- }
61
- const gateway = normalizeGatewayUrl(data.url || base);
62
- saveGatewayLogin({ url: gateway, apiKey: data.apiKey, account: data.account || {} });
63
- // another gateway than the one configured: the sessions and the service use this one from now on
64
- if (gateway !== normalizeGatewayUrl(cfg.gatewayUrl)) {
65
- updateSettingsFile(settingsFiles(home).user, (json) => { json.env = { ...(json.env || {}), CLAUDE_PRO_GATEWAY_URL: gateway }; });
66
- }
67
- if (data.computerId && data.computerId !== computerId()) setComputerId(data.computerId);
68
- const who = data.account?.name || data.account?.email || '你的账户';
69
- if (!hostEnabled(cfg.env)) {
70
- out(`已连接到 ${who}。CLAUDE_PRO_HOST=0:电脑服务不会自己启动,用 claude-pro host start 启动它,网页才能使用这台电脑。`);
71
- return 0;
72
- }
73
- updateHostState({ disabled: undefined, autostartDeclined: undefined });
74
- const auto = ensureAutostart({ force: true, env: cfg.env });
75
- if (startService && !hostRunning(readHostState())) startHostInBackground();
76
- // (one that runs already picks the new login up within seconds)
77
- out(`已连接到 ${who},可以在网页上使用这台电脑了。${auto?.file ? `\n登录后自动启动:${auto.file}` : ''}`);
78
- return 0;
79
- }