@yanzc/claude-pro 0.6.0 → 0.7.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/ui/repl.js CHANGED
@@ -6,21 +6,21 @@ import path from 'node:path';
6
6
  import os from 'node:os';
7
7
  import readline from 'node:readline';
8
8
  import { spawn } from 'node:child_process';
9
- import { c, ESC, stringWidth, truncate, padEnd, wordWrap } from './ansi.js';
9
+ import { c, ESC, stringWidth, truncate, padEnd, wordWrap, stripAnsi } from './ansi.js';
10
10
  import { Screen, queryCursorRow, mouseFilter } from './screen.js';
11
11
  import { Editor, topBorder } from './editor.js';
12
12
  import { SelectDialog } from './dialogs.js';
13
13
  import { MarkdownStream, renderMarkdown } from './markdown.js';
14
14
  import {
15
- DOT, toolHeader, renderToolResult, renderTodos, renderUserMessage, resultLines, formatTokens, formatDuration, toolLabel,
15
+ DOT, toolHeader, renderToolResult, renderTodos, renderUserMessage, resultLines, formatTokens, formatDuration, toolLabel, bashModeLines,
16
16
  } from './render.js';
17
17
  import { createRuntime } from '../runtime.js';
18
- import { SessionStore, firstUserText } from '../session.js';
18
+ import { SessionStore, firstUserText, moveSession } from '../session.js';
19
19
  import { defaultEffort, effortSupported, effortToSend, quickQuery } from '../api.js';
20
20
  import { CONFIG_DIR, VERSION, APP_NAME, INSTALL_DIR } from '../config.js';
21
21
  import { readGatewayLogin, normalizeGatewayUrl, formatUsd } from '../gateway.js';
22
22
  import { TOPIC_TITLE_SYSTEM, topicTitlePrompt } from '../prompts.js';
23
- import { buildCommands } from '../commands.js';
23
+ import { buildCommands, modelChoices, effortChoices } from '../commands.js';
24
24
  import { canRestart, writeRestartState, runSelfCheck, watchSource, restartNote, RESTART_EXIT_CODE, MAX_RESTARTS, RESTART_WINDOW_MS } from '../restart.js';
25
25
  import { resolvePath, displayPath } from '../utils/paths.js';
26
26
  import { ripgrepPath } from '../utils/shell.js';
@@ -28,13 +28,14 @@ import { describePause, formatClock, humanDuration, resumeText, shouldAnnounce }
28
28
  import { shutdownBackgroundShells, listBackgroundShells } from '../tools/bash.js';
29
29
  import { estimateTokens } from '../agent.js';
30
30
  import { readClipboardImage, imageFromFile, watchClipboard, writeClipboard, readClipboardText } from '../utils/clipboard.js';
31
- import { fitImagesIn } from '../utils/images.js';
31
+ import { fitImagesIn, imageSize } from '../utils/images.js';
32
32
  import { downloadsDir, filesToSend, formatBytes } from '../utils/downloads.js';
33
33
  import { copyUnique } from '../transfer.js';
34
34
  import { checkForUpdate, installUpdate, installedVersion, installedByNpm, isNewer, CHECK_EVERY_MS } from '../updater.js';
35
35
  import { PeerNode, peersEnabled, findPeer, resolvePeer, machineName, cleanName, peerMessagePrompt } from '../peers.js';
36
36
  import { RemoteControl, transcriptItems, onlineEnabled, REMOTE_WIDTH } from '../remote.js';
37
- import { ensureHost as startHostIfNeeded, hostEnabled } from '../host.js';
37
+ import { ensureHost as startHostIfNeeded, ensureAutostart, hostEnabled, listDirectory, recentDirectories, computerId, markBackgroundEnded } from '../host.js';
38
+ import { VirtualTerminal } from './vterm.js';
38
39
 
39
40
  // A model id as people say it: claude-sonnet-5-5 -> sonnet-5-5, claude-haiku-4-5-20251001 -> haiku-4-5.
40
41
  export const modelTag = (model) => String(model?.id ?? '').replace(/^claude-/, '').replace(/-\d{8}$/, '');
@@ -67,8 +68,33 @@ export function parseTopicTitle(answer, { required = false } = {}) {
67
68
 
68
69
  const imageBlock = (img) => ({ type: 'image', source: { type: 'base64', media_type: img.media_type, data: img.data } });
69
70
 
71
+ // The images the remote page sends with a message ({media_type, data: base64}), checked as the API would: at most
72
+ // REMOTE_MAX_IMAGES, each a PNG, JPEG, GIF or WebP of at most 5 MB. Throws what to tell the page.
73
+ const REMOTE_IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
74
+ const REMOTE_MAX_IMAGES = 6;
75
+ const REMOTE_MAX_IMAGE_BYTES = 5 * 1024 * 1024;
76
+ export function remoteImages(images) {
77
+ if (images == null) return [];
78
+ if (!Array.isArray(images)) throw new Error('images must be a list.');
79
+ if (images.length > REMOTE_MAX_IMAGES) throw new Error(`At most ${REMOTE_MAX_IMAGES} images can be sent at a time (this message has ${images.length}).`);
80
+ return images.map((img, i) => {
81
+ const n = images.length > 1 ? `Image ${i + 1}` : 'The image';
82
+ const type = String(img?.media_type || '').toLowerCase();
83
+ if (!REMOTE_IMAGE_TYPES.includes(type)) throw new Error(`${n} is ${type || 'of no type'}: only PNG, JPEG, GIF and WebP images can be sent.`);
84
+ const data = typeof img.data === 'string' ? img.data.replace(/^data:[^,]*,/, '').replace(/\s+/g, '') : '';
85
+ if (!data || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) throw new Error(`${n} is not base64 data.`);
86
+ const buf = Buffer.from(data, 'base64');
87
+ if (buf.length > REMOTE_MAX_IMAGE_BYTES) throw new Error(`${n} is ${(buf.length / 1024 / 1024).toFixed(1)} MB: at most 5 MB.`);
88
+ if (!imageSize(buf)) throw new Error(`${n} is not a readable ${type.slice(6).toUpperCase()} image.`);
89
+ return { media_type: type, data };
90
+ });
91
+ }
92
+
70
93
  const FOCUS_EVENTS_ON = '\x1b[?1004h';
71
94
  const FOCUS_EVENTS_OFF = '\x1b[?1004l';
95
+ // What a terminal that attaches to a background session is put in first (see attachClient): the fullscreen
96
+ // renderer's alternate screen and mouse reports (screen.js), cleared.
97
+ const ATTACH_MODES = '\x1b[?1049h\x1b[?1002h\x1b[?1006h\x1b[2J';
72
98
 
73
99
  const SPINNER = ['·', '✢', '✳', '✶', '✻', '✽', '✽', '✻', '✶', '✳', '✢', '·'];
74
100
  const VERBS = ['Thinking', 'Pondering', 'Crafting', 'Brewing', 'Computing', 'Conjuring', 'Cooking', 'Musing', 'Noodling', 'Percolating', 'Ruminating', 'Synthesizing', 'Working', 'Tinkering', 'Mulling', 'Deliberating', 'Churning', 'Forging', 'Hatching', 'Simmering'];
@@ -146,9 +172,14 @@ export class App {
146
172
  // `noProcessExit`: the tests, which drive the App themselves; it never ends the process, and it has no peers, no
147
173
  // gateway connection, no update checks and the default renderer. `selfCheck` (see selfcheck.js): it never ends the
148
174
  // process either, but otherwise starts as a session does, so that code only a real start runs is checked too.
149
- constructor({ flags, cwd, stdin = process.stdin, stdout = process.stdout, noProcessExit = false, selfCheck = false }) {
175
+ // `vterm` (see vterm.js): a background session (claude-pro --headless): no window, it is used from the web page
176
+ // and from `claude-pro attach`; what it prints goes to its log (process.stdout, a file the computer service gave it).
177
+ constructor({ flags, cwd, stdin = process.stdin, stdout = process.stdout, noProcessExit = false, selfCheck = false, vterm = null }) {
150
178
  this.flags = flags;
151
179
  this.cwd = cwd;
180
+ this.vterm = vterm;
181
+ this.headless = Boolean(vterm);
182
+ if (vterm) { stdin = vterm.input; stdout = vterm.output; }
152
183
  this.stdin = stdin;
153
184
  this.stdout = stdout;
154
185
  this.noProcessExit = noProcessExit || selfCheck;
@@ -188,6 +219,7 @@ export class App {
188
219
  this.remoteDialogs = 0;
189
220
  this.remoteStarting = null;
190
221
  this.remoteRefused = null; // a gateway key the gateway refused: not tried again by itself (a new /login is)
222
+ this.seedOutput = []; // lines the page is shown after the conversation when it starts from it (see resumeAfterRestart)
191
223
  this.selfCheck = selfCheck;
192
224
  this.sessionName = flags?.restart?.peerName || null; // this session's name when the sessions of this computer do not know it (CLAUDE_PRO_PEERS=0)
193
225
  this.customTitle = null; // the conversation's name given with /rename: the title, instead of the topic
@@ -202,8 +234,14 @@ export class App {
202
234
  this.store = new SessionStore(cwd);
203
235
  // What the terminal prints goes to the remote page too, except what it is told about as events.
204
236
  this.screen.onLog = (items) => {
237
+ const lines = () => items.flatMap((i) => (Array.isArray(i) ? i : [i])).flatMap((l) => String(l).split(/\r?\n/));
238
+ // a background session's log: what it printed, as plain text
239
+ if (this.headless) {
240
+ const stamp = new Date().toISOString().slice(11, 19);
241
+ try { process.stdout.write(`${lines().map((l) => `${stamp} ${stripAnsi(l)}`.trimEnd()).join('\n')}\n`); } catch { /* no log */ }
242
+ }
205
243
  if (!this.remote || this.remoteMuted) return;
206
- this.remote.output(items.flatMap((i) => (Array.isArray(i) ? i : [i])).flatMap((l) => String(l).split(/\r?\n/)));
244
+ this.remote.output(lines());
207
245
  };
208
246
  this.editor = new Editor({
209
247
  history: loadHistory(cwd),
@@ -234,7 +272,7 @@ export class App {
234
272
  // there (see screen.js). CLAUDE_PRO_PIN_INPUT=0 (here or in the settings) leaves it right below the output.
235
273
  const pinOff = (v) => /^(0|false|no|off)$/i.test(v || '');
236
274
  if (pinOff(process.env.CLAUDE_PRO_PIN_INPUT)) this.screen.pin = false;
237
- else if (stdin.isTTY && this.stdout.isTTY) this.screen.pinFrom(await queryCursorRow(stdin, this.stdout));
275
+ else if (stdin.isTTY && this.stdout.isTTY && !this.headless) this.screen.pinFrom(await queryCursorRow(stdin, this.stdout));
238
276
  stdin.setEncoding('utf8');
239
277
  this.stdout.write(ESC.bracketedPasteOn);
240
278
  this.watchCopies();
@@ -291,8 +329,9 @@ export class App {
291
329
  }, 120);
292
330
  if (restart) this.continueAfterRestart(restart);
293
331
  else if (initialPrompt?.trim()) this.onSubmit(initialPrompt, initialPrompt);
294
- // Nothing configured yet: the gateway is the default, and its login comes first, as in Claude Code.
295
- else if (this.config.usesGateway && !readGatewayLogin(this.config.gatewayUrl)) {
332
+ // Nothing configured yet: the gateway is the default, and its login comes first, as in Claude Code. (Not in a
333
+ // background session: nobody sits at this computer to log in in its browser.)
334
+ else if (this.config.usesGateway && !readGatewayLogin(this.config.gatewayUrl) && !this.headless) {
296
335
  Promise.resolve(this.commands.get('login').run('')).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
297
336
  }
298
337
  this.fileIndex.refresh();
@@ -404,6 +443,11 @@ export class App {
404
443
  if (!restart && this.agent?.messages.length) this.screen.log(c.dim(`Resume this session with: ${APP_NAME} --resume ${this.store.id}`));
405
444
  this.restoreTerminal({ handOver: restart });
406
445
  this.stdin.pause();
446
+ if (this.headless) {
447
+ // ended for good (/exit, the computer service's stop): the service does not open it again
448
+ if (code === 0 && !restart && this.remote?.id) markBackgroundEnded(this.remote.id);
449
+ setTimeout(() => this.vterm.closeAll(), 20).unref?.(); // the last screen first
450
+ }
407
451
  this.resolveExit?.(code);
408
452
  if (!this.noProcessExit) {
409
453
  // with remote control on, the gateway is told first (at most a second and a half; see RemoteControl.close)
@@ -419,13 +463,68 @@ export class App {
419
463
  async startPeer() {
420
464
  if (this.driven || !peersEnabled()) return;
421
465
  try {
422
- this.peers = await new PeerNode({ cwd: this.cwd, name: this.flags.restart?.peerName, id: this.flags.restart?.peerId, onMessage: (msg) => this.onPeerMessage(msg), getStatus: () => ({ busy: this.working() }) }).start();
466
+ this.peers = await new PeerNode({
467
+ cwd: this.cwd,
468
+ name: this.flags.restart?.peerName,
469
+ id: this.flags.restart?.peerId,
470
+ onMessage: (msg) => this.onPeerMessage(msg),
471
+ getStatus: () => ({ busy: this.working() }),
472
+ info: () => ({ kind: this.headless ? 'background' : 'terminal', remoteId: this.remote?.id || this.flags.remoteId || this.flags.restart?.remote?.id || null, conversationId: this.store.id }),
473
+ onControl: (body) => this.onControl(body),
474
+ onAttach: this.headless ? (socket, size) => this.attachClient(socket, size) : null,
475
+ }).start();
423
476
  } catch (e) {
424
477
  this.peers = null;
425
478
  this.notice(`Other sessions cannot reach this one: ${e.message}`, 'warn');
426
479
  }
427
480
  }
428
481
 
482
+ // The computer service (see host.js) about a background session: {action: 'exit'} ends it as /exit does (a turn
483
+ // that runs, or a question that waits, is stopped first), 'restart' restarts it as /restart does, 'interrupt' is
484
+ // Esc.
485
+ onControl({ action } = {}) {
486
+ if (action === 'interrupt') return this.remoteInterrupt();
487
+ if (action === 'exit') {
488
+ for (const d of this.dialogs.splice(0)) d.resolve(d.cancelValue);
489
+ this.interrupt();
490
+ setTimeout(() => this.exit(0), 50); // once the answer is out
491
+ return {};
492
+ }
493
+ if (action === 'restart') {
494
+ for (const d of this.dialogs.splice(0)) d.resolve(d.cancelValue);
495
+ this.interrupt();
496
+ const res = this.requestRestart({ reason: 'restarted from the web page', force: true });
497
+ if (!res.ok) throw new Error(res.message);
498
+ return {};
499
+ }
500
+ throw new Error(`Unknown action: ${action}`);
501
+ }
502
+
503
+ // `claude-pro attach` (see attach.js) on this background session: the screen, drawn whole for it, and its keys.
504
+ // From the client: one JSON object a line, {keys: base64} or {resize: [columns, rows]}.
505
+ attachClient(socket, { cols, rows } = {}) {
506
+ const client = { write: (d) => { if (!socket.destroyed) socket.write(d); }, close: () => socket.end() };
507
+ socket.on('error', () => { /* its close follows */ });
508
+ socket.on('close', () => this.vterm.detach(client));
509
+ this.vterm.attach(client, { cols, rows });
510
+ client.write(`${ATTACH_MODES}${ESC.bracketedPasteOn}`);
511
+ if (this.screen.full) this.screen.repaint();
512
+ let buf = '';
513
+ // (no setEncoding: an HTTP server's socket refuses it; the lines are ASCII anyway, JSON with base64)
514
+ socket.on('data', (d) => {
515
+ buf += d.toString('latin1');
516
+ for (let i = buf.indexOf('\n'); i >= 0; i = buf.indexOf('\n')) {
517
+ const line = buf.slice(0, i);
518
+ buf = buf.slice(i + 1);
519
+ let m;
520
+ try { m = JSON.parse(line); } catch { continue; }
521
+ if (Array.isArray(m?.resize)) this.vterm.resize(m.resize[0], m.resize[1]);
522
+ else if (typeof m?.keys === 'string') this.vterm.type(Buffer.from(m.keys, 'base64'));
523
+ }
524
+ });
525
+ socket.resume(); // the HTTP server leaves an upgraded socket paused
526
+ }
527
+
429
528
  // This session's name for the others.
430
529
  peerLabel() { return this.peers?.name || this.sessionName || cleanName(path.basename(this.cwd)) || 'claude-pro'; }
431
530
 
@@ -783,12 +882,17 @@ export class App {
783
882
  }
784
883
 
785
884
  // The computer service (see host.js): started in the background when none runs, so that the gateway's web page can
786
- // open sessions on this computer even when no session is open. Not in the tests nor in the self-check.
787
- ensureHost() {
885
+ // open sessions on this computer even when no session is open, and set up to start at logon (once; after /login,
886
+ // `login`, again unless `claude-pro host uninstall` said no). Not in the tests nor in the self-check.
887
+ ensureHost({ login = false } = {}) {
788
888
  const env = this.config.env;
789
889
  if (this.driven || this.selfCheck || process.env.NODE_TEST_CONTEXT || this.exiting) return;
790
890
  if (!onlineEnabled(env) || !hostEnabled(env) || !readGatewayLogin(this.config.gatewayUrl)) return;
791
891
  try { startHostIfNeeded(); } catch { /* the next session tries again */ }
892
+ try {
893
+ const auto = ensureAutostart({ force: login, env });
894
+ if (auto?.file && login) this.notice(`The computer service starts at logon from now on (${auto.file}; claude-pro host uninstall stops that).`);
895
+ } catch { /* not this time */ }
792
896
  }
793
897
 
794
898
  async connectRemote({ id }) {
@@ -798,12 +902,23 @@ export class App {
798
902
  gateway: { url: login.url || this.config.gatewayUrl, apiKey: login.apiKey },
799
903
  id,
800
904
  handlers: {
801
- info: () => ({ name: this.peerLabel(), machine: machineName(this.config.env), peerId: this.peers?.id || null, title: this.sessionLabel() || '', cwd: (this.agent.cwd || this.cwd).replace(/\\/g, '/'), model: modelInfo(this.config).model, version: VERSION }),
802
- seed: () => transcriptItems(this.agent.messages, { tools: this.runtime.tools, ctx: this.agent.makeCtx(), cwd: this.cwd }),
905
+ info: () => ({
906
+ name: this.peerLabel(), machine: machineName(this.config.env), peerId: this.peers?.id || null, title: this.sessionLabel() || '',
907
+ cwd: (this.agent.cwd || this.cwd).replace(/\\/g, '/'), model: modelInfo(this.config).model, version: VERSION,
908
+ computerId: computerId(), kind: this.headless ? 'background' : 'terminal', conversationId: this.store.id,
909
+ }),
910
+ seed: () => [
911
+ ...transcriptItems(this.agent.messages, { tools: this.runtime.tools, ctx: this.agent.makeCtx(), cwd: this.cwd }),
912
+ ...(this.seedOutput.length ? [{ k: 'output', lines: this.seedOutput.slice() }] : []),
913
+ ],
803
914
  status: () => this.remoteStatus(),
804
- send: (text) => this.remoteSend(text),
915
+ send: (text, images) => this.remoteSend(text, images),
805
916
  interrupt: () => this.remoteInterrupt(),
806
917
  answer: (body) => this.answerDialog(body),
918
+ options: () => this.remoteOptions(),
919
+ suggest: (body) => this.remoteSuggest(body),
920
+ list: (body) => this.remoteList(body),
921
+ output: (body) => this.remoteOutput(body),
807
922
  peerMessage: (msg) => this.onPeerMessage(msg),
808
923
  changed: () => {
809
924
  this.screen.schedule();
@@ -821,6 +936,7 @@ export class App {
821
936
  if (this.exiting) { remote.close(); return remote; }
822
937
  this.remote = remote;
823
938
  this.remoteRefused = null;
939
+ this.peers?.update(); // its id at the gateway, in the registry
824
940
  this.remotePeersTimer ??= setInterval(() => { if (this.remote?.online) this.refreshRemotePeers(); }, 60_000);
825
941
  this.remotePeersTimer.unref?.();
826
942
  this.screen.schedule();
@@ -882,15 +998,44 @@ export class App {
882
998
  name: this.peerLabel(),
883
999
  tasks: this.runtime.tasks.running().length,
884
1000
  restarting: Boolean(this.restartRequest),
1001
+ asking: this.dialogs.length > 0, // a question waits for an answer (the page reminds the user of it)
1002
+ conversationId: this.store.id,
1003
+ cost: Number(this.cost.toFixed(6)),
1004
+ context: { used: this.contextUsed(), window: cfg.mainModel.contextWindow },
1005
+ background: this.backgroundWork(),
1006
+ kind: this.headless ? 'background' : 'terminal',
885
1007
  };
886
1008
  }
887
1009
 
1010
+ // The tokens the conversation takes now, as /context counts them: what the last request used and what came
1011
+ // since, or before any request an estimate (kept until the conversation changes: the status is asked for often).
1012
+ contextUsed() {
1013
+ const a = this.agent;
1014
+ if (a.lastContextTokens) return a.contextEstimate;
1015
+ const key = `${a.messages.length}|${this.runtime.tools.length}`;
1016
+ if (this.contextGuess?.key !== key) {
1017
+ let used = 0;
1018
+ try { used = estimateTokens(this.runtime.systemPrompt()) + estimateTokens(a.toolSchemas()) + estimateTokens(a.messages); } catch { /* 0 */ }
1019
+ this.contextGuess = { key, used };
1020
+ }
1021
+ return this.contextGuess.used;
1022
+ }
1023
+
1024
+ // What runs in the background: the agent's background agents and shells.
1025
+ backgroundWork() {
1026
+ const agents = this.runtime.tasks.list().map((t) => ({ id: t.id, kind: 'agent', description: t.description, status: t.status, startedAt: t.started }));
1027
+ const shells = listBackgroundShells().map((s) => ({ id: s.id, kind: 'shell', description: s.description || s.command, status: s.status, startedAt: s.startedAt || null }));
1028
+ return [...agents, ...shells];
1029
+ }
1030
+
888
1031
  // The dialog open in the terminal, for the page to answer (options by index: values need not be strings).
889
1032
  remoteDialog() {
890
1033
  const d = this.dialogs[0];
891
1034
  if (!d) return null;
892
1035
  d.remoteId ??= ++this.remoteDialogs;
893
1036
  const base = { id: d.remoteId, title: d.title || '', question: d.question || '', body: d.body || [], markdown: d.markdown || null };
1037
+ // a question answered with typed text (TextDialog): a text box on the page, answered with {id, text}
1038
+ if (d.input) return { ...base, input: { placeholder: d.input.placeholder || '', value: d.value || '', multiline: Boolean(d.input.multiline) } };
894
1039
  if (!Array.isArray(d.options)) return base;
895
1040
  return { ...base, multi: Boolean(d.multi), options: d.options.map((o) => ({ label: String(o.label ?? ''), description: o.description || '', other: o.value === '__other__' })) };
896
1041
  }
@@ -899,7 +1044,13 @@ export class App {
899
1044
  const d = this.dialogs[0];
900
1045
  if (!d || d.remoteId !== id) throw new Error('That question is no longer open.');
901
1046
  if (cancel) { d.resolve(d.cancelValue); return {}; }
902
- if (!Array.isArray(d.options)) throw new Error('This dialog can only be answered in the terminal.');
1047
+ if (d.input) {
1048
+ if (typeof text !== 'string') throw new Error('Type an answer first.');
1049
+ d.resolve(text);
1050
+ this.screen.schedule();
1051
+ return {};
1052
+ }
1053
+ if (!Array.isArray(d.options)) throw new Error('This dialog cannot be answered from the page.');
903
1054
  const valueAt = (i) => {
904
1055
  const o = d.options[i];
905
1056
  if (!Number.isInteger(i) || !o || o.value === '__other__') throw new Error('No such option.');
@@ -918,19 +1069,89 @@ export class App {
918
1069
  return {};
919
1070
  }
920
1071
 
921
- // A message from the page: as if typed in the input box.
922
- remoteSend(text) {
923
- const value = String(text ?? '').replace(/\r\n/g, '\n');
1072
+ // A message from the page: as if typed in the input box, its images as if pasted there (alt+v). Images alone go
1073
+ // as their placeholders, which is what the input box sends for them.
1074
+ remoteSend(text, images) {
1075
+ const pictures = remoteImages(images);
1076
+ let value = String(text ?? '').replace(/\r\n/g, '\n');
1077
+ if (!value.trim() && pictures.length) value = pictures.map((_, i) => `[Image #${i + 1}]`).join(' ');
924
1078
  if (!value.trim()) throw new Error('The message is empty.');
925
1079
  if (this.exiting) throw new Error('The session is ending.');
926
1080
  if (this.busy && value.trim().startsWith('/')) throw new Error('Commands wait until the current task is done (or stopped).');
927
1081
  if (this.dialogs.length && !this.busy) throw new Error('A question is open: answer it first.');
928
1082
  const queued = this.busy;
929
- this.onSubmit(value, value);
1083
+ this.onSubmit(value, value, pictures);
930
1084
  this.screen.schedule();
931
1085
  return { queued };
932
1086
  }
933
1087
 
1088
+ // For the page's model, effort and mode menus: what /model and /effort offer, in plain text, and what is chosen
1089
+ // now (as the status says it).
1090
+ async remoteOptions() {
1091
+ const cfg = this.config;
1092
+ const [models, efforts] = await Promise.all([modelChoices(cfg), effortChoices(cfg)]);
1093
+ const { effort } = modelInfo(cfg);
1094
+ return { model: cfg.mainModel.id, models, effort: effort || defaultEffort(cfg.mainModel.id, cfg), efforts: efforts.options, mode: this.runtime.modes.mode };
1095
+ }
1096
+
1097
+ // For the page's input box: what the input box here would suggest (/commands, @files, &sessions), in plain text,
1098
+ // without anything happening here. Sessions on the other computers are asked for first when the list is old.
1099
+ async remoteSuggest(body = {}) {
1100
+ const text = String(body.text ?? '');
1101
+ const cursor = Number.isInteger(body.cursor) ? Math.max(0, Math.min(text.length, body.cursor)) : text.length;
1102
+ if (/(^|\s)[&&][^\s&&]*$/u.test(text.slice(0, cursor)) && this.remote?.online && Date.now() - this.remotePeersAt > 10_000) {
1103
+ await Promise.race([this.refreshRemotePeers(), new Promise((r) => setTimeout(r, 3000))]);
1104
+ }
1105
+ const found = this.suggest(text, cursor, { quiet: true });
1106
+ if (!found?.items?.length) return { items: [] };
1107
+ const plain = (s) => (s == null ? '' : stripAnsi(String(s)));
1108
+ return {
1109
+ items: found.items.slice(0, 50).map((it) => ({ value: it.value, label: plain(it.label ?? it.value), description: plain(it.description), submitOnEnter: Boolean(it.submitOnEnter), noSpace: Boolean(it.noSpace) })),
1110
+ from: found.from,
1111
+ to: found.to,
1112
+ };
1113
+ }
1114
+
1115
+ // For the page's directory browser (/cd): the computer service's listing (see host.js), "" being this session's
1116
+ // working directory.
1117
+ remoteList(body = {}) {
1118
+ const wanted = typeof body.path === 'string' && body.path.trim() ? body.path : this.cwd;
1119
+ return listDirectory(wanted, {
1120
+ recent: () => {
1121
+ if (!this.recentDirs || Date.now() - this.recentDirs.at > 30_000) this.recentDirs = { at: Date.now(), list: recentDirectories() };
1122
+ return this.recentDirs.list;
1123
+ },
1124
+ });
1125
+ }
1126
+
1127
+ // For the page's "the whole output": the full result of the tool call `id` ({text, truncated}, at most a MB): the
1128
+ // file it was saved to when it was too long for the conversation, or cleared from it later; what it printed so
1129
+ // far while it runs.
1130
+ remoteOutput({ id } = {}) {
1131
+ if (typeof id !== 'string' || !id) throw new Error('Which tool call?');
1132
+ const MAX = 1024 * 1024;
1133
+ const cut = (text, running = false) => ({ text: text.length > MAX ? text.slice(0, MAX) : text, truncated: text.length > MAX, ...(running ? { running } : {}) });
1134
+ let result = null;
1135
+ for (const m of this.agent.messages) {
1136
+ if (m.role !== 'user' || !Array.isArray(m.content)) continue;
1137
+ for (const b of m.content) if (b.type === 'tool_result' && b.tool_use_id === id) result = b;
1138
+ }
1139
+ if (!result) {
1140
+ const live = this.active.find((e) => e.tu?.id === id);
1141
+ if (live) return cut(String(live.progress || ''), true);
1142
+ throw new Error('There is no such tool call in this conversation.');
1143
+ }
1144
+ let text = typeof result.content === 'string' ? result.content
1145
+ : (Array.isArray(result.content) ? result.content : []).map((b) => (b.type === 'text' ? b.text : b.type === 'image' ? '[image]' : '')).join('\n');
1146
+ // saved whole in the projects' tool-results (see persistLargeOutput and the Bash tool): read from there
1147
+ const saved = /(?:saved to:?|saved at)\s+(\S+?\.txt)\b/.exec(text)?.[1];
1148
+ const results = path.join(CONFIG_DIR, 'projects');
1149
+ if (saved && path.resolve(saved).startsWith(results + path.sep) && path.resolve(saved).includes(`${path.sep}tool-results${path.sep}`)) {
1150
+ try { text = fs.readFileSync(saved, 'utf8'); } catch { /* the reference is what there is */ }
1151
+ }
1152
+ return cut(text);
1153
+ }
1154
+
934
1155
  remoteInterrupt() {
935
1156
  for (const d of this.dialogs.splice(0)) d.resolve(d.cancelValue);
936
1157
  this.interrupt();
@@ -958,16 +1179,17 @@ export class App {
958
1179
  // Restart as soon as nothing is running: at once when idle, otherwise when the current turn ends (the
959
1180
  // turn that asked for it still has to be answered and saved). `continueTurn`: the model gets a note in
960
1181
  // the new process and goes on by itself. Returns {ok, message}.
961
- requestRestart({ reason = '', then = '', continueTurn = false, force = false } = {}) {
1182
+ // `cwd`: the session goes on in that directory (/cd).
1183
+ requestRestart({ reason = '', then = '', continueTurn = false, force = false, cwd = null } = {}) {
962
1184
  if (!canRestart()) return { ok: false, message: 'This session cannot restart itself.' };
963
1185
  const now = Date.now();
964
1186
  const recent = this.restarts.filter((t) => now - t < RESTART_WINDOW_MS);
965
- if (recent.length >= MAX_RESTARTS) {
1187
+ if (recent.length >= MAX_RESTARTS && !cwd) {
966
1188
  return { ok: false, message: `The program was restarted ${recent.length} times in the last ${Math.round(RESTART_WINDOW_MS / 60_000)} minutes. That looks like a loop: stop restarting and tell the user what is going on.` };
967
1189
  }
968
1190
  const blockers = this.restartBlockers();
969
- if (blockers.length && !force) return { ok: false, message: `A restart would kill: ${blockers.join('; ')}.` };
970
- this.restartRequest = { reason, then, continueTurn };
1191
+ if (blockers.length && !force) return { ok: false, message: `${cwd ? 'Changing the directory restarts the session, which would stop' : 'A restart would kill'}: ${blockers.join('; ')}.` };
1192
+ this.restartRequest = { reason, then, continueTurn, cwd };
971
1193
  this.screen.schedule();
972
1194
  if (!this.busy) this.restartNow();
973
1195
  return { ok: true };
@@ -979,12 +1201,20 @@ export class App {
979
1201
  this.restartRequest = null;
980
1202
  const cfg = this.config;
981
1203
  const now = Date.now();
1204
+ // /cd: the conversation's file goes along to the new directory's project (see moveSession); the old one is
1205
+ // removed once the next process is sure to find the new one
1206
+ let moved = null;
1207
+ if (request.cwd) {
1208
+ try { moved = moveSession(this.store.file, this.store.id, request.cwd); } catch (e) { this.notice(`Could not change the directory: ${e.message}`, 'warn'); return; }
1209
+ }
982
1210
  const state = {
983
1211
  at: now,
984
1212
  reason: request.reason || '',
985
1213
  continueWith: request.continueTurn ? restartNote(request) : '',
1214
+ cwd: request.cwd || this.cwd,
1215
+ changedDirectory: Boolean(request.cwd),
986
1216
  sessionId: this.store.id,
987
- sessionFile: this.store.file,
1217
+ sessionFile: moved?.file || this.store.file,
988
1218
  modelOverride: cfg.modelOverride,
989
1219
  effortOverride: cfg.effortOverride,
990
1220
  effortBoost: cfg.effortBoost,
@@ -995,20 +1225,34 @@ export class App {
995
1225
  draftCursor: this.editor.cursor,
996
1226
  queue: this.queue.map((q) => ({ text: q.text, images: q.images || [] })),
997
1227
  checkpoints: this.runtime.checkpoints.snapshot(),
998
- restarts: [...this.restarts.filter((t) => now - t < RESTART_WINDOW_MS), now],
999
- peerName: this.peers?.name || this.sessionName,
1228
+ // a /cd is the user's: it does not count towards the restarts that look like a loop
1229
+ restarts: [...this.restarts.filter((t) => now - t < RESTART_WINDOW_MS), ...(request.cwd ? [] : [now])],
1230
+ // a name given with /rename or --name stays; the one taken from the directory follows it
1231
+ peerName: request.cwd && !this.customTitle ? null : this.peers?.name || this.sessionName,
1000
1232
  peerId: this.peers?.id,
1001
1233
  remote: this.remote?.handoff() || null,
1002
1234
  };
1003
1235
  try {
1004
1236
  writeRestartState(state);
1005
1237
  } catch (e) {
1238
+ moved?.undo();
1006
1239
  this.notice(`Could not restart: ${e.message}`, 'warn');
1007
1240
  return;
1008
1241
  }
1242
+ moved?.commit();
1009
1243
  this.exit(RESTART_EXIT_CODE, { restart: true });
1010
1244
  }
1011
1245
 
1246
+ // /cd: the session goes on in `dir` (an existing directory). It restarts there, so that everything that belongs to
1247
+ // a project is that directory's: its settings and CLAUDE.md, its memory, the system prompt's directory and git
1248
+ // state, the @ file index, the input history and where the conversation is kept. The conversation, the remote
1249
+ // page's id and a name given with /rename stay. Returns {ok, message}.
1250
+ changeDirectory(dir) {
1251
+ if (this.busy) return { ok: false, message: 'Wait for the current task to finish (or press Esc) before changing the directory.' };
1252
+ if (!canRestart()) return { ok: false, message: 'This session cannot change its directory: that restarts it, and it was not started by the claude-pro launcher. Start claude-pro in that directory instead.' };
1253
+ return this.requestRestart({ reason: `working directory ${dir}`, cwd: dir });
1254
+ }
1255
+
1012
1256
  // In the process a restart started: take up the session where the one before it left it.
1013
1257
  resumeAfterRestart(state, resumable) {
1014
1258
  const cfg = this.config;
@@ -1030,6 +1274,13 @@ export class App {
1030
1274
  // Fullscreen starts on an empty screen: without what the process before showed (an older version, or one
1031
1275
  // that ran classic), the conversation is drawn again from the session.
1032
1276
  if (this.screen.full && resumable && !Array.isArray(state.screenHistory)) this.printTranscript(this.agent.messages.slice(-80));
1277
+ if (state.changedDirectory) {
1278
+ // /cd: the line it answers with, here and on the remote page (which starts again from the conversation)
1279
+ const line = `Working directory: ${this.cwd}`;
1280
+ this.screen.log(line, '');
1281
+ this.seedOutput = [line];
1282
+ return;
1283
+ }
1033
1284
  this.screen.log(c.dim(`↻ Restarted${state.reason ? `: ${state.reason}` : ''}${state.continueWith ? ' · continuing' : ''}`), '');
1034
1285
  }
1035
1286
 
@@ -1213,6 +1464,7 @@ export class App {
1213
1464
  // Fullscreen (see screen.js) unless CLAUDE_PRO_TUI=default, as Claude Code's /tui: the input box fixed at the
1214
1465
  // bottom of the window, the conversation scrolled inside the program. Not in the tests that drive the App.
1215
1466
  fullscreenWanted() {
1467
+ if (this.headless) return true; // `claude-pro attach` gets the whole screen, drawn again when it comes
1216
1468
  const mode = String(this.config.env.CLAUDE_PRO_TUI || (this.driven ? 'default' : 'fullscreen')).toLowerCase();
1217
1469
  return mode === 'fullscreen' && this.stdout.isTTY !== false;
1218
1470
  }
@@ -1299,13 +1551,21 @@ export class App {
1299
1551
  }
1300
1552
  if (key.ctrl && key.name === 't') { this.showTodos = !this.showTodos; this.screen.schedule(); return; }
1301
1553
  if (key.ctrl && key.name === 'l') { if (this.screen.full) this.screen.repaint(); else this.screen.clearScreen(); return; }
1302
- if (key.ctrl && key.name === 'd' && !this.editor.text) { this.exit(0); return; }
1554
+ if (key.ctrl && key.name === 'd' && !this.editor.text) { this.keyboardExit(); return; }
1303
1555
  if (key.name === 'escape' && this.busy) { this.interrupt(); return; }
1304
1556
  this.exitArmed = 0;
1305
1557
  this.editor.handleKey(str, key);
1306
1558
  this.screen.schedule();
1307
1559
  }
1308
1560
 
1561
+ // ctrl+c twice, ctrl+d: the end of the session, except in a background one, where the keys come from
1562
+ // `claude-pro attach` and leaving it is detaching (/exit ends the session there).
1563
+ keyboardExit() {
1564
+ if (!this.headless) { this.exit(0); return; }
1565
+ this.exitArmed = 0;
1566
+ this.flash('This session runs in the background: ctrl+] detaches from it, /exit ends it');
1567
+ }
1568
+
1309
1569
  onCtrlC() {
1310
1570
  if (this.dialogs.length) {
1311
1571
  // Cancel the dialog and interrupt the run.
@@ -1315,7 +1575,7 @@ export class App {
1315
1575
  }
1316
1576
  if (this.busy) { this.interrupt(); return; }
1317
1577
  if (this.editor.text) { this.editor.discard(); this.screen.schedule(); return; }
1318
- if (Date.now() - this.exitArmed < 1500) { this.exit(0); return; }
1578
+ if (Date.now() - this.exitArmed < 1500) { this.keyboardExit(); return; }
1319
1579
  this.exitArmed = Date.now();
1320
1580
  this.screen.schedule();
1321
1581
  setTimeout(() => this.screen.schedule(), 1600);
@@ -1327,7 +1587,8 @@ export class App {
1327
1587
  this.screen.schedule();
1328
1588
  }
1329
1589
 
1330
- suggest(text, cursor) {
1590
+ // `quiet`: for the page (remoteSuggest), nothing shows here.
1591
+ suggest(text, cursor, { quiet = false } = {}) {
1331
1592
  if (text.startsWith('/') && !/\s/.test(text) && cursor === text.length) {
1332
1593
  const q = text.slice(1).toLowerCase();
1333
1594
  const all = [...this.commands.values()].filter((cmd) => !cmd.hidden);
@@ -1358,12 +1619,12 @@ export class App {
1358
1619
  // `&name`: the other sessions, on this computer and (through the gateway) on the account's others. At the start
1359
1620
  // it sends them the message; elsewhere it names them (/sendfile, or for the model).
1360
1621
  const amp = /(^|\s)[&&]([^\s&&]*)$/u.exec(before);
1361
- if (amp) return this.peerSuggestions(amp[2], cursor, amp.index === 0 && !amp[1]);
1622
+ if (amp) return this.peerSuggestions(amp[2], cursor, amp.index === 0 && !amp[1], { quiet });
1362
1623
  return null;
1363
1624
  }
1364
1625
 
1365
- peerSuggestions(q, cursor, atStart = true) {
1366
- if (this.remote?.online && Date.now() - this.remotePeersAt > 10_000) {
1626
+ peerSuggestions(q, cursor, atStart = true, { quiet = false } = {}) {
1627
+ if (!quiet && this.remote?.online && Date.now() - this.remotePeersAt > 10_000) {
1367
1628
  this.refreshRemotePeers().then(() => {
1368
1629
  if (!/[&&][^\s&&]*$/u.test(this.editor.text.slice(0, this.editor.cursor))) return;
1369
1630
  this.editor.refreshSuggestions();
@@ -1378,7 +1639,7 @@ export class App {
1378
1639
  .map((p) => ({ value: '&' + p.label, label: `&${p.label}`, description: `${p.machine} · ${p.cwd}${p.busy ? ' · busy' : ''}` })),
1379
1640
  ];
1380
1641
  if (!items.length) {
1381
- if (!q && atStart) this.flash(this.remote ? 'No other session is running here or online at the gateway' : 'No other session is running on this computer (/login to the gateway reaches your other computers)');
1642
+ if (!q && atStart && !quiet) this.flash(this.remote ? 'No other session is running here or online at the gateway' : 'No other session is running on this computer (/login to the gateway reaches your other computers)');
1382
1643
  return null;
1383
1644
  }
1384
1645
  return { items, from: cursor - q.length - 1, to: cursor };
@@ -1821,7 +2082,9 @@ export class App {
1821
2082
  loadSession(file, id, { quiet = false } = {}) {
1822
2083
  const loaded = SessionStore.load(file);
1823
2084
  this.previousSession = null; // the conversation before a /clear: resuming another one ends the offer
2085
+ this.seedOutput = [];
1824
2086
  this.store = new SessionStore(this.cwd, id);
2087
+ this.peers?.update(); // the conversation, in the registry
1825
2088
  this.topic = loaded.topic;
1826
2089
  this.customTitle = loaded.name;
1827
2090
  // a conversation that was given a name brings it back: the other sessions reach this one by it again
@@ -1854,7 +2117,9 @@ export class App {
1854
2117
  for (const m of messages) {
1855
2118
  const blocks = typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : m.content;
1856
2119
  for (const b of blocks) {
1857
- if (m.role === 'user' && b.type === 'text' && !b.text.startsWith('<system-reminder>')) this.screen.log(renderUserMessage(b.text.slice(0, 2000), this.width));
2120
+ const bash = m.role === 'user' && b.type === 'text' ? bashModeLines(b.text) : null;
2121
+ if (bash) this.screen.log(bash, '');
2122
+ else if (m.role === 'user' && b.type === 'text' && !b.text.startsWith('<system-reminder>')) this.screen.log(renderUserMessage(b.text.slice(0, 2000), this.width));
1858
2123
  if (m.role === 'assistant' && b.type === 'text') this.screen.log(renderMarkdown(b.text, { width: this.width - 1, firstPrefix: `${DOT} `, indent: ' ' }), '');
1859
2124
  if (m.role === 'assistant' && b.type === 'tool_use') {
1860
2125
  const tool = toolMap.get(b.name) || { name: b.name };
@@ -1867,6 +2132,8 @@ export class App {
1867
2132
 
1868
2133
  newSession() {
1869
2134
  this.store = new SessionStore(this.cwd);
2135
+ this.peers?.update();
2136
+ this.seedOutput = [];
1870
2137
  this.topic = null;
1871
2138
  this.customTitle = null;
1872
2139
  this.firstPrompt = null;
@@ -2361,7 +2628,10 @@ export class App {
2361
2628
  }
2362
2629
 
2363
2630
  export async function runRepl({ flags, cwd, initialPrompt }) {
2364
- const app = new App({ flags, cwd });
2631
+ // --headless: a background session (see vterm.js), its log on stdout
2632
+ const vterm = flags.headless ? new VirtualTerminal() : null;
2633
+ if (vterm) process.stdout.write(`${new Date().toISOString()} claude-pro ${VERSION} background session in ${cwd} (pid ${process.pid})\n`);
2634
+ const app = new App({ flags, cwd, vterm });
2365
2635
  process.on('uncaughtException', (e) => {
2366
2636
  app.restoreTerminal();
2367
2637
  process.stderr.write(`\nUnexpected error: ${e?.stack || e}\n`);