@yanzc/claude-pro 0.11.0 → 0.12.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.
@@ -0,0 +1,459 @@
1
+ // The local web console (claude-pro web, /web): a page on http://127.0.0.1:7878 that shows and edits what the
2
+ // terminal does (settings, providers, memory, extensions), every project's conversations, the usage, and the sessions
3
+ // running now, live, with a box to send them messages.
4
+ //
5
+ // One server for the user, shared by every session: `node server.js --serve`, started by the first /web
6
+ // (ensureWebServer). Its address and secret are in CONFIG_DIR/web.json (readable by the user alone); /web opens the
7
+ // page with the secret once, and the page keeps it as a cookie. It answers only on 127.0.0.1, only requests that name
8
+ // it as their host (no DNS rebinding), and changes only from its own page (Origin). It also runs the 后台会话, the
9
+ // sessions started from the page, in its own process (see host.js). It exits 30 minutes after the last page went
10
+ // away when it runs no session, and gives way to a newer one (another version, or its code changed in a source
11
+ // checkout) once its sessions are idle, handing them over.
12
+
13
+ import http from 'node:http';
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import crypto from 'node:crypto';
17
+ import { spawn } from 'node:child_process';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { CONFIG_DIR, VERSION } from '../config.js';
20
+
21
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
22
+ const PORT = 7878;
23
+ const IDLE_MS = 30 * 60_000;
24
+ const BODY_LIMIT = 20 * 1024 * 1024;
25
+ const COOKIE = 'cpweb';
26
+ export const stateFile = () => path.join(CONFIG_DIR, 'web.json');
27
+
28
+ // (__Host-: only this host can set it, not a page of another 7bit.fun subdomain; plain on http, in tests)
29
+ const REMOTE_COOKIE = 'cpremote';
30
+ const remoteCookieName = (origin) => (String(origin).startsWith('https:') ? `__Host-${REMOTE_COOKIE}` : REMOTE_COOKIE);
31
+ const STATIC = {
32
+ '/': ['page.html', 'text/html; charset=utf-8'],
33
+ '/app.js': ['app.js', 'text/javascript; charset=utf-8'],
34
+ '/app.css': ['app.css', 'text/css; charset=utf-8'],
35
+ };
36
+
37
+ // What the code of the console is: the version, and in a source checkout the times of its files, so that a server
38
+ // started by older code gives way to the new one.
39
+ export function codeStamp() {
40
+ const files = ['server.js', 'api.js', 'data.js', 'remote-access.js', 'page.html', 'login.html', 'app.js', 'app.css'].map((f) => path.join(HERE, f));
41
+ files.push(path.join(HERE, '..', 'live.js'), path.join(HERE, '..', 'remote.js'), path.join(HERE, '..', 'session.js'), path.join(HERE, '..', 'config.js'), path.join(HERE, '..', 'updater.js'));
42
+ const times = files.map((f) => { try { return Math.round(fs.statSync(f).mtimeMs); } catch { return 0; } });
43
+ return `${VERSION}:${crypto.createHash('sha1').update(times.join(',')).digest('hex').slice(0, 10)}`;
44
+ }
45
+
46
+ // ---------------------------------------------------------------- the server
47
+
48
+ function readBody(req) {
49
+ return new Promise((resolve, reject) => {
50
+ let size = 0;
51
+ const chunks = [];
52
+ req.on('data', (d) => {
53
+ size += d.length;
54
+ if (size > BODY_LIMIT) { reject(Object.assign(new Error('body too large'), { status: 413 })); req.destroy(); return; }
55
+ chunks.push(d);
56
+ });
57
+ req.on('end', () => {
58
+ const text = Buffer.concat(chunks).toString('utf8');
59
+ if (!text) return resolve(undefined);
60
+ try { resolve(JSON.parse(text)); } catch { reject(Object.assign(new Error('bad json'), { status: 400 })); }
61
+ });
62
+ req.on('error', reject);
63
+ });
64
+ }
65
+
66
+ const cookieOf = (req, name) => {
67
+ for (const part of String(req.headers.cookie || '').split(';')) {
68
+ const [k, ...v] = part.trim().split('=');
69
+ if (k === name) return decodeURIComponent(v.join('='));
70
+ }
71
+ return null;
72
+ };
73
+ const equal = (a, b) => {
74
+ const x = Buffer.from(String(a || ''));
75
+ const y = Buffer.from(String(b || ''));
76
+ return x.length === y.length && crypto.timingSafeEqual(x, y);
77
+ };
78
+
79
+ async function serve() {
80
+ // the secret of the server before this one, when there was one: the page's cookie stays good across a restart
81
+ const before = readState()?.token;
82
+ const token = typeof before === 'string' && /^[\w-]{32}$/.test(before) ? before : crypto.randomBytes(24).toString('base64url');
83
+ const code = codeStamp(); // the code this server runs (a later start compares it with the files as they are then)
84
+ const { routes, useHost } = await import('./api.js');
85
+ const data = await import('./data.js');
86
+ const ra = await import('./remote-access.js');
87
+ const { SessionHost } = await import('./host.js');
88
+ // the 后台会话 run here: a crash in one of them must not end the others (nor the console)
89
+ let host = null;
90
+ process.on('uncaughtException', (e) => host?.log(e, 'uncaught'));
91
+ process.on('unhandledRejection', (e) => host?.log(e, 'unhandled rejection'));
92
+ // 远程访问: what marks a request that came through the tunnel (made by this process to itself; never leaves it)
93
+ const tunnelSecret = crypto.randomBytes(24).toString('base64url');
94
+ let tunnel = null;
95
+ data.purgeTrash();
96
+ let port = PORT;
97
+ let lastActivity = Date.now();
98
+ let streams = 0;
99
+ const hosts = () => new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
100
+ const origins = () => new Set([`http://127.0.0.1:${port}`, `http://localhost:${port}`]);
101
+
102
+ const send = (res, status, body, headers = {}) => {
103
+ const text = JSON.stringify(body);
104
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...headers });
105
+ res.end(text);
106
+ };
107
+
108
+ // A running session by its peer id; one the console is taking up again (a hand-over) is waited for a moment.
109
+ async function livePeer(peerId) {
110
+ try { return data.findPeerById(peerId); } catch (e) {
111
+ const peer = await host?.waitForPeer(peerId);
112
+ if (peer) return peer;
113
+ throw e;
114
+ }
115
+ }
116
+
117
+ // POST /__login {password, remember}: the remote login page's form.
118
+ async function remoteLogin(req, res, ip, origin) {
119
+ if (!origin || String(req.headers.origin || '').toLowerCase() !== origin) return send(res, 403, { error: 'cross-site request refused' });
120
+ const blocked = ra.loginBlocked(ip);
121
+ if (blocked) return send(res, 429, { error: `密码错误次数太多,请 ${blocked} 分钟后再试` });
122
+ let body;
123
+ try { body = (await readBody(req)) || {}; } catch { return send(res, 400, { error: 'bad request' }); }
124
+ const ua = req.headers['user-agent'];
125
+ if (!ra.readRemote().enabled || !ra.checkPassword(String(body.password || ''))) {
126
+ ra.loginFailed(ip);
127
+ ra.noteLogin({ ip, ua, ok: false });
128
+ await new Promise((r) => setTimeout(r, 600)); // a little slower for each guess
129
+ return send(res, 401, { error: '密码不对' });
130
+ }
131
+ ra.loginPassed(ip);
132
+ ra.noteLogin({ ip, ua, ok: true });
133
+ const { token: value, maxAge } = ra.newSession({ remember: Boolean(body.remember), ip, ua });
134
+ return send(res, 200, { ok: true }, { 'set-cookie': `${remoteCookieName(origin)}=${value}; Path=/; HttpOnly; SameSite=Lax${origin.startsWith('https:') ? '; Secure' : ''}${maxAge ? `; Max-Age=${maxAge}` : ''}` });
135
+ }
136
+
137
+ function remoteView() {
138
+ const d = ra.readRemote();
139
+ const now = Date.now();
140
+ return {
141
+ enabled: Boolean(d.enabled), hasPassword: ra.hasPassword(d), minPassword: ra.MIN_PASSWORD,
142
+ tunnel: tunnel ? tunnel.state : { status: d.enabled ? 'connecting' : 'off', host: null, error: null },
143
+ gateway: Boolean(gatewayLoginNow()),
144
+ sessions: Object.entries(d.sessions || {}).filter(([, s]) => s.expires > now).map(([id, s]) => ({ id, created: s.created, lastSeen: s.lastSeen, expires: s.expires, ip: s.ip, ua: s.ua, remember: s.remember })),
145
+ logins: (d.logins || []).slice(0, 15),
146
+ };
147
+ }
148
+
149
+ // The tunnel follows web-remote.json (changed here, or by /web remote in a session) and the gateway login.
150
+ function gatewayLoginNow() {
151
+ try {
152
+ const g = JSON.parse(fs.readFileSync(path.join(CONFIG_DIR, 'gateway.json'), 'utf8'));
153
+ return g?.apiKey ? { url: String(g.url || process.env.CLAUDE_PRO_GATEWAY_URL || 'https://7bit.fun'), apiKey: g.apiKey } : null;
154
+ } catch { return null; }
155
+ }
156
+ function syncTunnel() {
157
+ const want = ra.readRemote().enabled && ra.hasPassword();
158
+ const login = want ? gatewayLoginNow() : null;
159
+ const key = login ? `${login.url}|${login.apiKey}` : '';
160
+ if (tunnel && tunnel.key === key) return;
161
+ tunnel?.close();
162
+ tunnel = null;
163
+ if (!login) return;
164
+ tunnel = new ra.TunnelClient({ gatewayUrl: login.url, apiKey: login.apiKey, localPort: port, secret: tunnelSecret });
165
+ tunnel.key = key;
166
+ }
167
+
168
+ const server = http.createServer(async (req, res) => {
169
+ lastActivity = Date.now();
170
+ res.setHeader('x-content-type-options', 'nosniff');
171
+ res.setHeader('x-frame-options', 'DENY');
172
+ res.setHeader('referrer-policy', 'no-referrer');
173
+ // only requests for this server by its own name: a page elsewhere cannot reach it through a name that points here
174
+ if (!hosts().has(String(req.headers.host || '').toLowerCase())) return send(res, 421, { error: 'wrong host' });
175
+ const url = new URL(req.url, `http://127.0.0.1:${port}`);
176
+ // 远程访问: through the tunnel, from https://<通讯号>.7bit.fun: its own password and cookie, and its own origin
177
+ const remote = equal(req.headers['x-cpweb-tunnel'], tunnelSecret) && /^(?:127\.0\.0\.1|::1|::ffff:127\.0\.0\.1)$/.test(req.socket.remoteAddress || '');
178
+ // (the address the browser is at, https://<通讯号>.7bit.fun, as the gateway says: changes must come from it)
179
+ const remoteOrigin = remote ? String(req.headers['x-cpweb-origin'] || '').toLowerCase() : '';
180
+ const ip = remote ? String(req.headers['x-cpweb-ip'] || '') : '127.0.0.1';
181
+ try {
182
+ if (remote) {
183
+ if (url.pathname === '/__login' && req.method === 'POST') return remoteLogin(req, res, ip, remoteOrigin);
184
+ const session = ra.validSession(cookieOf(req, remoteCookieName(remoteOrigin)));
185
+ if (!session) {
186
+ if (url.pathname.startsWith('/api/')) return send(res, 401, { error: '请先登录', login: true });
187
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'content-security-policy': "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'unsafe-inline'; frame-ancestors 'none'" });
188
+ return res.end(fs.readFileSync(path.join(HERE, 'login.html')));
189
+ }
190
+ if (url.pathname === '/api/logout' && req.method === 'POST') {
191
+ ra.endSession(cookieOf(req, remoteCookieName(remoteOrigin)));
192
+ return send(res, 200, { ok: true }, { 'set-cookie': `${remoteCookieName(remoteOrigin)}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax${remoteOrigin.startsWith('https:') ? '; Secure' : ''}` });
193
+ }
194
+ if (req.method !== 'GET' && req.method !== 'HEAD' && String(req.headers.origin || '').toLowerCase() !== remoteOrigin) return send(res, 403, { error: 'cross-site request refused' });
195
+ }
196
+ // the secret, once, from /web: kept as a cookie, then out of the address
197
+ if (!remote && req.method === 'GET' && url.pathname === '/' && url.searchParams.has('t')) {
198
+ if (!equal(url.searchParams.get('t'), token)) return send(res, 403, { error: '链接已失效:请在 claude-pro 里重新运行 /web' });
199
+ res.writeHead(302, { location: '/', 'set-cookie': `${COOKIE}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${30 * 86400}`, 'cache-control': 'no-store' });
200
+ return res.end();
201
+ }
202
+ if (req.method === 'GET' && STATIC[url.pathname]) {
203
+ const [file, type] = STATIC[url.pathname];
204
+ res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store', 'content-security-policy': "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; frame-ancestors 'none'" });
205
+ return res.end(fs.readFileSync(path.join(HERE, file)));
206
+ }
207
+ if (!url.pathname.startsWith('/api/')) return send(res, 404, { error: 'not found' });
208
+ const bearer = equal(String(req.headers.authorization || '').replace(/^Bearer /, ''), token);
209
+ const authed = remote || bearer || equal(cookieOf(req, COOKIE), token);
210
+ if (!authed) return send(res, 401, { error: '需要从 claude-pro 打开:在会话里输入 /web,或运行 claude-pro web' });
211
+ // (a request with the secret in its header is claude-pro's, not a page's: no cross-site question)
212
+ if (!remote && !bearer && req.method !== 'GET' && req.method !== 'HEAD') {
213
+ // a change only from the console's own page
214
+ if (!origins().has(String(req.headers.origin || '').toLowerCase())) return send(res, 403, { error: 'cross-site request refused' });
215
+ if (req.headers['content-length'] && req.headers['content-length'] !== '0' && !/^application\/json\b/i.test(String(req.headers['content-type'] || ''))) return send(res, 415, { error: 'JSON body required' });
216
+ }
217
+ if (url.pathname === '/api/ping') return send(res, 200, { ok: true, version: VERSION, code, pid: process.pid, remote, nativeFolderPicker: !remote && process.platform === 'win32', hosted: host?.size ?? 0 });
218
+ if (remote && url.pathname === '/api/projects/pick') return send(res, 403, { error: '远程访问请使用目录列表' });
219
+ // a newer console was started (ensureWebServer): this one gives way once its sessions are idle
220
+ if (url.pathname === '/api/handover' && req.method === 'POST') { host?.requestHandover(); return send(res, 200, { ok: true }); }
221
+ // a session an older version started in a hidden window moves in (App.maybeMoveIntoConsole): the state it leaves
222
+ if (url.pathname === '/api/adopt' && req.method === 'POST') {
223
+ if (!bearer) return send(res, 403, { error: 'claude-pro only' });
224
+ const state = (await readBody(req))?.state;
225
+ if (!host || !state || typeof state.cwd !== 'string' || !fs.existsSync(state.cwd)) return send(res, 400, { error: 'no state' });
226
+ if ([...host.apps].some((a) => a.store?.id === state.sessionId)) return send(res, 409, { error: 'running here already' });
227
+ const app = await host.launch({ cwd: state.cwd, restart: state });
228
+ if (app.exiting) return send(res, 500, { error: 'it did not start' });
229
+ return send(res, 200, { ok: true, peerId: app.peers?.id || null });
230
+ }
231
+ // 远程访问's own settings: on or off, the password, the devices logged in, the recent logins
232
+ if (url.pathname === '/api/remote' && req.method === 'GET') return send(res, 200, remoteView());
233
+ if (url.pathname === '/api/remote' && req.method === 'POST') {
234
+ const body = (await readBody(req)) || {};
235
+ if (typeof body.password === 'string' && body.password) {
236
+ try { ra.setPassword(body.password); } catch (e) { return send(res, 400, { error: e.message }); }
237
+ }
238
+ if (typeof body.enabled === 'boolean') {
239
+ if (body.enabled && !ra.hasPassword()) return send(res, 400, { error: '先设一个密码' });
240
+ ra.setEnabled(body.enabled);
241
+ }
242
+ if (body.logoutAll) ra.endAllSessions();
243
+ syncTunnel();
244
+ return send(res, 200, remoteView());
245
+ }
246
+
247
+ // an image of a running session's conversation, from its peer server
248
+ const liveImage = /^\/api\/live\/([0-9a-f]{12})\/image\/(\d+)$/.exec(url.pathname);
249
+ if (liveImage && req.method === 'GET') {
250
+ const peer = await livePeer(liveImage[1]);
251
+ const upstream = http.get({ host: '127.0.0.1', port: peer.port, path: `/image/${liveImage[2]}`, headers: { authorization: `Bearer ${peer.token}` } }, (up) => {
252
+ if (up.statusCode !== 200) { up.resume(); return send(res, 404, { error: 'no such image' }); }
253
+ res.writeHead(200, { 'content-type': up.headers['content-type'] || 'application/octet-stream', 'cache-control': 'private, max-age=3600' });
254
+ up.pipe(res);
255
+ });
256
+ upstream.on('error', () => { if (!res.headersSent) send(res, 502, { error: '连不上这个会话' }); else res.end(); });
257
+ return;
258
+ }
259
+ // a running session's live view: its peer server's event stream, passed through
260
+ const live = /^\/api\/live\/([0-9a-f]{12})\/events$/.exec(url.pathname);
261
+ if (live && req.method === 'GET') {
262
+ let upstream, upstreamResponse, counted = false;
263
+ res.once('close', () => {
264
+ if (counted) { streams--; lastActivity = Date.now(); }
265
+ upstreamResponse?.destroy();
266
+ upstream?.destroy();
267
+ });
268
+ const peer = await livePeer(live[1]);
269
+ if (res.destroyed || res.writableEnded) return;
270
+ upstream = http.get({ host: '127.0.0.1', port: peer.port, path: '/events', headers: { authorization: `Bearer ${peer.token}` } }, (up) => {
271
+ upstreamResponse = up;
272
+ if (res.destroyed || res.writableEnded) { up.destroy(); return; }
273
+ if (up.statusCode !== 200) { up.resume(); return send(res, up.statusCode === 404 ? 409 : 502, { error: up.statusCode === 404 ? '这个会话的 claude-pro 版本较旧,不支持实时查看' : '会话没有回应' }); }
274
+ streams++;
275
+ counted = true;
276
+ res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache', connection: 'keep-alive' });
277
+ res.write('retry: 2000\n\n');
278
+ up.pipe(res);
279
+ up.on('error', () => res.end());
280
+ });
281
+ upstream.on('error', () => {
282
+ if (res.destroyed || res.writableEnded) return;
283
+ if (!res.headersSent) send(res, 502, { error: '连不上这个会话' }); else res.end();
284
+ });
285
+ return;
286
+ }
287
+
288
+ for (const [method, pattern, handler] of routes) {
289
+ if (method !== req.method) continue;
290
+ const m = pattern.exec(url.pathname);
291
+ if (!m) continue;
292
+ const body = method === 'GET' || method === 'DELETE' ? undefined : await readBody(req);
293
+ const result = await handler(req, m.slice(1).map(decodeURIComponent), body, url);
294
+ if (result?.raw) {
295
+ const { type, data: payload, name } = result.raw;
296
+ res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store', ...(name ? { 'content-disposition': `attachment; filename="${name}"` } : {}) });
297
+ return res.end(payload);
298
+ }
299
+ return send(res, 200, result ?? {});
300
+ }
301
+ return send(res, 404, { error: `${req.method} ${url.pathname} is not part of the console` });
302
+ } catch (e) {
303
+ if (res.headersSent) { try { res.end(); } catch { /* gone */ } return; }
304
+ return send(res, e.status || 500, { error: e.message || String(e) });
305
+ }
306
+ });
307
+
308
+ // 7878, or the port the server before this one had (it may still be letting go of it for a moment: tried for 3 s),
309
+ // else any port
310
+ const wanted = Number(readState()?.port) || PORT;
311
+ const listen = (p) => new Promise((resolve, reject) => {
312
+ const onError = (e) => { server.off('listening', onListening); reject(e); };
313
+ const onListening = () => { server.off('error', onError); resolve(); };
314
+ server.once('error', onError);
315
+ server.once('listening', onListening);
316
+ server.listen(p, '127.0.0.1');
317
+ });
318
+ let bound = false;
319
+ for (const p of [...new Set([wanted, PORT])]) {
320
+ for (let i = 0; i < 15 && !bound; i++) {
321
+ try { await listen(p); bound = true; } catch (e) {
322
+ if (e.code !== 'EADDRINUSE') throw e;
323
+ await new Promise((r) => setTimeout(r, 200));
324
+ }
325
+ }
326
+ if (bound) break;
327
+ }
328
+ if (!bound) await listen(0);
329
+ port = server.address().port;
330
+ const state = { pid: process.pid, port, token, version: VERSION, code, startedAt: Date.now() };
331
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
332
+ const tmp = `${stateFile()}.${process.pid}.tmp`;
333
+ fs.writeFileSync(tmp, JSON.stringify(state), { mode: 0o600 });
334
+ fs.renameSync(tmp, stateFile());
335
+
336
+ syncTunnel();
337
+ setInterval(syncTunnel, 3000).unref();
338
+
339
+ // Its code changed (an update, an edit in a source checkout, see SessionHost.watch), or a session asked for a
340
+ // restart: once the sessions are idle a new server takes over, on the same port and with the same secret (an open
341
+ // page keeps working, with the new page code, read from disk at every load), and takes the sessions up again.
342
+ host = new SessionHost({
343
+ restartProcess: () => {
344
+ tunnel?.close();
345
+ server.close();
346
+ server.closeAllConnections?.();
347
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--serve'], { detached: true, stdio: 'ignore', windowsHide: true, env: process.env });
348
+ child.on('error', () => {});
349
+ child.unref();
350
+ setTimeout(() => process.exit(0), 200);
351
+ },
352
+ });
353
+ useHost(host);
354
+ host.watch();
355
+ host.recover().catch((e) => host.log(e, 'recover'));
356
+
357
+ // (web.json stays: the next server takes its secret over, so that the page's cookie still works; the list of
358
+ // sessions stays too: the next server brings them back)
359
+ const quit = () => process.exit(0);
360
+ // with 远程访问 on, or a session running, it stays (a phone may come any time)
361
+ setInterval(() => { if (!streams && !tunnel && !host.size && Date.now() - lastActivity > IDLE_MS) quit(); }, 60_000).unref();
362
+ process.on('SIGTERM', quit);
363
+ process.on('SIGINT', quit);
364
+ }
365
+
366
+ // ---------------------------------------------------------------- starting it, from a session or the command line
367
+
368
+ function readState() {
369
+ try { return JSON.parse(fs.readFileSync(stateFile(), 'utf8')); } catch { return null; }
370
+ }
371
+
372
+ async function ping(state) {
373
+ try {
374
+ const res = await fetch(`http://127.0.0.1:${state.port}/api/ping`, { headers: { authorization: `Bearer ${state.token}` }, signal: AbortSignal.timeout(1500) });
375
+ return res.ok ? await res.json() : null;
376
+ } catch { return null; }
377
+ }
378
+
379
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
380
+
381
+ // The running console, started (or restarted, when it is older code) if need be. Resolves with {url, port, started}:
382
+ // `url` opens the page logged in.
383
+ export async function ensureWebServer() {
384
+ let state = readState();
385
+ let alive = state ? await ping(state) : null;
386
+ if (alive && alive.code !== codeStamp()) {
387
+ if (alive.hosted) {
388
+ // it runs sessions: they are not cut off, it gives way once they are idle, handing them over (it is used meanwhile)
389
+ await fetch(`http://127.0.0.1:${state.port}/api/handover`, { method: 'POST', headers: { authorization: `Bearer ${state.token}` }, signal: AbortSignal.timeout(1500) }).catch(() => {});
390
+ } else {
391
+ try { process.kill(alive.pid); } catch { /* gone already */ }
392
+ await sleep(300);
393
+ alive = null;
394
+ }
395
+ }
396
+ let started = false;
397
+ if (!alive) {
398
+ const env = { ...process.env, FORCE_COLOR: '1' }; // the tool headers it renders keep their colours for the page
399
+ delete env.NO_COLOR;
400
+ delete env.CLAUDE_PRO_BACKGROUND; // (the server is no session: a 后台会话 that starts it must not pass that on)
401
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--serve'], { detached: true, stdio: 'ignore', windowsHide: true, env });
402
+ child.on('error', () => {});
403
+ child.unref();
404
+ started = true;
405
+ const until = Date.now() + 8000;
406
+ for (;;) {
407
+ await sleep(150);
408
+ state = readState();
409
+ if (state?.pid === child.pid && (alive = await ping(state))) break;
410
+ if (Date.now() > until) throw new Error('the web console did not start (see whether port 7878 or the config directory is usable)');
411
+ }
412
+ }
413
+ return { url: `http://127.0.0.1:${state.port}/?t=${state.token}`, port: state.port, started };
414
+ }
415
+
416
+ // A session of an older version, in a hidden window, moves into the console's process: the console (started if need
417
+ // be) takes it up from `state` (what a restart carries over). Resolves {ok, peerId} or {ok: false, error}.
418
+ export async function adoptIntoConsole(state) {
419
+ const { port } = await ensureWebServer();
420
+ const token = readState()?.token;
421
+ const res = await fetch(`http://127.0.0.1:${port}/api/adopt`, {
422
+ method: 'POST',
423
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
424
+ body: JSON.stringify({ state }),
425
+ signal: AbortSignal.timeout(30_000),
426
+ });
427
+ const body = await res.json().catch(() => ({}));
428
+ return res.ok ? body : { ok: false, error: body.error || `HTTP ${res.status}` };
429
+ }
430
+
431
+ // The page in the user's browser.
432
+ export function openBrowser(url) {
433
+ const [cmd, args] = process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
434
+ : process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
435
+ try {
436
+ const child = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true });
437
+ child.on('error', () => {});
438
+ child.unref();
439
+ return true;
440
+ } catch { return false; }
441
+ }
442
+
443
+ // `claude-pro web [--no-open]`
444
+ export async function webCommand(argv = []) {
445
+ try {
446
+ const { url, port, started } = await ensureWebServer();
447
+ const open = !argv.includes('--no-open');
448
+ if (open) openBrowser(url);
449
+ process.stdout.write(`claude-pro web console ${started ? 'started' : 'is running'} at http://127.0.0.1:${port}\n${open ? 'Opened it in your browser. ' : ''}Log-in link (keep it to yourself): ${url}\n`);
450
+ return 0;
451
+ } catch (e) {
452
+ process.stderr.write(`Could not start the web console: ${e.message}\n`);
453
+ return 1;
454
+ }
455
+ }
456
+
457
+ if (process.argv.includes('--serve') && process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
458
+ serve().catch((e) => { process.stderr.write(`${e.stack || e}\n`); process.exit(1); });
459
+ }