@yanzc/claude-pro 0.5.9 → 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/README.md +375 -357
- package/package.json +1 -1
- package/src/agents.js +3 -1
- package/src/attach.js +132 -0
- package/src/background.js +424 -0
- package/src/commands.js +119 -80
- package/src/config.js +16 -7
- package/src/connect.js +79 -0
- package/src/history.js +94 -0
- package/src/host.js +1410 -0
- package/src/main.js +54 -10
- package/src/peers.js +290 -215
- package/src/prompts.js +74 -58
- package/src/qr.js +1 -1
- package/src/remote.js +54 -17
- package/src/runtime.js +14 -8
- package/src/session.js +29 -2
- package/src/supervisor.js +6 -3
- package/src/tools/bash.js +5 -10
- package/src/tools/files.js +6 -10
- package/src/tools/index.js +1 -1
- package/src/tools/interaction.js +8 -37
- package/src/tools/search.js +15 -10
- package/src/tools/task.js +29 -7
- package/src/ui/dialogs.js +48 -0
- package/src/ui/render.js +10 -0
- package/src/ui/repl.js +393 -79
- package/src/ui/vterm.js +62 -0
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,
|
|
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
|
-
import { readGatewayLogin, formatUsd } from '../gateway.js';
|
|
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 {
|
|
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;
|
|
@@ -187,7 +218,9 @@ export class App {
|
|
|
187
218
|
this.remoteMuted = 0; // > 0 while printing something the page is told about in its own terms
|
|
188
219
|
this.remoteDialogs = 0;
|
|
189
220
|
this.remoteStarting = null;
|
|
190
|
-
this.
|
|
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)
|
|
223
|
+
this.selfCheck = selfCheck;
|
|
191
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)
|
|
192
225
|
this.customTitle = null; // the conversation's name given with /rename: the title, instead of the topic
|
|
193
226
|
this.remotePeers = []; // the account's sessions on other computers, as last listed by the gateway (see peers.js)
|
|
@@ -201,8 +234,14 @@ export class App {
|
|
|
201
234
|
this.store = new SessionStore(cwd);
|
|
202
235
|
// What the terminal prints goes to the remote page too, except what it is told about as events.
|
|
203
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
|
+
}
|
|
204
243
|
if (!this.remote || this.remoteMuted) return;
|
|
205
|
-
this.remote.output(
|
|
244
|
+
this.remote.output(lines());
|
|
206
245
|
};
|
|
207
246
|
this.editor = new Editor({
|
|
208
247
|
history: loadHistory(cwd),
|
|
@@ -233,7 +272,7 @@ export class App {
|
|
|
233
272
|
// there (see screen.js). CLAUDE_PRO_PIN_INPUT=0 (here or in the settings) leaves it right below the output.
|
|
234
273
|
const pinOff = (v) => /^(0|false|no|off)$/i.test(v || '');
|
|
235
274
|
if (pinOff(process.env.CLAUDE_PRO_PIN_INPUT)) this.screen.pin = false;
|
|
236
|
-
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));
|
|
237
276
|
stdin.setEncoding('utf8');
|
|
238
277
|
this.stdout.write(ESC.bracketedPasteOn);
|
|
239
278
|
this.watchCopies();
|
|
@@ -279,6 +318,7 @@ export class App {
|
|
|
279
318
|
if (restart) this.resumeAfterRestart(restart, resumable);
|
|
280
319
|
else if (this.flags.resumeFile) this.loadSession(this.flags.resumeFile, this.flags.resumeId);
|
|
281
320
|
else if (this.flags.resume) await this.commands.get('resume').run('');
|
|
321
|
+
if (!restart && this.flags.name?.trim()) this.renameSession(this.flags.name); // --name, as /rename does
|
|
282
322
|
this.autoStartRemote(restart);
|
|
283
323
|
|
|
284
324
|
this.screen.setLive((w) => this.renderLive(w));
|
|
@@ -289,8 +329,9 @@ export class App {
|
|
|
289
329
|
}, 120);
|
|
290
330
|
if (restart) this.continueAfterRestart(restart);
|
|
291
331
|
else if (initialPrompt?.trim()) this.onSubmit(initialPrompt, initialPrompt);
|
|
292
|
-
// Nothing configured yet: the gateway is the default, and its login comes first, as in Claude Code.
|
|
293
|
-
|
|
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) {
|
|
294
335
|
Promise.resolve(this.commands.get('login').run('')).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
|
|
295
336
|
}
|
|
296
337
|
this.fileIndex.refresh();
|
|
@@ -300,6 +341,11 @@ export class App {
|
|
|
300
341
|
// and every few minutes while it runs, so that a release reaches a session that stays open for days
|
|
301
342
|
this.updateTimer = setInterval(() => { if (!this.exiting) this.autoUpdate({ quiet: true }); }, CHECK_EVERY_MS);
|
|
302
343
|
this.updateTimer.unref?.();
|
|
344
|
+
// online or offline as this computer's gateway login changes (/login or /logout in another window)
|
|
345
|
+
this.loginTimer = setInterval(() => this.syncRemote(), 10_000);
|
|
346
|
+
this.loginTimer.unref?.();
|
|
347
|
+
// the computer service (a process of its own, see host.js), once the session is up
|
|
348
|
+
setTimeout(() => this.ensureHost(), 3000).unref?.();
|
|
303
349
|
}
|
|
304
350
|
return new Promise((resolve) => { this.resolveExit = resolve; });
|
|
305
351
|
}
|
|
@@ -388,6 +434,7 @@ export class App {
|
|
|
388
434
|
this.runtime?.mcp.close();
|
|
389
435
|
this.peers?.close();
|
|
390
436
|
clearInterval(this.remotePeersTimer);
|
|
437
|
+
clearInterval(this.loginTimer);
|
|
391
438
|
const remoteClosed = this.remote?.close({ restarting: restart });
|
|
392
439
|
const u = this.agent?.totalUsage();
|
|
393
440
|
if (!restart && u && u.requests) {
|
|
@@ -396,6 +443,11 @@ export class App {
|
|
|
396
443
|
if (!restart && this.agent?.messages.length) this.screen.log(c.dim(`Resume this session with: ${APP_NAME} --resume ${this.store.id}`));
|
|
397
444
|
this.restoreTerminal({ handOver: restart });
|
|
398
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
|
+
}
|
|
399
451
|
this.resolveExit?.(code);
|
|
400
452
|
if (!this.noProcessExit) {
|
|
401
453
|
// with remote control on, the gateway is told first (at most a second and a half; see RemoteControl.close)
|
|
@@ -411,13 +463,68 @@ export class App {
|
|
|
411
463
|
async startPeer() {
|
|
412
464
|
if (this.driven || !peersEnabled()) return;
|
|
413
465
|
try {
|
|
414
|
-
this.peers = await new PeerNode({
|
|
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();
|
|
415
476
|
} catch (e) {
|
|
416
477
|
this.peers = null;
|
|
417
478
|
this.notice(`Other sessions cannot reach this one: ${e.message}`, 'warn');
|
|
418
479
|
}
|
|
419
480
|
}
|
|
420
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
|
+
|
|
421
528
|
// This session's name for the others.
|
|
422
529
|
peerLabel() { return this.peers?.name || this.sessionName || cleanName(path.basename(this.cwd)) || 'claude-pro'; }
|
|
423
530
|
|
|
@@ -451,12 +558,12 @@ export class App {
|
|
|
451
558
|
let found = resolvePeer(local, this.remotePeers, target);
|
|
452
559
|
if (!found.peer && !found.error && this.remote) found = resolvePeer(local, await this.refreshRemotePeers(), target);
|
|
453
560
|
if (!found.peer) {
|
|
454
|
-
const offline = this.remote ? '' : ' Sessions on your other computers can be reached once this one is online at the gateway (/login
|
|
561
|
+
const offline = this.remote ? '' : ' Sessions on your other computers can be reached once this one is online at the gateway (/login).';
|
|
455
562
|
throw new Error(found.error || `No running session called "${String(target).replace(/^[@&]/, '')}". /peers lists them.${offline}`);
|
|
456
563
|
}
|
|
457
564
|
peer = found.peer;
|
|
458
565
|
}
|
|
459
|
-
if (peer.remote && !this.remote) throw new Error(`&${peer.label} is on another computer, and this session is not online at the gateway (/
|
|
566
|
+
if (peer.remote && !this.remote) throw new Error(`&${peer.label} is on another computer, and this session is not online at the gateway (/status says why).`);
|
|
460
567
|
if (!peer.remote && !this.peers) throw new Error('Talking to other sessions on this computer is off (CLAUDE_PRO_PEERS=0).');
|
|
461
568
|
const send = async () => {
|
|
462
569
|
let r;
|
|
@@ -724,44 +831,94 @@ export class App {
|
|
|
724
831
|
this.remote?.emit({ t: 'user', text: images ? `${text}\n[${images} image${images === 1 ? '' : 's'}]` : String(text) });
|
|
725
832
|
}
|
|
726
833
|
|
|
727
|
-
//
|
|
728
|
-
//
|
|
729
|
-
//
|
|
730
|
-
|
|
834
|
+
// Whether this session should be online at the gateway (see remote.js): whenever this computer is logged in to
|
|
835
|
+
// it. CLAUDE_PRO_ONLINE=0 keeps it off (the self-check sets it); the tests, which drive the App themselves, go
|
|
836
|
+
// online only with CLAUDE_PRO_ONLINE=1.
|
|
837
|
+
onlineWanted() {
|
|
838
|
+
const env = this.config.env;
|
|
839
|
+
if (!onlineEnabled(env)) return false;
|
|
840
|
+
if (this.driven && !/^(1|true|yes|on)$/i.test(env.CLAUDE_PRO_ONLINE || '')) return false;
|
|
841
|
+
return Boolean(readGatewayLogin(this.config.gatewayUrl));
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
// Online at the gateway from the start, without holding the start up: when this computer is logged in to it; with
|
|
845
|
+
// --remote-id (a session the gateway's web page opened through claude-pro host: online at once, with the id the
|
|
846
|
+
// page waits for); and after a restart as before (with the same id, so that open pages and messages on their way
|
|
847
|
+
// find it again).
|
|
731
848
|
autoStartRemote(restart) {
|
|
732
|
-
const
|
|
733
|
-
if (
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
this.startRemote({ id: carried?.id, quiet: !explicit || Boolean(carried?.id), persistent: !explicit }).catch((e) => {
|
|
738
|
-
this.notice(`${explicit ? 'Remote control could not start' : 'This session could not go online at the gateway'}: ${e.message}${e.code === 'NO_GATEWAY_LOGIN' ? '' : ' (/rc tries again)'}`, 'warn');
|
|
849
|
+
const id = restart?.remote?.id || this.flags.remoteId || null;
|
|
850
|
+
if (!id && !this.onlineWanted()) return;
|
|
851
|
+
this.startRemote({ id }).catch((e) => {
|
|
852
|
+
if (e.code === 'NO_GATEWAY_LOGIN' && !this.flags.remoteId) return;
|
|
853
|
+
this.notice(`This session could not go online at the gateway: ${e.message}`, 'warn');
|
|
739
854
|
});
|
|
740
855
|
}
|
|
741
856
|
|
|
742
857
|
// Connect this session to the gateway (see remote.js): the web page and the sessions on the account's other
|
|
743
|
-
// computers reach it from then on. Needs the gateway login of /login (the provider
|
|
744
|
-
// {code: 'NO_GATEWAY_LOGIN'} without it.
|
|
745
|
-
// the background
|
|
746
|
-
startRemote({ id
|
|
858
|
+
// computers reach it from then on. Needs the gateway login of /login (the provider of the model requests can be
|
|
859
|
+
// another one); throws {code: 'NO_GATEWAY_LOGIN'} without it. A gateway that cannot be reached now is tried
|
|
860
|
+
// again in the background; one that refuses the key throws, and that key is not tried again (see syncRemote).
|
|
861
|
+
startRemote({ id } = {}) {
|
|
747
862
|
if (this.remote) return Promise.resolve(this.remote);
|
|
748
|
-
this.remoteStarting ??= this.connectRemote({ id
|
|
863
|
+
this.remoteStarting ??= this.connectRemote({ id }).finally(() => { this.remoteStarting = null; });
|
|
749
864
|
return this.remoteStarting;
|
|
750
865
|
}
|
|
751
866
|
|
|
752
|
-
|
|
867
|
+
// Online or offline as this computer's gateway login is now: after /login and /logout, and every few seconds (a
|
|
868
|
+
// login or a logout in another window, another account). Resolves with the connection, or null.
|
|
869
|
+
syncRemote() {
|
|
870
|
+
if (this.exiting) return Promise.resolve(null);
|
|
871
|
+
if (this.remoteStarting) return this.remoteStarting.catch(() => null);
|
|
753
872
|
const login = readGatewayLogin(this.config.gatewayUrl);
|
|
754
|
-
|
|
873
|
+
const r = this.remote;
|
|
874
|
+
// logged out, or another account: not this account's session any more
|
|
875
|
+
if (r && (!login || login.apiKey !== r.apiKey || normalizeGatewayUrl(login.url || this.config.gatewayUrl) !== normalizeGatewayUrl(r.base))) this.stopRemote();
|
|
876
|
+
if (this.remote) return Promise.resolve(this.remote);
|
|
877
|
+
if (!login || login.apiKey === this.remoteRefused || !(this.flags.remoteId || this.onlineWanted())) return Promise.resolve(null);
|
|
878
|
+
return this.startRemote().catch((e) => {
|
|
879
|
+
this.notice(`This session could not go online at the gateway: ${e.message}`, 'warn');
|
|
880
|
+
return null;
|
|
881
|
+
});
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
// The computer service (see host.js): started in the background when none runs, so that the gateway's web page can
|
|
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 } = {}) {
|
|
888
|
+
const env = this.config.env;
|
|
889
|
+
if (this.driven || this.selfCheck || process.env.NODE_TEST_CONTEXT || this.exiting) return;
|
|
890
|
+
if (!onlineEnabled(env) || !hostEnabled(env) || !readGatewayLogin(this.config.gatewayUrl)) return;
|
|
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 */ }
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
async connectRemote({ id }) {
|
|
899
|
+
const login = readGatewayLogin(this.config.gatewayUrl);
|
|
900
|
+
if (!login) throw Object.assign(new Error(`this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login logs in)`), { code: 'NO_GATEWAY_LOGIN' });
|
|
755
901
|
const remote = new RemoteControl({
|
|
756
902
|
gateway: { url: login.url || this.config.gatewayUrl, apiKey: login.apiKey },
|
|
757
903
|
id,
|
|
758
904
|
handlers: {
|
|
759
|
-
info: () => ({
|
|
760
|
-
|
|
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
|
+
],
|
|
761
914
|
status: () => this.remoteStatus(),
|
|
762
|
-
send: (text) => this.remoteSend(text),
|
|
915
|
+
send: (text, images) => this.remoteSend(text, images),
|
|
763
916
|
interrupt: () => this.remoteInterrupt(),
|
|
764
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),
|
|
765
922
|
peerMessage: (msg) => this.onPeerMessage(msg),
|
|
766
923
|
changed: () => {
|
|
767
924
|
this.screen.schedule();
|
|
@@ -770,13 +927,18 @@ export class App {
|
|
|
770
927
|
},
|
|
771
928
|
});
|
|
772
929
|
remote.account = login.account?.email || login.account?.name || null;
|
|
773
|
-
|
|
930
|
+
try {
|
|
931
|
+
await remote.start({ persistent: true });
|
|
932
|
+
} catch (e) {
|
|
933
|
+
if (e.status === 401 || e.status === 403) this.remoteRefused = login.apiKey;
|
|
934
|
+
throw e;
|
|
935
|
+
}
|
|
774
936
|
if (this.exiting) { remote.close(); return remote; }
|
|
775
937
|
this.remote = remote;
|
|
776
|
-
this.
|
|
938
|
+
this.remoteRefused = null;
|
|
939
|
+
this.peers?.update(); // its id at the gateway, in the registry
|
|
777
940
|
this.remotePeersTimer ??= setInterval(() => { if (this.remote?.online) this.refreshRemotePeers(); }, 60_000);
|
|
778
941
|
this.remotePeersTimer.unref?.();
|
|
779
|
-
if (!quiet) this.logLocal(this.remoteInfo({ fresh: true }));
|
|
780
942
|
this.screen.schedule();
|
|
781
943
|
return remote;
|
|
782
944
|
}
|
|
@@ -785,26 +947,24 @@ export class App {
|
|
|
785
947
|
this.remote?.close();
|
|
786
948
|
this.remote = null;
|
|
787
949
|
this.remotePeers = [];
|
|
788
|
-
this.remoteStopped = true;
|
|
789
950
|
this.screen.schedule();
|
|
790
951
|
}
|
|
791
952
|
|
|
792
|
-
//
|
|
793
|
-
|
|
953
|
+
// This session at the gateway, for /status: {text, url} (url: its page, once registered).
|
|
954
|
+
remoteState() {
|
|
794
955
|
const r = this.remote;
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
return lines;
|
|
956
|
+
if (r) {
|
|
957
|
+
const who = r.account ? ` as ${r.account}` : '';
|
|
958
|
+
const pages = r.viewers ? c.dim(` · ${r.viewers} page${r.viewers === 1 ? '' : 's'} open now`) : '';
|
|
959
|
+
const text = r.online ? `${c.green('online')}${who}${pages}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
|
|
960
|
+
return { text, url: r.url };
|
|
961
|
+
}
|
|
962
|
+
if (this.remoteStarting) return { text: 'connecting…', url: null };
|
|
963
|
+
const login = readGatewayLogin(this.config.gatewayUrl);
|
|
964
|
+
if (!login) return { text: c.dim(`offline: this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login)`), url: null };
|
|
965
|
+
if (login.apiKey === this.remoteRefused) return { text: c.red('offline: the gateway refused this computer\'s key (/logout, then /login)'), url: null };
|
|
966
|
+
if (!onlineEnabled(this.config.env)) return { text: c.dim('offline (CLAUDE_PRO_ONLINE=0)'), url: null };
|
|
967
|
+
return { text: c.dim('offline'), url: null };
|
|
808
968
|
}
|
|
809
969
|
|
|
810
970
|
// The state the page shows below the transcript; sent whenever it changes.
|
|
@@ -838,15 +998,44 @@ export class App {
|
|
|
838
998
|
name: this.peerLabel(),
|
|
839
999
|
tasks: this.runtime.tasks.running().length,
|
|
840
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',
|
|
841
1007
|
};
|
|
842
1008
|
}
|
|
843
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
|
+
|
|
844
1031
|
// The dialog open in the terminal, for the page to answer (options by index: values need not be strings).
|
|
845
1032
|
remoteDialog() {
|
|
846
1033
|
const d = this.dialogs[0];
|
|
847
1034
|
if (!d) return null;
|
|
848
1035
|
d.remoteId ??= ++this.remoteDialogs;
|
|
849
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) } };
|
|
850
1039
|
if (!Array.isArray(d.options)) return base;
|
|
851
1040
|
return { ...base, multi: Boolean(d.multi), options: d.options.map((o) => ({ label: String(o.label ?? ''), description: o.description || '', other: o.value === '__other__' })) };
|
|
852
1041
|
}
|
|
@@ -855,7 +1044,13 @@ export class App {
|
|
|
855
1044
|
const d = this.dialogs[0];
|
|
856
1045
|
if (!d || d.remoteId !== id) throw new Error('That question is no longer open.');
|
|
857
1046
|
if (cancel) { d.resolve(d.cancelValue); return {}; }
|
|
858
|
-
if (
|
|
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.');
|
|
859
1054
|
const valueAt = (i) => {
|
|
860
1055
|
const o = d.options[i];
|
|
861
1056
|
if (!Number.isInteger(i) || !o || o.value === '__other__') throw new Error('No such option.');
|
|
@@ -874,19 +1069,89 @@ export class App {
|
|
|
874
1069
|
return {};
|
|
875
1070
|
}
|
|
876
1071
|
|
|
877
|
-
// A message from the page: as if typed in the input box.
|
|
878
|
-
|
|
879
|
-
|
|
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(' ');
|
|
880
1078
|
if (!value.trim()) throw new Error('The message is empty.');
|
|
881
1079
|
if (this.exiting) throw new Error('The session is ending.');
|
|
882
1080
|
if (this.busy && value.trim().startsWith('/')) throw new Error('Commands wait until the current task is done (or stopped).');
|
|
883
1081
|
if (this.dialogs.length && !this.busy) throw new Error('A question is open: answer it first.');
|
|
884
1082
|
const queued = this.busy;
|
|
885
|
-
this.onSubmit(value, value);
|
|
1083
|
+
this.onSubmit(value, value, pictures);
|
|
886
1084
|
this.screen.schedule();
|
|
887
1085
|
return { queued };
|
|
888
1086
|
}
|
|
889
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
|
+
|
|
890
1155
|
remoteInterrupt() {
|
|
891
1156
|
for (const d of this.dialogs.splice(0)) d.resolve(d.cancelValue);
|
|
892
1157
|
this.interrupt();
|
|
@@ -914,16 +1179,17 @@ export class App {
|
|
|
914
1179
|
// Restart as soon as nothing is running: at once when idle, otherwise when the current turn ends (the
|
|
915
1180
|
// turn that asked for it still has to be answered and saved). `continueTurn`: the model gets a note in
|
|
916
1181
|
// the new process and goes on by itself. Returns {ok, message}.
|
|
917
|
-
|
|
1182
|
+
// `cwd`: the session goes on in that directory (/cd).
|
|
1183
|
+
requestRestart({ reason = '', then = '', continueTurn = false, force = false, cwd = null } = {}) {
|
|
918
1184
|
if (!canRestart()) return { ok: false, message: 'This session cannot restart itself.' };
|
|
919
1185
|
const now = Date.now();
|
|
920
1186
|
const recent = this.restarts.filter((t) => now - t < RESTART_WINDOW_MS);
|
|
921
|
-
if (recent.length >= MAX_RESTARTS) {
|
|
1187
|
+
if (recent.length >= MAX_RESTARTS && !cwd) {
|
|
922
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.` };
|
|
923
1189
|
}
|
|
924
1190
|
const blockers = this.restartBlockers();
|
|
925
|
-
if (blockers.length && !force) return { ok: false, message:
|
|
926
|
-
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 };
|
|
927
1193
|
this.screen.schedule();
|
|
928
1194
|
if (!this.busy) this.restartNow();
|
|
929
1195
|
return { ok: true };
|
|
@@ -935,12 +1201,20 @@ export class App {
|
|
|
935
1201
|
this.restartRequest = null;
|
|
936
1202
|
const cfg = this.config;
|
|
937
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
|
+
}
|
|
938
1210
|
const state = {
|
|
939
1211
|
at: now,
|
|
940
1212
|
reason: request.reason || '',
|
|
941
1213
|
continueWith: request.continueTurn ? restartNote(request) : '',
|
|
1214
|
+
cwd: request.cwd || this.cwd,
|
|
1215
|
+
changedDirectory: Boolean(request.cwd),
|
|
942
1216
|
sessionId: this.store.id,
|
|
943
|
-
sessionFile: this.store.file,
|
|
1217
|
+
sessionFile: moved?.file || this.store.file,
|
|
944
1218
|
modelOverride: cfg.modelOverride,
|
|
945
1219
|
effortOverride: cfg.effortOverride,
|
|
946
1220
|
effortBoost: cfg.effortBoost,
|
|
@@ -951,20 +1225,34 @@ export class App {
|
|
|
951
1225
|
draftCursor: this.editor.cursor,
|
|
952
1226
|
queue: this.queue.map((q) => ({ text: q.text, images: q.images || [] })),
|
|
953
1227
|
checkpoints: this.runtime.checkpoints.snapshot(),
|
|
954
|
-
|
|
955
|
-
|
|
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,
|
|
956
1232
|
peerId: this.peers?.id,
|
|
957
|
-
remote: this.remote?.handoff() ||
|
|
1233
|
+
remote: this.remote?.handoff() || null,
|
|
958
1234
|
};
|
|
959
1235
|
try {
|
|
960
1236
|
writeRestartState(state);
|
|
961
1237
|
} catch (e) {
|
|
1238
|
+
moved?.undo();
|
|
962
1239
|
this.notice(`Could not restart: ${e.message}`, 'warn');
|
|
963
1240
|
return;
|
|
964
1241
|
}
|
|
1242
|
+
moved?.commit();
|
|
965
1243
|
this.exit(RESTART_EXIT_CODE, { restart: true });
|
|
966
1244
|
}
|
|
967
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
|
+
|
|
968
1256
|
// In the process a restart started: take up the session where the one before it left it.
|
|
969
1257
|
resumeAfterRestart(state, resumable) {
|
|
970
1258
|
const cfg = this.config;
|
|
@@ -986,6 +1274,13 @@ export class App {
|
|
|
986
1274
|
// Fullscreen starts on an empty screen: without what the process before showed (an older version, or one
|
|
987
1275
|
// that ran classic), the conversation is drawn again from the session.
|
|
988
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
|
+
}
|
|
989
1284
|
this.screen.log(c.dim(`↻ Restarted${state.reason ? `: ${state.reason}` : ''}${state.continueWith ? ' · continuing' : ''}`), '');
|
|
990
1285
|
}
|
|
991
1286
|
|
|
@@ -1169,6 +1464,7 @@ export class App {
|
|
|
1169
1464
|
// Fullscreen (see screen.js) unless CLAUDE_PRO_TUI=default, as Claude Code's /tui: the input box fixed at the
|
|
1170
1465
|
// bottom of the window, the conversation scrolled inside the program. Not in the tests that drive the App.
|
|
1171
1466
|
fullscreenWanted() {
|
|
1467
|
+
if (this.headless) return true; // `claude-pro attach` gets the whole screen, drawn again when it comes
|
|
1172
1468
|
const mode = String(this.config.env.CLAUDE_PRO_TUI || (this.driven ? 'default' : 'fullscreen')).toLowerCase();
|
|
1173
1469
|
return mode === 'fullscreen' && this.stdout.isTTY !== false;
|
|
1174
1470
|
}
|
|
@@ -1255,13 +1551,21 @@ export class App {
|
|
|
1255
1551
|
}
|
|
1256
1552
|
if (key.ctrl && key.name === 't') { this.showTodos = !this.showTodos; this.screen.schedule(); return; }
|
|
1257
1553
|
if (key.ctrl && key.name === 'l') { if (this.screen.full) this.screen.repaint(); else this.screen.clearScreen(); return; }
|
|
1258
|
-
if (key.ctrl && key.name === 'd' && !this.editor.text) { this.
|
|
1554
|
+
if (key.ctrl && key.name === 'd' && !this.editor.text) { this.keyboardExit(); return; }
|
|
1259
1555
|
if (key.name === 'escape' && this.busy) { this.interrupt(); return; }
|
|
1260
1556
|
this.exitArmed = 0;
|
|
1261
1557
|
this.editor.handleKey(str, key);
|
|
1262
1558
|
this.screen.schedule();
|
|
1263
1559
|
}
|
|
1264
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
|
+
|
|
1265
1569
|
onCtrlC() {
|
|
1266
1570
|
if (this.dialogs.length) {
|
|
1267
1571
|
// Cancel the dialog and interrupt the run.
|
|
@@ -1271,7 +1575,7 @@ export class App {
|
|
|
1271
1575
|
}
|
|
1272
1576
|
if (this.busy) { this.interrupt(); return; }
|
|
1273
1577
|
if (this.editor.text) { this.editor.discard(); this.screen.schedule(); return; }
|
|
1274
|
-
if (Date.now() - this.exitArmed < 1500) { this.
|
|
1578
|
+
if (Date.now() - this.exitArmed < 1500) { this.keyboardExit(); return; }
|
|
1275
1579
|
this.exitArmed = Date.now();
|
|
1276
1580
|
this.screen.schedule();
|
|
1277
1581
|
setTimeout(() => this.screen.schedule(), 1600);
|
|
@@ -1283,7 +1587,8 @@ export class App {
|
|
|
1283
1587
|
this.screen.schedule();
|
|
1284
1588
|
}
|
|
1285
1589
|
|
|
1286
|
-
|
|
1590
|
+
// `quiet`: for the page (remoteSuggest), nothing shows here.
|
|
1591
|
+
suggest(text, cursor, { quiet = false } = {}) {
|
|
1287
1592
|
if (text.startsWith('/') && !/\s/.test(text) && cursor === text.length) {
|
|
1288
1593
|
const q = text.slice(1).toLowerCase();
|
|
1289
1594
|
const all = [...this.commands.values()].filter((cmd) => !cmd.hidden);
|
|
@@ -1314,12 +1619,12 @@ export class App {
|
|
|
1314
1619
|
// `&name`: the other sessions, on this computer and (through the gateway) on the account's others. At the start
|
|
1315
1620
|
// it sends them the message; elsewhere it names them (/sendfile, or for the model).
|
|
1316
1621
|
const amp = /(^|\s)[&&]([^\s&&]*)$/u.exec(before);
|
|
1317
|
-
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 });
|
|
1318
1623
|
return null;
|
|
1319
1624
|
}
|
|
1320
1625
|
|
|
1321
|
-
peerSuggestions(q, cursor, atStart = true) {
|
|
1322
|
-
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) {
|
|
1323
1628
|
this.refreshRemotePeers().then(() => {
|
|
1324
1629
|
if (!/[&&][^\s&&]*$/u.test(this.editor.text.slice(0, this.editor.cursor))) return;
|
|
1325
1630
|
this.editor.refreshSuggestions();
|
|
@@ -1334,7 +1639,7 @@ export class App {
|
|
|
1334
1639
|
.map((p) => ({ value: '&' + p.label, label: `&${p.label}`, description: `${p.machine} · ${p.cwd}${p.busy ? ' · busy' : ''}` })),
|
|
1335
1640
|
];
|
|
1336
1641
|
if (!items.length) {
|
|
1337
|
-
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)');
|
|
1338
1643
|
return null;
|
|
1339
1644
|
}
|
|
1340
1645
|
return { items, from: cursor - q.length - 1, to: cursor };
|
|
@@ -1777,7 +2082,9 @@ export class App {
|
|
|
1777
2082
|
loadSession(file, id, { quiet = false } = {}) {
|
|
1778
2083
|
const loaded = SessionStore.load(file);
|
|
1779
2084
|
this.previousSession = null; // the conversation before a /clear: resuming another one ends the offer
|
|
2085
|
+
this.seedOutput = [];
|
|
1780
2086
|
this.store = new SessionStore(this.cwd, id);
|
|
2087
|
+
this.peers?.update(); // the conversation, in the registry
|
|
1781
2088
|
this.topic = loaded.topic;
|
|
1782
2089
|
this.customTitle = loaded.name;
|
|
1783
2090
|
// a conversation that was given a name brings it back: the other sessions reach this one by it again
|
|
@@ -1795,7 +2102,7 @@ export class App {
|
|
|
1795
2102
|
this.agent.lastContextTokens = estimateTokens(loaded.messages);
|
|
1796
2103
|
// Continue behind the system prompt the conversation had (and its cache), not a freshly built one.
|
|
1797
2104
|
this.store.systemPrompt = loaded.systemPrompt;
|
|
1798
|
-
this.runtime.resumeSystemPrompt(loaded.systemPrompt);
|
|
2105
|
+
this.runtime.resumeSystemPrompt(loaded.systemPrompt, loaded.promptCode);
|
|
1799
2106
|
if (!this.topic) this.refreshTopic(this.latestPrompt()); // a session from before topics were kept
|
|
1800
2107
|
this.remote?.resync();
|
|
1801
2108
|
if (quiet) return;
|
|
@@ -1810,7 +2117,9 @@ export class App {
|
|
|
1810
2117
|
for (const m of messages) {
|
|
1811
2118
|
const blocks = typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : m.content;
|
|
1812
2119
|
for (const b of blocks) {
|
|
1813
|
-
|
|
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));
|
|
1814
2123
|
if (m.role === 'assistant' && b.type === 'text') this.screen.log(renderMarkdown(b.text, { width: this.width - 1, firstPrefix: `${DOT} `, indent: ' ' }), '');
|
|
1815
2124
|
if (m.role === 'assistant' && b.type === 'tool_use') {
|
|
1816
2125
|
const tool = toolMap.get(b.name) || { name: b.name };
|
|
@@ -1823,6 +2132,8 @@ export class App {
|
|
|
1823
2132
|
|
|
1824
2133
|
newSession() {
|
|
1825
2134
|
this.store = new SessionStore(this.cwd);
|
|
2135
|
+
this.peers?.update();
|
|
2136
|
+
this.seedOutput = [];
|
|
1826
2137
|
this.topic = null;
|
|
1827
2138
|
this.customTitle = null;
|
|
1828
2139
|
this.firstPrompt = null;
|
|
@@ -2317,7 +2628,10 @@ export class App {
|
|
|
2317
2628
|
}
|
|
2318
2629
|
|
|
2319
2630
|
export async function runRepl({ flags, cwd, initialPrompt }) {
|
|
2320
|
-
|
|
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 });
|
|
2321
2635
|
process.on('uncaughtException', (e) => {
|
|
2322
2636
|
app.restoreTerminal();
|
|
2323
2637
|
process.stderr.write(`\nUnexpected error: ${e?.stack || e}\n`);
|