@yanzc/claude-pro 0.6.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +372 -370
- package/package.json +1 -1
- package/src/agent.js +18 -13
- package/src/attach.js +132 -0
- package/src/background.js +424 -0
- package/src/commands.js +80 -59
- package/src/connect.js +79 -0
- package/src/history.js +94 -0
- package/src/host.js +445 -66
- package/src/main.js +38 -10
- package/src/peers.js +290 -215
- package/src/print.js +0 -1
- package/src/prompts.js +2 -7
- package/src/remote.js +50 -15
- package/src/runtime.js +2 -6
- package/src/session.js +24 -0
- package/src/supervisor.js +6 -3
- package/src/tools/bash.js +2 -2
- package/src/tools/index.js +2 -3
- package/src/tools/interaction.js +2 -30
- package/src/tools/task.js +1 -1
- package/src/ui/ansi.js +0 -1
- package/src/ui/dialogs.js +48 -0
- package/src/ui/render.js +10 -4
- package/src/ui/repl.js +318 -77
- package/src/ui/vterm.js +62 -0
- package/src/modes.js +0 -154
- package/src/qr.js +0 -206
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
|
-
|
|
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(
|
|
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();
|
|
@@ -268,7 +306,6 @@ export class App {
|
|
|
268
306
|
try { this.onKey(str, key || {}); } catch (e) { this.logError(e); }
|
|
269
307
|
});
|
|
270
308
|
stdin.resume();
|
|
271
|
-
this.runtime.modes.listeners.add(() => this.screen.schedule());
|
|
272
309
|
// Started by a restart of this session: the output of the process before it is still on screen, so no
|
|
273
310
|
// welcome box and no transcript, just a line saying so.
|
|
274
311
|
const restart = this.flags.restart || null;
|
|
@@ -291,8 +328,9 @@ export class App {
|
|
|
291
328
|
}, 120);
|
|
292
329
|
if (restart) this.continueAfterRestart(restart);
|
|
293
330
|
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
|
-
|
|
331
|
+
// Nothing configured yet: the gateway is the default, and its login comes first, as in Claude Code. (Not in a
|
|
332
|
+
// background session: nobody sits at this computer to log in in its browser.)
|
|
333
|
+
else if (this.config.usesGateway && !readGatewayLogin(this.config.gatewayUrl) && !this.headless) {
|
|
296
334
|
Promise.resolve(this.commands.get('login').run('')).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
|
|
297
335
|
}
|
|
298
336
|
this.fileIndex.refresh();
|
|
@@ -404,6 +442,11 @@ export class App {
|
|
|
404
442
|
if (!restart && this.agent?.messages.length) this.screen.log(c.dim(`Resume this session with: ${APP_NAME} --resume ${this.store.id}`));
|
|
405
443
|
this.restoreTerminal({ handOver: restart });
|
|
406
444
|
this.stdin.pause();
|
|
445
|
+
if (this.headless) {
|
|
446
|
+
// ended for good (/exit, the computer service's stop): the service does not open it again
|
|
447
|
+
if (code === 0 && !restart && this.remote?.id) markBackgroundEnded(this.remote.id);
|
|
448
|
+
setTimeout(() => this.vterm.closeAll(), 20).unref?.(); // the last screen first
|
|
449
|
+
}
|
|
407
450
|
this.resolveExit?.(code);
|
|
408
451
|
if (!this.noProcessExit) {
|
|
409
452
|
// with remote control on, the gateway is told first (at most a second and a half; see RemoteControl.close)
|
|
@@ -419,13 +462,68 @@ export class App {
|
|
|
419
462
|
async startPeer() {
|
|
420
463
|
if (this.driven || !peersEnabled()) return;
|
|
421
464
|
try {
|
|
422
|
-
this.peers = await new PeerNode({
|
|
465
|
+
this.peers = await new PeerNode({
|
|
466
|
+
cwd: this.cwd,
|
|
467
|
+
name: this.flags.restart?.peerName,
|
|
468
|
+
id: this.flags.restart?.peerId,
|
|
469
|
+
onMessage: (msg) => this.onPeerMessage(msg),
|
|
470
|
+
getStatus: () => ({ busy: this.working() }),
|
|
471
|
+
info: () => ({ kind: this.headless ? 'background' : 'terminal', remoteId: this.remote?.id || this.flags.remoteId || this.flags.restart?.remote?.id || null, conversationId: this.store.id }),
|
|
472
|
+
onControl: (body) => this.onControl(body),
|
|
473
|
+
onAttach: this.headless ? (socket, size) => this.attachClient(socket, size) : null,
|
|
474
|
+
}).start();
|
|
423
475
|
} catch (e) {
|
|
424
476
|
this.peers = null;
|
|
425
477
|
this.notice(`Other sessions cannot reach this one: ${e.message}`, 'warn');
|
|
426
478
|
}
|
|
427
479
|
}
|
|
428
480
|
|
|
481
|
+
// The computer service (see host.js) about a background session: {action: 'exit'} ends it as /exit does (a turn
|
|
482
|
+
// that runs, or a question that waits, is stopped first), 'restart' restarts it as /restart does, 'interrupt' is
|
|
483
|
+
// Esc.
|
|
484
|
+
onControl({ action } = {}) {
|
|
485
|
+
if (action === 'interrupt') return this.remoteInterrupt();
|
|
486
|
+
if (action === 'exit') {
|
|
487
|
+
for (const d of this.dialogs.splice(0)) d.resolve(d.cancelValue);
|
|
488
|
+
this.interrupt();
|
|
489
|
+
setTimeout(() => this.exit(0), 50); // once the answer is out
|
|
490
|
+
return {};
|
|
491
|
+
}
|
|
492
|
+
if (action === 'restart') {
|
|
493
|
+
for (const d of this.dialogs.splice(0)) d.resolve(d.cancelValue);
|
|
494
|
+
this.interrupt();
|
|
495
|
+
const res = this.requestRestart({ reason: 'restarted from the web page', force: true });
|
|
496
|
+
if (!res.ok) throw new Error(res.message);
|
|
497
|
+
return {};
|
|
498
|
+
}
|
|
499
|
+
throw new Error(`Unknown action: ${action}`);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// `claude-pro attach` (see attach.js) on this background session: the screen, drawn whole for it, and its keys.
|
|
503
|
+
// From the client: one JSON object a line, {keys: base64} or {resize: [columns, rows]}.
|
|
504
|
+
attachClient(socket, { cols, rows } = {}) {
|
|
505
|
+
const client = { write: (d) => { if (!socket.destroyed) socket.write(d); }, close: () => socket.end() };
|
|
506
|
+
socket.on('error', () => { /* its close follows */ });
|
|
507
|
+
socket.on('close', () => this.vterm.detach(client));
|
|
508
|
+
this.vterm.attach(client, { cols, rows });
|
|
509
|
+
client.write(`${ATTACH_MODES}${ESC.bracketedPasteOn}`);
|
|
510
|
+
if (this.screen.full) this.screen.repaint();
|
|
511
|
+
let buf = '';
|
|
512
|
+
// (no setEncoding: an HTTP server's socket refuses it; the lines are ASCII anyway, JSON with base64)
|
|
513
|
+
socket.on('data', (d) => {
|
|
514
|
+
buf += d.toString('latin1');
|
|
515
|
+
for (let i = buf.indexOf('\n'); i >= 0; i = buf.indexOf('\n')) {
|
|
516
|
+
const line = buf.slice(0, i);
|
|
517
|
+
buf = buf.slice(i + 1);
|
|
518
|
+
let m;
|
|
519
|
+
try { m = JSON.parse(line); } catch { continue; }
|
|
520
|
+
if (Array.isArray(m?.resize)) this.vterm.resize(m.resize[0], m.resize[1]);
|
|
521
|
+
else if (typeof m?.keys === 'string') this.vterm.type(Buffer.from(m.keys, 'base64'));
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
socket.resume(); // the HTTP server leaves an upgraded socket paused
|
|
525
|
+
}
|
|
526
|
+
|
|
429
527
|
// This session's name for the others.
|
|
430
528
|
peerLabel() { return this.peers?.name || this.sessionName || cleanName(path.basename(this.cwd)) || 'claude-pro'; }
|
|
431
529
|
|
|
@@ -783,12 +881,17 @@ export class App {
|
|
|
783
881
|
}
|
|
784
882
|
|
|
785
883
|
// 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
|
|
787
|
-
|
|
884
|
+
// open sessions on this computer even when no session is open, and set up to start at logon (once; after /login,
|
|
885
|
+
// `login`, again unless `claude-pro host uninstall` said no). Not in the tests nor in the self-check.
|
|
886
|
+
ensureHost({ login = false } = {}) {
|
|
788
887
|
const env = this.config.env;
|
|
789
888
|
if (this.driven || this.selfCheck || process.env.NODE_TEST_CONTEXT || this.exiting) return;
|
|
790
889
|
if (!onlineEnabled(env) || !hostEnabled(env) || !readGatewayLogin(this.config.gatewayUrl)) return;
|
|
791
890
|
try { startHostIfNeeded(); } catch { /* the next session tries again */ }
|
|
891
|
+
try {
|
|
892
|
+
const auto = ensureAutostart({ force: login, env });
|
|
893
|
+
if (auto?.file && login) this.notice(`The computer service starts at logon from now on (${auto.file}; claude-pro host uninstall stops that).`);
|
|
894
|
+
} catch { /* not this time */ }
|
|
792
895
|
}
|
|
793
896
|
|
|
794
897
|
async connectRemote({ id }) {
|
|
@@ -798,12 +901,23 @@ export class App {
|
|
|
798
901
|
gateway: { url: login.url || this.config.gatewayUrl, apiKey: login.apiKey },
|
|
799
902
|
id,
|
|
800
903
|
handlers: {
|
|
801
|
-
info: () => ({
|
|
802
|
-
|
|
904
|
+
info: () => ({
|
|
905
|
+
name: this.peerLabel(), machine: machineName(this.config.env), peerId: this.peers?.id || null, title: this.sessionLabel() || '',
|
|
906
|
+
cwd: (this.agent.cwd || this.cwd).replace(/\\/g, '/'), model: modelInfo(this.config).model, version: VERSION,
|
|
907
|
+
computerId: computerId(), kind: this.headless ? 'background' : 'terminal', conversationId: this.store.id,
|
|
908
|
+
}),
|
|
909
|
+
seed: () => [
|
|
910
|
+
...transcriptItems(this.agent.messages, { tools: this.runtime.tools, ctx: this.agent.makeCtx(), cwd: this.cwd }),
|
|
911
|
+
...(this.seedOutput.length ? [{ k: 'output', lines: this.seedOutput.slice() }] : []),
|
|
912
|
+
],
|
|
803
913
|
status: () => this.remoteStatus(),
|
|
804
|
-
send: (text) => this.remoteSend(text),
|
|
914
|
+
send: (text, images) => this.remoteSend(text, images),
|
|
805
915
|
interrupt: () => this.remoteInterrupt(),
|
|
806
916
|
answer: (body) => this.answerDialog(body),
|
|
917
|
+
options: () => this.remoteOptions(),
|
|
918
|
+
suggest: (body) => this.remoteSuggest(body),
|
|
919
|
+
list: (body) => this.remoteList(body),
|
|
920
|
+
output: (body) => this.remoteOutput(body),
|
|
807
921
|
peerMessage: (msg) => this.onPeerMessage(msg),
|
|
808
922
|
changed: () => {
|
|
809
923
|
this.screen.schedule();
|
|
@@ -821,6 +935,7 @@ export class App {
|
|
|
821
935
|
if (this.exiting) { remote.close(); return remote; }
|
|
822
936
|
this.remote = remote;
|
|
823
937
|
this.remoteRefused = null;
|
|
938
|
+
this.peers?.update(); // its id at the gateway, in the registry
|
|
824
939
|
this.remotePeersTimer ??= setInterval(() => { if (this.remote?.online) this.refreshRemotePeers(); }, 60_000);
|
|
825
940
|
this.remotePeersTimer.unref?.();
|
|
826
941
|
this.screen.schedule();
|
|
@@ -834,21 +949,21 @@ export class App {
|
|
|
834
949
|
this.screen.schedule();
|
|
835
950
|
}
|
|
836
951
|
|
|
837
|
-
// This session at the gateway, for /status: {text
|
|
952
|
+
// This session at the gateway, for /status: {text}. (Its page is in the web page's list, 远程控制: no link here.)
|
|
838
953
|
remoteState() {
|
|
839
954
|
const r = this.remote;
|
|
840
955
|
if (r) {
|
|
841
956
|
const who = r.account ? ` as ${r.account}` : '';
|
|
842
957
|
const pages = r.viewers ? c.dim(` · ${r.viewers} page${r.viewers === 1 ? '' : 's'} open now`) : '';
|
|
843
958
|
const text = r.online ? `${c.green('online')}${who}${pages}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
|
|
844
|
-
return { text
|
|
959
|
+
return { text };
|
|
845
960
|
}
|
|
846
|
-
if (this.remoteStarting) return { text: 'connecting…'
|
|
961
|
+
if (this.remoteStarting) return { text: 'connecting…' };
|
|
847
962
|
const login = readGatewayLogin(this.config.gatewayUrl);
|
|
848
|
-
if (!login) return { text: c.dim(`offline: this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login)`)
|
|
849
|
-
if (login.apiKey === this.remoteRefused) return { text: c.red('offline: the gateway refused this computer\'s key (/logout, then /login)')
|
|
850
|
-
if (!onlineEnabled(this.config.env)) return { text: c.dim('offline (CLAUDE_PRO_ONLINE=0)')
|
|
851
|
-
return { text: c.dim('offline')
|
|
963
|
+
if (!login) return { text: c.dim(`offline: this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login)`) };
|
|
964
|
+
if (login.apiKey === this.remoteRefused) return { text: c.red('offline: the gateway refused this computer\'s key (/logout, then /login)') };
|
|
965
|
+
if (!onlineEnabled(this.config.env)) return { text: c.dim('offline (CLAUDE_PRO_ONLINE=0)') };
|
|
966
|
+
return { text: c.dim('offline') };
|
|
852
967
|
}
|
|
853
968
|
|
|
854
969
|
// The state the page shows below the transcript; sent whenever it changes.
|
|
@@ -874,7 +989,6 @@ export class App {
|
|
|
874
989
|
todos: (this.agent.todos || []).map((t) => ({ content: t.content, status: t.status })),
|
|
875
990
|
queue: this.queue.map((q) => q.display ?? q.text),
|
|
876
991
|
dialog: this.remoteDialog(),
|
|
877
|
-
mode: this.runtime.modes.mode,
|
|
878
992
|
model,
|
|
879
993
|
effort: effort || defaultEffort(cfg.mainModel.id, cfg),
|
|
880
994
|
title: this.sessionLabel() || path.basename(this.cwd),
|
|
@@ -882,15 +996,44 @@ export class App {
|
|
|
882
996
|
name: this.peerLabel(),
|
|
883
997
|
tasks: this.runtime.tasks.running().length,
|
|
884
998
|
restarting: Boolean(this.restartRequest),
|
|
999
|
+
asking: this.dialogs.length > 0, // a question waits for an answer (the page reminds the user of it)
|
|
1000
|
+
conversationId: this.store.id,
|
|
1001
|
+
cost: Number(this.cost.toFixed(6)),
|
|
1002
|
+
context: { used: this.contextUsed(), window: cfg.mainModel.contextWindow },
|
|
1003
|
+
background: this.backgroundWork(),
|
|
1004
|
+
kind: this.headless ? 'background' : 'terminal',
|
|
885
1005
|
};
|
|
886
1006
|
}
|
|
887
1007
|
|
|
1008
|
+
// The tokens the conversation takes now, as /context counts them: what the last request used and what came
|
|
1009
|
+
// since, or before any request an estimate (kept until the conversation changes: the status is asked for often).
|
|
1010
|
+
contextUsed() {
|
|
1011
|
+
const a = this.agent;
|
|
1012
|
+
if (a.lastContextTokens) return a.contextEstimate;
|
|
1013
|
+
const key = `${a.messages.length}|${this.runtime.tools.length}`;
|
|
1014
|
+
if (this.contextGuess?.key !== key) {
|
|
1015
|
+
let used = 0;
|
|
1016
|
+
try { used = estimateTokens(this.runtime.systemPrompt()) + estimateTokens(a.toolSchemas()) + estimateTokens(a.messages); } catch { /* 0 */ }
|
|
1017
|
+
this.contextGuess = { key, used };
|
|
1018
|
+
}
|
|
1019
|
+
return this.contextGuess.used;
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
// What runs in the background: the agent's background agents and shells.
|
|
1023
|
+
backgroundWork() {
|
|
1024
|
+
const agents = this.runtime.tasks.list().map((t) => ({ id: t.id, kind: 'agent', description: t.description, status: t.status, startedAt: t.started }));
|
|
1025
|
+
const shells = listBackgroundShells().map((s) => ({ id: s.id, kind: 'shell', description: s.description || s.command, status: s.status, startedAt: s.startedAt || null }));
|
|
1026
|
+
return [...agents, ...shells];
|
|
1027
|
+
}
|
|
1028
|
+
|
|
888
1029
|
// The dialog open in the terminal, for the page to answer (options by index: values need not be strings).
|
|
889
1030
|
remoteDialog() {
|
|
890
1031
|
const d = this.dialogs[0];
|
|
891
1032
|
if (!d) return null;
|
|
892
1033
|
d.remoteId ??= ++this.remoteDialogs;
|
|
893
1034
|
const base = { id: d.remoteId, title: d.title || '', question: d.question || '', body: d.body || [], markdown: d.markdown || null };
|
|
1035
|
+
// a question answered with typed text (TextDialog): a text box on the page, answered with {id, text}
|
|
1036
|
+
if (d.input) return { ...base, input: { placeholder: d.input.placeholder || '', value: d.value || '', multiline: Boolean(d.input.multiline) } };
|
|
894
1037
|
if (!Array.isArray(d.options)) return base;
|
|
895
1038
|
return { ...base, multi: Boolean(d.multi), options: d.options.map((o) => ({ label: String(o.label ?? ''), description: o.description || '', other: o.value === '__other__' })) };
|
|
896
1039
|
}
|
|
@@ -899,7 +1042,13 @@ export class App {
|
|
|
899
1042
|
const d = this.dialogs[0];
|
|
900
1043
|
if (!d || d.remoteId !== id) throw new Error('That question is no longer open.');
|
|
901
1044
|
if (cancel) { d.resolve(d.cancelValue); return {}; }
|
|
902
|
-
if (
|
|
1045
|
+
if (d.input) {
|
|
1046
|
+
if (typeof text !== 'string') throw new Error('Type an answer first.');
|
|
1047
|
+
d.resolve(text);
|
|
1048
|
+
this.screen.schedule();
|
|
1049
|
+
return {};
|
|
1050
|
+
}
|
|
1051
|
+
if (!Array.isArray(d.options)) throw new Error('This dialog cannot be answered from the page.');
|
|
903
1052
|
const valueAt = (i) => {
|
|
904
1053
|
const o = d.options[i];
|
|
905
1054
|
if (!Number.isInteger(i) || !o || o.value === '__other__') throw new Error('No such option.');
|
|
@@ -918,19 +1067,89 @@ export class App {
|
|
|
918
1067
|
return {};
|
|
919
1068
|
}
|
|
920
1069
|
|
|
921
|
-
// A message from the page: as if typed in the input box.
|
|
922
|
-
|
|
923
|
-
|
|
1070
|
+
// A message from the page: as if typed in the input box, its images as if pasted there (alt+v). Images alone go
|
|
1071
|
+
// as their placeholders, which is what the input box sends for them.
|
|
1072
|
+
remoteSend(text, images) {
|
|
1073
|
+
const pictures = remoteImages(images);
|
|
1074
|
+
let value = String(text ?? '').replace(/\r\n/g, '\n');
|
|
1075
|
+
if (!value.trim() && pictures.length) value = pictures.map((_, i) => `[Image #${i + 1}]`).join(' ');
|
|
924
1076
|
if (!value.trim()) throw new Error('The message is empty.');
|
|
925
1077
|
if (this.exiting) throw new Error('The session is ending.');
|
|
926
1078
|
if (this.busy && value.trim().startsWith('/')) throw new Error('Commands wait until the current task is done (or stopped).');
|
|
927
1079
|
if (this.dialogs.length && !this.busy) throw new Error('A question is open: answer it first.');
|
|
928
1080
|
const queued = this.busy;
|
|
929
|
-
this.onSubmit(value, value);
|
|
1081
|
+
this.onSubmit(value, value, pictures);
|
|
930
1082
|
this.screen.schedule();
|
|
931
1083
|
return { queued };
|
|
932
1084
|
}
|
|
933
1085
|
|
|
1086
|
+
// For the page's model, effort and mode menus: what /model and /effort offer, in plain text, and what is chosen
|
|
1087
|
+
// now (as the status says it).
|
|
1088
|
+
async remoteOptions() {
|
|
1089
|
+
const cfg = this.config;
|
|
1090
|
+
const [models, efforts] = await Promise.all([modelChoices(cfg), effortChoices(cfg)]);
|
|
1091
|
+
const { effort } = modelInfo(cfg);
|
|
1092
|
+
return { model: cfg.mainModel.id, models, effort: effort || defaultEffort(cfg.mainModel.id, cfg), efforts: efforts.options };
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
// For the page's input box: what the input box here would suggest (/commands, @files, &sessions), in plain text,
|
|
1096
|
+
// without anything happening here. Sessions on the other computers are asked for first when the list is old.
|
|
1097
|
+
async remoteSuggest(body = {}) {
|
|
1098
|
+
const text = String(body.text ?? '');
|
|
1099
|
+
const cursor = Number.isInteger(body.cursor) ? Math.max(0, Math.min(text.length, body.cursor)) : text.length;
|
|
1100
|
+
if (/(^|\s)[&&][^\s&&]*$/u.test(text.slice(0, cursor)) && this.remote?.online && Date.now() - this.remotePeersAt > 10_000) {
|
|
1101
|
+
await Promise.race([this.refreshRemotePeers(), new Promise((r) => setTimeout(r, 3000))]);
|
|
1102
|
+
}
|
|
1103
|
+
const found = this.suggest(text, cursor, { quiet: true });
|
|
1104
|
+
if (!found?.items?.length) return { items: [] };
|
|
1105
|
+
const plain = (s) => (s == null ? '' : stripAnsi(String(s)));
|
|
1106
|
+
return {
|
|
1107
|
+
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) })),
|
|
1108
|
+
from: found.from,
|
|
1109
|
+
to: found.to,
|
|
1110
|
+
};
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
// For the page's directory browser (/cd): the computer service's listing (see host.js), "" being this session's
|
|
1114
|
+
// working directory.
|
|
1115
|
+
remoteList(body = {}) {
|
|
1116
|
+
const wanted = typeof body.path === 'string' && body.path.trim() ? body.path : this.cwd;
|
|
1117
|
+
return listDirectory(wanted, {
|
|
1118
|
+
recent: () => {
|
|
1119
|
+
if (!this.recentDirs || Date.now() - this.recentDirs.at > 30_000) this.recentDirs = { at: Date.now(), list: recentDirectories() };
|
|
1120
|
+
return this.recentDirs.list;
|
|
1121
|
+
},
|
|
1122
|
+
});
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
// For the page's "the whole output": the full result of the tool call `id` ({text, truncated}, at most a MB): the
|
|
1126
|
+
// file it was saved to when it was too long for the conversation, or cleared from it later; what it printed so
|
|
1127
|
+
// far while it runs.
|
|
1128
|
+
remoteOutput({ id } = {}) {
|
|
1129
|
+
if (typeof id !== 'string' || !id) throw new Error('Which tool call?');
|
|
1130
|
+
const MAX = 1024 * 1024;
|
|
1131
|
+
const cut = (text, running = false) => ({ text: text.length > MAX ? text.slice(0, MAX) : text, truncated: text.length > MAX, ...(running ? { running } : {}) });
|
|
1132
|
+
let result = null;
|
|
1133
|
+
for (const m of this.agent.messages) {
|
|
1134
|
+
if (m.role !== 'user' || !Array.isArray(m.content)) continue;
|
|
1135
|
+
for (const b of m.content) if (b.type === 'tool_result' && b.tool_use_id === id) result = b;
|
|
1136
|
+
}
|
|
1137
|
+
if (!result) {
|
|
1138
|
+
const live = this.active.find((e) => e.tu?.id === id);
|
|
1139
|
+
if (live) return cut(String(live.progress || ''), true);
|
|
1140
|
+
throw new Error('There is no such tool call in this conversation.');
|
|
1141
|
+
}
|
|
1142
|
+
let text = typeof result.content === 'string' ? result.content
|
|
1143
|
+
: (Array.isArray(result.content) ? result.content : []).map((b) => (b.type === 'text' ? b.text : b.type === 'image' ? '[image]' : '')).join('\n');
|
|
1144
|
+
// saved whole in the projects' tool-results (see persistLargeOutput and the Bash tool): read from there
|
|
1145
|
+
const saved = /(?:saved to:?|saved at)\s+(\S+?\.txt)\b/.exec(text)?.[1];
|
|
1146
|
+
const results = path.join(CONFIG_DIR, 'projects');
|
|
1147
|
+
if (saved && path.resolve(saved).startsWith(results + path.sep) && path.resolve(saved).includes(`${path.sep}tool-results${path.sep}`)) {
|
|
1148
|
+
try { text = fs.readFileSync(saved, 'utf8'); } catch { /* the reference is what there is */ }
|
|
1149
|
+
}
|
|
1150
|
+
return cut(text);
|
|
1151
|
+
}
|
|
1152
|
+
|
|
934
1153
|
remoteInterrupt() {
|
|
935
1154
|
for (const d of this.dialogs.splice(0)) d.resolve(d.cancelValue);
|
|
936
1155
|
this.interrupt();
|
|
@@ -958,16 +1177,17 @@ export class App {
|
|
|
958
1177
|
// Restart as soon as nothing is running: at once when idle, otherwise when the current turn ends (the
|
|
959
1178
|
// turn that asked for it still has to be answered and saved). `continueTurn`: the model gets a note in
|
|
960
1179
|
// the new process and goes on by itself. Returns {ok, message}.
|
|
961
|
-
|
|
1180
|
+
// `cwd`: the session goes on in that directory (/cd).
|
|
1181
|
+
requestRestart({ reason = '', then = '', continueTurn = false, force = false, cwd = null } = {}) {
|
|
962
1182
|
if (!canRestart()) return { ok: false, message: 'This session cannot restart itself.' };
|
|
963
1183
|
const now = Date.now();
|
|
964
1184
|
const recent = this.restarts.filter((t) => now - t < RESTART_WINDOW_MS);
|
|
965
|
-
if (recent.length >= MAX_RESTARTS) {
|
|
1185
|
+
if (recent.length >= MAX_RESTARTS && !cwd) {
|
|
966
1186
|
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
1187
|
}
|
|
968
1188
|
const blockers = this.restartBlockers();
|
|
969
|
-
if (blockers.length && !force) return { ok: false, message:
|
|
970
|
-
this.restartRequest = { reason, then, continueTurn };
|
|
1189
|
+
if (blockers.length && !force) return { ok: false, message: `${cwd ? 'Changing the directory restarts the session, which would stop' : 'A restart would kill'}: ${blockers.join('; ')}.` };
|
|
1190
|
+
this.restartRequest = { reason, then, continueTurn, cwd };
|
|
971
1191
|
this.screen.schedule();
|
|
972
1192
|
if (!this.busy) this.restartNow();
|
|
973
1193
|
return { ok: true };
|
|
@@ -979,36 +1199,57 @@ export class App {
|
|
|
979
1199
|
this.restartRequest = null;
|
|
980
1200
|
const cfg = this.config;
|
|
981
1201
|
const now = Date.now();
|
|
1202
|
+
// /cd: the conversation's file goes along to the new directory's project (see moveSession); the old one is
|
|
1203
|
+
// removed once the next process is sure to find the new one
|
|
1204
|
+
let moved = null;
|
|
1205
|
+
if (request.cwd) {
|
|
1206
|
+
try { moved = moveSession(this.store.file, this.store.id, request.cwd); } catch (e) { this.notice(`Could not change the directory: ${e.message}`, 'warn'); return; }
|
|
1207
|
+
}
|
|
982
1208
|
const state = {
|
|
983
1209
|
at: now,
|
|
984
1210
|
reason: request.reason || '',
|
|
985
1211
|
continueWith: request.continueTurn ? restartNote(request) : '',
|
|
1212
|
+
cwd: request.cwd || this.cwd,
|
|
1213
|
+
changedDirectory: Boolean(request.cwd),
|
|
986
1214
|
sessionId: this.store.id,
|
|
987
|
-
sessionFile: this.store.file,
|
|
1215
|
+
sessionFile: moved?.file || this.store.file,
|
|
988
1216
|
modelOverride: cfg.modelOverride,
|
|
989
1217
|
effortOverride: cfg.effortOverride,
|
|
990
1218
|
effortBoost: cfg.effortBoost,
|
|
991
|
-
mode: this.runtime.modes.mode,
|
|
992
1219
|
todos: this.agent.todos,
|
|
993
1220
|
draft: this.editor.text,
|
|
994
1221
|
screenHistory: this.screen.history.slice(-3000),
|
|
995
1222
|
draftCursor: this.editor.cursor,
|
|
996
1223
|
queue: this.queue.map((q) => ({ text: q.text, images: q.images || [] })),
|
|
997
1224
|
checkpoints: this.runtime.checkpoints.snapshot(),
|
|
998
|
-
|
|
999
|
-
|
|
1225
|
+
// a /cd is the user's: it does not count towards the restarts that look like a loop
|
|
1226
|
+
restarts: [...this.restarts.filter((t) => now - t < RESTART_WINDOW_MS), ...(request.cwd ? [] : [now])],
|
|
1227
|
+
// a name given with /rename or --name stays; the one taken from the directory follows it
|
|
1228
|
+
peerName: request.cwd && !this.customTitle ? null : this.peers?.name || this.sessionName,
|
|
1000
1229
|
peerId: this.peers?.id,
|
|
1001
1230
|
remote: this.remote?.handoff() || null,
|
|
1002
1231
|
};
|
|
1003
1232
|
try {
|
|
1004
1233
|
writeRestartState(state);
|
|
1005
1234
|
} catch (e) {
|
|
1235
|
+
moved?.undo();
|
|
1006
1236
|
this.notice(`Could not restart: ${e.message}`, 'warn');
|
|
1007
1237
|
return;
|
|
1008
1238
|
}
|
|
1239
|
+
moved?.commit();
|
|
1009
1240
|
this.exit(RESTART_EXIT_CODE, { restart: true });
|
|
1010
1241
|
}
|
|
1011
1242
|
|
|
1243
|
+
// /cd: the session goes on in `dir` (an existing directory). It restarts there, so that everything that belongs to
|
|
1244
|
+
// a project is that directory's: its settings and CLAUDE.md, its memory, the system prompt's directory and git
|
|
1245
|
+
// state, the @ file index, the input history and where the conversation is kept. The conversation, the remote
|
|
1246
|
+
// page's id and a name given with /rename stay. Returns {ok, message}.
|
|
1247
|
+
changeDirectory(dir) {
|
|
1248
|
+
if (this.busy) return { ok: false, message: 'Wait for the current task to finish (or press Esc) before changing the directory.' };
|
|
1249
|
+
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.' };
|
|
1250
|
+
return this.requestRestart({ reason: `working directory ${dir}`, cwd: dir });
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1012
1253
|
// In the process a restart started: take up the session where the one before it left it.
|
|
1013
1254
|
resumeAfterRestart(state, resumable) {
|
|
1014
1255
|
const cfg = this.config;
|
|
@@ -1019,7 +1260,6 @@ export class App {
|
|
|
1019
1260
|
if ('effortOverride' in state) cfg.effortOverride = state.effortOverride || null;
|
|
1020
1261
|
// The Effort tool's level holds for the request the restart continues, not for the user's next one.
|
|
1021
1262
|
if (state.effortBoost) { cfg.effortBoost = state.effortBoost; cfg.effortBoostKeepNext = Boolean(state.continueWith); }
|
|
1022
|
-
if (state.mode === 'plan') this.runtime.modes.setMode('plan');
|
|
1023
1263
|
this.restarts = (Array.isArray(state.restarts) ? state.restarts : []).filter((t) => Number.isFinite(t));
|
|
1024
1264
|
if (resumable) {
|
|
1025
1265
|
this.loadSession(state.sessionFile, state.sessionId, { quiet: true });
|
|
@@ -1030,6 +1270,13 @@ export class App {
|
|
|
1030
1270
|
// Fullscreen starts on an empty screen: without what the process before showed (an older version, or one
|
|
1031
1271
|
// that ran classic), the conversation is drawn again from the session.
|
|
1032
1272
|
if (this.screen.full && resumable && !Array.isArray(state.screenHistory)) this.printTranscript(this.agent.messages.slice(-80));
|
|
1273
|
+
if (state.changedDirectory) {
|
|
1274
|
+
// /cd: the line it answers with, here and on the remote page (which starts again from the conversation)
|
|
1275
|
+
const line = `Working directory: ${this.cwd}`;
|
|
1276
|
+
this.screen.log(line, '');
|
|
1277
|
+
this.seedOutput = [line];
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1033
1280
|
this.screen.log(c.dim(`↻ Restarted${state.reason ? `: ${state.reason}` : ''}${state.continueWith ? ' · continuing' : ''}`), '');
|
|
1034
1281
|
}
|
|
1035
1282
|
|
|
@@ -1213,6 +1460,7 @@ export class App {
|
|
|
1213
1460
|
// Fullscreen (see screen.js) unless CLAUDE_PRO_TUI=default, as Claude Code's /tui: the input box fixed at the
|
|
1214
1461
|
// bottom of the window, the conversation scrolled inside the program. Not in the tests that drive the App.
|
|
1215
1462
|
fullscreenWanted() {
|
|
1463
|
+
if (this.headless) return true; // `claude-pro attach` gets the whole screen, drawn again when it comes
|
|
1216
1464
|
const mode = String(this.config.env.CLAUDE_PRO_TUI || (this.driven ? 'default' : 'fullscreen')).toLowerCase();
|
|
1217
1465
|
return mode === 'fullscreen' && this.stdout.isTTY !== false;
|
|
1218
1466
|
}
|
|
@@ -1289,7 +1537,6 @@ export class App {
|
|
|
1289
1537
|
}
|
|
1290
1538
|
if (key.ctrl && key.name === 'f') { this.openFind(); return; }
|
|
1291
1539
|
if (this.finder) { this.findKey(str, key); this.screen.schedule(); return; }
|
|
1292
|
-
if (key.name === 'tab' && key.shift) { this.runtime.modes.toggle(); this.screen.schedule(); return; }
|
|
1293
1540
|
// alt+v like Claude Code on Windows (ctrl+v is the terminal's own text paste there).
|
|
1294
1541
|
if ((key.meta || key.ctrl) && key.name === 'v') { this.pasteImage(); return; }
|
|
1295
1542
|
if (key.ctrl && key.name === 'o') {
|
|
@@ -1299,13 +1546,21 @@ export class App {
|
|
|
1299
1546
|
}
|
|
1300
1547
|
if (key.ctrl && key.name === 't') { this.showTodos = !this.showTodos; this.screen.schedule(); return; }
|
|
1301
1548
|
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.
|
|
1549
|
+
if (key.ctrl && key.name === 'd' && !this.editor.text) { this.keyboardExit(); return; }
|
|
1303
1550
|
if (key.name === 'escape' && this.busy) { this.interrupt(); return; }
|
|
1304
1551
|
this.exitArmed = 0;
|
|
1305
1552
|
this.editor.handleKey(str, key);
|
|
1306
1553
|
this.screen.schedule();
|
|
1307
1554
|
}
|
|
1308
1555
|
|
|
1556
|
+
// ctrl+c twice, ctrl+d: the end of the session, except in a background one, where the keys come from
|
|
1557
|
+
// `claude-pro attach` and leaving it is detaching (/exit ends the session there).
|
|
1558
|
+
keyboardExit() {
|
|
1559
|
+
if (!this.headless) { this.exit(0); return; }
|
|
1560
|
+
this.exitArmed = 0;
|
|
1561
|
+
this.flash('This session runs in the background: ctrl+] detaches from it, /exit ends it');
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1309
1564
|
onCtrlC() {
|
|
1310
1565
|
if (this.dialogs.length) {
|
|
1311
1566
|
// Cancel the dialog and interrupt the run.
|
|
@@ -1315,7 +1570,7 @@ export class App {
|
|
|
1315
1570
|
}
|
|
1316
1571
|
if (this.busy) { this.interrupt(); return; }
|
|
1317
1572
|
if (this.editor.text) { this.editor.discard(); this.screen.schedule(); return; }
|
|
1318
|
-
if (Date.now() - this.exitArmed < 1500) { this.
|
|
1573
|
+
if (Date.now() - this.exitArmed < 1500) { this.keyboardExit(); return; }
|
|
1319
1574
|
this.exitArmed = Date.now();
|
|
1320
1575
|
this.screen.schedule();
|
|
1321
1576
|
setTimeout(() => this.screen.schedule(), 1600);
|
|
@@ -1327,7 +1582,8 @@ export class App {
|
|
|
1327
1582
|
this.screen.schedule();
|
|
1328
1583
|
}
|
|
1329
1584
|
|
|
1330
|
-
|
|
1585
|
+
// `quiet`: for the page (remoteSuggest), nothing shows here.
|
|
1586
|
+
suggest(text, cursor, { quiet = false } = {}) {
|
|
1331
1587
|
if (text.startsWith('/') && !/\s/.test(text) && cursor === text.length) {
|
|
1332
1588
|
const q = text.slice(1).toLowerCase();
|
|
1333
1589
|
const all = [...this.commands.values()].filter((cmd) => !cmd.hidden);
|
|
@@ -1358,12 +1614,12 @@ export class App {
|
|
|
1358
1614
|
// `&name`: the other sessions, on this computer and (through the gateway) on the account's others. At the start
|
|
1359
1615
|
// it sends them the message; elsewhere it names them (/sendfile, or for the model).
|
|
1360
1616
|
const amp = /(^|\s)[&&]([^\s&&]*)$/u.exec(before);
|
|
1361
|
-
if (amp) return this.peerSuggestions(amp[2], cursor, amp.index === 0 && !amp[1]);
|
|
1617
|
+
if (amp) return this.peerSuggestions(amp[2], cursor, amp.index === 0 && !amp[1], { quiet });
|
|
1362
1618
|
return null;
|
|
1363
1619
|
}
|
|
1364
1620
|
|
|
1365
|
-
peerSuggestions(q, cursor, atStart = true) {
|
|
1366
|
-
if (this.remote?.online && Date.now() - this.remotePeersAt > 10_000) {
|
|
1621
|
+
peerSuggestions(q, cursor, atStart = true, { quiet = false } = {}) {
|
|
1622
|
+
if (!quiet && this.remote?.online && Date.now() - this.remotePeersAt > 10_000) {
|
|
1367
1623
|
this.refreshRemotePeers().then(() => {
|
|
1368
1624
|
if (!/[&&][^\s&&]*$/u.test(this.editor.text.slice(0, this.editor.cursor))) return;
|
|
1369
1625
|
this.editor.refreshSuggestions();
|
|
@@ -1378,7 +1634,7 @@ export class App {
|
|
|
1378
1634
|
.map((p) => ({ value: '&' + p.label, label: `&${p.label}`, description: `${p.machine} · ${p.cwd}${p.busy ? ' · busy' : ''}` })),
|
|
1379
1635
|
];
|
|
1380
1636
|
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)');
|
|
1637
|
+
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
1638
|
return null;
|
|
1383
1639
|
}
|
|
1384
1640
|
return { items, from: cursor - q.length - 1, to: cursor };
|
|
@@ -1439,12 +1695,12 @@ export class App {
|
|
|
1439
1695
|
shortcutsHelp() {
|
|
1440
1696
|
const rows = [
|
|
1441
1697
|
['! for bash mode', 'double tap esc to clear input'],
|
|
1442
|
-
['/ for commands', '
|
|
1443
|
-
['@ for file paths, & for other sessions', 'ctrl +
|
|
1698
|
+
['/ for commands', 'ctrl + o to toggle verbose output'],
|
|
1699
|
+
['@ for file paths, & for other sessions', 'ctrl + f to find in the conversation'],
|
|
1444
1700
|
['PgUp/PgDn, wheel to scroll', 'ctrl + home/end to the top/bottom'],
|
|
1445
1701
|
['# to memorize', 'ctrl + t to toggle todos'],
|
|
1446
1702
|
['\\⏎ or alt+⏎ for newline', 'ctrl + l to redraw, ctrl + d to exit'],
|
|
1447
|
-
['alt + v to paste an image', '
|
|
1703
|
+
['alt + v to paste an image', ''],
|
|
1448
1704
|
];
|
|
1449
1705
|
return rows.map(([a, b]) => c.dim(' ' + padEnd(a, 30) + b));
|
|
1450
1706
|
}
|
|
@@ -1821,7 +2077,9 @@ export class App {
|
|
|
1821
2077
|
loadSession(file, id, { quiet = false } = {}) {
|
|
1822
2078
|
const loaded = SessionStore.load(file);
|
|
1823
2079
|
this.previousSession = null; // the conversation before a /clear: resuming another one ends the offer
|
|
2080
|
+
this.seedOutput = [];
|
|
1824
2081
|
this.store = new SessionStore(this.cwd, id);
|
|
2082
|
+
this.peers?.update(); // the conversation, in the registry
|
|
1825
2083
|
this.topic = loaded.topic;
|
|
1826
2084
|
this.customTitle = loaded.name;
|
|
1827
2085
|
// a conversation that was given a name brings it back: the other sessions reach this one by it again
|
|
@@ -1854,7 +2112,9 @@ export class App {
|
|
|
1854
2112
|
for (const m of messages) {
|
|
1855
2113
|
const blocks = typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : m.content;
|
|
1856
2114
|
for (const b of blocks) {
|
|
1857
|
-
|
|
2115
|
+
const bash = m.role === 'user' && b.type === 'text' ? bashModeLines(b.text) : null;
|
|
2116
|
+
if (bash) this.screen.log(bash, '');
|
|
2117
|
+
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
2118
|
if (m.role === 'assistant' && b.type === 'text') this.screen.log(renderMarkdown(b.text, { width: this.width - 1, firstPrefix: `${DOT} `, indent: ' ' }), '');
|
|
1859
2119
|
if (m.role === 'assistant' && b.type === 'tool_use') {
|
|
1860
2120
|
const tool = toolMap.get(b.name) || { name: b.name };
|
|
@@ -1867,6 +2127,8 @@ export class App {
|
|
|
1867
2127
|
|
|
1868
2128
|
newSession() {
|
|
1869
2129
|
this.store = new SessionStore(this.cwd);
|
|
2130
|
+
this.peers?.update();
|
|
2131
|
+
this.seedOutput = [];
|
|
1870
2132
|
this.topic = null;
|
|
1871
2133
|
this.customTitle = null;
|
|
1872
2134
|
this.firstPrompt = null;
|
|
@@ -1890,27 +2152,6 @@ export class App {
|
|
|
1890
2152
|
});
|
|
1891
2153
|
}
|
|
1892
2154
|
|
|
1893
|
-
async approvePlan(plan) {
|
|
1894
|
-
this.flushStreaming();
|
|
1895
|
-
const md = renderMarkdown(plan, { width: this.width - 8 });
|
|
1896
|
-
const max = Math.max(8, this.screen.height - 14);
|
|
1897
|
-
const body = md.length > max ? [...md.slice(0, max), c.dim(`… +${md.length - max} lines (the full plan is printed above)`)] : md;
|
|
1898
|
-
if (md.length > max) this.logLocal(c.plan(`${DOT} Plan:`), ...md.map((l) => ' ' + l), '');
|
|
1899
|
-
const dialog = new SelectDialog({
|
|
1900
|
-
title: 'Ready to code?',
|
|
1901
|
-
body: ["Here is the plan:", '', ...body],
|
|
1902
|
-
question: 'Would you like to proceed?',
|
|
1903
|
-
color: c.plan,
|
|
1904
|
-
cancelValue: 'reject',
|
|
1905
|
-
options: [
|
|
1906
|
-
{ label: 'Yes, start coding', value: 'full' },
|
|
1907
|
-
{ label: 'No, keep planning', value: 'reject' },
|
|
1908
|
-
],
|
|
1909
|
-
});
|
|
1910
|
-
dialog.markdown = plan; // the remote page shows the whole plan
|
|
1911
|
-
return await this.showDialog(dialog);
|
|
1912
|
-
}
|
|
1913
|
-
|
|
1914
2155
|
async askQuestion(q) {
|
|
1915
2156
|
const answer = await this.showDialog(new SelectDialog({
|
|
1916
2157
|
title: q.header || 'Question',
|
|
@@ -2117,7 +2358,6 @@ export class App {
|
|
|
2117
2358
|
}
|
|
2118
2359
|
};
|
|
2119
2360
|
return {
|
|
2120
|
-
approvePlan: async () => 'reject',
|
|
2121
2361
|
askQuestion: async () => null,
|
|
2122
2362
|
notice: (text, kind) => app.notice(`[${def.name}] ${text}`, kind),
|
|
2123
2363
|
toolStart(tu, tool, input, agent) {
|
|
@@ -2315,13 +2555,11 @@ export class App {
|
|
|
2315
2555
|
}
|
|
2316
2556
|
|
|
2317
2557
|
footer(w) {
|
|
2318
|
-
const mode = this.runtime.modes.mode;
|
|
2319
2558
|
let left;
|
|
2320
2559
|
const flash = this.flashMessage && Date.now() < this.flashMessage.until ? this.flashMessage : null;
|
|
2321
2560
|
if (this.exitArmed && Date.now() - this.exitArmed < 1500) left = c.dim(' Press Ctrl-C again to exit');
|
|
2322
2561
|
else if (flash) left = (flash.kind === 'warn' ? c.yellow : c.dim)(' ' + truncate(flash.text, w - 4));
|
|
2323
2562
|
else if (this.restartRequest) left = c.dim(' ↻ restarting when this turn ends');
|
|
2324
|
-
else if (mode === 'plan') left = ' ' + c.plan('⏸ plan mode on (read-only)') + c.dim(' (shift+tab to leave)');
|
|
2325
2563
|
else if (this.editor.mode === 'bash') left = c.magenta(' ! for bash mode');
|
|
2326
2564
|
else if (this.editor.mode === 'memory') left = c.blue(' # to memorize');
|
|
2327
2565
|
else left = c.dim(' ? for shortcuts');
|
|
@@ -2361,7 +2599,10 @@ export class App {
|
|
|
2361
2599
|
}
|
|
2362
2600
|
|
|
2363
2601
|
export async function runRepl({ flags, cwd, initialPrompt }) {
|
|
2364
|
-
|
|
2602
|
+
// --headless: a background session (see vterm.js), its log on stdout
|
|
2603
|
+
const vterm = flags.headless ? new VirtualTerminal() : null;
|
|
2604
|
+
if (vterm) process.stdout.write(`${new Date().toISOString()} claude-pro ${VERSION} background session in ${cwd} (pid ${process.pid})\n`);
|
|
2605
|
+
const app = new App({ flags, cwd, vterm });
|
|
2365
2606
|
process.on('uncaughtException', (e) => {
|
|
2366
2607
|
app.restoreTerminal();
|
|
2367
2608
|
process.stderr.write(`\nUnexpected error: ${e?.stack || e}\n`);
|