@yanzc/claude-pro 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -36
- package/package.json +1 -1
- package/src/agent.js +4 -3
- package/src/browser/session.js +21 -1
- package/src/commands.js +103 -18
- package/src/config.js +1 -2
- package/src/live.js +148 -0
- package/src/main.js +5 -3
- package/src/peers.js +41 -4
- package/src/remote.js +73 -267
- package/src/runtime.js +36 -11
- package/src/selfcheck.js +3 -3
- package/src/session.js +116 -7
- package/src/supervisor.js +1 -1
- package/src/tools/bash.js +21 -12
- package/src/tools/browser.js +14 -8
- package/src/tools/code.js +18 -11
- package/src/tools/restart.js +1 -1
- package/src/ui/dialogs.js +23 -30
- package/src/ui/editor.js +65 -169
- package/src/ui/repl.js +399 -456
- package/src/ui/screen.js +47 -674
- package/src/updater.js +5 -4
- package/src/web/api.js +787 -0
- package/src/web/app.css +412 -0
- package/src/web/app.js +1850 -0
- package/src/web/data.js +424 -0
- package/src/web/host.js +334 -0
- package/src/web/login.html +66 -0
- package/src/web/page.html +41 -0
- package/src/web/remote-access.js +232 -0
- package/src/web/server.js +459 -0
package/src/main.js
CHANGED
|
@@ -25,16 +25,17 @@ Options:
|
|
|
25
25
|
--verbose Show detailed tool output
|
|
26
26
|
--no-mcp Do not start MCP servers
|
|
27
27
|
--name <name> Name this session, as /rename does (other sessions reach it with @name)
|
|
28
|
-
--rc, --remote-control Turn remote control on at the start, as /rc does (the gateway's web page shows the session)
|
|
29
28
|
-v, --version Print version
|
|
30
29
|
-h, --help Show help
|
|
31
30
|
|
|
32
31
|
There are no permission prompts: every tool runs immediately (full access). File edits are
|
|
33
32
|
checkpointed per prompt, and /rewind in a session undoes them. The old flags
|
|
34
33
|
--dangerously-skip-permissions, --permission-mode, --allowedTools and --disallowedTools
|
|
35
|
-
are accepted and ignored, and so
|
|
34
|
+
are accepted and ignored, and so are --plan (there is no plan mode: ask for a plan in the message) and --rc
|
|
35
|
+
(the gateway's remote control page is gone: claude-pro web is the console).
|
|
36
36
|
|
|
37
37
|
Commands:
|
|
38
|
+
claude-pro web [--no-open] Open the web console (settings, providers, every conversation, live sessions)
|
|
38
39
|
claude-pro config list [--advanced] Show ordinary settings (add --advanced for optional controls)
|
|
39
40
|
claude-pro config set <KEY> <VALUE> [--project|--local] Save a setting (default: ~/.claude-pro/settings.json)
|
|
40
41
|
claude-pro config unset <KEY> [--project|--local]
|
|
@@ -74,7 +75,7 @@ function parseArgs(argv) {
|
|
|
74
75
|
case '--system-prompt-file': flags.systemPromptFile = next(); break;
|
|
75
76
|
case '--verbose': flags.verbose = true; break;
|
|
76
77
|
case '--no-mcp': flags.noMcp = true; break;
|
|
77
|
-
case '--remote-control': case '--rc':
|
|
78
|
+
case '--remote-control': case '--rc': break; // remote control (the gateway's page) is gone: accepted and ignored
|
|
78
79
|
case '--name': flags.name = next(); break;
|
|
79
80
|
case '-v': case '--version': flags.version = true; break;
|
|
80
81
|
case '-h': case '--help': flags.help = true; break;
|
|
@@ -165,6 +166,7 @@ const REMOVED_COMMANDS = new Set(['host', 'attach', 'connect']);
|
|
|
165
166
|
export async function main(argv) {
|
|
166
167
|
let cwd = process.cwd();
|
|
167
168
|
if (argv[0] === 'config') return configCommand(argv.slice(1), cwd);
|
|
169
|
+
if (argv[0] === 'web') return (await import('./web/server.js')).webCommand(argv.slice(1));
|
|
168
170
|
if (REMOVED_COMMANDS.has(argv[0])) {
|
|
169
171
|
process.stderr.write(`claude-pro ${argv[0]} was removed (the computer service, attach and connect are no longer part of claude-pro). To send this as a prompt, quote it: claude-pro "${argv.join(' ')}"\n`);
|
|
170
172
|
return 2;
|
package/src/peers.js
CHANGED
|
@@ -80,12 +80,15 @@ export function findPeer(peers, ref) {
|
|
|
80
80
|
export class PeerNode {
|
|
81
81
|
// onMessage(msg): msg = {id, kind: 'task'|'reply', text, inReplyTo, from: {id, name, cwd}}
|
|
82
82
|
// `id`: the id this session had before a restart, so that answers on their way still find it.
|
|
83
|
-
// getStatus(): {busy}, what GET /status answers (an update waits until no session of the machine is busy
|
|
84
|
-
|
|
83
|
+
// getStatus(): {busy, ...}, what GET /status answers (an update waits until no session of the machine is busy; the
|
|
84
|
+
// web console lists the sessions with it). live: {feed: a LiveFeed (GET /events), command(type, body): the web
|
|
85
|
+
// console's commands (POST /command), as the gateway's page sends them}.
|
|
86
|
+
constructor({ cwd, name, id, onMessage, getStatus, live = null }) {
|
|
85
87
|
this.cwd = cwd;
|
|
86
88
|
this.wantedName = name || null;
|
|
87
89
|
this.onMessage = onMessage;
|
|
88
90
|
this.getStatus = getStatus;
|
|
91
|
+
this.live = live;
|
|
89
92
|
this.id = /^[0-9a-f]{12}$/.test(id || '') ? id : crypto.randomBytes(6).toString('hex');
|
|
90
93
|
this.token = crypto.randomBytes(16).toString('hex');
|
|
91
94
|
this.name = null;
|
|
@@ -121,7 +124,9 @@ export class PeerNode {
|
|
|
121
124
|
write() {
|
|
122
125
|
if (!this.port) return;
|
|
123
126
|
fs.mkdirSync(PEERS_DIR, { recursive: true });
|
|
124
|
-
|
|
127
|
+
// sessionClaims: this version marks the conversations it holds (session.js claimSession), so the age cleanup
|
|
128
|
+
// need not keep a whole project for it
|
|
129
|
+
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(), sessionClaims: true };
|
|
125
130
|
const json = JSON.stringify(data);
|
|
126
131
|
if (json === this.written) return;
|
|
127
132
|
// whole or not at all: the other sessions read these files at any time (listPeers)
|
|
@@ -145,7 +150,39 @@ export class PeerNode {
|
|
|
145
150
|
if (req.headers.authorization !== `Bearer ${this.token}`) return reply(401, { error: 'bad token' });
|
|
146
151
|
let status = {};
|
|
147
152
|
try { status = this.getStatus?.() || {}; } catch { /* nothing to say */ }
|
|
148
|
-
return reply(200, { busy: Boolean(status.busy) });
|
|
153
|
+
return reply(200, { ...status, busy: Boolean(status.busy) });
|
|
154
|
+
}
|
|
155
|
+
if (req.method === 'GET' && req.url === '/events' && this.live?.feed) {
|
|
156
|
+
if (req.headers.authorization !== `Bearer ${this.token}`) return reply(401, { error: 'bad token' });
|
|
157
|
+
this.live.feed.attach(res);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const image = /^\/image\/(\d+)$/.exec(req.url || '');
|
|
161
|
+
if (req.method === 'GET' && image && this.live?.image) {
|
|
162
|
+
if (req.headers.authorization !== `Bearer ${this.token}`) return reply(401, { error: 'bad token' });
|
|
163
|
+
let img = null;
|
|
164
|
+
try { img = this.live.image(Number(image[1])); } catch { /* none */ }
|
|
165
|
+
if (!img) return reply(404, { error: 'no such image' });
|
|
166
|
+
res.writeHead(200, { 'content-type': img.mediaType, 'cache-control': 'private, max-age=3600' });
|
|
167
|
+
res.end(img.data);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (req.method === 'POST' && req.url === '/command' && this.live?.command) {
|
|
171
|
+
if (req.headers.authorization !== `Bearer ${this.token}`) return reply(401, { error: 'bad token' });
|
|
172
|
+
let body = '';
|
|
173
|
+
req.setEncoding('utf8');
|
|
174
|
+
req.on('data', (d) => { body += d; if (body.length > 16 * MAX_BODY) req.destroy(); });
|
|
175
|
+
req.on('end', async () => {
|
|
176
|
+
let cmd;
|
|
177
|
+
try { cmd = JSON.parse(body); } catch { return reply(400, { ok: false, error: 'bad json' }); }
|
|
178
|
+
try {
|
|
179
|
+
const result = await this.live.command(String(cmd?.type || ''), cmd?.body && typeof cmd.body === 'object' ? cmd.body : {});
|
|
180
|
+
reply(200, { ...(result || {}), ok: true });
|
|
181
|
+
} catch (e) {
|
|
182
|
+
reply(200, { ok: false, error: e?.message || String(e) });
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
return;
|
|
149
186
|
}
|
|
150
187
|
if (req.method !== 'POST' || req.url !== '/message') return reply(404, { error: 'not found' });
|
|
151
188
|
if (req.headers.authorization !== `Bearer ${this.token}`) return reply(401, { error: 'bad token' });
|
package/src/remote.js
CHANGED
|
@@ -1,31 +1,21 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
// The same connection carries the messages of the account's sessions on other computers (`@公司 ...`, see peers.js).
|
|
8
|
-
//
|
|
9
|
-
// The page is told what happens as a list of transcript items (user messages, assistant text, thinking, tool
|
|
10
|
-
// calls, other terminal output) that events update. The same reducer (applyEvent) runs here, to send a snapshot
|
|
11
|
-
// when one is needed, and in the page, which carries a copy of it.
|
|
1
|
+
// Two things: the transcript model that the local web console's live view uses (applyEvent, hydrate, transcriptItems,
|
|
2
|
+
// snapshotItems: a conversation as a list of items — user messages, assistant text, thinking, tool calls, other
|
|
3
|
+
// terminal output — that events update; the page, web/app.js, carries a copy of the reducer), and this session's
|
|
4
|
+
// connection to the gateway's session relay (RemoteControl), which carries the tasks of the account's sessions on
|
|
5
|
+
// other computers (`@公司 ...`, see peers.js) and of contacts. The session never listens on the network: it connects
|
|
6
|
+
// out to the gateway with the API key from /connect.
|
|
12
7
|
|
|
13
8
|
import os from 'node:os';
|
|
14
9
|
import crypto from 'node:crypto';
|
|
15
|
-
import { stripAnsi } from './ui/ansi.js';
|
|
16
10
|
import { toolHeader, renderToolResult, bashModeLines } from './ui/render.js';
|
|
17
11
|
import { shownQuotes } from './ui/editor.js';
|
|
18
12
|
|
|
19
13
|
export const REMOTE_WIDTH = 100; // columns that tool headers and results are laid out for on the page
|
|
20
|
-
const MAX_ITEMS = 800; // kept for a snapshot; the oldest are dropped beyond that
|
|
21
14
|
const SEED_ITEMS = 500;
|
|
22
15
|
const SNAPSHOT_ITEMS = 400; // sent in a snapshot
|
|
23
16
|
const SNAPSHOT_BYTES = 1_500_000; // ... at most: the gateway takes 2 MB a POST
|
|
24
17
|
const ITEM_CHARS = 60_000; // a longer text or output is cut down in a snapshot
|
|
25
|
-
const SNAPSHOT_EVERY = 500; // events after which a fresh snapshot replaces them on the gateway
|
|
26
|
-
const FLUSH_MS = 150;
|
|
27
18
|
const STATUS_MS = 500; // how often the status is compared with what the gateway has
|
|
28
|
-
const IDLE_STATUS_MS = 3000; // ... and sent at most this often while nobody watches
|
|
29
19
|
const REQUEST_TIMEOUT_MS = 15_000;
|
|
30
20
|
const STREAM_SILENCE_MS = 50_000; // the gateway pings every 15 s: a command stream silent this long is dead
|
|
31
21
|
|
|
@@ -38,6 +28,7 @@ export function applyEvent(state, ev) {
|
|
|
38
28
|
const push = (item) => { items.push(item); return item; };
|
|
39
29
|
switch (ev.t) {
|
|
40
30
|
case 'user': return push({ k: 'user', text: ev.text });
|
|
31
|
+
case 'image': return push({ k: 'image', n: ev.n }); // (the local web console's: the gateway's page is not sent these)
|
|
41
32
|
case 'output': {
|
|
42
33
|
const last = items[items.length - 1];
|
|
43
34
|
if (last && last.k === 'output') { last.lines.push(...ev.lines); return last; }
|
|
@@ -110,7 +101,10 @@ function shownUserText(text) {
|
|
|
110
101
|
}
|
|
111
102
|
|
|
112
103
|
// Transcript items for a conversation (agent.messages), as the page shows them when it connects.
|
|
113
|
-
|
|
104
|
+
// `limit`: the newest items kept (the web console's history view takes them all); `images`: an image is {k: 'image', n}
|
|
105
|
+
// (the n-th image of the conversation) instead of the text [image].
|
|
106
|
+
export function transcriptItems(messages, { tools = [], ctx, cwd, width = REMOTE_WIDTH, limit = SEED_ITEMS, images = false } = {}) {
|
|
107
|
+
let imageCount = 0;
|
|
114
108
|
const toolMap = new Map(tools.map((t) => [t.name, t]));
|
|
115
109
|
const items = [];
|
|
116
110
|
const calls = new Map();
|
|
@@ -126,7 +120,7 @@ export function transcriptItems(messages, { tools = [], ctx, cwd, width = REMOTE
|
|
|
126
120
|
const text = raw.startsWith('<system-reminder>') ? '' : shownUserText(raw);
|
|
127
121
|
if (text) items.push({ k: 'user', text });
|
|
128
122
|
} else if (b.type === 'image') {
|
|
129
|
-
items.push({ k: 'user', text: '[image]' });
|
|
123
|
+
items.push(images ? { k: 'image', n: imageCount++ } : { k: 'user', text: '[image]' });
|
|
130
124
|
} else if (b.type === 'tool_result') {
|
|
131
125
|
const call = calls.get(b.tool_use_id);
|
|
132
126
|
if (!call) continue;
|
|
@@ -148,7 +142,7 @@ export function transcriptItems(messages, { tools = [], ctx, cwd, width = REMOTE
|
|
|
148
142
|
}
|
|
149
143
|
}
|
|
150
144
|
}
|
|
151
|
-
return items.slice(-
|
|
145
|
+
return Number.isFinite(limit) ? items.slice(-limit) : items;
|
|
152
146
|
}
|
|
153
147
|
|
|
154
148
|
// The newest items that fit in a snapshot the gateway takes, as copies (the POST may be serialized later, when
|
|
@@ -177,12 +171,6 @@ export function snapshotItems(items, { max = SNAPSHOT_ITEMS, bytes = SNAPSHOT_BY
|
|
|
177
171
|
return picked.reverse();
|
|
178
172
|
}
|
|
179
173
|
|
|
180
|
-
// The last lines of a running tool's output, for the page.
|
|
181
|
-
function progressTail(text) {
|
|
182
|
-
const lines = String(text || '').slice(-6000).replace(/\r\n/g, '\n').trimEnd().split('\n');
|
|
183
|
-
return lines.slice(-8).map((l) => l.replace(/^.*\r/, '').slice(0, 400)).join('\n');
|
|
184
|
-
}
|
|
185
|
-
|
|
186
174
|
// ---------------------------------------------------------------- the connection to the gateway
|
|
187
175
|
|
|
188
176
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
@@ -193,68 +181,29 @@ export const newRemoteId = () => crypto.randomBytes(9).toString('base64url');
|
|
|
193
181
|
// which only the self-check and the tests set).
|
|
194
182
|
export const onlineEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(env.CLAUDE_PRO_ONLINE || '');
|
|
195
183
|
|
|
196
|
-
//
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
//
|
|
200
|
-
// returns the result's fields, or a promise of them, or throws what to tell the page). A session declares the ones
|
|
201
|
-
// it has handlers for when it registers (`commands`); the gateway forwards only those and answers the others itself.
|
|
202
|
-
// A session that declares none (0.8.x, CLAUDE_PRO_REMOTE_COMMANDS=0) is read-only on the page.
|
|
203
|
-
const COMMANDS = { send: 'send', interrupt: 'interrupt', dialog: 'answer', options: 'options', suggest: 'suggest', list: 'list', output: 'output' };
|
|
204
|
-
|
|
184
|
+
// This session at the gateway's session relay: registered while it runs, with a stream kept open on which the tasks
|
|
185
|
+
// of the account's sessions on other computers (and of contacts) and the 通讯录's news arrive, and its status (busy,
|
|
186
|
+
// name, title, directory, model: what the other sessions are shown of it). Nothing of the conversation goes there.
|
|
187
|
+
// (Until 2026-11-21 the transcript went there too, for the gateway's 远程控制 page, which is gone.)
|
|
205
188
|
export class RemoteControl {
|
|
206
|
-
// gateway: {url, apiKey}. handlers: info() -> {name, title, cwd, model
|
|
207
|
-
// peerMessage(message), changed() (online
|
|
208
|
-
|
|
209
|
-
// `rc`: remote control is on (/rc): the gateway's web page shows the conversation and may steer the session. Off,
|
|
210
|
-
// the session is online only for messages between sessions: no conversation is uploaded, and its status is only
|
|
211
|
-
// whether it works and its name (see setRc).
|
|
212
|
-
constructor({ gateway, id, handlers, rc = false, fetchImpl = globalThis.fetch }) {
|
|
213
|
-
this.rc = Boolean(rc);
|
|
189
|
+
// gateway: {url, apiKey}. handlers: info() -> {name, title, cwd, model, version, machine, peerId}, status() -> object,
|
|
190
|
+
// peerMessage(message) (false defers delivery), contactEvent(event), changed() (online changed), refused(status).
|
|
191
|
+
constructor({ gateway, id, handlers, fetchImpl = globalThis.fetch }) {
|
|
214
192
|
this.base = String(gateway.url).replace(/\/+$/, '');
|
|
215
193
|
this.apiKey = gateway.apiKey;
|
|
216
194
|
this.id = /^[\w-]{8,64}$/.test(id || '') ? id : newRemoteId();
|
|
217
195
|
this.handlers = handlers;
|
|
218
196
|
this.fetch = fetchImpl;
|
|
219
|
-
this.online = false; // the
|
|
220
|
-
this.viewers = null; // pages watching, as the gateway counts them (null: not told yet)
|
|
197
|
+
this.online = false; // the stream is open
|
|
221
198
|
this.closed = false;
|
|
222
|
-
this.seq = 0;
|
|
223
|
-
this.state = hydrate(handlers.seed?.() || []);
|
|
224
|
-
this.events = []; // waiting to be uploaded
|
|
225
|
-
this.progress = new Map(); // tool id -> its live entry, whose output goes out at the next flush
|
|
226
|
-
this.outbox = []; // messages for the next POST /events
|
|
227
|
-
this.sending = false;
|
|
228
|
-
this.needSnapshot = true;
|
|
229
|
-
this.sinceSnapshot = 0;
|
|
230
|
-
this.lastStatus = '';
|
|
231
|
-
this.lastStatusAt = 0;
|
|
232
|
-
this.flushTimer = null;
|
|
233
|
-
this.streamAbort = null;
|
|
234
199
|
this.registered = false;
|
|
235
200
|
this.refused = null; // the status (401/403) of the gateway refusing the key after the start: the connection ended
|
|
236
201
|
this.seenPeer = new Set(); // ids of the messages from other sessions already handled (the gateway sends again what was not acknowledged)
|
|
237
|
-
this.replying = new Set(); // answers to the page's commands on their way (close() waits for them)
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
// The commands this session takes, as declared to the gateway.
|
|
241
|
-
get commands() { return this.rc ? Object.keys(COMMANDS).filter((type) => typeof this.handlers[COMMANDS[type]] === 'function') : []; }
|
|
242
|
-
|
|
243
|
-
// nobody watching, or remote control off: events are not uploaded (a snapshot follows when someone comes)
|
|
244
|
-
get viewing() { return this.rc && this.viewers !== 0; }
|
|
245
|
-
|
|
246
|
-
// Remote control on or off: the gateway is told at once (registering again), and a page that watched is closed by
|
|
247
|
-
// it. What happened while it was off is in the snapshot that goes out when it comes on: the conversation is kept
|
|
248
|
-
// here either way.
|
|
249
|
-
async setRc(on) {
|
|
250
|
-
on = Boolean(on);
|
|
251
|
-
if (this.rc === on) return;
|
|
252
|
-
this.rc = on;
|
|
253
|
-
this.events = [];
|
|
254
|
-
this.needSnapshot = true;
|
|
255
202
|
this.lastStatus = '';
|
|
256
|
-
|
|
257
|
-
this.
|
|
203
|
+
this.statusEpoch = 0;
|
|
204
|
+
this.statusSending = false;
|
|
205
|
+
this.statusTimer = null;
|
|
206
|
+
this.streamAbort = null;
|
|
258
207
|
}
|
|
259
208
|
|
|
260
209
|
// `persistent`: keep trying when the gateway cannot be reached now (a restart); otherwise the first failure is thrown.
|
|
@@ -281,28 +230,26 @@ export class RemoteControl {
|
|
|
281
230
|
signal: AbortSignal.timeout(timeout),
|
|
282
231
|
});
|
|
283
232
|
let res;
|
|
284
|
-
// Once more when the connection failed before any answer (a kept-alive socket the server had just closed)
|
|
285
|
-
// every request here can be repeated (registering is idempotent, the pages drop events they already have).
|
|
233
|
+
// Once more when the connection failed before any answer (a kept-alive socket the server had just closed).
|
|
286
234
|
try { res = await send(); } catch (e) { if (!retry || e.name === 'TimeoutError' || this.closed) throw e; res = await send(); }
|
|
287
235
|
const data = await res.json().catch(() => ({}));
|
|
288
236
|
if (!res.ok) {
|
|
289
237
|
const message = data?.error?.message || (typeof data?.error === 'string' ? data.error : `HTTP ${res.status}`);
|
|
290
|
-
throw Object.assign(new Error(res.status === 404 && route === '/v1/remote/sessions' ? `the gateway ${this.base}
|
|
238
|
+
throw Object.assign(new Error(res.status === 404 && route === '/v1/remote/sessions' ? `the gateway ${this.base} has no session relay (yet)` : String(message)), { status: res.status });
|
|
291
239
|
}
|
|
292
240
|
return data;
|
|
293
241
|
}
|
|
294
242
|
|
|
295
243
|
async register() {
|
|
296
244
|
const info = this.handlers.info?.() || {};
|
|
297
|
-
const
|
|
298
|
-
const shown = this.rc ? info : { ...info, title: '', cwd: '' };
|
|
299
|
-
const data = await this.request('POST', '/v1/remote/sessions', { id: this.id, host: os.hostname(), version: info.version, ...shown, rc: this.rc, ...(commands.length ? { commands } : {}) });
|
|
245
|
+
const data = await this.request('POST', '/v1/remote/sessions', { id: this.id, host: os.hostname(), ...info });
|
|
300
246
|
if (data.id) this.id = data.id;
|
|
301
247
|
this.registered = true;
|
|
302
|
-
this.
|
|
248
|
+
this.lastStatus = '';
|
|
249
|
+
this.statusEpoch++;
|
|
303
250
|
}
|
|
304
251
|
|
|
305
|
-
// The
|
|
252
|
+
// The stream, kept open (and opened again) until close(): while it is open the session is online.
|
|
306
253
|
async loop() {
|
|
307
254
|
let wait = 1000;
|
|
308
255
|
while (!this.closed) {
|
|
@@ -310,8 +257,8 @@ export class RemoteControl {
|
|
|
310
257
|
try {
|
|
311
258
|
if (!this.registered) {
|
|
312
259
|
await this.register();
|
|
313
|
-
// closed while it registered (/disconnect, another account): the
|
|
314
|
-
//
|
|
260
|
+
// closed while it registered (/disconnect, another account): the registration that just went through gets
|
|
261
|
+
// the bye that close() could not send yet
|
|
315
262
|
if (this.closed) {
|
|
316
263
|
this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/events`, { messages: [{ t: 'bye', restarting: false }] }, { timeout: 1500 }).catch(() => {});
|
|
317
264
|
break;
|
|
@@ -324,9 +271,6 @@ export class RemoteControl {
|
|
|
324
271
|
}
|
|
325
272
|
if (this.online) {
|
|
326
273
|
this.online = false;
|
|
327
|
-
// Nothing is uploaded while offline (see flush), and the stream's next opening sends a snapshot.
|
|
328
|
-
this.needSnapshot = true;
|
|
329
|
-
this.events = [];
|
|
330
274
|
this.handlers.changed?.();
|
|
331
275
|
}
|
|
332
276
|
if (this.closed) break;
|
|
@@ -345,7 +289,6 @@ export class RemoteControl {
|
|
|
345
289
|
this.closed = true;
|
|
346
290
|
this.registered = false; // no bye with a key the gateway refuses
|
|
347
291
|
this.online = false;
|
|
348
|
-
clearTimeout(this.flushTimer);
|
|
349
292
|
clearInterval(this.statusTimer);
|
|
350
293
|
this.streamAbort?.abort();
|
|
351
294
|
try { this.handlers.refused?.(status); } catch { /* the App's problem */ }
|
|
@@ -365,9 +308,10 @@ export class RemoteControl {
|
|
|
365
308
|
throw Object.assign(new Error(`HTTP ${res.status}`), { status: res.status });
|
|
366
309
|
}
|
|
367
310
|
this.online = true;
|
|
368
|
-
this.
|
|
311
|
+
this.lastStatus = ''; // the gateway may have been restarted: it gets the status again
|
|
312
|
+
this.statusEpoch++;
|
|
369
313
|
this.handlers.changed?.();
|
|
370
|
-
this.
|
|
314
|
+
this.flush();
|
|
371
315
|
let last = Date.now();
|
|
372
316
|
const watchdog = setInterval(() => { if (Date.now() - last > STREAM_SILENCE_MS) abort.abort(); }, 5000);
|
|
373
317
|
watchdog.unref?.();
|
|
@@ -383,9 +327,9 @@ export class RemoteControl {
|
|
|
383
327
|
buf = buf.slice(i).replace(/^\r?\n\r?\n/, '');
|
|
384
328
|
const data = block.split(/\r?\n/).filter((l) => l.startsWith('data:')).map((l) => l.slice(5).replace(/^ /, '')).join('\n');
|
|
385
329
|
if (!data) continue;
|
|
386
|
-
let
|
|
387
|
-
try {
|
|
388
|
-
this.
|
|
330
|
+
let frame;
|
|
331
|
+
try { frame = JSON.parse(data); } catch { continue; }
|
|
332
|
+
this.frame(frame);
|
|
389
333
|
}
|
|
390
334
|
}
|
|
391
335
|
} catch (e) {
|
|
@@ -395,65 +339,27 @@ export class RemoteControl {
|
|
|
395
339
|
}
|
|
396
340
|
}
|
|
397
341
|
|
|
398
|
-
|
|
399
|
-
if (this.closed) return;
|
|
400
|
-
if (cmd.type === 'viewers') {
|
|
401
|
-
const was = this.viewers;
|
|
402
|
-
this.viewers = Math.max(0, Number(cmd.count) || 0);
|
|
403
|
-
if (!was && this.viewers) this.needSnapshot = true; // someone came: what they see starts from now
|
|
404
|
-
this.handlers.changed?.();
|
|
405
|
-
this.scheduleFlush(0);
|
|
406
|
-
return;
|
|
407
|
-
}
|
|
408
|
-
if (cmd.type === 'snapshot') { this.needSnapshot = true; this.scheduleFlush(0); return; }
|
|
342
|
+
frame(frame) {
|
|
343
|
+
if (this.closed) return;
|
|
409
344
|
// 通讯录: someone asked this account to be a contact, or accepted its request
|
|
410
|
-
if (
|
|
411
|
-
if (
|
|
412
|
-
|
|
413
|
-
// A command of the page, answered with POST …/results {cid, ok: true, …fields} or {cid, ok: false, error} (the
|
|
414
|
-
// gateway waits 15 s for it, and takes it until 3 s after the stream closed). close() waits for the answers on
|
|
415
|
-
// their way: a /cd from the page restarts the session from inside its command.
|
|
416
|
-
const reply = (result) => {
|
|
417
|
-
const sent = this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/results`, result).catch(() => { /* the page times out */ });
|
|
418
|
-
this.replying.add(sent);
|
|
419
|
-
sent.finally(() => this.replying.delete(sent));
|
|
420
|
-
this.scheduleFlush(30); // what the command changed, on the page soon
|
|
421
|
-
};
|
|
422
|
-
const failed = (e) => reply({ cid: cmd.cid, ok: false, error: e?.message || String(e) });
|
|
423
|
-
const handler = Object.hasOwn(COMMANDS, cmd.type) ? this.handlers[COMMANDS[cmd.type]] : null;
|
|
424
|
-
if (!this.rc) { failed(new Error('Remote control is off for this session: /rc in its terminal turns it on.')); return; }
|
|
425
|
-
if (typeof handler !== 'function') {
|
|
426
|
-
// an older gateway forwards every command, declared or not
|
|
427
|
-
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).'));
|
|
428
|
-
return;
|
|
429
|
-
}
|
|
430
|
-
let r;
|
|
431
|
-
try {
|
|
432
|
-
r = handler(cmd.body && typeof cmd.body === 'object' && !Array.isArray(cmd.body) ? cmd.body : {});
|
|
433
|
-
} catch (e) {
|
|
434
|
-
failed(e);
|
|
435
|
-
return;
|
|
436
|
-
}
|
|
437
|
-
// an answer that takes a while (the gateway's list of models, a directory) is sent when it is there
|
|
438
|
-
if (typeof r?.then === 'function') r.then((v) => reply({ ...(v || {}), cid: cmd.cid, ok: true }), failed);
|
|
439
|
-
else reply({ ...(r || {}), cid: cmd.cid, ok: true });
|
|
345
|
+
if (frame.type === 'contact') { try { this.handlers.contactEvent?.(frame); } catch { /* the App's problem */ } return; }
|
|
346
|
+
if (frame.type === 'peer' && frame.cid) this.peerMessage(frame);
|
|
347
|
+
// (anything else, such as an older gateway's page commands, is not this session's any more)
|
|
440
348
|
}
|
|
441
349
|
|
|
442
|
-
// ------------------------------------------------------------ messages of
|
|
350
|
+
// ------------------------------------------------------------ messages of other sessions
|
|
443
351
|
|
|
444
352
|
// A message from a session on another computer: handed to the App once, then acknowledged, so that the gateway
|
|
445
353
|
// drops it from the session's mailbox (it sends what was not acknowledged again when the stream reconnects).
|
|
446
354
|
peerMessage(cmd) {
|
|
447
355
|
const ack = () => this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/results`, { cid: cmd.cid, ok: true }).catch(() => { /* sent again on reconnect, and dropped here as seen */ });
|
|
356
|
+
if (this.seenPeer.has(cmd.cid)) { ack(); return; }
|
|
448
357
|
try {
|
|
449
|
-
if (this.seenPeer.has(cmd.cid)) { ack(); return; }
|
|
450
|
-
this.seenPeer.add(cmd.cid);
|
|
451
|
-
if (this.seenPeer.size > 500) this.seenPeer.delete(this.seenPeer.values().next().value);
|
|
452
358
|
const f = cmd.from || {};
|
|
453
359
|
const machine = f.machine || f.host || 'computer';
|
|
454
360
|
// a contact's session (another person's account): its 通讯号 and how this account takes its tasks
|
|
455
361
|
const account = typeof f.account === 'string' && f.account ? f.account : null;
|
|
456
|
-
this.handlers.peerMessage?.({
|
|
362
|
+
const accepted = this.handlers.peerMessage?.({
|
|
457
363
|
id: cmd.cid,
|
|
458
364
|
kind: cmd.kind === 'reply' ? 'reply' : 'task',
|
|
459
365
|
text: String(cmd.text ?? ''),
|
|
@@ -463,7 +369,14 @@ export class RemoteControl {
|
|
|
463
369
|
...(account ? { account, trust: f.trust === 'auto' ? 'auto' : 'confirm' } : {}),
|
|
464
370
|
},
|
|
465
371
|
});
|
|
372
|
+
if (accepted === false) {
|
|
373
|
+
// A session moving into the console cannot take new work. Leave it in the mailbox for the next stream.
|
|
374
|
+
this.streamAbort?.abort();
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
466
377
|
} catch { /* the App's problem: the message is acknowledged anyway, or it would come back forever */ }
|
|
378
|
+
this.seenPeer.add(cmd.cid);
|
|
379
|
+
if (this.seenPeer.size > 500) this.seenPeer.delete(this.seenPeer.values().next().value);
|
|
467
380
|
ack();
|
|
468
381
|
}
|
|
469
382
|
|
|
@@ -489,156 +402,49 @@ export class RemoteControl {
|
|
|
489
402
|
return { id: data.id, delivered: data.delivered !== false };
|
|
490
403
|
}
|
|
491
404
|
|
|
492
|
-
// ------------------------------------------------------------
|
|
405
|
+
// ------------------------------------------------------------ status
|
|
493
406
|
|
|
494
|
-
|
|
495
|
-
ev.seq = ++this.seq;
|
|
496
|
-
applyEvent(this.state, ev);
|
|
497
|
-
if (this.state.items.length > MAX_ITEMS) this.state.items.splice(0, this.state.items.length - MAX_ITEMS + 100);
|
|
498
|
-
if (ev.t === 'done') this.progress.delete(ev.id); // also while offline, when nothing takes it: it holds all the tool's output
|
|
499
|
-
if (this.viewing && !this.needSnapshot) {
|
|
500
|
-
// A streamed reply's deltas in a row go out as one: one event each made a full snapshot (up to 1.5 MB) due every
|
|
501
|
-
// few seconds of a long reply, since SNAPSHOT_EVERY counts events. The page takes the newest seq of the merged
|
|
502
|
-
// ones; it only skips events at or below the seq it has.
|
|
503
|
-
const last = this.events[this.events.length - 1];
|
|
504
|
-
if (ev.t === 'delta' && last?.t === 'delta' && last.kind === ev.kind) { last.text += ev.text; last.seq = ev.seq; }
|
|
505
|
-
else this.events.push(ev);
|
|
506
|
-
this.scheduleFlush();
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
// Lines the terminal printed that no other event stands for (command output, notices, errors).
|
|
511
|
-
output(lines) {
|
|
512
|
-
const last = this.state.items[this.state.items.length - 1];
|
|
513
|
-
if (!lines.length || (last?.k !== 'output' && lines.every((l) => !stripAnsi(l).trim()))) return;
|
|
514
|
-
this.emit({ t: 'output', lines });
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
toolProgress(id, entry) {
|
|
518
|
-
if (!id) return;
|
|
519
|
-
this.progress.set(id, entry);
|
|
520
|
-
if (this.viewing) this.scheduleFlush();
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
// The conversation was replaced (/clear, /resume, /rewind): the pages start again from it.
|
|
524
|
-
resync() {
|
|
525
|
-
this.progress.clear();
|
|
526
|
-
this.events = [];
|
|
527
|
-
this.state = hydrate(this.handlers.seed?.() || []);
|
|
528
|
-
this.seq++;
|
|
529
|
-
this.needSnapshot = true;
|
|
530
|
-
this.scheduleFlush(0);
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
scheduleFlush(ms = FLUSH_MS) {
|
|
534
|
-
if (this.closed) return;
|
|
535
|
-
if (this.flushTimer && ms > 0) return;
|
|
536
|
-
clearTimeout(this.flushTimer);
|
|
537
|
-
this.flushTimer = setTimeout(() => { this.flushTimer = null; this.flush(); }, ms);
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
takeProgress() {
|
|
541
|
-
for (const [id, entry] of this.progress) {
|
|
542
|
-
const ev = { t: 'progress', id, text: progressTail(entry.progress), seq: ++this.seq };
|
|
543
|
-
if (applyEvent(this.state, ev) && this.viewing && !this.needSnapshot) this.events.push(ev);
|
|
544
|
-
}
|
|
545
|
-
this.progress.clear();
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
// Remote control off: only what the account's other sessions see of it (whether it works, its name, its model).
|
|
407
|
+
// What the other sessions are shown of this one, sent when it changed (and again after the stream reopened).
|
|
549
408
|
status() {
|
|
550
|
-
let status;
|
|
551
|
-
try { status = this.handlers.status?.() || {}; } catch
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
return { busy: Boolean(busy), name, model };
|
|
409
|
+
let status = {};
|
|
410
|
+
try { status = this.handlers.status?.() || {}; } catch { /* the basics stay as they were */ }
|
|
411
|
+
const { busy, name, title, cwd, model } = status;
|
|
412
|
+
return { busy: Boolean(busy), name, title, cwd, model };
|
|
555
413
|
}
|
|
556
414
|
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
// `asking` (a question waits) is in it too: the gateway tells the user about it even with no page open.
|
|
560
|
-
statusKey(status) {
|
|
561
|
-
if (this.viewing) return JSON.stringify({ ...status, elapsed: 0 });
|
|
562
|
-
const { busy, asking, title, model, cwd, name } = status;
|
|
563
|
-
return JSON.stringify({ busy, asking, title, model, cwd, name });
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
// What is sent at once, without the wait between statuses of an unwatched session: a task that started or ended,
|
|
567
|
-
// a question that came or was answered.
|
|
568
|
-
urgentKey(status) { return `${Boolean(status.busy)}|${Boolean(status.asking)}`; }
|
|
569
|
-
|
|
570
|
-
// What has changed goes into the next upload: a snapshot when one is due, else the events; and the status.
|
|
571
|
-
// Not while the command stream is down: every upload would fail and leave a snapshot due, so a session used to
|
|
572
|
-
// build and POST (twice) a snapshot of up to 1.5 MB every 500 ms for as long as the gateway was unreachable.
|
|
573
|
-
flush() {
|
|
574
|
-
if (this.closed || !this.registered || (!this.online && !this.closing)) return;
|
|
575
|
-
this.takeProgress();
|
|
415
|
+
async flush() {
|
|
416
|
+
if (this.closed || !this.registered || !this.online || this.statusSending) return;
|
|
576
417
|
const status = this.status();
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
this.lastStatus = this.statusKey(status);
|
|
582
|
-
this.lastUrgent = this.urgentKey(status);
|
|
583
|
-
this.lastStatusAt = Date.now();
|
|
584
|
-
this.outbox.push({ t: 'snapshot', seq: this.seq, items: snapshotItems(this.state.items), status });
|
|
585
|
-
} else if (this.events.length) {
|
|
586
|
-
this.sinceSnapshot += this.events.length;
|
|
587
|
-
this.outbox.push({ t: 'batch', events: this.events });
|
|
588
|
-
this.events = [];
|
|
589
|
-
}
|
|
590
|
-
const key = this.statusKey(status);
|
|
591
|
-
const urgent = this.urgentKey(status);
|
|
592
|
-
if (key !== this.lastStatus && (urgent !== this.lastUrgent || Date.now() - this.lastStatusAt >= (this.viewing ? 0 : IDLE_STATUS_MS))) {
|
|
593
|
-
this.lastStatus = key;
|
|
594
|
-
this.lastUrgent = urgent;
|
|
595
|
-
this.lastStatusAt = Date.now();
|
|
596
|
-
this.outbox.push({ t: 'status', status });
|
|
597
|
-
}
|
|
598
|
-
this.pump();
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
// One POST at a time, so that the gateway gets the messages in order. A failed one is not sent again: the
|
|
602
|
-
// next upload is a snapshot, which stands for everything that was lost.
|
|
603
|
-
async pump() {
|
|
604
|
-
if (this.sending || this.closing || !this.outbox.length) return;
|
|
605
|
-
this.sending = true;
|
|
606
|
-
const messages = this.outbox.splice(0);
|
|
418
|
+
const key = JSON.stringify(status);
|
|
419
|
+
if (key === this.lastStatus) return;
|
|
420
|
+
const epoch = this.statusEpoch;
|
|
421
|
+
this.statusSending = true; // one POST at a time: an older status must not overtake a newer one
|
|
607
422
|
try {
|
|
608
|
-
await this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/events`, { messages });
|
|
423
|
+
await this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/events`, { messages: [{ t: 'status', status }] });
|
|
424
|
+
if (!this.closed && epoch === this.statusEpoch) this.lastStatus = key;
|
|
609
425
|
} catch (e) {
|
|
610
|
-
this.
|
|
611
|
-
this.
|
|
426
|
+
if (this.closed || epoch !== this.statusEpoch) return;
|
|
427
|
+
this.lastStatus = ''; // the gateway may or may not have received the POST; send the current status again
|
|
612
428
|
if (e.status === 404) { this.registered = false; this.streamAbort?.abort(); }
|
|
613
429
|
if (e.status === 401 || e.status === 403) this.refuse(e.status);
|
|
614
430
|
} finally {
|
|
615
|
-
this.
|
|
431
|
+
this.statusSending = false;
|
|
616
432
|
}
|
|
617
|
-
if (this.outbox.length) this.pump();
|
|
618
433
|
}
|
|
619
434
|
|
|
620
435
|
// Ends the connection; resolves once the gateway was told (or gave up waiting). `restarting`: the session comes
|
|
621
|
-
// back at once with the same id
|
|
436
|
+
// back at once with the same id.
|
|
622
437
|
close({ restarting = false } = {}) {
|
|
623
438
|
this.closeDone ??= this.shutdown(restarting);
|
|
624
439
|
return this.closeDone;
|
|
625
440
|
}
|
|
626
441
|
|
|
627
442
|
async shutdown(restarting) {
|
|
628
|
-
// First the answers on their way, while the command stream is still open (the gateway takes them until 3 s
|
|
629
|
-
// after it closes). Among them the answer to the command that restarts the session: a /cd from the page closes
|
|
630
|
-
// it from inside that command (the page may not end, restart or update it otherwise, see App.remoteSend), and its answer
|
|
631
|
-
// is sent when the command returns, hence the wait for the current call to finish first.
|
|
632
443
|
await null;
|
|
633
|
-
if (this.replying.size) await Promise.race([Promise.allSettled([...this.replying]), new Promise((r) => setTimeout(r, 1500).unref?.())]);
|
|
634
|
-
this.closing = true; // what flush() collects now goes out with the last message, not on its own
|
|
635
|
-
this.flush();
|
|
636
444
|
this.closed = true;
|
|
637
|
-
clearTimeout(this.flushTimer);
|
|
638
445
|
clearInterval(this.statusTimer);
|
|
639
446
|
this.streamAbort?.abort();
|
|
640
447
|
if (!this.registered) return;
|
|
641
|
-
|
|
642
|
-
await this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/events`, { messages }, { timeout: 1500 }).catch(() => {});
|
|
448
|
+
await this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/events`, { messages: [{ t: 'bye', restarting }] }, { timeout: 1500 }).catch(() => {});
|
|
643
449
|
}
|
|
644
450
|
}
|