@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/README.md +37 -58
- package/package.json +1 -1
- package/src/agent.js +127 -25
- package/src/cache.js +18 -0
- package/src/commands.js +24 -28
- package/src/config.js +8 -2
- package/src/filestate.js +1 -1
- package/src/keepalive.js +129 -0
- package/src/main.js +12 -39
- package/src/mcp.js +58 -13
- package/src/peers.js +6 -75
- package/src/prompts.js +3 -3
- package/src/remote.js +77 -33
- package/src/runtime.js +3 -0
- package/src/session.js +48 -15
- package/src/supervisor.js +4 -6
- package/src/tools/bash.js +30 -14
- package/src/tools/files.js +366 -62
- package/src/tools/index.js +3 -1
- package/src/tools/search.js +14 -10
- package/src/tools/web.js +14 -6
- package/src/ui/ansi.js +24 -9
- package/src/ui/repl.js +314 -305
- package/src/ui/screen.js +38 -11
- package/src/updater.js +7 -3
- package/src/utils/clipboard.js +16 -75
- package/src/utils/diff.js +21 -3
- package/src/utils/dirs.js +136 -0
- package/src/utils/encoding.js +187 -0
- package/src/utils/paths.js +46 -5
- package/src/utils/shell.js +90 -19
- package/src/attach.js +0 -146
- package/src/background.js +0 -514
- package/src/connect.js +0 -79
- package/src/history.js +0 -163
- package/src/host.js +0 -1474
- package/src/ui/vterm.js +0 -62
package/src/peers.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Peers: the other interactive claude-pro sessions on this machine. Each session registers itself in
|
|
2
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
|
|
3
|
+
// so that sessions can send each other tasks: the user with `@name task` in the input box, the model with the
|
|
4
4
|
// MessagePeer tool. A task is answered automatically with the final text of the turn that handled it.
|
|
5
5
|
// Sessions on the user's other computers are reached through the gateway instead (see remote.js): they are
|
|
6
6
|
// listed as {id, name, machine, cwd, remote: true, label: 'machine/name'} and addressed by that label.
|
|
@@ -49,7 +49,7 @@ export function machineName(env = process.env) {
|
|
|
49
49
|
|
|
50
50
|
// Find the session `ref` (with or without @) names among the local ones and those on other computers: a local
|
|
51
51
|
// name (or id prefix); else machine/name, a name only one remote session has, a computer with only one session
|
|
52
|
-
// (
|
|
52
|
+
// (`@公司`), or an id prefix. `ids: false` leaves the id prefixes out (for what the user types).
|
|
53
53
|
// Returns {peer}, {error, ambiguous: true} when several match, or {error: null} when none does.
|
|
54
54
|
export function resolvePeer(local, remote, ref, { ids = true } = {}) {
|
|
55
55
|
const q = String(ref || '').replace(/^[@&&]/, '').toLowerCase();
|
|
@@ -62,7 +62,7 @@ export function resolvePeer(local, remote, ref, { ids = true } = {}) {
|
|
|
62
62
|
if (!hits.length) hits = remote.filter((p) => same(p.machine));
|
|
63
63
|
if (!hits.length && ids && q.length >= 4) hits = remote.filter((p) => p.id.toLowerCase().startsWith(q));
|
|
64
64
|
if (hits.length === 1) return { peer: hits[0] };
|
|
65
|
-
if (hits.length > 1) return { error: `"
|
|
65
|
+
if (hits.length > 1) return { error: `"@${String(ref).replace(/^[@&&]/, '')}" could be ${hits.map((p) => '@' + p.label).join(', ')}: say which.`, ambiguous: true };
|
|
66
66
|
return { error: null };
|
|
67
67
|
}
|
|
68
68
|
|
|
@@ -76,18 +76,11 @@ export class PeerNode {
|
|
|
76
76
|
// onMessage(msg): msg = {id, kind: 'task'|'reply', text, inReplyTo, from: {id, name, cwd}}
|
|
77
77
|
// `id`: the id this session had before a restart, so that answers on their way still find it.
|
|
78
78
|
// getStatus(): {busy}, what GET /status answers (an update waits until no session of the machine is busy).
|
|
79
|
-
|
|
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 }) {
|
|
79
|
+
constructor({ cwd, name, id, onMessage, getStatus }) {
|
|
84
80
|
this.cwd = cwd;
|
|
85
81
|
this.wantedName = name || null;
|
|
86
82
|
this.onMessage = onMessage;
|
|
87
83
|
this.getStatus = getStatus;
|
|
88
|
-
this.info = info;
|
|
89
|
-
this.onControl = onControl;
|
|
90
|
-
this.onAttach = onAttach;
|
|
91
84
|
this.id = /^[0-9a-f]{12}$/.test(id || '') ? id : crypto.randomBytes(6).toString('hex');
|
|
92
85
|
this.token = crypto.randomBytes(16).toString('hex');
|
|
93
86
|
this.name = null;
|
|
@@ -99,7 +92,6 @@ export class PeerNode {
|
|
|
99
92
|
|
|
100
93
|
async start() {
|
|
101
94
|
this.server = http.createServer((req, res) => this.handle(req, res));
|
|
102
|
-
this.server.on('upgrade', (req, socket) => this.upgrade(req, socket));
|
|
103
95
|
await new Promise((resolve, reject) => {
|
|
104
96
|
this.server.once('error', reject);
|
|
105
97
|
this.server.listen(0, '127.0.0.1', resolve);
|
|
@@ -130,37 +122,16 @@ export class PeerNode {
|
|
|
130
122
|
write() {
|
|
131
123
|
if (!this.port) return;
|
|
132
124
|
fs.mkdirSync(PEERS_DIR, { recursive: true });
|
|
133
|
-
|
|
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() };
|
|
125
|
+
const data = { id: this.id, name: this.name, cwd: this.cwd, pid: process.pid, port: this.port, token: this.token, startedAt: this.startedAt ??= Date.now() };
|
|
136
126
|
const json = JSON.stringify(data);
|
|
137
127
|
if (json === this.written) return;
|
|
138
|
-
// whole or not at all: the
|
|
128
|
+
// whole or not at all: the other sessions read these files at any time (listPeers)
|
|
139
129
|
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
140
130
|
fs.writeFileSync(tmp, json);
|
|
141
131
|
fs.renameSync(tmp, this.file);
|
|
142
132
|
this.written = json;
|
|
143
133
|
}
|
|
144
134
|
|
|
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
135
|
peers() { return listPeers({ excludeId: this.id }); }
|
|
165
136
|
|
|
166
137
|
close() {
|
|
@@ -177,21 +148,6 @@ export class PeerNode {
|
|
|
177
148
|
try { status = this.getStatus?.() || {}; } catch { /* nothing to say */ }
|
|
178
149
|
return reply(200, { busy: Boolean(status.busy) });
|
|
179
150
|
}
|
|
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
151
|
if (req.method !== 'POST' || req.url !== '/message') return reply(404, { error: 'not found' });
|
|
196
152
|
if (req.headers.authorization !== `Bearer ${this.token}`) return reply(401, { error: 'bad token' });
|
|
197
153
|
let body = '';
|
|
@@ -251,31 +207,6 @@ export class PeerNode {
|
|
|
251
207
|
}
|
|
252
208
|
}
|
|
253
209
|
|
|
254
|
-
// POST /control to a session of this computer (an entry of listPeers()): resolves with its answer, rejects with
|
|
255
|
-
// what went wrong.
|
|
256
|
-
export function controlPeer(peer, body, { timeout = 5000 } = {}) {
|
|
257
|
-
const data = JSON.stringify(body);
|
|
258
|
-
return new Promise((resolve, reject) => {
|
|
259
|
-
const req = http.request({
|
|
260
|
-
host: '127.0.0.1', port: peer.port, path: '/control', method: 'POST', timeout,
|
|
261
|
-
headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(data), authorization: `Bearer ${peer.token}` },
|
|
262
|
-
}, (res) => {
|
|
263
|
-
let out = '';
|
|
264
|
-
res.setEncoding('utf8');
|
|
265
|
-
res.on('data', (d) => { out += d; });
|
|
266
|
-
res.on('end', () => {
|
|
267
|
-
let answer = {};
|
|
268
|
-
try { answer = JSON.parse(out); } catch { /* none */ }
|
|
269
|
-
if (res.statusCode === 200) resolve(answer);
|
|
270
|
-
else reject(new Error(answer.error || `HTTP ${res.statusCode}`));
|
|
271
|
-
});
|
|
272
|
-
});
|
|
273
|
-
req.on('timeout', () => req.destroy(new Error('the session did not answer')));
|
|
274
|
-
req.on('error', reject);
|
|
275
|
-
req.end(data);
|
|
276
|
-
});
|
|
277
|
-
}
|
|
278
|
-
|
|
279
210
|
// What the model is given for a message from another session.
|
|
280
211
|
export function peerMessagePrompt(msg) {
|
|
281
212
|
const where = msg.from.machine ? ` on the computer "${msg.from.machine}"` : '';
|
package/src/prompts.js
CHANGED
|
@@ -78,7 +78,7 @@ You run on the user's own test machine with full access: tool calls run without
|
|
|
78
78
|
- Before deleting or overwriting something, look at what is there: it may be the user's work in progress.
|
|
79
79
|
- Follow security best practices: never expose, log or commit secrets, and never write code that does.
|
|
80
80
|
- Do not commit unless the user asks or the project's instructions say when to.
|
|
81
|
-
- Edits made with Write, Edit and NotebookEdit are checkpointed per user prompt and can be undone with /rewind; changes made through Bash are not.
|
|
81
|
+
- Edits made with Write, Edit, MultiEdit and NotebookEdit are checkpointed per user prompt and can be undone with /rewind; changes made through Bash are not.
|
|
82
82
|
|
|
83
83
|
# Tools
|
|
84
84
|
- Call independent tools together in one response so that they run in parallel; run dependent ones one after another.
|
|
@@ -114,7 +114,7 @@ ${readOnly ? '' : `
|
|
|
114
114
|
- Do not do anything that cannot be undone unless your task asks for it (force-pushing, publishing a package, deleting data outside the project, sending messages or spending money through external services): say in your report what should be done and why, and leave it to the main agent.
|
|
115
115
|
- Never expose, log or commit secrets, and never write code that does.
|
|
116
116
|
- Do not commit, push or publish unless your task asks for it: the main agent decides that.
|
|
117
|
-
- Edits made with Write, Edit and NotebookEdit can be undone with /rewind; changes made through Bash cannot.
|
|
117
|
+
- Edits made with Write, Edit, MultiEdit and NotebookEdit can be undone with /rewind; changes made through Bash cannot.
|
|
118
118
|
`}
|
|
119
119
|
${environmentBlock(cwd, { model, shellName, snapshot })}${files ? `\n\n# Project instructions\nThe instructions that apply in this project: its environment, commands and conventions. Follow them for how you work here; committing, pushing and publishing stay the main agent's to decide, whatever they say.\n\n${files}` : ''}${mcpInstructions ? `\n\n${mcpInstructions}` : ''}`;
|
|
120
120
|
}
|
|
@@ -148,7 +148,7 @@ First write exactly one <work-state> block containing one valid JSON object. Do
|
|
|
148
148
|
</work-state>
|
|
149
149
|
All array items must be strings. Keep paths, commands, error messages and next actions precise. The state is machine-validated, so do not add prose before or after the JSON inside <work-state>.
|
|
150
150
|
|
|
151
|
-
Then
|
|
151
|
+
Then write a detailed narrative in <summary> tags. Do your reasoning in your thinking, not in the reply: only the work-state and the summary are kept, so text outside them is thrown away (and writing it makes the compaction take minutes longer). The narrative should retain technical details, code patterns and architectural decisions that would be useful if the structured state is incomplete.
|
|
152
152
|
|
|
153
153
|
Use these summary sections:
|
|
154
154
|
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
package/src/remote.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
1
|
+
// Publish a local interactive session to the gateway, so that the account's browser can watch it and steer it: send
|
|
2
|
+
// it messages (as if typed in its input box: /commands, !shell, #memory, pasted images), answer its questions, stop
|
|
3
|
+
// it, switch model and effort, complete input, browse directories for /cd and read a tool call's whole output. The
|
|
4
|
+
// session never listens on the network: it connects out to the codex-gateway with the gateway API key from /login,
|
|
5
|
+
// declares the commands it takes when it registers, and gets them on its command stream. With
|
|
6
|
+
// CLAUDE_PRO_REMOTE_COMMANDS=0 it declares none and is read-only on the page.
|
|
6
7
|
// The same connection carries the messages of the account's sessions on other computers (`@公司 ...`, see peers.js).
|
|
7
8
|
//
|
|
8
9
|
// The page is told what happens as a list of transcript items (user messages, assistant text, thinking, tool
|
|
@@ -101,7 +102,7 @@ export function hydrate(items) {
|
|
|
101
102
|
function shownUserText(text) {
|
|
102
103
|
return String(text)
|
|
103
104
|
.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '')
|
|
104
|
-
.replace(/<peer-message from="([^"]*)" kind="(task|reply)">\n?/g, (_, from, kind) => `✉ ${kind === 'reply' ? 'answer from' : 'task from'}
|
|
105
|
+
.replace(/<peer-message from="([^"]*)" kind="(task|reply)">\n?/g, (_, from, kind) => `✉ ${kind === 'reply' ? 'answer from' : 'task from'} @${from}: `)
|
|
105
106
|
.replace(/\n?<\/peer-message>/g, '')
|
|
106
107
|
.trim();
|
|
107
108
|
}
|
|
@@ -190,10 +191,19 @@ export const newRemoteId = () => crypto.randomBytes(9).toString('base64url');
|
|
|
190
191
|
// which only the self-check and the tests set).
|
|
191
192
|
export const onlineEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(env.CLAUDE_PRO_ONLINE || '');
|
|
192
193
|
|
|
194
|
+
// Whether the page may steer the session, not only watch it (CLAUDE_PRO_REMOTE_COMMANDS=0: read-only).
|
|
195
|
+
export const remoteCommandsEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(String(env.CLAUDE_PRO_REMOTE_COMMANDS ?? '').trim());
|
|
196
|
+
|
|
197
|
+
// The commands of the page, and the handler of each (see App.connectRemote; each gets the command's body and
|
|
198
|
+
// returns the result's fields, or a promise of them, or throws what to tell the page). A session declares the ones
|
|
199
|
+
// it has handlers for when it registers (`commands`); the gateway forwards only those and answers the others itself.
|
|
200
|
+
// A session that declares none (0.8.x, CLAUDE_PRO_REMOTE_COMMANDS=0) is read-only on the page.
|
|
201
|
+
const COMMANDS = { send: 'send', interrupt: 'interrupt', dialog: 'answer', options: 'options', suggest: 'suggest', list: 'list', output: 'output' };
|
|
202
|
+
|
|
193
203
|
export class RemoteControl {
|
|
194
204
|
// gateway: {url, apiKey}. handlers: info() -> {name, title, cwd, model}, seed() -> items, status() -> object,
|
|
195
|
-
//
|
|
196
|
-
//
|
|
205
|
+
// peerMessage(message), changed() (online or viewers changed), refused(status) (the key was refused: closed), and
|
|
206
|
+
// the page's commands: send, interrupt, answer (dialog), options, suggest, list, output (see COMMANDS).
|
|
197
207
|
constructor({ gateway, id, handlers, fetchImpl = globalThis.fetch }) {
|
|
198
208
|
this.base = String(gateway.url).replace(/\/+$/, '');
|
|
199
209
|
this.apiKey = gateway.apiKey;
|
|
@@ -217,10 +227,14 @@ export class RemoteControl {
|
|
|
217
227
|
this.flushTimer = null;
|
|
218
228
|
this.streamAbort = null;
|
|
219
229
|
this.registered = false;
|
|
230
|
+
this.refused = null; // the status (401/403) of the gateway refusing the key after the start: the connection ended
|
|
220
231
|
this.seenPeer = new Set(); // ids of the messages from other sessions already handled (the gateway sends again what was not acknowledged)
|
|
221
|
-
this.replying = new Set(); // answers to the page's commands on their way
|
|
232
|
+
this.replying = new Set(); // answers to the page's commands on their way (close() waits for them)
|
|
222
233
|
}
|
|
223
234
|
|
|
235
|
+
// The commands this session takes, as declared to the gateway.
|
|
236
|
+
get commands() { return Object.keys(COMMANDS).filter((type) => typeof this.handlers[COMMANDS[type]] === 'function'); }
|
|
237
|
+
|
|
224
238
|
get viewing() { return this.viewers !== 0; } // nobody watching: events are not uploaded (a snapshot follows when someone comes)
|
|
225
239
|
|
|
226
240
|
// `persistent`: keep trying when the gateway cannot be reached now (a restart); otherwise the first failure is thrown.
|
|
@@ -260,7 +274,8 @@ export class RemoteControl {
|
|
|
260
274
|
|
|
261
275
|
async register() {
|
|
262
276
|
const info = this.handlers.info?.() || {};
|
|
263
|
-
const
|
|
277
|
+
const commands = this.commands;
|
|
278
|
+
const data = await this.request('POST', '/v1/remote/sessions', { id: this.id, host: os.hostname(), version: info.version, ...info, ...(commands.length ? { commands } : {}) });
|
|
264
279
|
if (data.id) this.id = data.id;
|
|
265
280
|
this.url = data.url || this.url || `${this.base}/user`;
|
|
266
281
|
this.registered = true;
|
|
@@ -271,20 +286,44 @@ export class RemoteControl {
|
|
|
271
286
|
async loop() {
|
|
272
287
|
let wait = 1000;
|
|
273
288
|
while (!this.closed) {
|
|
289
|
+
const began = Date.now();
|
|
274
290
|
try {
|
|
275
291
|
if (!this.registered) await this.register();
|
|
276
292
|
await this.listen();
|
|
277
|
-
wait = 1000;
|
|
278
293
|
} catch (e) {
|
|
279
294
|
if (e.status === 404) this.registered = false; // the gateway forgot the session (restarted): register again
|
|
295
|
+
if (e.status === 401 || e.status === 403) { this.refuse(e.status); break; }
|
|
296
|
+
}
|
|
297
|
+
if (this.online) {
|
|
298
|
+
this.online = false;
|
|
299
|
+
// Nothing is uploaded while offline (see flush), and the stream's next opening sends a snapshot.
|
|
300
|
+
this.needSnapshot = true;
|
|
301
|
+
this.events = [];
|
|
302
|
+
this.handlers.changed?.();
|
|
280
303
|
}
|
|
281
|
-
if (this.online) { this.online = false; this.handlers.changed?.(); }
|
|
282
304
|
if (this.closed) break;
|
|
305
|
+
// The backoff starts afresh only after a stream that held: one the gateway closes at once is not a recovery.
|
|
306
|
+
if (Date.now() - began > 30_000) wait = 1000;
|
|
283
307
|
await sleep(wait);
|
|
284
308
|
wait = Math.min(wait * 2, 30_000);
|
|
285
309
|
}
|
|
286
310
|
}
|
|
287
311
|
|
|
312
|
+
// The gateway refused the key (401/403: the key was revoked, the account changed): that does not get better by
|
|
313
|
+
// retrying, so the connection ends and the App leaves this key alone until the login changes (handlers.refused).
|
|
314
|
+
refuse(status) {
|
|
315
|
+
if (this.closed) return;
|
|
316
|
+
this.refused = status;
|
|
317
|
+
this.closed = true;
|
|
318
|
+
this.registered = false; // no bye with a key the gateway refuses
|
|
319
|
+
this.online = false;
|
|
320
|
+
clearTimeout(this.flushTimer);
|
|
321
|
+
clearInterval(this.statusTimer);
|
|
322
|
+
this.streamAbort?.abort();
|
|
323
|
+
try { this.handlers.refused?.(status); } catch { /* the App's problem */ }
|
|
324
|
+
this.handlers.changed?.();
|
|
325
|
+
}
|
|
326
|
+
|
|
288
327
|
async listen() {
|
|
289
328
|
const abort = new AbortController();
|
|
290
329
|
this.streamAbort = abort;
|
|
@@ -292,7 +331,10 @@ export class RemoteControl {
|
|
|
292
331
|
headers: { authorization: `Bearer ${this.apiKey}`, accept: 'text/event-stream' },
|
|
293
332
|
signal: abort.signal,
|
|
294
333
|
});
|
|
295
|
-
if (!res.ok)
|
|
334
|
+
if (!res.ok) {
|
|
335
|
+
res.body?.cancel?.().catch(() => {}); // or its socket stays open until garbage collection
|
|
336
|
+
throw Object.assign(new Error(`HTTP ${res.status}`), { status: res.status });
|
|
337
|
+
}
|
|
296
338
|
this.online = true;
|
|
297
339
|
this.needSnapshot = true; // the gateway may have been restarted: it gets the whole conversation again
|
|
298
340
|
this.handlers.changed?.();
|
|
@@ -336,33 +378,32 @@ export class RemoteControl {
|
|
|
336
378
|
if (cmd.type === 'snapshot') { this.needSnapshot = true; this.scheduleFlush(0); return; }
|
|
337
379
|
if (!cmd.cid) return;
|
|
338
380
|
if (cmd.type === 'peer') { this.peerMessage(cmd); return; }
|
|
339
|
-
//
|
|
381
|
+
// A command of the page, answered with POST …/results {cid, ok: true, …fields} or {cid, ok: false, error} (the
|
|
382
|
+
// gateway waits 15 s for it, and takes it until 3 s after the stream closed). close() waits for the answers on
|
|
383
|
+
// their way: a /cd or /exit from the page ends the session from inside its command.
|
|
340
384
|
const reply = (result) => {
|
|
341
385
|
const sent = this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/results`, result).catch(() => { /* the page times out */ });
|
|
342
386
|
this.replying.add(sent);
|
|
343
387
|
sent.finally(() => this.replying.delete(sent));
|
|
344
|
-
this.scheduleFlush(30);
|
|
388
|
+
this.scheduleFlush(30); // what the command changed, on the page soon
|
|
345
389
|
};
|
|
346
390
|
const failed = (e) => reply({ cid: cmd.cid, ok: false, error: e?.message || String(e) });
|
|
391
|
+
const handler = Object.hasOwn(COMMANDS, cmd.type) ? this.handlers[COMMANDS[cmd.type]] : null;
|
|
392
|
+
if (typeof handler !== 'function') {
|
|
393
|
+
// an older gateway forwards every command, declared or not
|
|
394
|
+
failed(new Error(this.commands.length ? `Unknown command: ${cmd.type}` : 'This session is read-only on the web page (CLAUDE_PRO_REMOTE_COMMANDS=0 on its computer).'));
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
347
397
|
let r;
|
|
348
398
|
try {
|
|
349
|
-
|
|
350
|
-
// send, interrupt and dialog act; options, suggest and list only look (and are answered while it works)
|
|
351
|
-
if (cmd.type === 'send') r = this.handlers.send(String(body.text ?? ''), body.images);
|
|
352
|
-
else if (cmd.type === 'interrupt') r = this.handlers.interrupt();
|
|
353
|
-
else if (cmd.type === 'dialog') r = this.handlers.answer(body);
|
|
354
|
-
else if (cmd.type === 'options' && this.handlers.options) r = this.handlers.options(body);
|
|
355
|
-
else if (cmd.type === 'suggest' && this.handlers.suggest) r = this.handlers.suggest(body);
|
|
356
|
-
else if (cmd.type === 'list' && this.handlers.list) r = this.handlers.list(body);
|
|
357
|
-
else if (cmd.type === 'output' && this.handlers.output) r = this.handlers.output(body);
|
|
358
|
-
else throw new Error(`Unknown command: ${cmd.type}`);
|
|
399
|
+
r = handler(cmd.body && typeof cmd.body === 'object' && !Array.isArray(cmd.body) ? cmd.body : {});
|
|
359
400
|
} catch (e) {
|
|
360
401
|
failed(e);
|
|
361
402
|
return;
|
|
362
403
|
}
|
|
363
|
-
// an answer that takes a while (
|
|
364
|
-
if (typeof r?.then === 'function') r.then((v) => reply({ cid: cmd.cid, ok: true
|
|
365
|
-
else reply({ cid: cmd.cid, ok: true
|
|
404
|
+
// an answer that takes a while (the gateway's list of models, a directory) is sent when it is there
|
|
405
|
+
if (typeof r?.then === 'function') r.then((v) => reply({ ...(v || {}), cid: cmd.cid, ok: true }), failed);
|
|
406
|
+
else reply({ ...(r || {}), cid: cmd.cid, ok: true });
|
|
366
407
|
}
|
|
367
408
|
|
|
368
409
|
// ------------------------------------------------------------ messages of the account's other sessions
|
|
@@ -470,8 +511,10 @@ export class RemoteControl {
|
|
|
470
511
|
urgentKey(status) { return `${Boolean(status.busy)}|${Boolean(status.asking)}`; }
|
|
471
512
|
|
|
472
513
|
// What has changed goes into the next upload: a snapshot when one is due, else the events; and the status.
|
|
514
|
+
// Not while the command stream is down: every upload would fail and leave a snapshot due, so a session used to
|
|
515
|
+
// build and POST (twice) a snapshot of up to 1.5 MB every 500 ms for as long as the gateway was unreachable.
|
|
473
516
|
flush() {
|
|
474
|
-
if (this.closed || !this.registered) return;
|
|
517
|
+
if (this.closed || !this.registered || (!this.online && !this.closing)) return;
|
|
475
518
|
this.takeProgress();
|
|
476
519
|
const status = this.status();
|
|
477
520
|
if (this.needSnapshot || this.sinceSnapshot > SNAPSHOT_EVERY) {
|
|
@@ -510,6 +553,7 @@ export class RemoteControl {
|
|
|
510
553
|
this.needSnapshot = true;
|
|
511
554
|
this.events = [];
|
|
512
555
|
if (e.status === 404) { this.registered = false; this.streamAbort?.abort(); }
|
|
556
|
+
if (e.status === 401 || e.status === 403) this.refuse(e.status);
|
|
513
557
|
} finally {
|
|
514
558
|
this.sending = false;
|
|
515
559
|
}
|
|
@@ -524,10 +568,10 @@ export class RemoteControl {
|
|
|
524
568
|
}
|
|
525
569
|
|
|
526
570
|
async shutdown(restarting) {
|
|
527
|
-
// First the answers on their way, while the command stream is still open (the gateway
|
|
528
|
-
//
|
|
529
|
-
// page closes it from inside that command, and its answer is sent when the command returns, hence the
|
|
530
|
-
// the current call to finish first.
|
|
571
|
+
// First the answers on their way, while the command stream is still open (the gateway takes them until 3 s
|
|
572
|
+
// after it closes). Among them the answer to the command that ends the session: a /cd, /restart or /exit from
|
|
573
|
+
// the page closes it from inside that command, and its answer is sent when the command returns, hence the
|
|
574
|
+
// wait for the current call to finish first.
|
|
531
575
|
await null;
|
|
532
576
|
if (this.replying.size) await Promise.race([Promise.allSettled([...this.replying]), new Promise((r) => setTimeout(r, 1500).unref?.())]);
|
|
533
577
|
this.closing = true; // what flush() collects now goes out with the last message, not on its own
|
package/src/runtime.js
CHANGED
|
@@ -147,6 +147,9 @@ export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
|
|
|
147
147
|
throw err;
|
|
148
148
|
} finally {
|
|
149
149
|
runtime.agent.addSubUsage(sub.usage); // whatever became of it, it was billed
|
|
150
|
+
// Its edits count for the agent that sent it: the main agent verifies after edits (see verifyCommand), and
|
|
151
|
+
// an implementation handed to a sub-agent used to go unverified.
|
|
152
|
+
if (sub.editsThisRun > 0 && ctx.agent) ctx.agent.editsThisRun += sub.editsThisRun;
|
|
150
153
|
}
|
|
151
154
|
if (result.interrupted) throw Object.assign(new Error('aborted'), { name: 'AbortError' });
|
|
152
155
|
return { text: result.text, toolUses: sub.toolUseCount, tokens: sub.usage.output + sub.lastContextTokens };
|
package/src/session.js
CHANGED
|
@@ -105,11 +105,16 @@ export class SessionStore {
|
|
|
105
105
|
// What the conversation's requests have cost so far (USD, see pricing.js), written after each one; the newest wins.
|
|
106
106
|
setCost(usd) { this.append({ type: 'meta', cost: usd, at: Date.now() }); }
|
|
107
107
|
// Until when the conversation's prompt cache lasts (ms since epoch; 0: cold), for the footer's clock of a
|
|
108
|
-
// resumed conversation (see CacheStats.clock)
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
108
|
+
// resumed conversation (see CacheStats.clock), and what the cache holds (Agent.cacheState; null: nothing warm),
|
|
109
|
+
// so that a restarted conversation goes on refreshing it (keepalive.js). Written after each of its requests and
|
|
110
|
+
// compactions.
|
|
111
|
+
setCacheUntil(until, state = null) {
|
|
112
|
+
const json = JSON.stringify(state);
|
|
113
|
+
const clock = until != null && until !== this.cacheUntil;
|
|
114
|
+
if (!clock && json === (this.cacheStateJson ?? 'null')) return;
|
|
115
|
+
if (clock) this.cacheUntil = until;
|
|
116
|
+
this.cacheStateJson = json;
|
|
117
|
+
this.append({ type: 'meta', ...(clock ? { cacheUntil: until } : {}), cacheState: state, at: Date.now() });
|
|
113
118
|
}
|
|
114
119
|
// The system prompt this conversation runs behind, kept so that a resumed one continues behind the same prompt
|
|
115
120
|
// and so with the prompt cache it already has (see runtime.resumeSystemPrompt). Written when it first appears
|
|
@@ -132,6 +137,7 @@ export class SessionStore {
|
|
|
132
137
|
let e;
|
|
133
138
|
try { e = JSON.parse(line); } catch { continue; }
|
|
134
139
|
if (e.type === 'message' || e.type === 'reset') lastAt = Math.max(lastAt, e.at || 0);
|
|
140
|
+
if (e.type === 'reset') meta = { ...meta, cacheState: null }; // what was cached is not the new messages' prefix
|
|
135
141
|
if (e.type === 'meta') meta = { ...meta, ...e };
|
|
136
142
|
else if (e.type === 'message') {
|
|
137
143
|
messages.push(e.message);
|
|
@@ -152,27 +158,54 @@ export class SessionStore {
|
|
|
152
158
|
promptCode: typeof meta.promptCode === 'string' ? meta.promptCode : null,
|
|
153
159
|
cost: Number(meta.cost) > 0 ? Number(meta.cost) : 0,
|
|
154
160
|
cacheUntil: Number.isFinite(meta.cacheUntil) && meta.cacheUntil >= 0 ? meta.cacheUntil : null,
|
|
161
|
+
cacheState: meta.cacheState && typeof meta.cacheState === 'object' ? meta.cacheState : null,
|
|
155
162
|
};
|
|
156
163
|
}
|
|
157
164
|
|
|
165
|
+
// The conversations of the project, newest first: {id, file, mtime, title, count}. Each file's title and message
|
|
166
|
+
// count are kept in sessions-index.json by its size and time, so that only the files that changed since are
|
|
167
|
+
// parsed (parsing all of them, tens of MB with screenshots, made -c and /resume wait a third of a second and
|
|
168
|
+
// more as conversations piled up).
|
|
158
169
|
static list(cwd) {
|
|
159
170
|
const dir = projectDir(cwd);
|
|
160
171
|
let files = [];
|
|
161
172
|
try { files = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl')); } catch { return []; }
|
|
162
|
-
|
|
173
|
+
const indexFile = path.join(dir, SESSION_INDEX);
|
|
174
|
+
let index = {};
|
|
175
|
+
try { index = JSON.parse(fs.readFileSync(indexFile, 'utf8')) || {}; } catch { /* none yet, or damaged: rebuilt */ }
|
|
176
|
+
const next = {};
|
|
177
|
+
let changed = false;
|
|
178
|
+
const sessions = files.map((f) => {
|
|
163
179
|
const file = path.join(dir, f);
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
title =
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
180
|
+
let st;
|
|
181
|
+
try { st = fs.statSync(file); } catch { return null; }
|
|
182
|
+
let e = index[f];
|
|
183
|
+
if (!e || e.mtime !== st.mtimeMs || e.size !== st.size) {
|
|
184
|
+
let title = null, count = 0;
|
|
185
|
+
try {
|
|
186
|
+
const loaded = SessionStore.load(file);
|
|
187
|
+
title = loaded.name || loaded.topic || loaded.title; // its name, else what it was about last, else its first message
|
|
188
|
+
count = loaded.messages.length;
|
|
189
|
+
} catch { /* ignore */ }
|
|
190
|
+
e = { mtime: st.mtimeMs, size: st.size, title, count };
|
|
191
|
+
changed = true;
|
|
192
|
+
}
|
|
193
|
+
next[f] = e;
|
|
194
|
+
return { id: f.slice(0, -6), file, mtime: st.mtimeMs, title: e.title || '(no prompt)', count: e.count };
|
|
195
|
+
}).filter((s) => s && s.count > 0).sort((a, b) => b.mtime - a.mtime);
|
|
196
|
+
if (changed || Object.keys(index).length !== Object.keys(next).length) {
|
|
197
|
+
try { // whole or not at all: another window may list at the same time (a lost update is only a re-parse)
|
|
198
|
+
const tmp = `${indexFile}.${process.pid}.tmp`;
|
|
199
|
+
fs.writeFileSync(tmp, JSON.stringify(next));
|
|
200
|
+
fs.renameSync(tmp, indexFile);
|
|
201
|
+
} catch { /* parsed again next time */ }
|
|
202
|
+
}
|
|
203
|
+
return sessions;
|
|
173
204
|
}
|
|
174
205
|
}
|
|
175
206
|
|
|
207
|
+
const SESSION_INDEX = 'sessions-index.json';
|
|
208
|
+
|
|
176
209
|
export function firstUserText(message) {
|
|
177
210
|
const blocks = typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : message.content;
|
|
178
211
|
const t = blocks.find((b) => b.type === 'text' && !b.text.startsWith('<system-reminder>') && !b.text.startsWith('['));
|
package/src/supervisor.js
CHANGED
|
@@ -39,18 +39,17 @@ export function sessionEntry(entry, platform = process.platform) {
|
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
// Whether this invocation is an interactive session that should run under the supervisor.
|
|
42
|
-
// A background session (--headless, started by the computer service) has no terminal and is one all the same.
|
|
43
42
|
export function shouldSupervise(argv, env = process.env, isTty = (fd) => tty.isatty(fd)) {
|
|
44
43
|
if (env[ENV_SUPERVISED] || /^(1|true|yes)$/i.test(env.CLAUDE_PRO_NO_SUPERVISOR || '')) return false;
|
|
45
|
-
if (['config', 'host', 'attach', 'connect'].includes(argv[0])) return false;
|
|
46
|
-
if (
|
|
44
|
+
if (['config', 'host', 'attach', 'connect'].includes(argv[0])) return false; // a command, or a removed one (see main.js)
|
|
45
|
+
if (!isTty(0) || !isTty(1)) return false;
|
|
47
46
|
return !argv.some((a) => NOT_INTERACTIVE.has(a));
|
|
48
47
|
}
|
|
49
48
|
|
|
50
49
|
function putTerminalRight() {
|
|
51
50
|
// The child may have died with the terminal in the mode it had set for itself.
|
|
52
51
|
// (the fullscreen renderer's alternate screen and mouse reporting included)
|
|
53
|
-
if (!tty.isatty(1)) return;
|
|
52
|
+
if (!tty.isatty(1)) return;
|
|
54
53
|
try { process.stdout.write('\x1b[?1000l\x1b[?1002l\x1b[?1006l\x1b[?1049l\x1b[?2004l\x1b[?25h'); } catch { /* nothing to do */ }
|
|
55
54
|
try { if (tty.isatty(0)) process.stdin.setRawMode(false); } catch { /* nothing to do */ }
|
|
56
55
|
}
|
|
@@ -86,8 +85,7 @@ export function supervise(argv, { entry, env = process.env, execPath = process.e
|
|
|
86
85
|
const childEnv = { ...env, [ENV_SUPERVISED]: '1', [ENV_RESTART_FILE]: stateFile };
|
|
87
86
|
if (restarted) childEnv[ENV_RESTARTED] = '1'; else delete childEnv[ENV_RESTARTED];
|
|
88
87
|
const startedAt = Date.now();
|
|
89
|
-
|
|
90
|
-
child = spawn(execPath, [sessionEntry(entry), ...argv], { stdio: 'inherit', env: childEnv, windowsHide: argv.includes('--headless') });
|
|
88
|
+
child = spawn(execPath, [sessionEntry(entry), ...argv], { stdio: 'inherit', env: childEnv });
|
|
91
89
|
child.on('error', (e) => {
|
|
92
90
|
child = null;
|
|
93
91
|
err.write(`claude-pro: could not start (${e.message})\n`);
|