@yanzc/claude-pro 0.11.0 → 0.13.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,22 @@
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';
11
+ import { c } from './ui/ansi.js';
17
12
  import { shownQuotes } from './ui/editor.js';
18
13
 
19
14
  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
15
  const SEED_ITEMS = 500;
22
16
  const SNAPSHOT_ITEMS = 400; // sent in a snapshot
23
17
  const SNAPSHOT_BYTES = 1_500_000; // ... at most: the gateway takes 2 MB a POST
24
18
  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
19
  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
20
  const REQUEST_TIMEOUT_MS = 15_000;
30
21
  const STREAM_SILENCE_MS = 50_000; // the gateway pings every 15 s: a command stream silent this long is dead
31
22
 
@@ -38,6 +29,7 @@ export function applyEvent(state, ev) {
38
29
  const push = (item) => { items.push(item); return item; };
39
30
  switch (ev.t) {
40
31
  case 'user': return push({ k: 'user', text: ev.text });
32
+ case 'image': return push({ k: 'image', n: ev.n }); // (the local web console's: the gateway's page is not sent these)
41
33
  case 'output': {
42
34
  const last = items[items.length - 1];
43
35
  if (last && last.k === 'output') { last.lines.push(...ev.lines); return last; }
@@ -110,11 +102,20 @@ function shownUserText(text) {
110
102
  }
111
103
 
112
104
  // 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 } = {}) {
105
+ // `limit`: the newest items kept (the web console's history view takes them all); `images`: an image is {k: 'image', n}
106
+ // (the n-th image of the conversation) instead of the text [image]; `turns`: the lines shown where turns ended
107
+ // ([{after, text}], see SessionStore.turnEnd), each put back after its message as the terminal printed it.
108
+ export function transcriptItems(messages, { tools = [], ctx, cwd, width = REMOTE_WIDTH, limit = SEED_ITEMS, images = false, turns = [] } = {}) {
109
+ let imageCount = 0;
114
110
  const toolMap = new Map(tools.map((t) => [t.name, t]));
115
111
  const items = [];
116
112
  const calls = new Map();
117
- for (const m of messages || []) {
113
+ const ends = new Map();
114
+ for (const t of turns || []) if (t?.text && Number.isInteger(t.after)) ends.set(t.after, [...(ends.get(t.after) || []), t.text]);
115
+ const list = messages || [];
116
+ for (let i = 0; i < list.length; i++) {
117
+ const m = list[i];
118
+ for (const text of ends.get(i) || []) items.push({ k: 'output', lines: [c.dim(text), ''] }); // (after the first i messages)
118
119
  const blocks = typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : (m.content || []);
119
120
  for (const b of blocks) {
120
121
  if (m.role === 'user') {
@@ -126,7 +127,7 @@ export function transcriptItems(messages, { tools = [], ctx, cwd, width = REMOTE
126
127
  const text = raw.startsWith('<system-reminder>') ? '' : shownUserText(raw);
127
128
  if (text) items.push({ k: 'user', text });
128
129
  } else if (b.type === 'image') {
129
- items.push({ k: 'user', text: '[image]' });
130
+ items.push(images ? { k: 'image', n: imageCount++ } : { k: 'user', text: '[image]' });
130
131
  } else if (b.type === 'tool_result') {
131
132
  const call = calls.get(b.tool_use_id);
132
133
  if (!call) continue;
@@ -148,7 +149,8 @@ export function transcriptItems(messages, { tools = [], ctx, cwd, width = REMOTE
148
149
  }
149
150
  }
150
151
  }
151
- return items.slice(-SEED_ITEMS);
152
+ for (const text of ends.get(list.length) || []) items.push({ k: 'output', lines: [c.dim(text), ''] });
153
+ return Number.isFinite(limit) ? items.slice(-limit) : items;
152
154
  }
153
155
 
154
156
  // The newest items that fit in a snapshot the gateway takes, as copies (the POST may be serialized later, when
@@ -177,12 +179,6 @@ export function snapshotItems(items, { max = SNAPSHOT_ITEMS, bytes = SNAPSHOT_BY
177
179
  return picked.reverse();
178
180
  }
179
181
 
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
182
  // ---------------------------------------------------------------- the connection to the gateway
187
183
 
188
184
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -193,68 +189,29 @@ export const newRemoteId = () => crypto.randomBytes(9).toString('base64url');
193
189
  // which only the self-check and the tests set).
194
190
  export const onlineEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(env.CLAUDE_PRO_ONLINE || '');
195
191
 
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
-
192
+ // This session at the gateway's session relay: registered while it runs, with a stream kept open on which the tasks
193
+ // of the account's sessions on other computers (and of contacts) and the 通讯录's news arrive, and its status (busy,
194
+ // name, title, directory, model: what the other sessions are shown of it). Nothing of the conversation goes there.
195
+ // (Until 2026-11-21 the transcript went there too, for the gateway's 远程控制 page, which is gone.)
205
196
  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).
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);
197
+ // gateway: {url, apiKey}. handlers: info() -> {name, title, cwd, model, version, machine, peerId}, status() -> object,
198
+ // peerMessage(message) (false defers delivery), contactEvent(event), changed() (online changed), refused(status).
199
+ constructor({ gateway, id, handlers, fetchImpl = globalThis.fetch }) {
214
200
  this.base = String(gateway.url).replace(/\/+$/, '');
215
201
  this.apiKey = gateway.apiKey;
216
202
  this.id = /^[\w-]{8,64}$/.test(id || '') ? id : newRemoteId();
217
203
  this.handlers = handlers;
218
204
  this.fetch = fetchImpl;
219
- this.online = false; // the command stream is open
220
- this.viewers = null; // pages watching, as the gateway counts them (null: not told yet)
205
+ this.online = false; // the stream is open
221
206
  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
207
  this.registered = false;
235
208
  this.refused = null; // the status (401/403) of the gateway refusing the key after the start: the connection ended
236
209
  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
210
  this.lastStatus = '';
256
- if (this.registered) await this.register();
257
- this.scheduleFlush(0);
211
+ this.statusEpoch = 0;
212
+ this.statusSending = false;
213
+ this.statusTimer = null;
214
+ this.streamAbort = null;
258
215
  }
259
216
 
260
217
  // `persistent`: keep trying when the gateway cannot be reached now (a restart); otherwise the first failure is thrown.
@@ -281,28 +238,26 @@ export class RemoteControl {
281
238
  signal: AbortSignal.timeout(timeout),
282
239
  });
283
240
  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).
241
+ // Once more when the connection failed before any answer (a kept-alive socket the server had just closed).
286
242
  try { res = await send(); } catch (e) { if (!retry || e.name === 'TimeoutError' || this.closed) throw e; res = await send(); }
287
243
  const data = await res.json().catch(() => ({}));
288
244
  if (!res.ok) {
289
245
  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} does not offer remote control (yet)` : String(message)), { status: res.status });
246
+ 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
247
  }
292
248
  return data;
293
249
  }
294
250
 
295
251
  async register() {
296
252
  const info = this.handlers.info?.() || {};
297
- const commands = this.commands;
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 } : {}) });
253
+ const data = await this.request('POST', '/v1/remote/sessions', { id: this.id, host: os.hostname(), ...info });
300
254
  if (data.id) this.id = data.id;
301
255
  this.registered = true;
302
- this.needSnapshot = true;
256
+ this.lastStatus = '';
257
+ this.statusEpoch++;
303
258
  }
304
259
 
305
- // The command stream, kept open (and opened again) until close(): while it is open the session is online.
260
+ // The stream, kept open (and opened again) until close(): while it is open the session is online.
306
261
  async loop() {
307
262
  let wait = 1000;
308
263
  while (!this.closed) {
@@ -310,8 +265,8 @@ export class RemoteControl {
310
265
  try {
311
266
  if (!this.registered) {
312
267
  await this.register();
313
- // closed while it registered (/disconnect, another account): the session that ended must not go online again,
314
- // and the registration that just went through gets the bye that close() could not send yet
268
+ // closed while it registered (/disconnect, another account): the registration that just went through gets
269
+ // the bye that close() could not send yet
315
270
  if (this.closed) {
316
271
  this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/events`, { messages: [{ t: 'bye', restarting: false }] }, { timeout: 1500 }).catch(() => {});
317
272
  break;
@@ -324,9 +279,6 @@ export class RemoteControl {
324
279
  }
325
280
  if (this.online) {
326
281
  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
282
  this.handlers.changed?.();
331
283
  }
332
284
  if (this.closed) break;
@@ -345,7 +297,6 @@ export class RemoteControl {
345
297
  this.closed = true;
346
298
  this.registered = false; // no bye with a key the gateway refuses
347
299
  this.online = false;
348
- clearTimeout(this.flushTimer);
349
300
  clearInterval(this.statusTimer);
350
301
  this.streamAbort?.abort();
351
302
  try { this.handlers.refused?.(status); } catch { /* the App's problem */ }
@@ -365,9 +316,10 @@ export class RemoteControl {
365
316
  throw Object.assign(new Error(`HTTP ${res.status}`), { status: res.status });
366
317
  }
367
318
  this.online = true;
368
- this.needSnapshot = true; // the gateway may have been restarted: it gets the whole conversation again
319
+ this.lastStatus = ''; // the gateway may have been restarted: it gets the status again
320
+ this.statusEpoch++;
369
321
  this.handlers.changed?.();
370
- this.scheduleFlush(0);
322
+ this.flush();
371
323
  let last = Date.now();
372
324
  const watchdog = setInterval(() => { if (Date.now() - last > STREAM_SILENCE_MS) abort.abort(); }, 5000);
373
325
  watchdog.unref?.();
@@ -383,9 +335,9 @@ export class RemoteControl {
383
335
  buf = buf.slice(i).replace(/^\r?\n\r?\n/, '');
384
336
  const data = block.split(/\r?\n/).filter((l) => l.startsWith('data:')).map((l) => l.slice(5).replace(/^ /, '')).join('\n');
385
337
  if (!data) continue;
386
- let cmd;
387
- try { cmd = JSON.parse(data); } catch { continue; }
388
- this.command(cmd);
338
+ let frame;
339
+ try { frame = JSON.parse(data); } catch { continue; }
340
+ this.frame(frame);
389
341
  }
390
342
  }
391
343
  } catch (e) {
@@ -395,65 +347,27 @@ export class RemoteControl {
395
347
  }
396
348
  }
397
349
 
398
- command(cmd) {
399
- if (this.closed) return; // the page of a session that has gone offline steers nothing
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; }
350
+ frame(frame) {
351
+ if (this.closed) return;
409
352
  // 通讯录: someone asked this account to be a contact, or accepted its request
410
- if (cmd.type === 'contact') { try { this.handlers.contactEvent?.(cmd); } catch { /* the App's problem */ } return; }
411
- if (!cmd.cid) return;
412
- if (cmd.type === 'peer') { this.peerMessage(cmd); return; }
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 });
353
+ if (frame.type === 'contact') { try { this.handlers.contactEvent?.(frame); } catch { /* the App's problem */ } return; }
354
+ if (frame.type === 'peer' && frame.cid) this.peerMessage(frame);
355
+ // (anything else, such as an older gateway's page commands, is not this session's any more)
440
356
  }
441
357
 
442
- // ------------------------------------------------------------ messages of the account's other sessions
358
+ // ------------------------------------------------------------ messages of other sessions
443
359
 
444
360
  // A message from a session on another computer: handed to the App once, then acknowledged, so that the gateway
445
361
  // drops it from the session's mailbox (it sends what was not acknowledged again when the stream reconnects).
446
362
  peerMessage(cmd) {
447
363
  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 */ });
364
+ if (this.seenPeer.has(cmd.cid)) { ack(); return; }
448
365
  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
366
  const f = cmd.from || {};
453
367
  const machine = f.machine || f.host || 'computer';
454
368
  // a contact's session (another person's account): its 通讯号 and how this account takes its tasks
455
369
  const account = typeof f.account === 'string' && f.account ? f.account : null;
456
- this.handlers.peerMessage?.({
370
+ const accepted = this.handlers.peerMessage?.({
457
371
  id: cmd.cid,
458
372
  kind: cmd.kind === 'reply' ? 'reply' : 'task',
459
373
  text: String(cmd.text ?? ''),
@@ -463,7 +377,14 @@ export class RemoteControl {
463
377
  ...(account ? { account, trust: f.trust === 'auto' ? 'auto' : 'confirm' } : {}),
464
378
  },
465
379
  });
380
+ if (accepted === false) {
381
+ // A session moving into the console cannot take new work. Leave it in the mailbox for the next stream.
382
+ this.streamAbort?.abort();
383
+ return;
384
+ }
466
385
  } catch { /* the App's problem: the message is acknowledged anyway, or it would come back forever */ }
386
+ this.seenPeer.add(cmd.cid);
387
+ if (this.seenPeer.size > 500) this.seenPeer.delete(this.seenPeer.values().next().value);
467
388
  ack();
468
389
  }
469
390
 
@@ -489,156 +410,49 @@ export class RemoteControl {
489
410
  return { id: data.id, delivered: data.delivered !== false };
490
411
  }
491
412
 
492
- // ------------------------------------------------------------ events
413
+ // ------------------------------------------------------------ status
493
414
 
494
- emit(ev) {
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).
415
+ // What the other sessions are shown of this one, sent when it changed (and again after the stream reopened).
549
416
  status() {
550
- let status;
551
- try { status = this.handlers.status?.() || {}; } catch (e) { status = { error: e.message }; }
552
- if (this.rc) return status;
553
- const { busy, name, model } = status;
554
- return { busy: Boolean(busy), name, model };
417
+ let status = {};
418
+ try { status = this.handlers.status?.() || {}; } catch { /* the basics stay as they were */ }
419
+ const { busy, name, title, cwd, model } = status;
420
+ return { busy: Boolean(busy), name, title, cwd, model };
555
421
  }
556
422
 
557
- // What decides whether the status is sent again: all of it while a page watches; while none does, only what
558
- // the gateway's session list shows (the token count of a busy session would otherwise go out every few seconds).
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();
423
+ async flush() {
424
+ if (this.closed || !this.registered || !this.online || this.statusSending) return;
576
425
  const status = this.status();
577
- if (this.rc && (this.needSnapshot || this.sinceSnapshot > SNAPSHOT_EVERY)) {
578
- this.needSnapshot = false;
579
- this.events = [];
580
- this.sinceSnapshot = 0;
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);
426
+ const key = JSON.stringify(status);
427
+ if (key === this.lastStatus) return;
428
+ const epoch = this.statusEpoch;
429
+ this.statusSending = true; // one POST at a time: an older status must not overtake a newer one
607
430
  try {
608
- await this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/events`, { messages });
431
+ await this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/events`, { messages: [{ t: 'status', status }] });
432
+ if (!this.closed && epoch === this.statusEpoch) this.lastStatus = key;
609
433
  } catch (e) {
610
- this.needSnapshot = true;
611
- this.events = [];
434
+ if (this.closed || epoch !== this.statusEpoch) return;
435
+ this.lastStatus = ''; // the gateway may or may not have received the POST; send the current status again
612
436
  if (e.status === 404) { this.registered = false; this.streamAbort?.abort(); }
613
437
  if (e.status === 401 || e.status === 403) this.refuse(e.status);
614
438
  } finally {
615
- this.sending = false;
439
+ this.statusSending = false;
616
440
  }
617
- if (this.outbox.length) this.pump();
618
441
  }
619
442
 
620
443
  // 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, and the pages wait for it.
444
+ // back at once with the same id.
622
445
  close({ restarting = false } = {}) {
623
446
  this.closeDone ??= this.shutdown(restarting);
624
447
  return this.closeDone;
625
448
  }
626
449
 
627
450
  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
451
  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
452
  this.closed = true;
637
- clearTimeout(this.flushTimer);
638
453
  clearInterval(this.statusTimer);
639
454
  this.streamAbort?.abort();
640
455
  if (!this.registered) return;
641
- const messages = [...this.outbox.splice(0), { t: 'bye', restarting }];
642
- await this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/events`, { messages }, { timeout: 1500 }).catch(() => {});
456
+ await this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/events`, { messages: [{ t: 'bye', restarting }] }, { timeout: 1500 }).catch(() => {});
643
457
  }
644
458
  }
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);