@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/main.js
CHANGED
|
@@ -25,6 +25,8 @@ Options:
|
|
|
25
25
|
--name <name> Name this session, as /rename does (other sessions reach it with &name)
|
|
26
26
|
--remote-id <id> Go online at the gateway at once with this id (the gateway's web page opens
|
|
27
27
|
sessions this way, through claude-pro host)
|
|
28
|
+
--headless A background session: no window, used from the web page (with --remote-id)
|
|
29
|
+
and from claude-pro attach; what it prints goes to stdout as a log
|
|
28
30
|
-v, --version Print version
|
|
29
31
|
-h, --help Show help
|
|
30
32
|
|
|
@@ -40,6 +42,10 @@ Commands:
|
|
|
40
42
|
claude-pro config unset <KEY> [--project|--local]
|
|
41
43
|
claude-pro host [start|stop|status|install|uninstall] The computer service: lets the gateway's web page
|
|
42
44
|
open sessions on this computer (claude-pro host --help)
|
|
45
|
+
claude-pro connect <code> [--url U] Join this computer to your gateway account with the web page's pairing
|
|
46
|
+
code; the computer service then starts, and starts at logon
|
|
47
|
+
claude-pro attach [name] Use a background session of this computer here, in this terminal
|
|
48
|
+
(ctrl+] detaches; it goes on in the background)
|
|
43
49
|
`;
|
|
44
50
|
|
|
45
51
|
const REMOTE_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
|
@@ -76,6 +82,7 @@ function parseArgs(argv) {
|
|
|
76
82
|
case '--verbose': flags.verbose = true; break;
|
|
77
83
|
case '--no-mcp': flags.noMcp = true; break;
|
|
78
84
|
case '--remote-control': case '--rc': break; // online by default now
|
|
85
|
+
case '--headless': flags.headless = true; break;
|
|
79
86
|
case '--name': flags.name = next(); break;
|
|
80
87
|
case '--remote-id': {
|
|
81
88
|
const id = next();
|
|
@@ -159,9 +166,11 @@ function readStdin({ optional }) {
|
|
|
159
166
|
}
|
|
160
167
|
|
|
161
168
|
export async function main(argv) {
|
|
162
|
-
|
|
169
|
+
let cwd = process.cwd();
|
|
163
170
|
if (argv[0] === 'config') return configCommand(argv.slice(1), cwd);
|
|
164
171
|
if (argv[0] === 'host') return (await import('./host.js')).hostCommand(argv.slice(1));
|
|
172
|
+
if (argv[0] === 'attach') return (await import('./attach.js')).attachCommand(argv.slice(1));
|
|
173
|
+
if (argv[0] === 'connect') return (await import('./connect.js')).connectCommand(argv.slice(1));
|
|
165
174
|
if (argv[0] === '--self-check') return (await import('./selfcheck.js')).selfCheck(); // see restart.js
|
|
166
175
|
const { flags, positional } = parseArgs(argv);
|
|
167
176
|
if (flags.version) { console.log(`${VERSION} (claude-pro)`); return 0; }
|
|
@@ -170,8 +179,9 @@ export async function main(argv) {
|
|
|
170
179
|
let prompt = positional.join(' ');
|
|
171
180
|
|
|
172
181
|
// Started by a restart of a running session: that session is picked up again, whatever the command line
|
|
173
|
-
// that started the first one said (-c, --resume, a first prompt).
|
|
174
|
-
|
|
182
|
+
// that started the first one said (-c, --resume, a first prompt). A background session (--headless) has no
|
|
183
|
+
// terminal and is interactive all the same.
|
|
184
|
+
const interactive = flags.headless || !(flags.print || !process.stdout.isTTY || !process.stdin.isTTY);
|
|
175
185
|
const restart = interactive ? takeRestartState() : null;
|
|
176
186
|
if (restart) {
|
|
177
187
|
flags.restart = restart;
|
|
@@ -179,19 +189,38 @@ export async function main(argv) {
|
|
|
179
189
|
flags.resume = false;
|
|
180
190
|
flags.resumeId = undefined;
|
|
181
191
|
prompt = '';
|
|
192
|
+
// the session's working directory, which /cd may have changed (the supervisor starts every process where the
|
|
193
|
+
// first one started)
|
|
194
|
+
if (typeof restart.cwd === 'string' && restart.cwd !== cwd) {
|
|
195
|
+
try {
|
|
196
|
+
if (fs.statSync(restart.cwd).isDirectory()) { process.chdir(restart.cwd); cwd = process.cwd(); }
|
|
197
|
+
} catch { /* gone meanwhile: where the first one started */ }
|
|
198
|
+
}
|
|
182
199
|
}
|
|
183
200
|
|
|
184
201
|
if (flags.continue || (flags.resume && flags.resumeId)) {
|
|
185
202
|
const sessions = SessionStore.list(cwd);
|
|
186
203
|
const found = flags.resumeId ? sessions.find((s) => s.id.startsWith(flags.resumeId)) : sessions[0];
|
|
187
|
-
if (!found) {
|
|
204
|
+
if (!found && flags.headless) {
|
|
205
|
+
// a background session opened again (after a crash, a reboot) that never had a conversation: a new one
|
|
206
|
+
process.stdout.write(`No conversation ${flags.resumeId || ''} here: starting a new one.\n`);
|
|
207
|
+
flags.continue = false;
|
|
208
|
+
flags.resume = false;
|
|
209
|
+
flags.resumeId = undefined;
|
|
210
|
+
} else if (!found) {
|
|
188
211
|
process.stderr.write(flags.resumeId ? `No conversation found with id ${flags.resumeId}\n` : 'No conversation found to continue\n');
|
|
189
212
|
return 1;
|
|
213
|
+
} else {
|
|
214
|
+
flags.resumeFile = found.file;
|
|
215
|
+
flags.resumeId = found.id;
|
|
190
216
|
}
|
|
191
|
-
flags.resumeFile = found.file;
|
|
192
|
-
flags.resumeId = found.id;
|
|
193
217
|
}
|
|
194
218
|
|
|
219
|
+
if (flags.headless) {
|
|
220
|
+
if (!fs.existsSync(cwd)) return 1;
|
|
221
|
+
const { runRepl } = await import('./ui/repl.js');
|
|
222
|
+
return await runRepl({ flags, cwd, initialPrompt: prompt });
|
|
223
|
+
}
|
|
195
224
|
// mintty (Git Bash's default window) connects programs through pipes, not a console.
|
|
196
225
|
if (!flags.print && !process.stdin.isTTY && process.env.TERM_PROGRAM === 'mintty') {
|
|
197
226
|
process.stderr.write('Interactive mode needs a real console. In mintty/Git Bash run `winpty claude-pro` (or `winpty node bin/claude-pro.js`), or use Windows Terminal. For scripts use `claude-pro -p`.\n');
|
package/src/peers.js
CHANGED
|
@@ -1,215 +1,290 @@
|
|
|
1
|
-
// Peers: the other interactive claude-pro sessions on this machine. Each session registers itself in
|
|
2
|
-
// CONFIG_DIR/peers/<id>.json (name, directory, pid, and a port and token of a small HTTP server on 127.0.0.1)
|
|
3
|
-
// so that sessions can send each other tasks: the user with `&name task` in the input box, the model with the
|
|
4
|
-
// MessagePeer tool. A task is answered automatically with the final text of the turn that handled it.
|
|
5
|
-
// Sessions on the user's other computers are reached through the gateway instead (see remote.js): they are
|
|
6
|
-
// listed as {id, name, machine, cwd, remote: true, label: 'machine/name'} and addressed by that label.
|
|
7
|
-
|
|
8
|
-
import fs from 'node:fs';
|
|
9
|
-
import os from 'node:os';
|
|
10
|
-
import path from 'node:path';
|
|
11
|
-
import http from 'node:http';
|
|
12
|
-
import crypto from 'node:crypto';
|
|
13
|
-
import { CONFIG_DIR } from './config.js';
|
|
14
|
-
|
|
15
|
-
export const PEERS_DIR = path.join(CONFIG_DIR, 'peers');
|
|
16
|
-
const MAX_BODY = 2_000_000;
|
|
17
|
-
|
|
18
|
-
export function peersEnabled(env = process.env) {
|
|
19
|
-
return !/^(0|false|no|off)$/i.test(env.CLAUDE_PRO_PEERS || '');
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function alive(pid) {
|
|
23
|
-
try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export const cleanName = (s) => String(s || '').replace(/[^\p{L}\p{M}\p{N}_.-]+/gu, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 40) || 'agent';
|
|
27
|
-
|
|
28
|
-
// The sessions that are running now (stale entries of sessions that died are removed).
|
|
29
|
-
export function listPeers({ excludeId } = {}) {
|
|
30
|
-
let files = [];
|
|
31
|
-
try { files = fs.readdirSync(PEERS_DIR).filter((f) => f.endsWith('.json')); } catch { return []; }
|
|
32
|
-
const peers = [];
|
|
33
|
-
for (const f of files) {
|
|
34
|
-
const file = path.join(PEERS_DIR, f);
|
|
35
|
-
let p;
|
|
36
|
-
try { p = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { continue; }
|
|
37
|
-
if (!p?.id || !p.port || !alive(p.pid)) { try { fs.unlinkSync(file); } catch { /* ignore */ } continue; }
|
|
38
|
-
if (p.id !== excludeId) peers.push(p);
|
|
39
|
-
}
|
|
40
|
-
return peers.sort((a, b) => a.startedAt - b.startedAt);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// The name of this computer for sessions on the other computers: CLAUDE_PRO_MACHINE_NAME (公司, home...), else
|
|
44
|
-
// the host name. Letters of any script, digits, _ . and -.
|
|
45
|
-
export function machineName(env = process.env) {
|
|
46
|
-
const raw = env.CLAUDE_PRO_MACHINE_NAME || os.hostname() || 'computer';
|
|
47
|
-
return String(raw).replace(/[^\p{L}\p{M}\p{N}_.-]+/gu, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 40) || 'computer';
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// Find the session `ref` (with or without @) names among the local ones and those on other computers: a local
|
|
51
|
-
// name (or id prefix); else machine/name, a name only one remote session has, a computer with only one session
|
|
52
|
-
// (`&公司`), or an id prefix. `ids: false` leaves the id prefixes out (for what the user types).
|
|
53
|
-
// Returns {peer}, {error, ambiguous: true} when several match, or {error: null} when none does.
|
|
54
|
-
export function resolvePeer(local, remote, ref, { ids = true } = {}) {
|
|
55
|
-
const q = String(ref || '').replace(/^[@&&]/, '').toLowerCase();
|
|
56
|
-
if (!q) return { error: null };
|
|
57
|
-
const near = ids ? findPeer(local, q) : local.find((p) => p.name.toLowerCase() === q);
|
|
58
|
-
if (near) return { peer: near };
|
|
59
|
-
const same = (v) => String(v || '').toLowerCase() === q;
|
|
60
|
-
let hits = remote.filter((p) => same(p.label));
|
|
61
|
-
if (!hits.length) hits = remote.filter((p) => same(p.name));
|
|
62
|
-
if (!hits.length) hits = remote.filter((p) => same(p.machine));
|
|
63
|
-
if (!hits.length && ids && q.length >= 4) hits = remote.filter((p) => p.id.toLowerCase().startsWith(q));
|
|
64
|
-
if (hits.length === 1) return { peer: hits[0] };
|
|
65
|
-
if (hits.length > 1) return { error: `"&${String(ref).replace(/^[@&&]/, '')}" could be ${hits.map((p) => '&' + p.label).join(', ')}: say which.`, ambiguous: true };
|
|
66
|
-
return { error: null };
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export function findPeer(peers, ref) {
|
|
70
|
-
const q = String(ref || '').replace(/^[@&&]/, '').toLowerCase();
|
|
71
|
-
if (!q) return null;
|
|
72
|
-
return peers.find((p) => p.name.toLowerCase() === q) || peers.find((p) => p.id.startsWith(q)) || null;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
export class PeerNode {
|
|
76
|
-
// onMessage(msg): msg = {id, kind: 'task'|'reply', text, inReplyTo, from: {id, name, cwd}}
|
|
77
|
-
// `id`: the id this session had before a restart, so that answers on their way still find it.
|
|
78
|
-
// getStatus(): {busy}, what GET /status answers (an update waits until no session of the machine is busy).
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
this.
|
|
85
|
-
this.
|
|
86
|
-
this.
|
|
87
|
-
this.
|
|
88
|
-
this.
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
this.server =
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
this.
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
this.
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
this.
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
req.
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
req.
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
1
|
+
// Peers: the other interactive claude-pro sessions on this machine. Each session registers itself in
|
|
2
|
+
// CONFIG_DIR/peers/<id>.json (name, directory, pid, and a port and token of a small HTTP server on 127.0.0.1)
|
|
3
|
+
// so that sessions can send each other tasks: the user with `&name task` in the input box, the model with the
|
|
4
|
+
// MessagePeer tool. A task is answered automatically with the final text of the turn that handled it.
|
|
5
|
+
// Sessions on the user's other computers are reached through the gateway instead (see remote.js): they are
|
|
6
|
+
// listed as {id, name, machine, cwd, remote: true, label: 'machine/name'} and addressed by that label.
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import http from 'node:http';
|
|
12
|
+
import crypto from 'node:crypto';
|
|
13
|
+
import { CONFIG_DIR } from './config.js';
|
|
14
|
+
|
|
15
|
+
export const PEERS_DIR = path.join(CONFIG_DIR, 'peers');
|
|
16
|
+
const MAX_BODY = 2_000_000;
|
|
17
|
+
|
|
18
|
+
export function peersEnabled(env = process.env) {
|
|
19
|
+
return !/^(0|false|no|off)$/i.test(env.CLAUDE_PRO_PEERS || '');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function alive(pid) {
|
|
23
|
+
try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const cleanName = (s) => String(s || '').replace(/[^\p{L}\p{M}\p{N}_.-]+/gu, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 40) || 'agent';
|
|
27
|
+
|
|
28
|
+
// The sessions that are running now (stale entries of sessions that died are removed).
|
|
29
|
+
export function listPeers({ excludeId } = {}) {
|
|
30
|
+
let files = [];
|
|
31
|
+
try { files = fs.readdirSync(PEERS_DIR).filter((f) => f.endsWith('.json')); } catch { return []; }
|
|
32
|
+
const peers = [];
|
|
33
|
+
for (const f of files) {
|
|
34
|
+
const file = path.join(PEERS_DIR, f);
|
|
35
|
+
let p;
|
|
36
|
+
try { p = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { continue; }
|
|
37
|
+
if (!p?.id || !p.port || !alive(p.pid)) { try { fs.unlinkSync(file); } catch { /* ignore */ } continue; }
|
|
38
|
+
if (p.id !== excludeId) peers.push(p);
|
|
39
|
+
}
|
|
40
|
+
return peers.sort((a, b) => a.startedAt - b.startedAt);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// The name of this computer for sessions on the other computers: CLAUDE_PRO_MACHINE_NAME (公司, home...), else
|
|
44
|
+
// the host name. Letters of any script, digits, _ . and -.
|
|
45
|
+
export function machineName(env = process.env) {
|
|
46
|
+
const raw = env.CLAUDE_PRO_MACHINE_NAME || os.hostname() || 'computer';
|
|
47
|
+
return String(raw).replace(/[^\p{L}\p{M}\p{N}_.-]+/gu, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 40) || 'computer';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Find the session `ref` (with or without @) names among the local ones and those on other computers: a local
|
|
51
|
+
// name (or id prefix); else machine/name, a name only one remote session has, a computer with only one session
|
|
52
|
+
// (`&公司`), or an id prefix. `ids: false` leaves the id prefixes out (for what the user types).
|
|
53
|
+
// Returns {peer}, {error, ambiguous: true} when several match, or {error: null} when none does.
|
|
54
|
+
export function resolvePeer(local, remote, ref, { ids = true } = {}) {
|
|
55
|
+
const q = String(ref || '').replace(/^[@&&]/, '').toLowerCase();
|
|
56
|
+
if (!q) return { error: null };
|
|
57
|
+
const near = ids ? findPeer(local, q) : local.find((p) => p.name.toLowerCase() === q);
|
|
58
|
+
if (near) return { peer: near };
|
|
59
|
+
const same = (v) => String(v || '').toLowerCase() === q;
|
|
60
|
+
let hits = remote.filter((p) => same(p.label));
|
|
61
|
+
if (!hits.length) hits = remote.filter((p) => same(p.name));
|
|
62
|
+
if (!hits.length) hits = remote.filter((p) => same(p.machine));
|
|
63
|
+
if (!hits.length && ids && q.length >= 4) hits = remote.filter((p) => p.id.toLowerCase().startsWith(q));
|
|
64
|
+
if (hits.length === 1) return { peer: hits[0] };
|
|
65
|
+
if (hits.length > 1) return { error: `"&${String(ref).replace(/^[@&&]/, '')}" could be ${hits.map((p) => '&' + p.label).join(', ')}: say which.`, ambiguous: true };
|
|
66
|
+
return { error: null };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function findPeer(peers, ref) {
|
|
70
|
+
const q = String(ref || '').replace(/^[@&&]/, '').toLowerCase();
|
|
71
|
+
if (!q) return null;
|
|
72
|
+
return peers.find((p) => p.name.toLowerCase() === q) || peers.find((p) => p.id.startsWith(q)) || null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export class PeerNode {
|
|
76
|
+
// onMessage(msg): msg = {id, kind: 'task'|'reply', text, inReplyTo, from: {id, name, cwd}}
|
|
77
|
+
// `id`: the id this session had before a restart, so that answers on their way still find it.
|
|
78
|
+
// getStatus(): {busy}, what GET /status answers (an update waits until no session of the machine is busy).
|
|
79
|
+
// info(): more of the session for the registry: {kind: 'terminal'|'background', remoteId, conversationId} (the
|
|
80
|
+
// computer service finds its background sessions by them, `claude-pro attach` lists them).
|
|
81
|
+
// onControl(body): POST /control, the computer service ending or restarting a background session ({action}).
|
|
82
|
+
// onAttach(socket, {cols, rows}): GET /attach upgraded, `claude-pro attach` taking over its screen (see attach.js).
|
|
83
|
+
constructor({ cwd, name, id, onMessage, getStatus, info, onControl, onAttach }) {
|
|
84
|
+
this.cwd = cwd;
|
|
85
|
+
this.wantedName = name || null;
|
|
86
|
+
this.onMessage = onMessage;
|
|
87
|
+
this.getStatus = getStatus;
|
|
88
|
+
this.info = info;
|
|
89
|
+
this.onControl = onControl;
|
|
90
|
+
this.onAttach = onAttach;
|
|
91
|
+
this.id = /^[0-9a-f]{12}$/.test(id || '') ? id : crypto.randomBytes(6).toString('hex');
|
|
92
|
+
this.token = crypto.randomBytes(16).toString('hex');
|
|
93
|
+
this.name = null;
|
|
94
|
+
this.server = null;
|
|
95
|
+
this.port = null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
get file() { return path.join(PEERS_DIR, `${this.id}.json`); }
|
|
99
|
+
|
|
100
|
+
async start() {
|
|
101
|
+
this.server = http.createServer((req, res) => this.handle(req, res));
|
|
102
|
+
this.server.on('upgrade', (req, socket) => this.upgrade(req, socket));
|
|
103
|
+
await new Promise((resolve, reject) => {
|
|
104
|
+
this.server.once('error', reject);
|
|
105
|
+
this.server.listen(0, '127.0.0.1', resolve);
|
|
106
|
+
});
|
|
107
|
+
this.server.unref();
|
|
108
|
+
this.port = this.server.address().port;
|
|
109
|
+
this.setName(this.wantedName || path.basename(this.cwd) || 'agent');
|
|
110
|
+
return this;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Take `name`, or name-2, name-3... when another live session has it. Returns the name taken.
|
|
114
|
+
setName(name) {
|
|
115
|
+
const base = cleanName(name);
|
|
116
|
+
const taken = new Set(listPeers({ excludeId: this.id }).map((p) => p.name.toLowerCase()));
|
|
117
|
+
let n = base;
|
|
118
|
+
for (let i = 2; taken.has(n.toLowerCase()); i++) n = `${base}-${i}`;
|
|
119
|
+
this.name = n;
|
|
120
|
+
this.write();
|
|
121
|
+
return n;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
setCwd(cwd) {
|
|
125
|
+
if (cwd === this.cwd) return;
|
|
126
|
+
this.cwd = cwd;
|
|
127
|
+
this.write();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
write() {
|
|
131
|
+
if (!this.port) return;
|
|
132
|
+
fs.mkdirSync(PEERS_DIR, { recursive: true });
|
|
133
|
+
let more = {};
|
|
134
|
+
try { more = this.info?.() || {}; } catch { /* the basics only */ }
|
|
135
|
+
const data = { ...more, id: this.id, name: this.name, cwd: this.cwd, pid: process.pid, port: this.port, token: this.token, startedAt: this.startedAt ??= Date.now() };
|
|
136
|
+
const json = JSON.stringify(data);
|
|
137
|
+
if (json === this.written) return;
|
|
138
|
+
// whole or not at all: the computer service reads these files every few seconds
|
|
139
|
+
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
140
|
+
fs.writeFileSync(tmp, json);
|
|
141
|
+
fs.renameSync(tmp, this.file);
|
|
142
|
+
this.written = json;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// The registry entry again, when what info() says has changed.
|
|
146
|
+
update() { try { this.write(); } catch { /* the next change writes it */ } }
|
|
147
|
+
|
|
148
|
+
// GET /attach, upgraded to a connection of its own (see attach.js): with the token, and a session that takes it.
|
|
149
|
+
upgrade(req, socket) {
|
|
150
|
+
const url = new URL(req.url, 'http://x');
|
|
151
|
+
if (url.pathname !== '/attach' || req.headers.authorization !== `Bearer ${this.token}` || !this.onAttach) {
|
|
152
|
+
socket.end('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n');
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: claude-pro-attach\r\nConnection: Upgrade\r\n\r\n');
|
|
156
|
+
socket.setNoDelay(true);
|
|
157
|
+
try {
|
|
158
|
+
this.onAttach(socket, { cols: Number(url.searchParams.get('cols')) || 0, rows: Number(url.searchParams.get('rows')) || 0 });
|
|
159
|
+
} catch {
|
|
160
|
+
socket.destroy();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
peers() { return listPeers({ excludeId: this.id }); }
|
|
165
|
+
|
|
166
|
+
close() {
|
|
167
|
+
try { fs.unlinkSync(this.file); } catch { /* ignore */ }
|
|
168
|
+
try { this.server?.close(); } catch { /* ignore */ }
|
|
169
|
+
this.port = null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
handle(req, res) {
|
|
173
|
+
const reply = (code, body) => { res.writeHead(code, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)); };
|
|
174
|
+
if (req.method === 'GET' && req.url === '/status') {
|
|
175
|
+
if (req.headers.authorization !== `Bearer ${this.token}`) return reply(401, { error: 'bad token' });
|
|
176
|
+
let status = {};
|
|
177
|
+
try { status = this.getStatus?.() || {}; } catch { /* nothing to say */ }
|
|
178
|
+
return reply(200, { busy: Boolean(status.busy) });
|
|
179
|
+
}
|
|
180
|
+
if (req.method === 'POST' && req.url === '/control') {
|
|
181
|
+
if (req.headers.authorization !== `Bearer ${this.token}`) return reply(401, { error: 'bad token' });
|
|
182
|
+
let body = '';
|
|
183
|
+
req.setEncoding('utf8');
|
|
184
|
+
req.on('data', (d) => { body += d; if (body.length > 10_000) req.destroy(); });
|
|
185
|
+
req.on('end', async () => {
|
|
186
|
+
try {
|
|
187
|
+
if (!this.onControl) throw new Error('not here');
|
|
188
|
+
reply(200, { ok: true, ...((await this.onControl(JSON.parse(body || '{}'))) || {}) });
|
|
189
|
+
} catch (e) {
|
|
190
|
+
reply(400, { error: e.message });
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (req.method !== 'POST' || req.url !== '/message') return reply(404, { error: 'not found' });
|
|
196
|
+
if (req.headers.authorization !== `Bearer ${this.token}`) return reply(401, { error: 'bad token' });
|
|
197
|
+
let body = '';
|
|
198
|
+
req.setEncoding('utf8');
|
|
199
|
+
req.on('data', (d) => { body += d; if (body.length > MAX_BODY) req.destroy(); });
|
|
200
|
+
req.on('end', () => {
|
|
201
|
+
let msg;
|
|
202
|
+
try { msg = JSON.parse(body); } catch { return reply(400, { error: 'bad json' }); }
|
|
203
|
+
if (typeof msg?.text !== 'string' || !msg.from?.name) return reply(400, { error: 'text and from are required' });
|
|
204
|
+
const id = crypto.randomBytes(4).toString('hex');
|
|
205
|
+
reply(200, { ok: true, id, name: this.name });
|
|
206
|
+
// files on this computer: [{path, name, size}] (the receiver copies them where it keeps what it is sent)
|
|
207
|
+
const files = (Array.isArray(msg.files) ? msg.files : []).filter((f) => f && typeof f.path === 'string' && path.isAbsolute(f.path))
|
|
208
|
+
.map((f) => ({ path: f.path, name: String(f.name || path.basename(f.path)), size: Number(f.size) || 0 }));
|
|
209
|
+
try { this.onMessage?.({ id, kind: msg.kind === 'reply' ? 'reply' : 'task', text: msg.text, inReplyTo: msg.inReplyTo || null, from: msg.from, ...(files.length ? { files } : {}) }); } catch { /* the receiver's problem */ }
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Whether a session of this machine is working now. A session that does not answer (gone, or a version without
|
|
214
|
+
// /status) counts as idle: it cannot hold an update back forever.
|
|
215
|
+
status(peer) {
|
|
216
|
+
return new Promise((resolve) => {
|
|
217
|
+
const req = http.get({ host: '127.0.0.1', port: peer.port, path: '/status', timeout: 2000, headers: { authorization: `Bearer ${peer.token}` } }, (res) => {
|
|
218
|
+
let out = '';
|
|
219
|
+
res.setEncoding('utf8');
|
|
220
|
+
res.on('data', (d) => { out += d; });
|
|
221
|
+
res.on('end', () => {
|
|
222
|
+
try { resolve(res.statusCode === 200 ? { busy: Boolean(JSON.parse(out).busy) } : { busy: false }); } catch { resolve({ busy: false }); }
|
|
223
|
+
});
|
|
224
|
+
});
|
|
225
|
+
req.on('timeout', () => req.destroy());
|
|
226
|
+
req.on('error', () => resolve({ busy: false }));
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Send to a peer (an entry of peers(), or its name). Resolves with {id} (the id the receiver gave the message).
|
|
231
|
+
async send(target, { text, kind = 'task', inReplyTo = null, files = [] }) {
|
|
232
|
+
const peer = typeof target === 'string' ? findPeer(this.peers(), target) : target;
|
|
233
|
+
if (!peer) throw new Error(`No running session called "${target}". /peers lists them.`);
|
|
234
|
+
const body = JSON.stringify({ kind, text, inReplyTo, from: { id: this.id, name: this.name, cwd: this.cwd }, ...(files.length ? { files } : {}) });
|
|
235
|
+
return await new Promise((resolve, reject) => {
|
|
236
|
+
const req = http.request({
|
|
237
|
+
host: '127.0.0.1', port: peer.port, path: '/message', method: 'POST', timeout: 10_000,
|
|
238
|
+
headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body), authorization: `Bearer ${peer.token}` },
|
|
239
|
+
}, (res) => {
|
|
240
|
+
let out = '';
|
|
241
|
+
res.setEncoding('utf8');
|
|
242
|
+
res.on('data', (d) => { out += d; });
|
|
243
|
+
res.on('end', () => {
|
|
244
|
+
let data = {};
|
|
245
|
+
try { data = JSON.parse(out); } catch { /* ignore */ }
|
|
246
|
+
if (res.statusCode !== 200) reject(new Error(`${peer.name} refused the message: ${data.error || res.statusCode}`));
|
|
247
|
+
else resolve({ id: data.id, peer });
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
req.on('timeout', () => req.destroy(new Error(`${peer.name} did not answer`)));
|
|
251
|
+
req.on('error', (e) => reject(new Error(`Could not reach ${peer.name}: ${e.message}`)));
|
|
252
|
+
req.end(body);
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// POST /control to a session of this computer (an entry of listPeers()): resolves with its answer, rejects with
|
|
258
|
+
// what went wrong.
|
|
259
|
+
export function controlPeer(peer, body, { timeout = 5000 } = {}) {
|
|
260
|
+
const data = JSON.stringify(body);
|
|
261
|
+
return new Promise((resolve, reject) => {
|
|
262
|
+
const req = http.request({
|
|
263
|
+
host: '127.0.0.1', port: peer.port, path: '/control', method: 'POST', timeout,
|
|
264
|
+
headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(data), authorization: `Bearer ${peer.token}` },
|
|
265
|
+
}, (res) => {
|
|
266
|
+
let out = '';
|
|
267
|
+
res.setEncoding('utf8');
|
|
268
|
+
res.on('data', (d) => { out += d; });
|
|
269
|
+
res.on('end', () => {
|
|
270
|
+
let answer = {};
|
|
271
|
+
try { answer = JSON.parse(out); } catch { /* none */ }
|
|
272
|
+
if (res.statusCode === 200) resolve(answer);
|
|
273
|
+
else reject(new Error(answer.error || `HTTP ${res.statusCode}`));
|
|
274
|
+
});
|
|
275
|
+
});
|
|
276
|
+
req.on('timeout', () => req.destroy(new Error('the session did not answer')));
|
|
277
|
+
req.on('error', reject);
|
|
278
|
+
req.end(data);
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// What the model is given for a message from another session.
|
|
283
|
+
export function peerMessagePrompt(msg) {
|
|
284
|
+
const where = msg.from.machine ? ` on the computer "${msg.from.machine}"` : '';
|
|
285
|
+
const from = `${msg.from.name}${msg.from.cwd ? ` (working in ${msg.from.cwd}${where})` : where}`;
|
|
286
|
+
if (msg.kind === 'reply') {
|
|
287
|
+
return `<peer-message from="${msg.from.name}" kind="reply">\n${msg.text}\n</peer-message>\n<system-reminder>This is the answer of another ${'claude-pro'} session, ${from}, to a message you sent it with MessagePeer. Carry on with your task using it.</system-reminder>`;
|
|
288
|
+
}
|
|
289
|
+
return `<peer-message from="${msg.from.name}" kind="task">\n${msg.text}\n</peer-message>\n<system-reminder>This task was sent to you by another claude-pro session, ${from}, not typed by your user. Do it as you would a request of the user. The final text of your answer is sent back to ${msg.from.name} automatically, so end with a self-contained report of what you did or found.</system-reminder>`;
|
|
290
|
+
}
|