@yanzc/claude-pro 0.6.0 → 0.7.1
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 +372 -370
- package/package.json +1 -1
- package/src/agent.js +18 -13
- package/src/attach.js +132 -0
- package/src/background.js +424 -0
- package/src/commands.js +80 -59
- package/src/connect.js +79 -0
- package/src/history.js +94 -0
- package/src/host.js +445 -66
- package/src/main.js +38 -10
- package/src/peers.js +290 -215
- package/src/print.js +0 -1
- package/src/prompts.js +2 -7
- package/src/remote.js +50 -15
- package/src/runtime.js +2 -6
- package/src/session.js +24 -0
- package/src/supervisor.js +6 -3
- package/src/tools/bash.js +2 -2
- package/src/tools/index.js +2 -3
- package/src/tools/interaction.js +2 -30
- package/src/tools/task.js +1 -1
- package/src/ui/ansi.js +0 -1
- package/src/ui/dialogs.js +48 -0
- package/src/ui/render.js +10 -4
- package/src/ui/repl.js +318 -77
- package/src/ui/vterm.js +62 -0
- package/src/modes.js +0 -154
- package/src/qr.js +0 -206
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
|
+
}
|
package/src/print.js
CHANGED
|
@@ -27,7 +27,6 @@ export async function runPrint({ prompt, flags, cwd, stdout = process.stdout, st
|
|
|
27
27
|
};
|
|
28
28
|
const mainRateLimit = rateLimitReporter();
|
|
29
29
|
const io = {
|
|
30
|
-
approvePlan: async () => 'reject', // non-interactive: a plan is only presented, never executed
|
|
31
30
|
askQuestion: async () => null,
|
|
32
31
|
notice: (text) => err(c.yellow(text)),
|
|
33
32
|
toolStart: (tu, tool, input, agent) => {
|
package/src/prompts.js
CHANGED
|
@@ -64,7 +64,7 @@ Do not make up URLs. Give a URL only when it came from the user, a file or a too
|
|
|
64
64
|
- If you cannot or will not help with something, say so briefly without lecturing, and offer alternatives if possible.
|
|
65
65
|
|
|
66
66
|
# How you work
|
|
67
|
-
You run on the user's own test machine with full access: tool calls run without asking the user for confirmation, except where a control of the program (
|
|
67
|
+
You run on the user's own test machine with full access: tool calls run without asking the user for confirmation, except where a control of the program (a hook) steps in. Use that freedom to get the job done. Do not ask for permission to read, write, install, run or delete what the task needs, and decide how to go about it (how much to plan, whether to use sub-agents, how to verify) by what the task needs rather than by a fixed procedure.
|
|
68
68
|
- Aim at the user's goal rather than the letter of the steps they described: when you see a clearly better way to reach it, take it and say why, unless they asked for their way specifically. Do not change the goal itself or a constraint they set.
|
|
69
69
|
- When you have enough information to act, act. Do not re-derive facts already established in the conversation, re-argue a decision the user has made, or lay out options you will not pursue; when you weigh a choice, give a recommendation, not a survey.
|
|
70
70
|
- Work end to end: understand, implement, run and verify before reporting back. Do not stop at a plan unless asked for one.
|
|
@@ -86,7 +86,7 @@ You run on the user's own test machine with full access: tool calls run without
|
|
|
86
86
|
# Tools
|
|
87
87
|
- Call independent tools together in one response so that they run in parallel; run dependent ones one after another.
|
|
88
88
|
- Delegate to sub-agents (Task) when that makes the work better, faster or keeps your context small: broad searches, independent subtasks, a second look at risky work. Weigh what it costs first: each agent builds its own context and spends its own tokens (from the user's usage limit too), it does not see what you or other agents know, and agents that edit related files at the same time get in each other's way. Closely coupled work that needs shared state is usually better done yourself. Use run_in_background for long jobs.
|
|
89
|
-
- If a tool call is blocked (by
|
|
89
|
+
- If a tool call is blocked (by a hook or another control of the program), do not retry it or get around it another way: adjust your approach within what is allowed, or tell the user what is in the way.
|
|
90
90
|
- Tool results and user messages may include <system-reminder> tags: information added by the harness, not part of the user's request.
|
|
91
91
|
|
|
92
92
|
${selfRestart ? `# Your own source code
|
|
@@ -137,11 +137,6 @@ ${message}
|
|
|
137
137
|
${current ? 'Does this message start a new topic (a different task or question), or does it continue the current one (a follow-up, "continue", an answer, a correction)? ' : ''}Reply with only a JSON object: {"isNewTopic": ${current ? 'true or false' : 'true'}, "title": ...}. For a new topic, "title" names it in 2 to 6 words (at most about 16 characters in Chinese or Japanese), in the language of the user's message, with no quotes, no emoji and no punctuation at the end. Otherwise "title" is null.`;
|
|
138
138
|
}
|
|
139
139
|
|
|
140
|
-
export const PLAN_MODE_REMINDER = `<system-reminder>
|
|
141
|
-
Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
|
|
142
|
-
Research the codebase with read-only tools, then present a concise implementation plan by calling the ExitPlanMode tool. Do not ask for approval in plain text; use ExitPlanMode.
|
|
143
|
-
</system-reminder>`;
|
|
144
|
-
|
|
145
140
|
// The system prompt of the plain summary request (see Agent.requestSummary).
|
|
146
141
|
export const SUMMARY_SYSTEM = 'You are a helpful AI assistant tasked with summarizing conversations.';
|
|
147
142
|
|