@yanzc/claude-pro 0.10.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/src/remote.js CHANGED
@@ -1,31 +1,21 @@
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 /connect,
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.
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
- export function transcriptItems(messages, { tools = [], ctx, cwd, width = REMOTE_WIDTH } = {}) {
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(-SEED_ITEMS);
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,51 +181,31 @@ 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
- // Whether the page may steer the session, not only watch it (CLAUDE_PRO_REMOTE_COMMANDS=0: read-only).
197
- export const remoteCommandsEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(String(env.CLAUDE_PRO_REMOTE_COMMANDS ?? '').trim());
198
-
199
- // The commands of the page, and the handler of each (see App.connectRemote; each gets the command's body and
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}, seed() -> items, status() -> object,
207
- // peerMessage(message), changed() (online or viewers changed), refused(status) (the key was refused: closed), and
208
- // the page's commands: send, interrupt, answer (dialog), options, suggest, list, output (see COMMANDS).
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).
209
191
  constructor({ gateway, id, handlers, fetchImpl = globalThis.fetch }) {
210
192
  this.base = String(gateway.url).replace(/\/+$/, '');
211
193
  this.apiKey = gateway.apiKey;
212
194
  this.id = /^[\w-]{8,64}$/.test(id || '') ? id : newRemoteId();
213
195
  this.handlers = handlers;
214
196
  this.fetch = fetchImpl;
215
- this.online = false; // the command stream is open
216
- this.viewers = null; // pages watching, as the gateway counts them (null: not told yet)
197
+ this.online = false; // the stream is open
217
198
  this.closed = false;
218
- this.seq = 0;
219
- this.state = hydrate(handlers.seed?.() || []);
220
- this.events = []; // waiting to be uploaded
221
- this.progress = new Map(); // tool id -> its live entry, whose output goes out at the next flush
222
- this.outbox = []; // messages for the next POST /events
223
- this.sending = false;
224
- this.needSnapshot = true;
225
- this.sinceSnapshot = 0;
226
- this.lastStatus = '';
227
- this.lastStatusAt = 0;
228
- this.flushTimer = null;
229
- this.streamAbort = null;
230
199
  this.registered = false;
231
200
  this.refused = null; // the status (401/403) of the gateway refusing the key after the start: the connection ended
232
201
  this.seenPeer = new Set(); // ids of the messages from other sessions already handled (the gateway sends again what was not acknowledged)
233
- this.replying = new Set(); // answers to the page's commands on their way (close() waits for them)
202
+ this.lastStatus = '';
203
+ this.statusEpoch = 0;
204
+ this.statusSending = false;
205
+ this.statusTimer = null;
206
+ this.streamAbort = null;
234
207
  }
235
208
 
236
- // The commands this session takes, as declared to the gateway.
237
- get commands() { return Object.keys(COMMANDS).filter((type) => typeof this.handlers[COMMANDS[type]] === 'function'); }
238
-
239
- get viewing() { return this.viewers !== 0; } // nobody watching: events are not uploaded (a snapshot follows when someone comes)
240
-
241
209
  // `persistent`: keep trying when the gateway cannot be reached now (a restart); otherwise the first failure is thrown.
242
210
  async start({ persistent = false } = {}) {
243
211
  try {
@@ -262,27 +230,26 @@ export class RemoteControl {
262
230
  signal: AbortSignal.timeout(timeout),
263
231
  });
264
232
  let res;
265
- // Once more when the connection failed before any answer (a kept-alive socket the server had just closed):
266
- // 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).
267
234
  try { res = await send(); } catch (e) { if (!retry || e.name === 'TimeoutError' || this.closed) throw e; res = await send(); }
268
235
  const data = await res.json().catch(() => ({}));
269
236
  if (!res.ok) {
270
237
  const message = data?.error?.message || (typeof data?.error === 'string' ? data.error : `HTTP ${res.status}`);
271
- throw Object.assign(new Error(res.status === 404 && route === '/v1/remote/sessions' ? `the gateway ${this.base} does not offer remote control (yet)` : String(message)), { status: res.status });
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 });
272
239
  }
273
240
  return data;
274
241
  }
275
242
 
276
243
  async register() {
277
244
  const info = this.handlers.info?.() || {};
278
- const commands = this.commands;
279
- const data = await this.request('POST', '/v1/remote/sessions', { id: this.id, host: os.hostname(), version: info.version, ...info, ...(commands.length ? { commands } : {}) });
245
+ const data = await this.request('POST', '/v1/remote/sessions', { id: this.id, host: os.hostname(), ...info });
280
246
  if (data.id) this.id = data.id;
281
247
  this.registered = true;
282
- this.needSnapshot = true;
248
+ this.lastStatus = '';
249
+ this.statusEpoch++;
283
250
  }
284
251
 
285
- // The command stream, kept open (and opened again) until close(): while it is open the session is online.
252
+ // The stream, kept open (and opened again) until close(): while it is open the session is online.
286
253
  async loop() {
287
254
  let wait = 1000;
288
255
  while (!this.closed) {
@@ -290,8 +257,8 @@ export class RemoteControl {
290
257
  try {
291
258
  if (!this.registered) {
292
259
  await this.register();
293
- // closed while it registered (/disconnect, another account): the session that ended must not go online again,
294
- // and the registration that just went through gets the bye that close() could not send yet
260
+ // closed while it registered (/disconnect, another account): the registration that just went through gets
261
+ // the bye that close() could not send yet
295
262
  if (this.closed) {
296
263
  this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/events`, { messages: [{ t: 'bye', restarting: false }] }, { timeout: 1500 }).catch(() => {});
297
264
  break;
@@ -304,9 +271,6 @@ export class RemoteControl {
304
271
  }
305
272
  if (this.online) {
306
273
  this.online = false;
307
- // Nothing is uploaded while offline (see flush), and the stream's next opening sends a snapshot.
308
- this.needSnapshot = true;
309
- this.events = [];
310
274
  this.handlers.changed?.();
311
275
  }
312
276
  if (this.closed) break;
@@ -325,7 +289,6 @@ export class RemoteControl {
325
289
  this.closed = true;
326
290
  this.registered = false; // no bye with a key the gateway refuses
327
291
  this.online = false;
328
- clearTimeout(this.flushTimer);
329
292
  clearInterval(this.statusTimer);
330
293
  this.streamAbort?.abort();
331
294
  try { this.handlers.refused?.(status); } catch { /* the App's problem */ }
@@ -345,9 +308,10 @@ export class RemoteControl {
345
308
  throw Object.assign(new Error(`HTTP ${res.status}`), { status: res.status });
346
309
  }
347
310
  this.online = true;
348
- this.needSnapshot = true; // the gateway may have been restarted: it gets the whole conversation again
311
+ this.lastStatus = ''; // the gateway may have been restarted: it gets the status again
312
+ this.statusEpoch++;
349
313
  this.handlers.changed?.();
350
- this.scheduleFlush(0);
314
+ this.flush();
351
315
  let last = Date.now();
352
316
  const watchdog = setInterval(() => { if (Date.now() - last > STREAM_SILENCE_MS) abort.abort(); }, 5000);
353
317
  watchdog.unref?.();
@@ -363,9 +327,9 @@ export class RemoteControl {
363
327
  buf = buf.slice(i).replace(/^\r?\n\r?\n/, '');
364
328
  const data = block.split(/\r?\n/).filter((l) => l.startsWith('data:')).map((l) => l.slice(5).replace(/^ /, '')).join('\n');
365
329
  if (!data) continue;
366
- let cmd;
367
- try { cmd = JSON.parse(data); } catch { continue; }
368
- this.command(cmd);
330
+ let frame;
331
+ try { frame = JSON.parse(data); } catch { continue; }
332
+ this.frame(frame);
369
333
  }
370
334
  }
371
335
  } catch (e) {
@@ -375,74 +339,59 @@ export class RemoteControl {
375
339
  }
376
340
  }
377
341
 
378
- command(cmd) {
379
- if (this.closed) return; // the page of a session that has gone offline steers nothing
380
- if (cmd.type === 'viewers') {
381
- const was = this.viewers;
382
- this.viewers = Math.max(0, Number(cmd.count) || 0);
383
- if (!was && this.viewers) this.needSnapshot = true; // someone came: what they see starts from now
384
- this.handlers.changed?.();
385
- this.scheduleFlush(0);
386
- return;
387
- }
388
- if (cmd.type === 'snapshot') { this.needSnapshot = true; this.scheduleFlush(0); return; }
389
- if (!cmd.cid) return;
390
- if (cmd.type === 'peer') { this.peerMessage(cmd); return; }
391
- // A command of the page, answered with POST …/results {cid, ok: true, …fields} or {cid, ok: false, error} (the
392
- // gateway waits 15 s for it, and takes it until 3 s after the stream closed). close() waits for the answers on
393
- // their way: a /cd from the page restarts the session from inside its command.
394
- const reply = (result) => {
395
- const sent = this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/results`, result).catch(() => { /* the page times out */ });
396
- this.replying.add(sent);
397
- sent.finally(() => this.replying.delete(sent));
398
- this.scheduleFlush(30); // what the command changed, on the page soon
399
- };
400
- const failed = (e) => reply({ cid: cmd.cid, ok: false, error: e?.message || String(e) });
401
- const handler = Object.hasOwn(COMMANDS, cmd.type) ? this.handlers[COMMANDS[cmd.type]] : null;
402
- if (typeof handler !== 'function') {
403
- // an older gateway forwards every command, declared or not
404
- 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).'));
405
- return;
406
- }
407
- let r;
408
- try {
409
- r = handler(cmd.body && typeof cmd.body === 'object' && !Array.isArray(cmd.body) ? cmd.body : {});
410
- } catch (e) {
411
- failed(e);
412
- return;
413
- }
414
- // an answer that takes a while (the gateway's list of models, a directory) is sent when it is there
415
- if (typeof r?.then === 'function') r.then((v) => reply({ ...(v || {}), cid: cmd.cid, ok: true }), failed);
416
- else reply({ ...(r || {}), cid: cmd.cid, ok: true });
342
+ frame(frame) {
343
+ if (this.closed) return;
344
+ // 通讯录: someone asked this account to be a contact, or accepted its request
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)
417
348
  }
418
349
 
419
- // ------------------------------------------------------------ messages of the account's other sessions
350
+ // ------------------------------------------------------------ messages of other sessions
420
351
 
421
352
  // A message from a session on another computer: handed to the App once, then acknowledged, so that the gateway
422
353
  // drops it from the session's mailbox (it sends what was not acknowledged again when the stream reconnects).
423
354
  peerMessage(cmd) {
424
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; }
425
357
  try {
426
- if (this.seenPeer.has(cmd.cid)) { ack(); return; }
427
- this.seenPeer.add(cmd.cid);
428
- if (this.seenPeer.size > 500) this.seenPeer.delete(this.seenPeer.values().next().value);
429
358
  const f = cmd.from || {};
430
359
  const machine = f.machine || f.host || 'computer';
431
- this.handlers.peerMessage?.({
360
+ // a contact's session (another person's account): its 通讯号 and how this account takes its tasks
361
+ const account = typeof f.account === 'string' && f.account ? f.account : null;
362
+ const accepted = this.handlers.peerMessage?.({
432
363
  id: cmd.cid,
433
364
  kind: cmd.kind === 'reply' ? 'reply' : 'task',
434
365
  text: String(cmd.text ?? ''),
435
366
  inReplyTo: cmd.inReplyTo || null,
436
- from: { id: f.id, name: `${machine}/${f.name || 'session'}`, cwd: f.cwd || '', machine, remote: true },
367
+ from: {
368
+ id: f.id, name: `${account ? `${account}:` : ''}${machine}/${f.name || 'session'}`, cwd: account ? '' : (f.cwd || ''), machine, remote: true,
369
+ ...(account ? { account, trust: f.trust === 'auto' ? 'auto' : 'confirm' } : {}),
370
+ },
437
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
+ }
438
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);
439
380
  ack();
440
381
  }
441
382
 
442
- // The sessions of this gateway account, on every computer, as the gateway lists them (this one included).
383
+ // The sessions of this gateway account, on every computer, as the gateway lists them (this one included), and
384
+ // the online sessions of the account's contacts (each with `account`, the contact's 通讯号).
443
385
  async sessions() {
444
386
  const data = await this.request('GET', '/v1/remote/sessions');
445
- return Array.isArray(data?.data) ? data.data : [];
387
+ return { own: Array.isArray(data?.data) ? data.data : [], contacts: Array.isArray(data?.contacts) ? data.contacts : [] };
388
+ }
389
+
390
+ // 通讯录 at the gateway: no action lists them ({handle, contacts: [{handle, status, trust, online}]}); handle,
391
+ // add, accept, reject, remove, block, trust act ({handle[, trust]}) and answer with the list as it is then.
392
+ async contacts(action = '', body = {}) {
393
+ if (!action) return await this.request('GET', '/v1/remote/contacts');
394
+ return await this.request('POST', `/v1/remote/contacts/${action}`, body, { retry: false });
446
395
  }
447
396
 
448
397
  // A message to another session of the account: resolves with {id} (the message's id, which a reply names).
@@ -453,151 +402,49 @@ export class RemoteControl {
453
402
  return { id: data.id, delivered: data.delivered !== false };
454
403
  }
455
404
 
456
- // ------------------------------------------------------------ events
457
-
458
- emit(ev) {
459
- ev.seq = ++this.seq;
460
- applyEvent(this.state, ev);
461
- if (this.state.items.length > MAX_ITEMS) this.state.items.splice(0, this.state.items.length - MAX_ITEMS + 100);
462
- if (ev.t === 'done') this.progress.delete(ev.id); // also while offline, when nothing takes it: it holds all the tool's output
463
- if (this.viewing && !this.needSnapshot) {
464
- // 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
465
- // few seconds of a long reply, since SNAPSHOT_EVERY counts events. The page takes the newest seq of the merged
466
- // ones; it only skips events at or below the seq it has.
467
- const last = this.events[this.events.length - 1];
468
- if (ev.t === 'delta' && last?.t === 'delta' && last.kind === ev.kind) { last.text += ev.text; last.seq = ev.seq; }
469
- else this.events.push(ev);
470
- this.scheduleFlush();
471
- }
472
- }
473
-
474
- // Lines the terminal printed that no other event stands for (command output, notices, errors).
475
- output(lines) {
476
- const last = this.state.items[this.state.items.length - 1];
477
- if (!lines.length || (last?.k !== 'output' && lines.every((l) => !stripAnsi(l).trim()))) return;
478
- this.emit({ t: 'output', lines });
479
- }
480
-
481
- toolProgress(id, entry) {
482
- if (!id) return;
483
- this.progress.set(id, entry);
484
- if (this.viewing) this.scheduleFlush();
485
- }
486
-
487
- // The conversation was replaced (/clear, /resume, /rewind): the pages start again from it.
488
- resync() {
489
- this.progress.clear();
490
- this.events = [];
491
- this.state = hydrate(this.handlers.seed?.() || []);
492
- this.seq++;
493
- this.needSnapshot = true;
494
- this.scheduleFlush(0);
495
- }
496
-
497
- scheduleFlush(ms = FLUSH_MS) {
498
- if (this.closed) return;
499
- if (this.flushTimer && ms > 0) return;
500
- clearTimeout(this.flushTimer);
501
- this.flushTimer = setTimeout(() => { this.flushTimer = null; this.flush(); }, ms);
502
- }
503
-
504
- takeProgress() {
505
- for (const [id, entry] of this.progress) {
506
- const ev = { t: 'progress', id, text: progressTail(entry.progress), seq: ++this.seq };
507
- if (applyEvent(this.state, ev) && this.viewing && !this.needSnapshot) this.events.push(ev);
508
- }
509
- this.progress.clear();
510
- }
405
+ // ------------------------------------------------------------ status
511
406
 
407
+ // What the other sessions are shown of this one, sent when it changed (and again after the stream reopened).
512
408
  status() {
513
- try { return this.handlers.status?.() || {}; } catch (e) { return { error: e.message }; }
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 };
514
413
  }
515
414
 
516
- // What decides whether the status is sent again: all of it while a page watches; while none does, only what
517
- // the gateway's session list shows (the token count of a busy session would otherwise go out every few seconds).
518
- // `asking` (a question waits) is in it too: the gateway tells the user about it even with no page open.
519
- statusKey(status) {
520
- if (this.viewing) return JSON.stringify({ ...status, elapsed: 0 });
521
- const { busy, asking, title, model, cwd, name } = status;
522
- return JSON.stringify({ busy, asking, title, model, cwd, name });
523
- }
524
-
525
- // What is sent at once, without the wait between statuses of an unwatched session: a task that started or ended,
526
- // a question that came or was answered.
527
- urgentKey(status) { return `${Boolean(status.busy)}|${Boolean(status.asking)}`; }
528
-
529
- // What has changed goes into the next upload: a snapshot when one is due, else the events; and the status.
530
- // Not while the command stream is down: every upload would fail and leave a snapshot due, so a session used to
531
- // build and POST (twice) a snapshot of up to 1.5 MB every 500 ms for as long as the gateway was unreachable.
532
- flush() {
533
- if (this.closed || !this.registered || (!this.online && !this.closing)) return;
534
- this.takeProgress();
415
+ async flush() {
416
+ if (this.closed || !this.registered || !this.online || this.statusSending) return;
535
417
  const status = this.status();
536
- if (this.needSnapshot || this.sinceSnapshot > SNAPSHOT_EVERY) {
537
- this.needSnapshot = false;
538
- this.events = [];
539
- this.sinceSnapshot = 0;
540
- this.lastStatus = this.statusKey(status);
541
- this.lastUrgent = this.urgentKey(status);
542
- this.lastStatusAt = Date.now();
543
- this.outbox.push({ t: 'snapshot', seq: this.seq, items: snapshotItems(this.state.items), status });
544
- } else if (this.events.length) {
545
- this.sinceSnapshot += this.events.length;
546
- this.outbox.push({ t: 'batch', events: this.events });
547
- this.events = [];
548
- }
549
- const key = this.statusKey(status);
550
- const urgent = this.urgentKey(status);
551
- if (key !== this.lastStatus && (urgent !== this.lastUrgent || Date.now() - this.lastStatusAt >= (this.viewing ? 0 : IDLE_STATUS_MS))) {
552
- this.lastStatus = key;
553
- this.lastUrgent = urgent;
554
- this.lastStatusAt = Date.now();
555
- this.outbox.push({ t: 'status', status });
556
- }
557
- this.pump();
558
- }
559
-
560
- // One POST at a time, so that the gateway gets the messages in order. A failed one is not sent again: the
561
- // next upload is a snapshot, which stands for everything that was lost.
562
- async pump() {
563
- if (this.sending || this.closing || !this.outbox.length) return;
564
- this.sending = true;
565
- 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
566
422
  try {
567
- 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;
568
425
  } catch (e) {
569
- this.needSnapshot = true;
570
- this.events = [];
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
571
428
  if (e.status === 404) { this.registered = false; this.streamAbort?.abort(); }
572
429
  if (e.status === 401 || e.status === 403) this.refuse(e.status);
573
430
  } finally {
574
- this.sending = false;
431
+ this.statusSending = false;
575
432
  }
576
- if (this.outbox.length) this.pump();
577
433
  }
578
434
 
579
435
  // Ends the connection; resolves once the gateway was told (or gave up waiting). `restarting`: the session comes
580
- // back at once with the same id, and the pages wait for it.
436
+ // back at once with the same id.
581
437
  close({ restarting = false } = {}) {
582
438
  this.closeDone ??= this.shutdown(restarting);
583
439
  return this.closeDone;
584
440
  }
585
441
 
586
442
  async shutdown(restarting) {
587
- // First the answers on their way, while the command stream is still open (the gateway takes them until 3 s
588
- // after it closes). Among them the answer to the command that restarts the session: a /cd from the page closes
589
- // it from inside that command (the page may not end, restart or update it otherwise, see App.remoteSend), and its answer
590
- // is sent when the command returns, hence the wait for the current call to finish first.
591
443
  await null;
592
- if (this.replying.size) await Promise.race([Promise.allSettled([...this.replying]), new Promise((r) => setTimeout(r, 1500).unref?.())]);
593
- this.closing = true; // what flush() collects now goes out with the last message, not on its own
594
- this.flush();
595
444
  this.closed = true;
596
- clearTimeout(this.flushTimer);
597
445
  clearInterval(this.statusTimer);
598
446
  this.streamAbort?.abort();
599
447
  if (!this.registered) return;
600
- const messages = [...this.outbox.splice(0), { t: 'bye', restarting }];
601
- 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(() => {});
602
449
  }
603
450
  }
package/src/runtime.js CHANGED
@@ -13,25 +13,21 @@ import { isAbort } from './api.js';
13
13
  import { McpManager } from './mcp.js';
14
14
  import { HookRunner } from './hooks.js';
15
15
  import { BackgroundTasks, taskNotification } from './tasks.js';
16
- import { autoMemoryDir, sweepOldData, projectDir } from './session.js';
16
+ import { autoMemoryDir, claimSession, sweepOldData, projectDir } from './session.js';
17
17
  import { loadAutoMemoryIndex, takeEnvSnapshot, takeEnvSnapshotAsync, localDate } from './context.js';
18
18
  import { canRestart } from './restart.js';
19
19
  import { RuntimeTrace } from './trace.js';
20
20
 
21
21
  export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
22
22
  const config = loadConfig({ cwd, flags });
23
+ // Whose background shells, interpreters and browser tabs are whose (tools/bash.js, code.js, browser.js): the web
24
+ // console runs several sessions in one process.
25
+ config.owner = crypto.randomUUID();
23
26
  const trace = new RuntimeTrace({ cwd, sessionId, enabled: config.traceEnabled });
24
27
  applyRememberedChoices(config, flags); // what /model and /effort chose last time
28
+ if (flags.initialChoices && 'model' in flags.initialChoices) config.modelOverride = flags.initialChoices.model;
29
+ if (flags.initialChoices && 'effort' in flags.initialChoices) config.effortOverride = flags.initialChoices.effort;
25
30
  if (flags.verify) config.verifyOverride = flags.verify;
26
- // Old conversations and what goes with them, in the background a while after the start (not in the self-check's
27
- // throwaway process, nor a test's: CLAUDE_PRO_CONFIG_DIR points elsewhere then anyway)
28
- if (process.env.CLAUDE_PRO_SELF_CHECK !== '1') {
29
- setTimeout(() => {
30
- sweepOldData({ days: config.setting('cleanupPeriodDays'), keep: [sessionId, config.sessionId] })
31
- .then((done) => { if (done.files) trace.append('cleanup', { conversations: done.conversations, files: done.files, bytes: done.bytes }); })
32
- .catch(() => {});
33
- }, 15_000).unref();
34
- }
35
31
  pruneStaleShellFiles();
36
32
  // Full access: nothing is ever asked.
37
33
  const checkpoints = new CheckpointStore(path.join(projectDir(cwd), 'checkpoints', `${Date.now()}-${crypto.randomBytes(3).toString('hex')}`));
@@ -47,7 +43,7 @@ export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
47
43
  const runtime = { config, checkpoints, agents, mcp, shell, io, cwd, hooks, tasks, memoryDir, trace };
48
44
  runtime.skills = loadSkills(cwd);
49
45
  // The self-check builds the Restart tool too, so that a mistake in it is found before a restart relies on it.
50
- const restartable = canRestart() || process.env.CLAUDE_PRO_SELF_CHECK === '1';
46
+ const restartable = (io?.canRestart ? io.canRestart() : canRestart()) || process.env.CLAUDE_PRO_SELF_CHECK === '1';
51
47
  // The agent fixes its own code (and restarts for it) only in a source checkout: an installed copy is replaced by
52
48
  // the next update, so there it reports its defects instead.
53
49
  const selfEdit = restartable && SOURCE_CHECKOUT;
@@ -202,5 +198,34 @@ export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
202
198
  runtime.agent.notifications.push({ taskId: task.id, text: taskNotification(task) });
203
199
  io.backgroundTaskDone?.(task);
204
200
  });
201
+
202
+ // A /resume must claim the new id before it reads the old transcript. If loading fails, keep the previous claim.
203
+ let ownedId, release;
204
+ runtime.useSession = (id, load = () => {}) => {
205
+ if (!id || id === ownedId) return load();
206
+ const next = claimSession(id);
207
+ let value;
208
+ try { value = load(); } catch (e) { next(); throw e; }
209
+ release?.();
210
+ ownedId = id;
211
+ release = next;
212
+ return value;
213
+ };
214
+ runtime.releaseSession = () => { release?.(); ownedId = release = undefined; };
215
+ // The REPL switches via useSession; print mode can only resume the id given at startup.
216
+ try { runtime.useSession(!io?.store && flags.resumeFile ? (flags.resumeId || sessionId) : sessionId); }
217
+ catch (e) { mcp.close(); throw e; }
218
+
219
+ if (process.env.CLAUDE_PRO_SELF_CHECK !== '1') {
220
+ setTimeout(() => {
221
+ if (io?.exiting) return;
222
+ // Read live state at the deletion point, also covering local Apps still in startup.
223
+ const isOwned = (id) => id === config.sessionId || id === io?.store?.id || [...(io?.host?.apps || [])].some((app) =>
224
+ !app.exiting && (id === app.store?.id || (!app.runtime && (id === app.flags?.resumeId || id === app.flags?.restart?.sessionId))));
225
+ sweepOldData({ days: config.setting('cleanupPeriodDays'), isOwned })
226
+ .then((done) => { if (done.files) trace.append('cleanup', { conversations: done.conversations, files: done.files, bytes: done.bytes }); })
227
+ .catch(() => {});
228
+ }, 15_000).unref();
229
+ }
205
230
  return runtime;
206
231
  }
package/src/selfcheck.js CHANGED
@@ -10,14 +10,14 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
10
10
  async function check() {
11
11
  const problems = [];
12
12
  const fail = (text) => problems.push(text);
13
- // The App starts as a session does (the fullscreen renderer, ...), so that code only a real start runs is checked
13
+ // The App starts as a session does, so that code only a real start runs is checked
14
14
  // too, but this process must not show up as a session or go online.
15
15
  Object.assign(process.env, { CLAUDE_PRO_PEERS: '0', CLAUDE_PRO_ONLINE: '0' });
16
16
 
17
17
  let App;
18
18
  try {
19
19
  ({ App } = await import('./ui/repl.js'));
20
- for (const file of ['./main.js', './print.js', './restart.js', './supervisor.js']) await import(file);
20
+ for (const file of ['./main.js', './print.js', './restart.js', './supervisor.js', './web/server.js', './web/api.js', './web/host.js']) await import(file);
21
21
  } catch (e) {
22
22
  return [`A module does not load: ${e?.stack || e}`];
23
23
  }
@@ -34,7 +34,7 @@ async function check() {
34
34
  exited = app.start('');
35
35
  exited.catch((e) => fail(`Starting failed: ${e?.stack || e}`));
36
36
  const began = Date.now();
37
- while (!(screen.includes('Welcome to') && screen.includes('for shortcuts'))) {
37
+ while (!(screen.includes('Welcome to') && (screen.includes('explain this codebase') || screen.includes('Enter to confirm')))) {
38
38
  if (problems.length) return problems;
39
39
  if (Date.now() - began > STARTUP_LIMIT_MS) return [`The interface did not come up within ${STARTUP_LIMIT_MS / 1000} seconds.\n${screen.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').slice(-800)}`];
40
40
  await sleep(25);