@yanzc/claude-pro 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -36
- package/package.json +1 -1
- package/src/agent.js +4 -3
- package/src/browser/session.js +21 -1
- package/src/commands.js +198 -33
- package/src/config.js +17 -2
- package/src/gateway.js +33 -0
- package/src/live.js +148 -0
- package/src/main.js +5 -3
- package/src/peers.js +41 -4
- package/src/providers.js +25 -6
- package/src/remote.js +82 -268
- package/src/runtime.js +36 -11
- package/src/selfcheck.js +3 -3
- package/src/session.js +128 -8
- package/src/supervisor.js +1 -1
- package/src/tools/bash.js +21 -12
- package/src/tools/browser.js +14 -8
- package/src/tools/code.js +18 -11
- package/src/tools/restart.js +1 -1
- package/src/ui/dialogs.js +23 -30
- package/src/ui/editor.js +65 -169
- package/src/ui/repl.js +467 -474
- package/src/ui/screen.js +47 -674
- package/src/updater.js +5 -4
- package/src/web/api.js +881 -0
- package/src/web/app.css +530 -0
- package/src/web/app.js +2188 -0
- package/src/web/data.js +436 -0
- package/src/web/host.js +332 -0
- package/src/web/login.html +67 -0
- package/src/web/logo.svg +1 -0
- package/src/web/page.html +44 -0
- package/src/web/remote-access.js +232 -0
- package/src/web/server.js +476 -0
package/src/ui/repl.js
CHANGED
|
@@ -3,16 +3,15 @@
|
|
|
3
3
|
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
-
import os from 'node:os';
|
|
7
6
|
import readline from 'node:readline';
|
|
8
7
|
import { spawn } from 'node:child_process';
|
|
9
8
|
import { c, ESC, glyphs, stringWidth, stripAnsi, truncate, padEnd, wordWrap } from './ansi.js';
|
|
10
|
-
import { Screen,
|
|
11
|
-
import { Editor,
|
|
9
|
+
import { Screen, HeadlessScreen, queryCursorRow } from './screen.js';
|
|
10
|
+
import { Editor, shownQuotes } from './editor.js';
|
|
12
11
|
import { SelectDialog } from './dialogs.js';
|
|
13
12
|
import { MarkdownStream, renderMarkdown } from './markdown.js';
|
|
14
13
|
import {
|
|
15
|
-
DOT, toolHeader, renderToolResult,
|
|
14
|
+
DOT, toolHeader, renderToolResult, renderUserMessage, resultLines, formatTokens, formatDuration, toolLabel, bashModeLines,
|
|
16
15
|
} from './render.js';
|
|
17
16
|
import { createRuntime } from '../runtime.js';
|
|
18
17
|
import { SessionStore, firstUserText, moveSession } from '../session.js';
|
|
@@ -21,7 +20,7 @@ import { CONFIG_DIR, VERSION, APP_NAME, INSTALL_DIR } from '../config.js';
|
|
|
21
20
|
import { gatewayLogin, loadGatewayModels, normalizeGatewayUrl, formatUsd } from '../gateway.js';
|
|
22
21
|
import { connectedProviders } from '../providers.js';
|
|
23
22
|
import { TOPIC_TITLE_SYSTEM, topicTitlePrompt } from '../prompts.js';
|
|
24
|
-
import { buildCommands,
|
|
23
|
+
import { buildCommands, webModelChoices, effortChoices } from '../commands.js';
|
|
25
24
|
import { canRestart, writeRestartState, runSelfCheck, watchSource, restartNote, reloadTiming, RESTART_EXIT_CODE, MAX_RESTARTS, RESTART_WINDOW_MS } from '../restart.js';
|
|
26
25
|
import { resolvePath, displayPath } from '../utils/paths.js';
|
|
27
26
|
import { listDirectory, recentDirectories } from '../utils/dirs.js';
|
|
@@ -29,13 +28,14 @@ import { ripgrepPath } from '../utils/shell.js';
|
|
|
29
28
|
import { describePause, formatClock, humanDuration, resumeText, shouldAnnounce } from '../ratelimit.js';
|
|
30
29
|
import { shutdownBackgroundShells, listBackgroundShells } from '../tools/bash.js';
|
|
31
30
|
import { shutdownInterpreters } from '../tools/code.js';
|
|
32
|
-
import {
|
|
31
|
+
import { browserSessionFor, closeBrowserSession } from '../browser/session.js';
|
|
33
32
|
import { estimateTokens } from '../agent.js';
|
|
34
33
|
import { readClipboardImage, imageFromFile, writeClipboard, readClipboardText } from '../utils/clipboard.js';
|
|
35
34
|
import { fitImagesIn, imageSize } from '../utils/images.js';
|
|
36
35
|
import { checkForUpdate, installUpdate, installedVersion, installedByNpm, isNewer } from '../updater.js';
|
|
37
36
|
import { PeerNode, peersEnabled, findPeer, resolvePeer, machineName, cleanName, peerMessagePrompt } from '../peers.js';
|
|
38
|
-
import {
|
|
37
|
+
import { LiveFeed } from '../live.js';
|
|
38
|
+
import { RemoteControl, transcriptItems, onlineEnabled, REMOTE_WIDTH } from '../remote.js';
|
|
39
39
|
|
|
40
40
|
// A model id as people say it: claude-sonnet-5-5 -> sonnet-5-5, claude-haiku-4-5-20251001 -> haiku-4-5.
|
|
41
41
|
// (every model with its provider in front: 7bit/opus-5-5, deepseek/deepseek-v4-pro)
|
|
@@ -232,14 +232,17 @@ export class App {
|
|
|
232
232
|
// `noProcessExit`: the tests, which drive the App themselves; it never ends the process, and it has no peers, no
|
|
233
233
|
// gateway connection, no update checks and the default renderer. `selfCheck` (see selfcheck.js): it never ends the
|
|
234
234
|
// process either, but otherwise starts as a session does, so that code only a real start runs is checked too.
|
|
235
|
-
|
|
235
|
+
// `host`: a 后台会话, one of the sessions the web console runs in its own process (see web/host.js): no terminal
|
|
236
|
+
// (what it prints goes to the console's live view only), the process is the host's, and so are restarts.
|
|
237
|
+
constructor({ flags, cwd, stdin = process.stdin, stdout = process.stdout, noProcessExit = false, selfCheck = false, host = null }) {
|
|
236
238
|
this.flags = flags;
|
|
237
239
|
this.cwd = cwd;
|
|
238
240
|
this.stdin = stdin;
|
|
239
241
|
this.stdout = stdout;
|
|
240
|
-
this.
|
|
242
|
+
this.host = host;
|
|
243
|
+
this.noProcessExit = noProcessExit || selfCheck || Boolean(host);
|
|
241
244
|
this.driven = noProcessExit;
|
|
242
|
-
this.screen = new Screen(stdout);
|
|
245
|
+
this.screen = host ? new HeadlessScreen(stdout) : new Screen(stdout);
|
|
243
246
|
this.busy = false;
|
|
244
247
|
// Attachment expansion is asynchronous. Claim the turn before the first await so two
|
|
245
248
|
// rapid submits cannot start two Agent.run() calls against the same message array.
|
|
@@ -255,7 +258,6 @@ export class App {
|
|
|
255
258
|
this.md = null;
|
|
256
259
|
this.thinking = null;
|
|
257
260
|
this.verbose = !!flags.verbose;
|
|
258
|
-
this.showTodos = true;
|
|
259
261
|
this.turnStart = 0;
|
|
260
262
|
this.turnTokens = 0;
|
|
261
263
|
this.verb = 'Thinking';
|
|
@@ -278,12 +280,27 @@ export class App {
|
|
|
278
280
|
this.turnPeers = []; // tasks from other sessions that the running turn answers: [{msg}]
|
|
279
281
|
this.userSentToPeers = new Set(); // ids of messages the user sent to other sessions with @name
|
|
280
282
|
this.remote = null; // the browser page that watches and steers this session (see remote.js), when it is on
|
|
281
|
-
|
|
283
|
+
// the local web console's live view of this session (claude-pro web, see live.js and web/server.js)
|
|
284
|
+
this.liveFeed = new LiveFeed({
|
|
285
|
+
seed: () => [
|
|
286
|
+
...transcriptItems(this.agent?.messages || [], { tools: this.runtime?.tools || [], ctx: this.agent?.makeCtx(), cwd: this.cwd, images: true, turns: this.turnMarks }),
|
|
287
|
+
...(this.seedOutput.length ? [{ k: 'output', lines: this.seedOutput.slice() }] : []),
|
|
288
|
+
],
|
|
289
|
+
status: () => this.liveStatus(),
|
|
290
|
+
});
|
|
291
|
+
// run by the web console (a 后台会话): only the console shows it, and ends it. `legacyHidden`: one an older version
|
|
292
|
+
// of the console started in a hidden window, a process of its own: it moves into the console's (maybeMoveIntoConsole)
|
|
293
|
+
this.legacyHidden = !host && /^(1|true|yes)$/i.test(process.env.CLAUDE_PRO_BACKGROUND || '');
|
|
294
|
+
this.hidden = Boolean(host) || this.legacyHidden;
|
|
282
295
|
this.remoteMuted = 0; // > 0 while printing something the page is told about in its own terms
|
|
283
296
|
this.remoteDialogs = 0;
|
|
284
297
|
this.remoteStarting = null;
|
|
285
298
|
this.remoteRefused = null; // a gateway key the gateway refused: not tried again by itself (a new /connect is)
|
|
286
299
|
this.seedOutput = []; // lines the page is shown after the conversation when it starts from it (see resumeAfterRestart)
|
|
300
|
+
// Where the turns of the conversation ended, with their "✻ Done at …" lines: [{after, text, msg}] (`msg`: the
|
|
301
|
+
// message the line follows, to find it again when the messages are replaced), and the array they were made on.
|
|
302
|
+
this.turnMarks = [];
|
|
303
|
+
this.marksBase = null;
|
|
287
304
|
this.selfCheck = selfCheck;
|
|
288
305
|
this.sessionName = flags?.restart?.peerName || null; // this session's name when the sessions of this computer do not know it (CLAUDE_PRO_PEERS=0)
|
|
289
306
|
this.customTitle = null; // the conversation's name given with /rename: the title, instead of the topic
|
|
@@ -292,14 +309,23 @@ export class App {
|
|
|
292
309
|
this.remotePeersLoading = null;
|
|
293
310
|
this.remotePeersTimer = null;
|
|
294
311
|
this.cost = 0; // what this conversation's requests have cost so far (USD at list prices): the footer and /cost
|
|
295
|
-
this.fileIndex = new FileIndex(cwd, () => this.runtime?.config, () => {
|
|
312
|
+
this.fileIndex = new FileIndex(cwd, () => this.runtime?.config, () => {
|
|
313
|
+
const e = this.editor;
|
|
314
|
+
if (!e) return;
|
|
315
|
+
// a Tab pressed while the list was being made had nothing to complete: it does now
|
|
316
|
+
const miss = e.lastMiss;
|
|
317
|
+
if (miss && miss.text === e.text && miss.cursor === e.cursor && Date.now() - miss.at < 5000) e.complete();
|
|
318
|
+
else e.refreshSuggestions();
|
|
319
|
+
this.screen?.schedule();
|
|
320
|
+
});
|
|
321
|
+
this.storeError = (e, store) => this.notice(`Could not save the conversation to ${store.file} (${e.code || e.message}): it is written again whole before a restart, but /resume may miss what was not saved.`, 'warn');
|
|
296
322
|
this.store = new SessionStore(cwd);
|
|
297
|
-
|
|
323
|
+
this.store.onError = this.storeError;
|
|
298
324
|
// What the terminal prints goes to the remote page too, except what it is told about as events.
|
|
299
325
|
this.screen.onLog = (items) => {
|
|
300
326
|
const lines = () => items.flatMap((i) => (Array.isArray(i) ? i : [i])).flatMap((l) => String(l).split(/\r?\n/));
|
|
301
|
-
if (
|
|
302
|
-
this.
|
|
327
|
+
if (this.remoteMuted || !this.liveFeed?.active) return;
|
|
328
|
+
this.liveFeed.output(lines());
|
|
303
329
|
};
|
|
304
330
|
this.editor = new Editor({
|
|
305
331
|
history: loadHistory(cwd),
|
|
@@ -308,15 +334,20 @@ export class App {
|
|
|
308
334
|
imageFromPath: (p) => {
|
|
309
335
|
const r = imageFromFile(resolvePath(p, this.cwd));
|
|
310
336
|
if (r.error && !/not found|Not a file/.test(r.error)) this.flash(r.error, 'warn');
|
|
311
|
-
if (r.image) this.flashMessage = null;
|
|
312
337
|
return r.image || null;
|
|
313
338
|
},
|
|
314
|
-
getSuggestions: (text, cursor) => this.suggest(text, cursor),
|
|
339
|
+
getSuggestions: (text, cursor, opts) => this.suggest(text, cursor, opts),
|
|
315
340
|
onChange: () => this.screen.schedule(),
|
|
316
341
|
});
|
|
317
342
|
}
|
|
318
343
|
|
|
319
344
|
get agent() { return this.runtime.agent; }
|
|
345
|
+
// Whether this session can restart (to load new code, or for /cd): under the supervisor, or in the web console.
|
|
346
|
+
canRestart() { return Boolean(this.host) || canRestart(); }
|
|
347
|
+
get owner() { return this.runtime?.config?.owner; }
|
|
348
|
+
// Whether the conversation is being worked on, not only looked at: a session the web console took up because its
|
|
349
|
+
// conversation was opened is not, until it runs a turn (`used`, carried over by a restart).
|
|
350
|
+
inUse() { return !this.host || Boolean(this.used); }
|
|
320
351
|
get config() { return this.runtime.config; }
|
|
321
352
|
get width() { return this.screen.width; }
|
|
322
353
|
isTurnRunning() { return this.busy || this.turnStarting; }
|
|
@@ -324,20 +355,29 @@ export class App {
|
|
|
324
355
|
// ---------------------------------------------------------------- lifecycle
|
|
325
356
|
|
|
326
357
|
async start(initialPrompt) {
|
|
358
|
+
if (this.exiting) return this.exitCode;
|
|
327
359
|
const stdin = this.stdin;
|
|
328
360
|
stdin.setRawMode(true);
|
|
329
361
|
// Where the cursor is, before anything is drawn: the input box is kept on the last rows of the window from
|
|
330
362
|
// there (see screen.js).
|
|
331
363
|
if (stdin.isTTY && this.stdout.isTTY) this.screen.pinFrom(await queryCursorRow(stdin, this.stdout));
|
|
364
|
+
if (this.exiting) return this.exitCode;
|
|
332
365
|
stdin.setEncoding('utf8');
|
|
333
366
|
this.stdout.write(ESC.bracketedPasteOn);
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
367
|
+
if (!this.host) { // (the host's process is not this session's)
|
|
368
|
+
process.on('exit', () => this.restoreTerminal());
|
|
369
|
+
process.on('SIGTERM', () => this.exit(143));
|
|
370
|
+
process.on('SIGHUP', () => this.exit(129));
|
|
371
|
+
}
|
|
338
372
|
|
|
339
373
|
await this.startPeer();
|
|
340
|
-
|
|
374
|
+
if (this.exiting) return this.exitCode;
|
|
375
|
+
const runtime = await createRuntime({ cwd: this.cwd, flags: this.flags, io: this, sessionId: this.store.id });
|
|
376
|
+
if (this.exiting) {
|
|
377
|
+
this.closeRuntime(runtime); // exit could not clean up the runtime while it was still being built
|
|
378
|
+
return this.exitCode;
|
|
379
|
+
}
|
|
380
|
+
this.runtime = runtime;
|
|
341
381
|
// The conversation's id, sent to the gateway with each request (see streamMessage); it follows /clear and /resume.
|
|
342
382
|
Object.defineProperty(this.runtime.config, 'sessionId', { get: () => this.store.id, configurable: true });
|
|
343
383
|
// Every request's cost (the conversation's, its sub-agents', side queries'), kept with the session.
|
|
@@ -351,15 +391,11 @@ export class App {
|
|
|
351
391
|
// so that the footer shows it before the first request.
|
|
352
392
|
// not in the self-check a restart runs first: that would ask the gateway once more for every restart
|
|
353
393
|
if (!this.driven && !this.selfCheck) loadGatewayModels(this.runtime.config).then(() => this.screen.schedule());
|
|
354
|
-
// What the session showed before a restart:
|
|
394
|
+
// What the session showed before a restart: repainted after a resize.
|
|
355
395
|
if (Array.isArray(this.flags.restart?.screenHistory)) this.screen.history = this.flags.restart.screenHistory.filter((l) => typeof l === 'string');
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
const keys = mouseFilter(stdin, (m) => this.onMouse(m));
|
|
360
|
-
this.keys = keys;
|
|
361
|
-
readline.emitKeypressEvents(keys);
|
|
362
|
-
keys.on('keypress', (str, key) => {
|
|
396
|
+
// Keys typed while starting up stay buffered in stdin until we listen.
|
|
397
|
+
readline.emitKeypressEvents(stdin);
|
|
398
|
+
stdin.on('keypress', (str, key) => {
|
|
363
399
|
if (/^\x1b\[\d+;\d+R$/.test(key?.sequence || '')) return; // a late answer to the cursor position query, not a key
|
|
364
400
|
try { this.onKey(str, key || {}); } catch (e) { this.logError(e); }
|
|
365
401
|
});
|
|
@@ -375,14 +411,22 @@ export class App {
|
|
|
375
411
|
if (restart) this.resumeAfterRestart(restart, resumable);
|
|
376
412
|
else if (this.flags.resumeFile) this.loadSession(this.flags.resumeFile, this.flags.resumeId);
|
|
377
413
|
else if (this.flags.resume) await this.commands.get('resume').run('');
|
|
414
|
+
if (this.exiting) return this.exitCode;
|
|
378
415
|
if (!restart && this.flags.name?.trim()) this.renameSession(this.flags.name); // --name, as /rename does
|
|
379
416
|
this.autoStartRemote(restart);
|
|
417
|
+
// 远程访问 on: the console's server (and its tunnel) is brought up again by any session that starts
|
|
418
|
+
if (!this.driven && !this.selfCheck && !this.host) { // (in the console's process it is up already)
|
|
419
|
+
import('../web/remote-access.js')
|
|
420
|
+
.then((ra) => (ra.readRemote().enabled ? import('../web/server.js').then((w) => w.ensureWebServer()) : null))
|
|
421
|
+
.catch(() => { /* /web remote says what is wrong */ });
|
|
422
|
+
}
|
|
380
423
|
|
|
381
424
|
this.screen.setLive((w) => this.renderLive(w));
|
|
425
|
+
// the restart line took the place of the same one of the process before (see resumeAfterRestart): the screen is
|
|
426
|
+
// written again from the history, which no longer has the old one
|
|
427
|
+
if (this.collapsedRestart) { this.collapsedRestart = false; this.screen.repaint(); }
|
|
382
428
|
this.spinnerTimer = setInterval(() => {
|
|
383
|
-
|
|
384
|
-
if (this.isTurnRunning() || this.active.length || clock !== this.shownClock) this.screen.schedule();
|
|
385
|
-
this.shownClock = clock;
|
|
429
|
+
if (this.isTurnRunning() || this.active.length) this.screen.schedule();
|
|
386
430
|
}, 120);
|
|
387
431
|
if (restart) this.continueAfterRestart(restart);
|
|
388
432
|
else if (initialPrompt?.trim()) this.onSubmit(initialPrompt, initialPrompt);
|
|
@@ -391,6 +435,11 @@ export class App {
|
|
|
391
435
|
Promise.resolve(this.commands.get('connect').run('')).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
|
|
392
436
|
}
|
|
393
437
|
this.startSourceWatch();
|
|
438
|
+
if (this.legacyHidden && !this.selfCheck) {
|
|
439
|
+
this.moveTimer = setInterval(() => this.maybeMoveIntoConsole(), 60_000);
|
|
440
|
+
this.moveTimer.unref?.();
|
|
441
|
+
setTimeout(() => this.maybeMoveIntoConsole(), 5000).unref?.();
|
|
442
|
+
}
|
|
394
443
|
if (!this.driven) {
|
|
395
444
|
// Updates are deliberately manual: /update checks npm and installs the selected release.
|
|
396
445
|
// Do not query the registry or install/restart a running session in the background.
|
|
@@ -398,7 +447,7 @@ export class App {
|
|
|
398
447
|
this.loginTimer = setInterval(() => this.syncRemote(), 10_000);
|
|
399
448
|
this.loginTimer.unref?.();
|
|
400
449
|
}
|
|
401
|
-
return new Promise((resolve) => { this.resolveExit = resolve; });
|
|
450
|
+
return this.exiting ? this.exitCode : new Promise((resolve) => { this.resolveExit = resolve; });
|
|
402
451
|
}
|
|
403
452
|
|
|
404
453
|
// What the session is about now: the current model named the topic last, or else the first thing asked
|
|
@@ -472,34 +521,54 @@ export class App {
|
|
|
472
521
|
} catch { /* ignore */ }
|
|
473
522
|
}
|
|
474
523
|
|
|
524
|
+
closeRuntime(runtime) {
|
|
525
|
+
// In the console process, no owner means there is nothing to clean up, not every session.
|
|
526
|
+
const owner = this.host ? runtime?.config?.owner : undefined;
|
|
527
|
+
if (!this.host || owner) {
|
|
528
|
+
shutdownBackgroundShells(owner);
|
|
529
|
+
shutdownInterpreters(owner);
|
|
530
|
+
}
|
|
531
|
+
if (this.host && owner) closeBrowserSession(owner);
|
|
532
|
+
runtime?.agent?.keepAlive?.stop();
|
|
533
|
+
runtime?.tasks?.killAll();
|
|
534
|
+
runtime?.mcp?.close();
|
|
535
|
+
runtime?.releaseSession?.();
|
|
536
|
+
}
|
|
537
|
+
|
|
475
538
|
exit(code = 0, { restart = false } = {}) {
|
|
476
539
|
if (this.exiting) return;
|
|
477
540
|
this.exiting = true;
|
|
478
|
-
this.
|
|
479
|
-
|
|
480
|
-
clearTimeout(this.reloadTimer);
|
|
481
|
-
this.sourceWatch?.close();
|
|
482
|
-
shutdownBackgroundShells();
|
|
483
|
-
shutdownInterpreters();
|
|
484
|
-
this.runtime?.tasks.killAll();
|
|
485
|
-
this.runtime?.mcp.close();
|
|
486
|
-
this.peers?.close();
|
|
487
|
-
clearInterval(this.remotePeersTimer);
|
|
488
|
-
clearInterval(this.loginTimer);
|
|
489
|
-
const remoteClosed = this.remote?.close({ restarting: restart });
|
|
490
|
-
const u = this.agent?.totalUsage();
|
|
541
|
+
this.exitCode = code;
|
|
542
|
+
let remoteClosed;
|
|
491
543
|
const farewell = []; // left on the terminal once the program's screen is gone (see Screen.close)
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
544
|
+
try {
|
|
545
|
+
this.controller?.abort();
|
|
546
|
+
clearInterval(this.spinnerTimer);
|
|
547
|
+
clearTimeout(this.reloadTimer);
|
|
548
|
+
this.sourceWatch?.close();
|
|
549
|
+
clearTimeout(this.updateRetry);
|
|
550
|
+
clearInterval(this.moveTimer);
|
|
551
|
+
this.closeRuntime(this.runtime);
|
|
552
|
+
this.peers?.close();
|
|
553
|
+
this.liveFeed?.close();
|
|
554
|
+
clearInterval(this.remotePeersTimer);
|
|
555
|
+
clearInterval(this.loginTimer);
|
|
556
|
+
remoteClosed = this.remote?.close({ restarting: restart });
|
|
557
|
+
const agent = this.runtime?.agent;
|
|
558
|
+
const u = agent?.totalUsage();
|
|
559
|
+
if (!restart && u?.requests) {
|
|
560
|
+
farewell.push(c.dim(`Total usage: ${formatTokens(u.input + u.cacheRead + u.cacheWrite)} input (${formatTokens(u.cacheRead)} cached), ${formatTokens(u.output)} output, ${u.requests + u.compactions} requests`));
|
|
561
|
+
}
|
|
562
|
+
if (!restart && agent?.messages.length) farewell.push(c.dim(`Resume this session with: ${APP_NAME} --resume ${this.store.id}`));
|
|
563
|
+
} finally {
|
|
564
|
+
this.resolveExit?.(code);
|
|
565
|
+
this.restoreTerminal({ handOver: restart, farewell });
|
|
566
|
+
this.stdin.pause();
|
|
567
|
+
if (!this.noProcessExit) {
|
|
568
|
+
// with remote control on, the gateway is told first (at most a second and a half; see RemoteControl.close)
|
|
569
|
+
if (remoteClosed) remoteClosed.finally(() => process.exit(code));
|
|
570
|
+
else setTimeout(() => process.exit(code), 50).unref();
|
|
571
|
+
}
|
|
503
572
|
}
|
|
504
573
|
}
|
|
505
574
|
|
|
@@ -510,13 +579,34 @@ export class App {
|
|
|
510
579
|
async startPeer() {
|
|
511
580
|
if (this.driven || !peersEnabled()) return;
|
|
512
581
|
try {
|
|
513
|
-
|
|
582
|
+
const peer = new PeerNode({
|
|
514
583
|
cwd: this.cwd,
|
|
515
584
|
name: this.flags.restart?.peerName,
|
|
516
585
|
id: this.flags.restart?.peerId,
|
|
517
586
|
onMessage: (msg) => this.onPeerMessage(msg),
|
|
518
|
-
getStatus: () =>
|
|
519
|
-
|
|
587
|
+
getStatus: () => this.liveStatus(),
|
|
588
|
+
live: { feed: this.liveFeed, command: (type, body) => this.pageCommand(type, body), image: (n) => this.liveImage(n) },
|
|
589
|
+
});
|
|
590
|
+
if (this.legacyHidden) {
|
|
591
|
+
const handle = peer.handle.bind(peer);
|
|
592
|
+
peer.handle = (req, res) => {
|
|
593
|
+
if (req.method === 'POST' && req.url === '/message' && req.headers.authorization === `Bearer ${peer.token}`) {
|
|
594
|
+
// PeerNode acknowledges before calling onMessage. Refuse at the endpoint, and do not move while an
|
|
595
|
+
// already accepted request is still uploading its message.
|
|
596
|
+
if (this.moving || this.exiting) {
|
|
597
|
+
res.writeHead(503, { 'content-type': 'application/json' });
|
|
598
|
+
res.end(JSON.stringify({ error: 'Session is moving or ending; try again.' }));
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
this.peerMessages = (this.peerMessages || 0) + 1;
|
|
602
|
+
res.once('close', () => { this.peerMessages--; });
|
|
603
|
+
}
|
|
604
|
+
handle(req, res);
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
await peer.start();
|
|
608
|
+
if (this.exiting) peer.close();
|
|
609
|
+
else this.peers = peer;
|
|
520
610
|
} catch (e) {
|
|
521
611
|
this.peers = null;
|
|
522
612
|
this.notice(`Other sessions cannot reach this one: ${e.message}`, 'warn');
|
|
@@ -713,9 +803,25 @@ export class App {
|
|
|
713
803
|
}
|
|
714
804
|
|
|
715
805
|
// A message of the user in the transcript (typed here, on the remote page, or sent by another session).
|
|
716
|
-
echoUser(text
|
|
806
|
+
echoUser(text) {
|
|
717
807
|
this.logLocal(renderUserMessage(text, this.width));
|
|
718
|
-
this.
|
|
808
|
+
this.liveFeed.emit({ t: 'user', text: String(text) });
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// The images of the user's messages, in order (what transcriptItems numbers {k: 'image', n}).
|
|
812
|
+
conversationImages() {
|
|
813
|
+
const out = [];
|
|
814
|
+
for (const m of this.agent?.messages || []) {
|
|
815
|
+
if (m.role !== 'user' || !Array.isArray(m.content)) continue;
|
|
816
|
+
for (const b of m.content) if (b.type === 'image') out.push(b);
|
|
817
|
+
}
|
|
818
|
+
return out;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
// The n-th image of the conversation, for the web console: {mediaType, data (Buffer)} or null.
|
|
822
|
+
liveImage(n) {
|
|
823
|
+
const b = this.conversationImages()[n];
|
|
824
|
+
return b?.source?.type === 'base64' ? { mediaType: b.source.media_type, data: Buffer.from(b.source.data, 'base64') } : null;
|
|
719
825
|
}
|
|
720
826
|
|
|
721
827
|
// Whether this session should be online at the gateway (see remote.js): whenever this computer is logged in to
|
|
@@ -731,8 +837,6 @@ export class App {
|
|
|
731
837
|
// Online at the gateway from the start when this computer is logged in, and after a restart with the same
|
|
732
838
|
// session id so that an already-open page keeps following it.
|
|
733
839
|
autoStartRemote(restart) {
|
|
734
|
-
// Remote control (the web page shows and steers the session) only after /rc or --rc, and through restarts.
|
|
735
|
-
this.remoteControl = Boolean(restart ? restart.remoteControl : this.flags.remoteControl);
|
|
736
840
|
const id = restart?.remote?.id || null;
|
|
737
841
|
if (!id && !this.onlineWanted()) return;
|
|
738
842
|
this.startRemote({ id }).catch((e) => {
|
|
@@ -771,33 +875,16 @@ export class App {
|
|
|
771
875
|
async connectRemote({ id }) {
|
|
772
876
|
const login = gatewayLogin(this.config.gatewayUrl);
|
|
773
877
|
if (!login) throw Object.assign(new Error(`this computer is not logged in to the gateway ${this.config.gatewayUrl} (/connect 7bit.fun connects it)`), { code: 'NO_GATEWAY_LOGIN' });
|
|
774
|
-
// What the page may do here, besides watching (see remote.js): nothing with CLAUDE_PRO_REMOTE_COMMANDS=0.
|
|
775
|
-
const commands = remoteCommandsEnabled(this.config.env) ? {
|
|
776
|
-
send: (body) => this.remoteSend(body.text, body.images),
|
|
777
|
-
interrupt: () => this.remoteInterrupt(),
|
|
778
|
-
answer: (body) => this.answerDialog(body),
|
|
779
|
-
options: () => this.remoteOptions(),
|
|
780
|
-
suggest: (body) => this.remoteSuggest(body),
|
|
781
|
-
list: (body) => this.remoteList(body),
|
|
782
|
-
output: (body) => this.remoteOutput(body),
|
|
783
|
-
} : {};
|
|
784
878
|
const remote = new RemoteControl({
|
|
785
879
|
gateway: { url: login.url || this.config.gatewayUrl, apiKey: login.apiKey },
|
|
786
880
|
id,
|
|
787
|
-
rc: this.remoteControl,
|
|
788
881
|
handlers: {
|
|
789
882
|
info: () => ({
|
|
790
883
|
name: this.peerLabel(), machine: machineName(this.config.env), peerId: this.peers?.id || null, title: this.sessionLabel() || '',
|
|
791
884
|
cwd: (this.agent.cwd || this.cwd).replace(/\\/g, '/'), model: modelInfo(this.config).model, version: VERSION,
|
|
792
|
-
kind: 'terminal',
|
|
793
885
|
}),
|
|
794
|
-
seed: () => [
|
|
795
|
-
...transcriptItems(this.agent.messages, { tools: this.runtime.tools, ctx: this.agent.makeCtx(), cwd: this.cwd }),
|
|
796
|
-
...(this.seedOutput.length ? [{ k: 'output', lines: this.seedOutput.slice() }] : []),
|
|
797
|
-
],
|
|
798
886
|
status: () => this.remoteStatus(),
|
|
799
|
-
|
|
800
|
-
peerMessage: (msg) => this.onPeerMessage(msg),
|
|
887
|
+
peerMessage: (msg) => this.moving || this.exiting ? false : this.onPeerMessage(msg),
|
|
801
888
|
contactEvent: (ev) => this.onContactEvent(ev),
|
|
802
889
|
changed: () => {
|
|
803
890
|
this.screen.schedule();
|
|
@@ -827,21 +914,6 @@ export class App {
|
|
|
827
914
|
return remote;
|
|
828
915
|
}
|
|
829
916
|
|
|
830
|
-
// /rc: the web page (远程控制) shows this session's conversation and may steer it, or (off) only messages between
|
|
831
|
-
// sessions go through the gateway. Resolves with what to tell the user.
|
|
832
|
-
async setRemoteControl(on) {
|
|
833
|
-
this.remoteControl = Boolean(on);
|
|
834
|
-
this.screen.schedule();
|
|
835
|
-
if (!on) {
|
|
836
|
-
if (this.remote) await this.remote.setRc(false);
|
|
837
|
-
return 'Remote control is off: the web page no longer shows this session (messages between sessions still go through the gateway).';
|
|
838
|
-
}
|
|
839
|
-
const remote = this.remote || await this.syncRemote();
|
|
840
|
-
if (!remote) return `Remote control is on, but this session is not online at the gateway: ${stripAnsi(this.remoteState().text)}`;
|
|
841
|
-
await remote.setRc(true);
|
|
842
|
-
return 'Remote control is on: 远程控制 on the gateway\'s web page shows this session and can send it messages and commands. /rc off turns it off.';
|
|
843
|
-
}
|
|
844
|
-
|
|
845
917
|
stopRemote() {
|
|
846
918
|
this.remote?.close();
|
|
847
919
|
this.remote = null;
|
|
@@ -849,14 +921,12 @@ export class App {
|
|
|
849
921
|
this.screen.schedule();
|
|
850
922
|
}
|
|
851
923
|
|
|
852
|
-
// This session at the gateway
|
|
924
|
+
// This session at the gateway (its session relay: tasks across computers and from contacts), for /status: {text}.
|
|
853
925
|
remoteState() {
|
|
854
926
|
const r = this.remote;
|
|
855
927
|
if (r) {
|
|
856
928
|
const who = r.account ? ` as ${r.account}` : '';
|
|
857
|
-
const
|
|
858
|
-
const readOnly = !r.rc ? c.dim(' · remote control off (/rc turns it on)') : r.commands.length ? c.dim(' · remote control on') : c.dim(' · remote control on, read-only on the page (CLAUDE_PRO_REMOTE_COMMANDS=0)');
|
|
859
|
-
const text = r.online ? `${c.green('online')}${who}${pages}${readOnly}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
|
|
929
|
+
const text = r.online ? `${c.green('online')}${who}${c.dim(' · your other computers and your contacts can send it tasks')}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
|
|
860
930
|
return { text };
|
|
861
931
|
}
|
|
862
932
|
if (this.remoteStarting) return { text: 'connecting…' };
|
|
@@ -896,12 +966,12 @@ export class App {
|
|
|
896
966
|
cwd: (this.agent.cwd || this.cwd).replace(/\\/g, '/'),
|
|
897
967
|
name: this.peerLabel(),
|
|
898
968
|
tasks: this.runtime.tasks.running().length,
|
|
899
|
-
|
|
969
|
+
background: this.backgroundWork(),
|
|
970
|
+
restarting: Boolean(this.restartRequest || this.host?.restartWaits(this)),
|
|
900
971
|
asking: this.dialogs.length > 0, // a question waits for an answer (the page reminds the user of it)
|
|
901
972
|
conversationId: this.store.id,
|
|
902
973
|
cost: Number(this.cost.toFixed(6)),
|
|
903
974
|
context: { used: this.contextUsed(), window: cfg.model.contextWindow },
|
|
904
|
-
background: this.backgroundWork(),
|
|
905
975
|
kind: 'terminal',
|
|
906
976
|
};
|
|
907
977
|
}
|
|
@@ -923,13 +993,6 @@ export class App {
|
|
|
923
993
|
return this.contextGuess.used;
|
|
924
994
|
}
|
|
925
995
|
|
|
926
|
-
// What runs in the background: the agent's background agents and shells.
|
|
927
|
-
backgroundWork() {
|
|
928
|
-
const agents = this.runtime.tasks.list().map((t) => ({ id: t.id, kind: 'agent', description: t.description, status: t.status, startedAt: t.started }));
|
|
929
|
-
const shells = listBackgroundShells().map((s) => ({ id: s.id, kind: 'shell', description: s.description || s.command, status: s.status, startedAt: s.startedAt || null }));
|
|
930
|
-
return [...agents, ...shells];
|
|
931
|
-
}
|
|
932
|
-
|
|
933
996
|
// The dialog open in the terminal, for the page to answer (options by index: values need not be strings).
|
|
934
997
|
remoteDialog() {
|
|
935
998
|
const d = this.dialogs[0];
|
|
@@ -996,19 +1059,15 @@ export class App {
|
|
|
996
1059
|
return {};
|
|
997
1060
|
}
|
|
998
1061
|
|
|
999
|
-
//
|
|
1000
|
-
// <value> or /effort <value>), what is chosen (`current`), and the model and effort in use, as the status says.
|
|
1062
|
+
// The page's model and effort menus, from the kept lists. The page sends /model or /effort with the choice.
|
|
1001
1063
|
async remoteOptions() {
|
|
1002
1064
|
const cfg = this.config;
|
|
1003
|
-
const [models, efforts] = await Promise.all([
|
|
1004
|
-
const chosen = cfg.modelOverride || 'default';
|
|
1005
|
-
const same = (m) => m.id === cfg.model.id && m.provider === cfg.model.provider;
|
|
1006
|
-
const current = models.find((o) => o.value === chosen) || models.find((o) => o.value !== 'default' && same(cfg.resolveModel(o.value)));
|
|
1065
|
+
const [models, efforts] = await Promise.all([webModelChoices(cfg), effortChoices(cfg, { cached: true })]);
|
|
1007
1066
|
const effortChosen = cfg.effortOverride || 'default';
|
|
1008
1067
|
const { effort } = modelInfo(cfg);
|
|
1009
1068
|
return {
|
|
1010
1069
|
model: cfg.model.id,
|
|
1011
|
-
models
|
|
1070
|
+
models,
|
|
1012
1071
|
effort: effort || defaultEffort(cfg.model.id, cfg),
|
|
1013
1072
|
efforts: efforts.options.map((o) => ({ ...o, ...(o.value === effortChosen ? { current: true } : {}) })),
|
|
1014
1073
|
};
|
|
@@ -1087,10 +1146,30 @@ export class App {
|
|
|
1087
1146
|
return Boolean(this.isTurnRunning() || this.dialogs.length || this.queue.length || this.restartBlockers().length);
|
|
1088
1147
|
}
|
|
1089
1148
|
|
|
1149
|
+
// What runs in the background for this session, for the web console's live view: its background agents and the
|
|
1150
|
+
// commands it started with run_in_background that still run. [{kind: 'agent'|'shell', id, label, command, since}]
|
|
1151
|
+
backgroundWork() {
|
|
1152
|
+
const out = [];
|
|
1153
|
+
for (const t of this.runtime?.tasks?.running() || []) out.push({ kind: 'agent', id: t.id, label: t.description || t.subagentType || 'agent', since: t.started || null });
|
|
1154
|
+
const owner = this.owner;
|
|
1155
|
+
// (in the console's process the shells of all its sessions are in one list: without an owner, none is this one's)
|
|
1156
|
+
if (owner || !this.host) {
|
|
1157
|
+
for (const s of listBackgroundShells(owner)) {
|
|
1158
|
+
if (s.status !== 'running') continue;
|
|
1159
|
+
const command = String(s.command || '').replace(/\s+/g, ' ').trim().slice(0, 300);
|
|
1160
|
+
out.push({ kind: 'shell', id: s.id, label: s.description || command, command, since: s.startedAt || null });
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
return out;
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1090
1166
|
restartBlockers() {
|
|
1091
1167
|
const found = [];
|
|
1092
|
-
for (const t of this.runtime
|
|
1093
|
-
|
|
1168
|
+
for (const t of this.runtime?.tasks?.running() || []) found.push(`background agent ${t.id} "${t.description}"`);
|
|
1169
|
+
const owner = this.owner;
|
|
1170
|
+
if (owner || !this.host) {
|
|
1171
|
+
for (const s of listBackgroundShells(owner)) if (s.status === 'running') found.push(`background shell ${s.id} (${String(s.command).slice(0, 40)})`);
|
|
1172
|
+
}
|
|
1094
1173
|
return found;
|
|
1095
1174
|
}
|
|
1096
1175
|
|
|
@@ -1099,7 +1178,7 @@ export class App {
|
|
|
1099
1178
|
// the new process and goes on by itself. Returns {ok, message}.
|
|
1100
1179
|
// `cwd`: the session goes on in that directory (/cd).
|
|
1101
1180
|
requestRestart({ reason = '', then = '', continueTurn = false, force = false, cwd = null } = {}) {
|
|
1102
|
-
if (!canRestart()) return { ok: false, message: 'This session cannot restart itself.' };
|
|
1181
|
+
if (!this.canRestart()) return { ok: false, message: 'This session cannot restart itself.' };
|
|
1103
1182
|
const now = Date.now();
|
|
1104
1183
|
const recent = this.restarts.filter((t) => now - t < RESTART_WINDOW_MS);
|
|
1105
1184
|
if (recent.length >= MAX_RESTARTS && !cwd) {
|
|
@@ -1113,21 +1192,56 @@ export class App {
|
|
|
1113
1192
|
return { ok: true };
|
|
1114
1193
|
}
|
|
1115
1194
|
|
|
1116
|
-
// Leave the state of the session for the next process and go; the supervisor starts it again.
|
|
1195
|
+
// Leave the state of the session for the next process and go; the supervisor starts it again. In the web console
|
|
1196
|
+
// (`host`) a restart that loads new code restarts the console's process with all its sessions, once all of them
|
|
1197
|
+
// are idle (see web/host.js); a /cd needs no new code, and this session alone starts again, at once.
|
|
1117
1198
|
restartNow() {
|
|
1118
1199
|
const request = this.restartRequest || {};
|
|
1119
1200
|
this.restartRequest = null;
|
|
1120
|
-
|
|
1121
|
-
const now = Date.now();
|
|
1201
|
+
if (this.host && !request.cwd) { this.host.restartFor(this, request); return; }
|
|
1122
1202
|
// /cd: the conversation's file goes along to the new directory's project (see moveSession); the old one is
|
|
1123
1203
|
// removed once the next process is sure to find the new one
|
|
1124
1204
|
let moved = null;
|
|
1125
1205
|
if (request.cwd) {
|
|
1126
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; }
|
|
1127
1207
|
}
|
|
1208
|
+
const state = this.restartState(request, { moved });
|
|
1209
|
+
if (this.host) {
|
|
1210
|
+
moved?.commit();
|
|
1211
|
+
this.host.relaunch(this, state);
|
|
1212
|
+
return;
|
|
1213
|
+
}
|
|
1214
|
+
try {
|
|
1215
|
+
writeRestartState(state);
|
|
1216
|
+
} catch (e) {
|
|
1217
|
+
moved?.undo();
|
|
1218
|
+
this.notice(`Could not restart: ${e.message}`, 'warn');
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
moved?.commit();
|
|
1222
|
+
this.exit(RESTART_EXIT_CODE, { restart: true });
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
// Recover a missing conversation write before releasing the only in-memory copy.
|
|
1226
|
+
flushUnsavedConversation() {
|
|
1227
|
+
const store = this.store;
|
|
1228
|
+
if (!store?.lost) return true;
|
|
1229
|
+
const messages = this.runtime?.agent?.messages;
|
|
1230
|
+
if (!messages) return false;
|
|
1231
|
+
store.lost = false;
|
|
1232
|
+
store.reset(messages); // append sets lost again if this write fails too
|
|
1233
|
+
return !store.lost;
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
// What the next process (in the web console: the next App) needs to take the session up where it is now.
|
|
1237
|
+
// `counts`: towards the restarts that look like a loop; not a /cd (the user's), nor a restart of the web console that
|
|
1238
|
+
// another of its sessions or a change of the source caused.
|
|
1239
|
+
restartState(request = {}, { moved = null, counts = !request.cwd } = {}) {
|
|
1240
|
+
const cfg = this.config;
|
|
1241
|
+
const now = Date.now();
|
|
1128
1242
|
// a write of the conversation failed at some point: the file lacks part of it, and the next process goes on from it
|
|
1129
|
-
|
|
1130
|
-
|
|
1243
|
+
this.flushUnsavedConversation();
|
|
1244
|
+
return {
|
|
1131
1245
|
at: now,
|
|
1132
1246
|
reason: request.reason || '',
|
|
1133
1247
|
continueWith: request.continueTurn ? restartNote(request) : '',
|
|
@@ -1135,7 +1249,7 @@ export class App {
|
|
|
1135
1249
|
changedDirectory: Boolean(request.cwd),
|
|
1136
1250
|
// the browser instance in use (it may be any of several): the next process connects to it again, where the
|
|
1137
1251
|
// tab ids in the conversation are still its tabs'
|
|
1138
|
-
browser:
|
|
1252
|
+
browser: browserSessionFor(this.owner).preferred || null,
|
|
1139
1253
|
sessionId: this.store.id,
|
|
1140
1254
|
sessionFile: moved?.file || this.store.file,
|
|
1141
1255
|
modelOverride: cfg.modelOverride,
|
|
@@ -1149,23 +1263,39 @@ export class App {
|
|
|
1149
1263
|
// `peer`: a task of another session, which gets the answer of the turn that handles it
|
|
1150
1264
|
queue: this.queue.map((q) => ({ text: q.text, images: q.images || [], display: q.display ?? null, peer: q.peer || null })),
|
|
1151
1265
|
checkpoints: this.runtime.checkpoints.snapshot(),
|
|
1152
|
-
|
|
1153
|
-
restarts: [...this.restarts.filter((t) => now - t < RESTART_WINDOW_MS), ...(request.cwd ? [] : [now])],
|
|
1266
|
+
restarts: [...this.restarts.filter((t) => now - t < RESTART_WINDOW_MS), ...(counts ? [now] : [])],
|
|
1154
1267
|
// a name given with /rename or --name stays; the one taken from the directory follows it
|
|
1155
1268
|
peerName: request.cwd && !this.customTitle ? null : this.peers?.name || this.sessionName,
|
|
1156
1269
|
peerId: this.peers?.id,
|
|
1157
1270
|
remote: this.remote?.handoff() || null,
|
|
1158
|
-
|
|
1271
|
+
restartNote: this.restartNote || null, // the last restart line, merged with the next one when nothing came between
|
|
1272
|
+
used: this.inUse(),
|
|
1159
1273
|
};
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
// A session of an older version that the console started in a hidden window, a process (and a supervisor) of its
|
|
1277
|
+
// own: once it is idle the console takes it up in its own process (see web/host.js), with the same id and the state
|
|
1278
|
+
// a restart carries over, and this process ends (exit code 0: the supervisor does not start it again).
|
|
1279
|
+
async maybeMoveIntoConsole() {
|
|
1280
|
+
if (!this.legacyHidden || this.moving || this.exiting || !this.runtime || this.peerMessages || this.working() || this.restartRequest || this.reloading || this.updating) return;
|
|
1281
|
+
this.moving = true;
|
|
1160
1282
|
try {
|
|
1161
|
-
|
|
1283
|
+
const { adoptIntoConsole } = await import('../web/server.js');
|
|
1284
|
+
if (this.exiting || this.working() || this.restartRequest || this.reloading || this.updating) return;
|
|
1285
|
+
if (!this.flushUnsavedConversation()) return;
|
|
1286
|
+
const state = this.restartState({ reason: 'moved into the web console' }, { counts: false });
|
|
1287
|
+
const r = await adoptIntoConsole(state);
|
|
1288
|
+
if (!r?.ok) { this.moveRefused = r?.error || 'refused'; return; }
|
|
1289
|
+
// the console's session has this one's id now, and its peer file: closed here without removing it
|
|
1290
|
+
try { this.peers?.server?.close(); } catch { /* gone */ }
|
|
1291
|
+
this.peers = null;
|
|
1292
|
+
this.exit(0, { restart: true }); // (the gateway's remote page, if any, goes on with the console's session)
|
|
1162
1293
|
} catch (e) {
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1294
|
+
this.moveRefused = e.message; // tried again in a minute
|
|
1295
|
+
} finally {
|
|
1296
|
+
this.moving = false;
|
|
1297
|
+
if (!this.exiting && this.sourceChanged) this.maybeAutoReload().catch((e) => this.logError(e));
|
|
1166
1298
|
}
|
|
1167
|
-
moved?.commit();
|
|
1168
|
-
this.exit(RESTART_EXIT_CODE, { restart: true });
|
|
1169
1299
|
}
|
|
1170
1300
|
|
|
1171
1301
|
// /cd: the session goes on in `dir` (an existing directory). It restarts there, so that everything that belongs to
|
|
@@ -1174,7 +1304,7 @@ export class App {
|
|
|
1174
1304
|
// page's id and a name given with /rename stay. Returns {ok, message}.
|
|
1175
1305
|
changeDirectory(dir) {
|
|
1176
1306
|
if (this.isTurnRunning()) return { ok: false, message: 'Wait for the current task to finish (or press Esc) before changing the directory.' };
|
|
1177
|
-
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.' };
|
|
1307
|
+
if (!this.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.' };
|
|
1178
1308
|
return this.requestRestart({ reason: `working directory ${dir}`, cwd: dir });
|
|
1179
1309
|
}
|
|
1180
1310
|
|
|
@@ -1189,16 +1319,14 @@ export class App {
|
|
|
1189
1319
|
// The Effort tool's level holds for the request the restart continues, not for the user's next one.
|
|
1190
1320
|
if (state.effortBoost) { cfg.effortBoost = state.effortBoost; cfg.effortBoostKeepNext = Boolean(state.continueWith); }
|
|
1191
1321
|
this.restarts = (Array.isArray(state.restarts) ? state.restarts : []).filter((t) => Number.isFinite(t));
|
|
1322
|
+
this.used = state.used !== false; // (a state from before it was kept: a session in use)
|
|
1192
1323
|
if (resumable) {
|
|
1193
1324
|
this.loadSession(state.sessionFile, state.sessionId, { quiet: true });
|
|
1194
1325
|
if (Array.isArray(state.todos)) this.agent.todos = state.todos;
|
|
1195
1326
|
if (state.checkpoints) this.runtime.checkpoints.adopt(state.checkpoints);
|
|
1196
1327
|
}
|
|
1197
|
-
if (state.browser && typeof state.browser === 'object' && typeof state.browser.dir === 'string')
|
|
1328
|
+
if (state.browser && typeof state.browser === 'object' && typeof state.browser.dir === 'string') browserSessionFor(this.owner).preferred = state.browser;
|
|
1198
1329
|
if (typeof state.draft === 'string' && state.draft) this.editor.restoreDraft(state.draft, state.draftCursor, state.draftParts);
|
|
1199
|
-
// Fullscreen starts on an empty screen: without what the process before showed (an older version, or one
|
|
1200
|
-
// that ran classic), the conversation is drawn again from the session.
|
|
1201
|
-
if (this.screen.full && resumable && !Array.isArray(state.screenHistory)) this.printTranscript(this.agent.messages.slice(-80));
|
|
1202
1330
|
if (state.changedDirectory) {
|
|
1203
1331
|
// /cd: the line it answers with, here and on the remote page (which starts again from the conversation)
|
|
1204
1332
|
const line = `Working directory: ${this.cwd}`;
|
|
@@ -1206,7 +1334,25 @@ export class App {
|
|
|
1206
1334
|
this.seedOutput = [line];
|
|
1207
1335
|
return;
|
|
1208
1336
|
}
|
|
1209
|
-
|
|
1337
|
+
const text = `${glyphs.restart} Restarted${state.reason ? `: ${state.reason}` : ''}${state.continueWith ? ' · continuing' : ''}`;
|
|
1338
|
+
// The same restart line as last time with nothing shown since (idle while the source keeps changing): one line
|
|
1339
|
+
// with a count instead of a screenful of them.
|
|
1340
|
+
let count = 1;
|
|
1341
|
+
const prev = state.restartNote;
|
|
1342
|
+
const hist = this.screen.history;
|
|
1343
|
+
if (prev && prev.text === text && !state.continueWith) {
|
|
1344
|
+
let i = hist.length;
|
|
1345
|
+
while (i > 0 && hist[i - 1] === '') i--;
|
|
1346
|
+
if (i > 0 && hist[i - 1] === prev.line) {
|
|
1347
|
+
hist.splice(i - 1);
|
|
1348
|
+
count = (prev.count || 1) + 1;
|
|
1349
|
+
this.collapsedRestart = true;
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
const line = c.dim(count > 1 ? `${text} (×${count})` : text);
|
|
1353
|
+
if (this.collapsedRestart) this.screen.queueLog([line, '']); // drawn by the repaint in start()
|
|
1354
|
+
else this.screen.log(line, '');
|
|
1355
|
+
this.restartNote = { text, count, line };
|
|
1210
1356
|
}
|
|
1211
1357
|
|
|
1212
1358
|
// The turn that goes on after a restart: the note for the model, and what the user had queued meanwhile.
|
|
@@ -1231,7 +1377,7 @@ export class App {
|
|
|
1231
1377
|
// once, every edit of one session made each of the other open sessions check and restart, into a half-made
|
|
1232
1378
|
// change: 8 of them, a dozen times in a day's work.)
|
|
1233
1379
|
startSourceWatch() {
|
|
1234
|
-
if (!canRestart()) return;
|
|
1380
|
+
if (!canRestart() || this.host) return; // (the web console follows the source for all its sessions: web/host.js)
|
|
1235
1381
|
this.sourceWatch = watchSource(INSTALL_DIR, (file) => {
|
|
1236
1382
|
this.sourceChanged = file || true;
|
|
1237
1383
|
if (this.isTurnRunning()) this.sourceChangedInTurn = true;
|
|
@@ -1249,7 +1395,8 @@ export class App {
|
|
|
1249
1395
|
}
|
|
1250
1396
|
|
|
1251
1397
|
async maybeAutoReload() {
|
|
1252
|
-
if (
|
|
1398
|
+
if (this.host) { this.host.check(); return; } // all the console's sessions restart together, once all are idle
|
|
1399
|
+
if (!this.sourceChanged || this.updating || this.reloading || this.isTurnRunning() || this.exiting || this.moving || this.restartRequest || this.dialogs.length || this.queue.length) return;
|
|
1253
1400
|
if (this.skipAutoReload) { this.skipAutoReload = false; return; } // the user just interrupted: not now
|
|
1254
1401
|
if (this.restartBlockers().length) return; // looked at again whenever the program is next idle
|
|
1255
1402
|
clearTimeout(this.reloadTimer);
|
|
@@ -1300,7 +1447,7 @@ export class App {
|
|
|
1300
1447
|
} else if (r.status === 'installed') {
|
|
1301
1448
|
this.notice(`${APP_NAME} ${r.version} is installed already; this session restarts to load it ${this.working() ? 'once its work is done' : 'now'}.`);
|
|
1302
1449
|
this.updateRestart = r.version;
|
|
1303
|
-
if (canRestart()) { this.sourceChanged ||= true; if (!this.isTurnRunning()) this.maybeAutoReload(); }
|
|
1450
|
+
if (this.canRestart()) { this.sourceChanged ||= true; if (!this.isTurnRunning()) this.maybeAutoReload(); }
|
|
1304
1451
|
} else if (r.status === 'failed') {
|
|
1305
1452
|
this.notice(`Could not update ${APP_NAME}${r.version ? ` to ${r.version}` : ''}: ${r.error}`, 'warn');
|
|
1306
1453
|
} else {
|
|
@@ -1348,7 +1495,7 @@ export class App {
|
|
|
1348
1495
|
if (r.status === 'updated' || r.status === 'installed') {
|
|
1349
1496
|
this.pendingUpdate = null;
|
|
1350
1497
|
this.updateRestart = r.version;
|
|
1351
|
-
if (canRestart()) {
|
|
1498
|
+
if (this.canRestart()) {
|
|
1352
1499
|
this.notice(`${APP_NAME} was updated to ${r.version} (from ${VERSION}); restarting to load it. The conversation carries over.`);
|
|
1353
1500
|
this.sourceChanged = true;
|
|
1354
1501
|
this.maybeAutoReload();
|
|
@@ -1362,20 +1509,12 @@ export class App {
|
|
|
1362
1509
|
|
|
1363
1510
|
printWelcome() {
|
|
1364
1511
|
const cfg = this.config;
|
|
1365
|
-
const w = Math.min(this.width - 1, 76);
|
|
1366
|
-
const inner = w - 4;
|
|
1367
|
-
const row = (s) => c.claude('│') + ' ' + padEnd(truncate(s, inner), inner) + ' ' + c.claude('│');
|
|
1368
1512
|
const model = cfg.model;
|
|
1369
1513
|
const lines = [
|
|
1370
|
-
c.claude(
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
row(''),
|
|
1375
|
-
row(c.dim(` cwd: ${this.cwd}`)),
|
|
1376
|
-
row(c.dim(` model: ${model.label}${cfg.effort ? ` · effort ${cfg.effort}` : ''} · ${formatTokens(model.contextWindow)} context`)),
|
|
1377
|
-
row(c.dim(` backend: ${cfg.endpointLabel}`)),
|
|
1378
|
-
c.claude(glyphs.bottomLeft + '─'.repeat(w - 2) + glyphs.bottomRight),
|
|
1514
|
+
`${c.claude('✻')} Welcome to ${c.bold(APP_NAME)}! ${c.dim(`v${VERSION} · /help · ? for shortcuts · ${APP_NAME} web: the web console`)}`,
|
|
1515
|
+
c.dim(` cwd: ${this.cwd}`),
|
|
1516
|
+
c.dim(` model: ${model.label}${cfg.effort ? ` · effort ${cfg.effort}` : ''} · ${formatTokens(model.contextWindow)} context`),
|
|
1517
|
+
c.dim(` backend: ${cfg.endpointLabel}`),
|
|
1379
1518
|
];
|
|
1380
1519
|
lines.push('', c.dim(' Full access: every tool runs immediately, nothing is ever asked. File edits are checkpointed;'), c.dim(' /rewind puts files and/or the conversation back (shell-command changes are not tracked).'));
|
|
1381
1520
|
// (the model in use cannot be reached: said, with what connects it)
|
|
@@ -1387,56 +1526,12 @@ export class App {
|
|
|
1387
1526
|
const ok = mcp.filter((m) => m.status === 'connected').length;
|
|
1388
1527
|
lines.push(c.dim(` MCP: ${ok}/${mcp.length} servers connected${ok < mcp.length ? ' · /mcp for details' : ''}`));
|
|
1389
1528
|
}
|
|
1390
|
-
lines.push(''
|
|
1529
|
+
lines.push('');
|
|
1391
1530
|
this.logLocal(lines);
|
|
1392
1531
|
}
|
|
1393
1532
|
|
|
1394
1533
|
// ---------------------------------------------------------------- input
|
|
1395
1534
|
|
|
1396
|
-
// Always fullscreen on a terminal (there is no other mode to choose). Output that is no terminal (isTTY false: a
|
|
1397
|
-
// test's fake terminal that asks for it) is written as it comes, with the input box after it.
|
|
1398
|
-
fullscreenWanted() {
|
|
1399
|
-
return this.stdout.isTTY !== false;
|
|
1400
|
-
}
|
|
1401
|
-
|
|
1402
|
-
// Fullscreen: the wheel scrolls the conversation (3 rows a notch); a drag,
|
|
1403
|
-
// a double or a triple click selects text. Selection is copied only with Ctrl+C.
|
|
1404
|
-
// In the input box a click moves the cursor and a drag selects its text (see Editor.mouse).
|
|
1405
|
-
onMouse(m) {
|
|
1406
|
-
if (!this.screen.full || this.exiting) return;
|
|
1407
|
-
if (m.button & 64) {
|
|
1408
|
-
if (m.button & 128) return;
|
|
1409
|
-
const speed = 3;
|
|
1410
|
-
this.screen.scrollBy(m.button & 1 ? -speed : speed);
|
|
1411
|
-
return;
|
|
1412
|
-
}
|
|
1413
|
-
// Right-click is intentionally inert. Clipboard operations use Ctrl+C and Ctrl+V only.
|
|
1414
|
-
const had = this.screen.selection;
|
|
1415
|
-
const hadInput = this.editor.selection;
|
|
1416
|
-
const r = this.screen.mouse(m);
|
|
1417
|
-
if (r?.input) this.editor.mouse(r.input);
|
|
1418
|
-
else if ((m.button & 3) === 0 && !(m.button & 32) && !m.release) this.editor.clearSelection(); // a press elsewhere
|
|
1419
|
-
if ((this.screen.selection && this.screen.selection !== had) || (this.editor.selection && this.editor.selection !== hadInput)) {
|
|
1420
|
-
this.flashMessage = null; // the footer says what a selection takes
|
|
1421
|
-
this.screen.schedule();
|
|
1422
|
-
}
|
|
1423
|
-
}
|
|
1424
|
-
|
|
1425
|
-
// Quote what is selected in the conversation in the message being written, as ChatGPT's "Ask ChatGPT" does:
|
|
1426
|
-
// ctrl+q (alt+q where the terminal keeps ctrl+q), as the footer says while there is a selection. The box shows
|
|
1427
|
-
// "[Quote #1 +12 lines]"; the model gets the text and the line of the conversation it is under (see
|
|
1428
|
-
// Editor.insertQuote), so that it knows which part, and which file or command, the question is about.
|
|
1429
|
-
quoteSelection() {
|
|
1430
|
-
if (!this.screen.full) { this.flash('Quoting needs the fullscreen view: select text with the mouse, then ctrl+q', 'warn'); return; }
|
|
1431
|
-
const quote = this.screen.selectionQuote();
|
|
1432
|
-
if (!quote?.text.trim()) { this.flash('Select part of the conversation first (drag over it, or double/triple-click), then ctrl+q', 'warn'); return; }
|
|
1433
|
-
if (this.dialogs.length) { this.flash('Answer the open question first, then quote', 'warn'); return; }
|
|
1434
|
-
if (this.finder) this.closeFind();
|
|
1435
|
-
this.screen.clearSelection();
|
|
1436
|
-
const label = this.editor.insertQuote(quote.text, quote.source);
|
|
1437
|
-
this.flash(`${label}${quote.source ? ` from ${quote.source}` : ''}: type your question below it`);
|
|
1438
|
-
}
|
|
1439
|
-
|
|
1440
1535
|
copyText(text) {
|
|
1441
1536
|
writeClipboard(text).then((ok) => {
|
|
1442
1537
|
if (ok) this.flash(`Copied ${text.length.toLocaleString()} characters to the clipboard`);
|
|
@@ -1447,30 +1542,14 @@ export class App {
|
|
|
1447
1542
|
clipboardEditor() {
|
|
1448
1543
|
const dialog = this.dialogs[0];
|
|
1449
1544
|
if (dialog) return dialog.editor || dialog.other || null;
|
|
1450
|
-
return this.
|
|
1545
|
+
return this.editor;
|
|
1451
1546
|
}
|
|
1452
1547
|
|
|
1453
|
-
|
|
1454
|
-
const f = this.finder;
|
|
1455
|
-
const clean = String(text ?? '').replace(/[\r\n\t]+/g, ' ');
|
|
1456
|
-
if (!f || !clean) return;
|
|
1457
|
-
if (f.selected) {
|
|
1458
|
-
f.text = clean;
|
|
1459
|
-
f.cursor = clean.length;
|
|
1460
|
-
f.selected = false;
|
|
1461
|
-
} else {
|
|
1462
|
-
f.text = f.text.slice(0, f.cursor) + clean + f.text.slice(f.cursor);
|
|
1463
|
-
f.cursor += clean.length;
|
|
1464
|
-
}
|
|
1465
|
-
this.screen.setFind(f.text);
|
|
1466
|
-
}
|
|
1467
|
-
|
|
1468
|
-
// Pasted text into the input box, the open dialog's text field or the find box.
|
|
1548
|
+
// Pasted text into the input box or the open dialog's text field.
|
|
1469
1549
|
insertPastedText(text, target = this.clipboardEditor()) {
|
|
1470
1550
|
const clean = String(text || '').replace(/\x1b\[20[01]~/g, '');
|
|
1471
1551
|
if (!clean) return;
|
|
1472
1552
|
if (target) target.insertPaste(clean);
|
|
1473
|
-
else if (this.finder) this.insertFindText(clean);
|
|
1474
1553
|
this.screen.schedule();
|
|
1475
1554
|
}
|
|
1476
1555
|
|
|
@@ -1478,9 +1557,8 @@ export class App {
|
|
|
1478
1557
|
// is only done when the terminal had nothing to paste (alt+v, ctrl+v as a key, an empty bracketed paste).
|
|
1479
1558
|
pasteClipboard(target = this.clipboardEditor()) {
|
|
1480
1559
|
if (this.readingClipboard || this.exiting) return;
|
|
1481
|
-
if (!target
|
|
1560
|
+
if (!target) return; // selection dialogs have no text field to paste into
|
|
1482
1561
|
this.readingClipboard = true;
|
|
1483
|
-
this.flash('Reading clipboard…');
|
|
1484
1562
|
const allowImage = Boolean(target?.insertImage);
|
|
1485
1563
|
const image = allowImage
|
|
1486
1564
|
? readClipboardImage().catch((e) => ({ image: null, error: e.message }))
|
|
@@ -1506,7 +1584,7 @@ export class App {
|
|
|
1506
1584
|
}
|
|
1507
1585
|
|
|
1508
1586
|
onKey(str, key) {
|
|
1509
|
-
if (this.exiting) return;
|
|
1587
|
+
if (this.exiting || this.moving) return;
|
|
1510
1588
|
// Terminals paste (ctrl+v in Windows Terminal and VS Code) as bracketed paste: readline reports paste-start/end
|
|
1511
1589
|
// and emits the text as ordinary keys between them. That text goes in at once. A paste with no text is what a
|
|
1512
1590
|
// terminal sends for an image on the clipboard, which only the system clipboard has (alt+v reads it on demand).
|
|
@@ -1524,57 +1602,22 @@ export class App {
|
|
|
1524
1602
|
}
|
|
1525
1603
|
return;
|
|
1526
1604
|
}
|
|
1527
|
-
if (this.screen.full) {
|
|
1528
|
-
const half = Math.max(1, Math.floor((this.screen.lastArea || this.screen.height) / 2));
|
|
1529
|
-
if (key.name === 'pageup') { this.screen.scrollBy(half); return; }
|
|
1530
|
-
if (key.name === 'pagedown') { this.screen.scrollBy(-half); return; }
|
|
1531
|
-
if (key.ctrl && key.name === 'home') { this.screen.scrollBy('top'); return; }
|
|
1532
|
-
if (key.ctrl && key.name === 'end') { this.screen.scrollBy('bottom'); return; }
|
|
1533
|
-
// ctrl+f looks for what is selected, if anything
|
|
1534
|
-
if (key.ctrl && key.name === 'f' && !this.dialogs.length) {
|
|
1535
|
-
const seed = this.screen.selection ? this.screen.selectedText() : '';
|
|
1536
|
-
this.screen.clearSelection();
|
|
1537
|
-
this.openFind(seed);
|
|
1538
|
-
return;
|
|
1539
|
-
}
|
|
1540
|
-
// A selection: ctrl+c copies it (and does not interrupt), esc only clears it, any other key clears it and
|
|
1541
|
-
// then does what it does.
|
|
1542
|
-
if (this.screen.selection) {
|
|
1543
|
-
if (key.ctrl && key.name === 'c') { this.copyText(this.screen.selectedText()); this.screen.clearSelection(); return; }
|
|
1544
|
-
if ((key.ctrl || key.meta) && key.name === 'q') { this.quoteSelection(); return; }
|
|
1545
|
-
this.screen.clearSelection();
|
|
1546
|
-
if (key.name === 'escape') return;
|
|
1547
|
-
}
|
|
1548
|
-
}
|
|
1549
|
-
// A selection in the input box (see Editor.mouse), the same way: ctrl+c copies it (and neither interrupts nor
|
|
1550
|
-
// clears the message), esc only clears it, any other key clears it and then does what it does.
|
|
1551
|
-
if (this.editor.selection) {
|
|
1552
|
-
const shown = !this.dialogs.length && !this.finder; // else the box is not on screen, and the key is not for it
|
|
1553
|
-
if (shown && key.ctrl && key.name === 'c') { this.copyText(this.editor.selectedText()); this.editor.clearSelection(); return; }
|
|
1554
|
-
this.editor.clearSelection();
|
|
1555
|
-
if (shown && key.name === 'escape') return;
|
|
1556
|
-
}
|
|
1557
1605
|
if (key.name === 'paste-start' || key.sequence === '\x1b[200~') {
|
|
1558
1606
|
this.bracketedPaste = { raw: '' };
|
|
1559
1607
|
return;
|
|
1560
1608
|
}
|
|
1561
|
-
if (key.ctrl && key.name === 'c' && this.finder && !this.dialogs.length) { this.closeFind(); return; } // not the hidden input's text
|
|
1562
1609
|
if (key.ctrl && key.name === 'c') { this.onCtrlC(); return; }
|
|
1563
1610
|
if ((key.ctrl || key.meta) && key.name === 'v') { this.pasteClipboard(); return; } // alt+v: the clipboard's image
|
|
1564
|
-
if ((key.ctrl || key.meta) && key.name === 'q') { this.quoteSelection(); return; } // nothing selected: says how
|
|
1565
1611
|
const dialog = this.dialogs[0];
|
|
1566
1612
|
if (dialog) {
|
|
1567
1613
|
dialog.handleKey(str, key);
|
|
1568
1614
|
this.screen.schedule();
|
|
1569
1615
|
return;
|
|
1570
1616
|
}
|
|
1571
|
-
if (key.ctrl && key.name === '
|
|
1572
|
-
if (this.finder) { this.findKey(str, key); this.screen.schedule(); return; }
|
|
1573
|
-
if (key.ctrl && key.name === 't') { this.showTodos = !this.showTodos; this.screen.schedule(); return; }
|
|
1574
|
-
if (key.ctrl && key.name === 'l') { if (this.screen.full) this.screen.repaint(); else this.screen.clearScreen(); return; }
|
|
1617
|
+
if (key.ctrl && key.name === 'l') { this.screen.clearScreen(); return; }
|
|
1575
1618
|
if (key.ctrl && key.name === 'd' && !this.editor.text) { this.keyboardExit(); return; }
|
|
1576
1619
|
// esc closes an open completion list first (the editor does that), and only then stops the turn
|
|
1577
|
-
if (key.name === 'escape' && this.isTurnRunning() && !this.editor.
|
|
1620
|
+
if (key.name === 'escape' && this.isTurnRunning() && !this.editor.completing) { this.interrupt(); return; }
|
|
1578
1621
|
this.exitArmed = 0;
|
|
1579
1622
|
this.editor.handleKey(str, key);
|
|
1580
1623
|
this.screen.schedule();
|
|
@@ -1687,7 +1730,6 @@ export class App {
|
|
|
1687
1730
|
onSubmit(value, raw, images = [], display = undefined, parts = null) {
|
|
1688
1731
|
const text = value.trim();
|
|
1689
1732
|
if (!text) { this.screen.schedule(); return; }
|
|
1690
|
-
if (this.screen.scrolledUp) this.screen.scrollBy('bottom'); // what was sent, and what comes of it, is in view
|
|
1691
1733
|
appendHistory(this.cwd, raw, parts);
|
|
1692
1734
|
if (this.sendTypedToPeer(text)) return;
|
|
1693
1735
|
if (this.isTurnRunning() && !this.modelSwitchAtPause(text)) {
|
|
@@ -1710,7 +1752,7 @@ export class App {
|
|
|
1710
1752
|
return;
|
|
1711
1753
|
}
|
|
1712
1754
|
if (!/^\/[\w:-]+$/.test(text.split(/\s/)[0])) { this.startTurn(value, { display }); return; } // e.g. a path like /usr/bin
|
|
1713
|
-
this.notice(`Unknown command: /${name}. Type /
|
|
1755
|
+
this.notice(`Unknown command: /${name}. Type / and press Tab for the list of commands, or /help.`, 'warn');
|
|
1714
1756
|
return;
|
|
1715
1757
|
}
|
|
1716
1758
|
this.startTurn(value, { display });
|
|
@@ -1756,102 +1798,15 @@ export class App {
|
|
|
1756
1798
|
shortcutsHelp() {
|
|
1757
1799
|
const rows = [
|
|
1758
1800
|
['! for bash mode', 'double tap esc to clear input'],
|
|
1759
|
-
['/ for commands', '
|
|
1760
|
-
['@ for files and sessions', '
|
|
1761
|
-
['
|
|
1762
|
-
['
|
|
1763
|
-
['
|
|
1764
|
-
['ctrl + c to copy selection', 'ctrl + q to quote it in your message'],
|
|
1765
|
-
['ctrl + v to paste text or an image', ''],
|
|
1801
|
+
['/ for commands', 'tab to complete / and @'],
|
|
1802
|
+
['@ for files and sessions', '/verbose for detailed tool output'],
|
|
1803
|
+
['# to memorize', 'esc to interrupt'],
|
|
1804
|
+
['\\⏎ or alt+⏎ for newline', 'ctrl + l to clear, ctrl + d to exit'],
|
|
1805
|
+
['ctrl + v to paste text or an image', 'claude-pro web: the web console'],
|
|
1766
1806
|
];
|
|
1767
1807
|
return rows.map(([a, b]) => c.dim(' ' + padEnd(a, 30) + b));
|
|
1768
1808
|
}
|
|
1769
1809
|
|
|
1770
|
-
// ---------------------------------------------------------------- finding in the conversation (ctrl+f)
|
|
1771
|
-
//
|
|
1772
|
-
// As in VS Code: a box takes the input box's place, the conversation shows the matches as they are typed, the
|
|
1773
|
-
// current one apart, and goes to it. In a conversation the newest matter most: the first one shown is the
|
|
1774
|
-
// nearest above the bottom of the view, enter (or ↑) goes on to older ones, shift+enter (or ↓) back to newer
|
|
1775
|
-
// ones, round from either end. Esc closes the box and leaves the view where it is. The text typed last comes
|
|
1776
|
-
// back selected (typing replaces it), or what is selected with the mouse. Fullscreen only: in the classic
|
|
1777
|
-
// renderer the conversation is in the terminal's own scrollback.
|
|
1778
|
-
|
|
1779
|
-
openFind(seed = '') {
|
|
1780
|
-
if (!this.screen.full) { this.flash('ctrl+f needs the fullscreen view; here use the terminal\'s own find', 'warn'); return; }
|
|
1781
|
-
if (this.finder && !seed.trim()) { this.finder.selected = Boolean(this.finder.text); this.screen.schedule(); return; } // open: select what is typed
|
|
1782
|
-
const text = (seed.split('\n').find((l) => l.trim()) || '').trim() || this.lastFind || '';
|
|
1783
|
-
if (!this.finder) this.screen.openFind();
|
|
1784
|
-
this.finder = { text, cursor: text.length, selected: Boolean(text) };
|
|
1785
|
-
this.screen.setFind(text);
|
|
1786
|
-
this.screen.schedule();
|
|
1787
|
-
}
|
|
1788
|
-
|
|
1789
|
-
closeFind() {
|
|
1790
|
-
if (!this.finder) return;
|
|
1791
|
-
this.lastFind = this.finder.text;
|
|
1792
|
-
this.finder = null;
|
|
1793
|
-
this.screen.closeFind();
|
|
1794
|
-
this.screen.schedule();
|
|
1795
|
-
}
|
|
1796
|
-
|
|
1797
|
-
findKey(str, key) {
|
|
1798
|
-
const f = this.finder;
|
|
1799
|
-
const name = key.name;
|
|
1800
|
-
const edit = (text, cursor) => {
|
|
1801
|
-
Object.assign(f, { text, cursor, selected: false });
|
|
1802
|
-
this.screen.setFind(text);
|
|
1803
|
-
};
|
|
1804
|
-
const insert = (s) => {
|
|
1805
|
-
const t = s.replace(/[\r\n\t]+/g, ' ');
|
|
1806
|
-
if (!t) return;
|
|
1807
|
-
if (f.selected) edit(t, t.length);
|
|
1808
|
-
else edit(f.text.slice(0, f.cursor) + t + f.text.slice(f.cursor), f.cursor + t.length);
|
|
1809
|
-
};
|
|
1810
|
-
// a bracketed paste never gets here: App.onKey takes it whole (see insertFindText)
|
|
1811
|
-
if (name === 'escape') { this.closeFind(); return; }
|
|
1812
|
-
const back = (name === 'return' && (key.meta || key.shift)) || name === 'enter' || key.sequence === '\x1b[13;2u' || (name === 'f3' && key.shift);
|
|
1813
|
-
if (back || name === 'down' || (key.ctrl && name === 'n')) { f.selected = false; this.screen.findStep(-1); return; }
|
|
1814
|
-
if (name === 'return' || name === 'f3' || name === 'up' || (key.ctrl && name === 'p')) { f.selected = false; this.screen.findStep(1); return; }
|
|
1815
|
-
const chars = [...f.text.slice(0, f.cursor)];
|
|
1816
|
-
if (name === 'backspace') {
|
|
1817
|
-
if (f.selected) edit('', 0);
|
|
1818
|
-
else if (chars.length) { const keep = chars.slice(0, -1).join(''); edit(keep + f.text.slice(f.cursor), keep.length); }
|
|
1819
|
-
return;
|
|
1820
|
-
}
|
|
1821
|
-
if (name === 'delete') {
|
|
1822
|
-
if (f.selected) edit('', 0);
|
|
1823
|
-
else if (f.cursor < f.text.length) { const next = [...f.text.slice(f.cursor)].slice(1).join(''); edit(f.text.slice(0, f.cursor) + next, f.cursor); }
|
|
1824
|
-
return;
|
|
1825
|
-
}
|
|
1826
|
-
if (key.ctrl && name === 'u') { edit('', 0); return; }
|
|
1827
|
-
if (name === 'left') { f.selected = false; f.cursor = chars.slice(0, -1).join('').length; return; }
|
|
1828
|
-
if (name === 'right') { f.selected = false; f.cursor = Math.min(f.text.length, f.cursor + ([...f.text.slice(f.cursor)][0]?.length || 0)); return; }
|
|
1829
|
-
if (name === 'home' || (key.ctrl && name === 'a')) { f.selected = false; f.cursor = 0; return; }
|
|
1830
|
-
if (name === 'end' || (key.ctrl && name === 'e')) { f.selected = false; f.cursor = f.text.length; return; }
|
|
1831
|
-
if (str && !key.ctrl && !key.meta && !/[\x00-\x1f\x7f]/.test(str)) insert(str);
|
|
1832
|
-
}
|
|
1833
|
-
|
|
1834
|
-
// The find box, in the input box's place: what is typed (selected: in reverse video), and how many matches.
|
|
1835
|
-
renderFind(width) {
|
|
1836
|
-
const f = this.finder;
|
|
1837
|
-
const boxW = Math.max(20, width - 1);
|
|
1838
|
-
const textW = boxW - 6;
|
|
1839
|
-
const s = this.screen.findStatus();
|
|
1840
|
-
const count = !f.text ? '' : s?.total ? `${s.index + 1}/${s.total}` : c.red('No results');
|
|
1841
|
-
const title = { left: 'Find in the conversation', right: count };
|
|
1842
|
-
// the part of the text that fits, the cursor in it
|
|
1843
|
-
let before = f.text.slice(0, f.cursor);
|
|
1844
|
-
while (before && stringWidth(before) > textW - 1) before = [...before].slice(1).join('');
|
|
1845
|
-
const shown = truncate(before + f.text.slice(f.cursor), textW, '');
|
|
1846
|
-
const content = f.selected && shown ? c.inverse(shown) : shown;
|
|
1847
|
-
const lines = [
|
|
1848
|
-
topBorder(boxW, c.yellow, title),
|
|
1849
|
-
c.yellow('│') + ' ' + c.yellow(glyphs.find) + ' ' + padEnd(content, textW) + ' ' + c.yellow('│'),
|
|
1850
|
-
c.yellow(glyphs.bottomLeft + '─'.repeat(boxW - 2) + glyphs.bottomRight),
|
|
1851
|
-
];
|
|
1852
|
-
return { lines, cursor: { row: 1, col: 4 + stringWidth(before) } };
|
|
1853
|
-
}
|
|
1854
|
-
|
|
1855
1810
|
// ---------------------------------------------------------------- turns
|
|
1856
1811
|
|
|
1857
1812
|
// Where a mentioned path is (null when there is no such file): relative to the project root, which is
|
|
@@ -1934,7 +1889,7 @@ export class App {
|
|
|
1934
1889
|
this.turnStarting = true;
|
|
1935
1890
|
this.turnStart = Date.now();
|
|
1936
1891
|
this.verb = VERBS[Math.floor(Math.random() * VERBS.length)];
|
|
1937
|
-
if (echo) this.echoUser(display ?? prompt
|
|
1892
|
+
if (echo) this.echoUser(display ?? prompt);
|
|
1938
1893
|
this.refreshTopic(topic ?? display ?? prompt);
|
|
1939
1894
|
let content;
|
|
1940
1895
|
try {
|
|
@@ -1976,15 +1931,41 @@ export class App {
|
|
|
1976
1931
|
return [{ type: 'text', text: `<system-reminder>The user refers to other sessions: ${notes.join('; ')}. MessagePeer (to: the name in quotes) sends a session a task.</system-reminder>` }];
|
|
1977
1932
|
}
|
|
1978
1933
|
|
|
1979
|
-
//
|
|
1934
|
+
// The status line under each answer: "✻ Done at 14:05 · worked 1m 3s · $0.12 (total $3.40) · ctx 45k/1M · opus-5-5 max".
|
|
1935
|
+
doneText() {
|
|
1936
|
+
const at = new Date().toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', hour12: false });
|
|
1937
|
+
const parts = [`✻ Done at ${at}`, `worked ${formatDuration(Date.now() - this.turnStart)}`];
|
|
1938
|
+
const spent = this.cost - (this.turnCostStart || 0);
|
|
1939
|
+
if (spent > 0) parts.push(this.cost > spent + 0.005 ? `${formatUsd(spent)} (total ${formatUsd(this.cost)})` : formatUsd(spent));
|
|
1940
|
+
try {
|
|
1941
|
+
const cfg = this.config;
|
|
1942
|
+
const k = (n) => formatTokens(n).replace(/\.0([kM])$/, '$1');
|
|
1943
|
+
parts.push(`ctx ${k(this.agent.contextEstimate)}/${k(cfg.model.contextWindow)}`);
|
|
1944
|
+
const { model, effort } = modelInfo(cfg);
|
|
1945
|
+
const level = effort || defaultEffort(cfg.model.id, cfg);
|
|
1946
|
+
parts.push(level ? `${model} ${level}` : model);
|
|
1947
|
+
} catch { /* no model information: the time and the cost are enough */ }
|
|
1948
|
+
return parts.join(' · ');
|
|
1949
|
+
}
|
|
1950
|
+
|
|
1951
|
+
// A turn ended with `text` under its answer: kept with the conversation, so that the web console shows it again
|
|
1952
|
+
// when it rebuilds the view from the messages (a reload, a restart of the session or of the console).
|
|
1953
|
+
markTurn(text) {
|
|
1954
|
+
const msgs = this.agent?.messages || [];
|
|
1955
|
+
if (!msgs.length) return;
|
|
1956
|
+
if (this.marksBase !== msgs) { this.marksBase = msgs; this.turnMarks = this.turnMarks.filter((m) => msgs[m.after - 1] === m.msg); }
|
|
1957
|
+
this.turnMarks.push({ after: msgs.length, text, msg: msgs[msgs.length - 1] });
|
|
1958
|
+
this.store.turnEnd(msgs.length, text);
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
// A short message about something the user just did (a paste, a copy, a completion with nothing to offer): a
|
|
1962
|
+
// line of its own, as there is no footer to show it in.
|
|
1980
1963
|
flash(text, kind = 'info') {
|
|
1981
|
-
this.
|
|
1982
|
-
this.screen.schedule();
|
|
1983
|
-
clearTimeout(this.flashTimer);
|
|
1984
|
-
this.flashTimer = setTimeout(() => this.screen.schedule(), 4100);
|
|
1964
|
+
this.notice(text, kind);
|
|
1985
1965
|
}
|
|
1986
1966
|
|
|
1987
1967
|
async runAgent(content, { peers = [] } = {}) {
|
|
1968
|
+
this.used = true; // (see inUse)
|
|
1988
1969
|
this.turnStarting = false;
|
|
1989
1970
|
this.busy = true;
|
|
1990
1971
|
this.turnPeers.push(...peers);
|
|
@@ -1993,6 +1974,7 @@ export class App {
|
|
|
1993
1974
|
this.controller = new AbortController();
|
|
1994
1975
|
this.turnStart = Date.now();
|
|
1995
1976
|
this.turnTokens = 0;
|
|
1977
|
+
this.turnCostStart = this.cost;
|
|
1996
1978
|
this.verb = VERBS[Math.floor(Math.random() * VERBS.length)];
|
|
1997
1979
|
this.screen.schedule();
|
|
1998
1980
|
try {
|
|
@@ -2014,10 +1996,12 @@ export class App {
|
|
|
2014
1996
|
} finally {
|
|
2015
1997
|
this.flushStreaming();
|
|
2016
1998
|
this.flushActive(true);
|
|
2017
|
-
// When the answer came and how long the turn took, under the answer (the user asked for the time, 2026-11-21)
|
|
1999
|
+
// When the answer came and how long the turn took, under the answer (the user asked for the time, 2026-11-21),
|
|
2000
|
+
// with what there is no footer for: the cost, the context in use, the model.
|
|
2018
2001
|
if (result && !result.interrupted && !error) {
|
|
2019
|
-
const
|
|
2020
|
-
this.screen.log(c.dim(
|
|
2002
|
+
const text = this.doneText();
|
|
2003
|
+
this.screen.log(c.dim(text), '');
|
|
2004
|
+
this.markTurn(text);
|
|
2021
2005
|
}
|
|
2022
2006
|
this.answerPeers(result, error);
|
|
2023
2007
|
this.busy = false;
|
|
@@ -2135,10 +2119,11 @@ export class App {
|
|
|
2135
2119
|
|
|
2136
2120
|
// `quiet`: do not print the transcript (a restart: it is still on screen).
|
|
2137
2121
|
loadSession(file, id, { quiet = false } = {}) {
|
|
2138
|
-
const loaded = SessionStore.load(file);
|
|
2122
|
+
const loaded = this.runtime.useSession(id, () => SessionStore.load(file));
|
|
2139
2123
|
this.previousSession = null; // the conversation before a /clear: resuming another one ends the offer
|
|
2140
2124
|
this.seedOutput = [];
|
|
2141
2125
|
this.store = new SessionStore(this.cwd, id);
|
|
2126
|
+
this.store.onError = this.storeError;
|
|
2142
2127
|
this.runtime.trace?.setSessionId(id);
|
|
2143
2128
|
this.topic = loaded.topic;
|
|
2144
2129
|
this.customTitle = loaded.name;
|
|
@@ -2152,6 +2137,8 @@ export class App {
|
|
|
2152
2137
|
this.cost = loaded.cost;
|
|
2153
2138
|
this.agent.cache.clockUntil = this.store.cacheUntil = loaded.cacheUntil;
|
|
2154
2139
|
this.agent.messages = loaded.messages;
|
|
2140
|
+
this.marksBase = loaded.messages;
|
|
2141
|
+
this.turnMarks = (loaded.turns || []).map((t) => ({ ...t, msg: loaded.messages[t.after - 1] }));
|
|
2155
2142
|
this.agent.restoreFileState(loaded.messages, loaded.times);
|
|
2156
2143
|
this.agent.lastActivityAt = loaded.lastAt; // a long pause before this turn clears old tool results, as it would have
|
|
2157
2144
|
this.agent.lastContextTokens = estimateTokens(loaded.messages);
|
|
@@ -2159,9 +2146,11 @@ export class App {
|
|
|
2159
2146
|
this.store.systemPrompt = loaded.systemPrompt;
|
|
2160
2147
|
this.runtime.resumeSystemPrompt(loaded.systemPrompt, loaded.promptCode);
|
|
2161
2148
|
// Its cache still warm (a restart, a quick resume): it goes on being refreshed while idle (keepalive.js).
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
this.
|
|
2149
|
+
// (in the web console a conversation is taken up as soon as it is opened: one only looked at costs nothing, no
|
|
2150
|
+
// cache refreshes and no title request, until it is used)
|
|
2151
|
+
this.agent.restoreCacheState(loaded.cacheState, { keepWarm: this.inUse() });
|
|
2152
|
+
if (!this.topic && this.inUse()) this.refreshTopic(this.latestPrompt()); // a session from before topics were kept
|
|
2153
|
+
this.liveFeed.resync();
|
|
2165
2154
|
if (quiet) return;
|
|
2166
2155
|
const restoredCount = loaded.messages.length;
|
|
2167
2156
|
const shown = loaded.messages.slice(-30);
|
|
@@ -2197,14 +2186,19 @@ export class App {
|
|
|
2197
2186
|
}
|
|
2198
2187
|
|
|
2199
2188
|
newSession() {
|
|
2200
|
-
|
|
2189
|
+
const store = new SessionStore(this.cwd);
|
|
2190
|
+
this.runtime.useSession(store.id);
|
|
2191
|
+
this.store = store;
|
|
2192
|
+
this.store.onError = this.storeError;
|
|
2201
2193
|
this.runtime.trace?.setSessionId(this.store.id);
|
|
2202
2194
|
this.seedOutput = [];
|
|
2195
|
+
this.turnMarks = [];
|
|
2196
|
+
this.marksBase = this.agent?.messages || null;
|
|
2203
2197
|
this.topic = null;
|
|
2204
2198
|
this.customTitle = null;
|
|
2205
2199
|
this.firstPrompt = null;
|
|
2206
2200
|
this.cost = 0;
|
|
2207
|
-
this.
|
|
2201
|
+
this.liveFeed.resync();
|
|
2208
2202
|
}
|
|
2209
2203
|
|
|
2210
2204
|
// ---------------------------------------------------------------- dialogs
|
|
@@ -2248,9 +2242,9 @@ export class App {
|
|
|
2248
2242
|
if (ev.block.type === 'text') {
|
|
2249
2243
|
this.flushThinking();
|
|
2250
2244
|
this.md = new MarkdownStream({ width: w, firstPrefix: `${DOT} `, indent: ' ' });
|
|
2251
|
-
this.
|
|
2245
|
+
this.emitEvent({ t: 'start', kind: 'text' });
|
|
2252
2246
|
} else if (ev.block.type === 'thinking') {
|
|
2253
|
-
this.
|
|
2247
|
+
this.emitEvent({ t: 'start', kind: 'thinking' });
|
|
2254
2248
|
this.thinking = new MarkdownStream({ width: w, firstPrefix: c.dim('✻ '), indent: ' ', style: (s) => c.dim(c.italic(s)) });
|
|
2255
2249
|
} else if (ev.block.type === 'tool_use') {
|
|
2256
2250
|
this.flushThinking();
|
|
@@ -2262,13 +2256,13 @@ export class App {
|
|
|
2262
2256
|
if (this.md) {
|
|
2263
2257
|
const lines = this.md.write(ev.text);
|
|
2264
2258
|
if (lines.length) this.logLocal({ soon: true }, lines);
|
|
2265
|
-
this.
|
|
2259
|
+
this.emitEvent({ t: 'delta', kind: 'text', text: ev.text });
|
|
2266
2260
|
}
|
|
2267
2261
|
break;
|
|
2268
2262
|
case 'thinking':
|
|
2269
2263
|
this.turnTokens += estimateTokens(ev.text);
|
|
2270
2264
|
if (this.thinking) {
|
|
2271
|
-
this.
|
|
2265
|
+
this.emitEvent({ t: 'delta', kind: 'thinking', text: ev.text });
|
|
2272
2266
|
const lines = this.thinking.write(ev.text);
|
|
2273
2267
|
if (lines.length) this.logLocal({ soon: true }, lines);
|
|
2274
2268
|
}
|
|
@@ -2285,7 +2279,7 @@ export class App {
|
|
|
2285
2279
|
if (lines.length) this.logLocal(lines);
|
|
2286
2280
|
this.logLocal('');
|
|
2287
2281
|
this.md = null;
|
|
2288
|
-
this.
|
|
2282
|
+
this.emitEvent({ t: 'stop' });
|
|
2289
2283
|
} else if (ev.block.type === 'thinking') {
|
|
2290
2284
|
this.flushThinking();
|
|
2291
2285
|
} else if (ev.block.type === 'tool_use') {
|
|
@@ -2300,7 +2294,7 @@ export class App {
|
|
|
2300
2294
|
this.rateLimitEvent(ev);
|
|
2301
2295
|
break;
|
|
2302
2296
|
case 'reset':
|
|
2303
|
-
if (this.md || this.thinking) this.
|
|
2297
|
+
if (this.md || this.thinking) this.emitEvent({ t: 'stop' });
|
|
2304
2298
|
this.md = null;
|
|
2305
2299
|
this.thinking = null;
|
|
2306
2300
|
this.pendingToolBlocks.clear();
|
|
@@ -2329,7 +2323,7 @@ export class App {
|
|
|
2329
2323
|
const t = this.thinking;
|
|
2330
2324
|
if (!t) return;
|
|
2331
2325
|
this.thinking = null;
|
|
2332
|
-
this.
|
|
2326
|
+
this.emitEvent({ t: 'stop' });
|
|
2333
2327
|
const lines = t.end();
|
|
2334
2328
|
if (lines.length) this.logLocal(lines);
|
|
2335
2329
|
if (t.emittedAny) this.logLocal('');
|
|
@@ -2341,7 +2335,7 @@ export class App {
|
|
|
2341
2335
|
const lines = this.md.end();
|
|
2342
2336
|
if (lines.length) this.logLocal(lines, '');
|
|
2343
2337
|
this.md = null;
|
|
2344
|
-
this.
|
|
2338
|
+
this.emitEvent({ t: 'stop' });
|
|
2345
2339
|
}
|
|
2346
2340
|
this.pendingToolBlocks.clear();
|
|
2347
2341
|
}
|
|
@@ -2354,13 +2348,13 @@ export class App {
|
|
|
2354
2348
|
if (!this.isMain(agent)) return {};
|
|
2355
2349
|
const entry = { tu, tool, input, status: 'running', progress: '', sub: [], subCount: 0, ctx: agent.makeCtx(), started: Date.now() };
|
|
2356
2350
|
this.active.push(entry);
|
|
2357
|
-
this.
|
|
2351
|
+
this.emitEvent({ t: 'tool', id: tu.id, head: toolHeader(tool, input, entry.ctx, { width: REMOTE_WIDTH, dot: false }) });
|
|
2358
2352
|
this.screen.schedule();
|
|
2359
2353
|
return {
|
|
2360
2354
|
progress: (p, meta) => {
|
|
2361
2355
|
// `all`: the whole output so far (the progress is its end), for the page's "the whole output"
|
|
2362
|
-
if (typeof p === 'string') { entry.progress = p; entry.progressLines = meta?.lines; entry.progressAll = meta?.all; this.
|
|
2363
|
-
else if (p?.type === 'subtool') { entry.sub.push(p.header); entry.subCount++; this.
|
|
2356
|
+
if (typeof p === 'string') { entry.progress = p; entry.progressLines = meta?.lines; entry.progressAll = meta?.all; this.liveFeed.toolProgress(tu.id, entry); }
|
|
2357
|
+
else if (p?.type === 'subtool') { entry.sub.push(p.header); entry.subCount++; this.emitEvent({ t: 'sub', id: tu.id, head: p.header }); }
|
|
2364
2358
|
this.screen.schedule();
|
|
2365
2359
|
},
|
|
2366
2360
|
done: (result) => {
|
|
@@ -2376,20 +2370,60 @@ export class App {
|
|
|
2376
2370
|
if (!this.isMain(agent)) return;
|
|
2377
2371
|
const ctx = agent.makeCtx();
|
|
2378
2372
|
const entry = { tu, tool, input: tu.input, status: 'rejected', rejected: true, rejectMessage: message, ctx };
|
|
2379
|
-
if (this.
|
|
2380
|
-
this.
|
|
2373
|
+
if (this.liveFeed.active) {
|
|
2374
|
+
this.emitEvent({ t: 'tool', id: tu.id, head: toolHeader(tool, tu.input, ctx, { width: REMOTE_WIDTH, dot: false }) });
|
|
2381
2375
|
this.remoteToolDone(entry);
|
|
2382
2376
|
}
|
|
2383
2377
|
this.logLocal(toolHeader(tool, tu.input, ctx, { status: 'rejected', width: this.width }), renderToolResult(entry, { width: this.width, cwd: this.cwd }), '');
|
|
2384
2378
|
}
|
|
2385
2379
|
|
|
2380
|
+
// An event of the transcript, for the gateway's page and the local web console's live view (each takes its own copy).
|
|
2381
|
+
emitEvent(ev) {
|
|
2382
|
+
this.liveFeed.emit({ ...ev });
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2385
|
+
// What the local web console shows of this session: its list and the status under the live view.
|
|
2386
|
+
liveStatus() {
|
|
2387
|
+
let status = {};
|
|
2388
|
+
try { status = this.remoteStatus(); } catch { /* the basics below */ }
|
|
2389
|
+
return { ...status, busy: this.working(), turn: this.isTurnRunning(), sessionId: this.store?.id, pid: process.pid, hidden: this.hidden };
|
|
2390
|
+
}
|
|
2391
|
+
|
|
2392
|
+
// A command of the local web console's live view: the same ones the gateway's page sends (see remote.js).
|
|
2393
|
+
pageCommand(type, body = {}) {
|
|
2394
|
+
const handlers = {
|
|
2395
|
+
send: (b) => this.remoteSend(b.text, b.images),
|
|
2396
|
+
interrupt: () => this.remoteInterrupt(),
|
|
2397
|
+
dialog: (b) => this.answerDialog(b),
|
|
2398
|
+
options: () => this.remoteOptions(),
|
|
2399
|
+
suggest: (b) => this.remoteSuggest(b),
|
|
2400
|
+
list: (b) => this.remoteList(b),
|
|
2401
|
+
output: (b) => this.remoteOutput(b),
|
|
2402
|
+
end: (b) => this.pageEnd(b),
|
|
2403
|
+
};
|
|
2404
|
+
if (!Object.hasOwn(handlers, type)) throw new Error(`Unknown command: ${type}`);
|
|
2405
|
+
if (['send', 'interrupt', 'dialog', 'end'].includes(type)) {
|
|
2406
|
+
if (this.exiting) throw new Error('The session is ending.');
|
|
2407
|
+
if (this.moving) throw new Error('The session is moving into the web console; try again.');
|
|
2408
|
+
}
|
|
2409
|
+
return handlers[type](body);
|
|
2410
|
+
}
|
|
2411
|
+
|
|
2412
|
+
// The web console only ends sessions it owns. The host process survives and the current HTTP request can reply.
|
|
2413
|
+
pageEnd({ force = false } = {}) {
|
|
2414
|
+
if (!this.host) throw new Error('请在对应的终端结束这个会话');
|
|
2415
|
+
if (!force && this.working()) throw new Error('会话正在工作:先停止当前任务,或选择强制结束');
|
|
2416
|
+
this.exit(0);
|
|
2417
|
+
return { ending: true };
|
|
2418
|
+
}
|
|
2419
|
+
|
|
2386
2420
|
// A tool call finished (or was refused, or interrupted): its result on the remote page, once.
|
|
2387
2421
|
remoteToolDone(entry) {
|
|
2388
|
-
if (!this.
|
|
2422
|
+
if (!this.liveFeed.active || !entry.tu?.id || entry.remoteDone) return;
|
|
2389
2423
|
entry.remoteDone = true;
|
|
2390
2424
|
let lines = [];
|
|
2391
2425
|
try { lines = renderToolResult(entry, { width: REMOTE_WIDTH, cwd: this.cwd }); } catch { /* shown without */ }
|
|
2392
|
-
this.
|
|
2426
|
+
this.emitEvent({ t: 'done', id: entry.tu.id, status: entry.result?.isError || entry.rejected ? 'error' : 'done', lines });
|
|
2393
2427
|
}
|
|
2394
2428
|
|
|
2395
2429
|
// Move finished tool entries (in call order) from the live region to the transcript.
|
|
@@ -2441,16 +2475,43 @@ export class App {
|
|
|
2441
2475
|
takeQueued() {
|
|
2442
2476
|
if (!this.queue.length) return [];
|
|
2443
2477
|
const items = this.queue.splice(0);
|
|
2444
|
-
for (const q of items) this.echoUser(q.display ?? q.text
|
|
2478
|
+
for (const q of items) this.echoUser(q.display ?? q.text);
|
|
2445
2479
|
this.turnPeers.push(...items.map((q) => q.peer).filter(Boolean));
|
|
2446
2480
|
this.refreshTopic(items.map((q) => q.display ?? q.text).join('\n\n'));
|
|
2447
2481
|
// Content blocks for the agent: each queued message's text followed by its images.
|
|
2448
2482
|
return items.flatMap((q) => [{ type: 'text', text: q.text }, ...q.images.map(imageBlock)]);
|
|
2449
2483
|
}
|
|
2450
2484
|
|
|
2451
|
-
messageAdded(msg, agent) {
|
|
2485
|
+
messageAdded(msg, agent) {
|
|
2486
|
+
if (!this.isMain(agent)) return;
|
|
2487
|
+
this.store.message(msg);
|
|
2488
|
+
if (!this.liveFeed.active || msg.role !== 'user' || !Array.isArray(msg.content)) return;
|
|
2489
|
+
const count = msg.content.filter((b) => b.type === 'image').length;
|
|
2490
|
+
if (!count) return;
|
|
2491
|
+
// Publish after pushMessage adds the fitted images: the page can immediately fetch them via liveImage.
|
|
2492
|
+
const end = this.conversationImages().length;
|
|
2493
|
+
for (let n = end - count; n < end; n++) this.liveFeed.emit({ t: 'image', n });
|
|
2494
|
+
}
|
|
2452
2495
|
systemPrompt(text, agent) { if (this.isMain(agent)) this.store.setSystemPrompt(text); }
|
|
2453
|
-
messagesReplaced(msgs, agent) {
|
|
2496
|
+
messagesReplaced(msgs, agent) {
|
|
2497
|
+
if (!this.isMain(agent)) return;
|
|
2498
|
+
this.store.reset(msgs);
|
|
2499
|
+
// The turn lines go with their messages: where the same message is (a rewind keeps a prefix, a partial compaction
|
|
2500
|
+
// the other part), or where they were when only messages' contents changed (cleared tool results, lighter images);
|
|
2501
|
+
// those of what was summarized go. Written again: the reset drops them from the file.
|
|
2502
|
+
const before = this.marksBase;
|
|
2503
|
+
this.marksBase = msgs;
|
|
2504
|
+
if (!this.turnMarks.length) return;
|
|
2505
|
+
const sameLength = before === msgs || before?.length === msgs.length;
|
|
2506
|
+
const kept = [];
|
|
2507
|
+
for (const m of this.turnMarks) {
|
|
2508
|
+
let at = msgs[m.after - 1] === m.msg ? m.after : msgs.indexOf(m.msg) + 1;
|
|
2509
|
+
if (!at && sameLength && m.after <= msgs.length) at = m.after;
|
|
2510
|
+
if (at > 0) kept.push({ after: at, text: m.text, msg: msgs[at - 1] });
|
|
2511
|
+
}
|
|
2512
|
+
this.turnMarks = kept.sort((a, b) => a.after - b.after);
|
|
2513
|
+
if (kept.length) this.store.setTurns(kept);
|
|
2514
|
+
}
|
|
2454
2515
|
usage(_u, agent) {
|
|
2455
2516
|
if (this.isMain(agent)) this.store.setCacheUntil(agent.cache.clockUntil, agent.cacheState()); // for a resumed or restarted conversation
|
|
2456
2517
|
this.screen.schedule();
|
|
@@ -2566,8 +2627,6 @@ export class App {
|
|
|
2566
2627
|
if (!this.dialogs.length) {
|
|
2567
2628
|
if (lines.length) lines.push('');
|
|
2568
2629
|
lines.push(this.spinnerLine());
|
|
2569
|
-
const todos = this.agent.todos;
|
|
2570
|
-
if (this.showTodos && todos.length) lines.push(...renderTodos(todos).map((l) => truncate(l, w)));
|
|
2571
2630
|
}
|
|
2572
2631
|
} else if (this.active.length) {
|
|
2573
2632
|
for (const e of this.active) lines.push(...this.renderActiveEntry(e, w));
|
|
@@ -2585,93 +2644,27 @@ export class App {
|
|
|
2585
2644
|
}
|
|
2586
2645
|
if (lines.length) lines.push('');
|
|
2587
2646
|
const placeholder = this.isTurnRunning() ? 'Type a message to queue it for the agent…' : (this.agent.messages.length ? '' : 'Try "explain this codebase" or "fix the failing test"');
|
|
2588
|
-
const
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
const maxRows = Math.max(3, this.screen.height - 1 - lines.length - after.length - 2 - 2);
|
|
2594
|
-
const r = this.finder ? this.renderFind(width) : this.editor.render(width, { placeholder, title: this.boxTitle(), maxRows });
|
|
2647
|
+
const hint = this.hint();
|
|
2648
|
+
const after = this.editor.suggestions ? this.editor.renderSuggestions(w) : hint ? [hint] : [];
|
|
2649
|
+
// the input's text gets the screen less what is above and below it, and two rows of the conversation
|
|
2650
|
+
const maxRows = Math.max(3, this.screen.height - 1 - lines.length - after.length - 1 - 2);
|
|
2651
|
+
const r = this.editor.render(width, { placeholder, maxRows });
|
|
2595
2652
|
const top = lines.length;
|
|
2596
2653
|
lines.push(...r.lines);
|
|
2597
2654
|
if (r.cursor) cursor = { row: top + r.cursor.row, col: r.cursor.col };
|
|
2598
|
-
const input = r.text ? { ...r.text, row: top + r.text.row } : null; // where the mouse reaches the input box's text
|
|
2599
2655
|
lines.push(...after);
|
|
2600
|
-
return { lines, cursor
|
|
2601
|
-
}
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
//
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
// The prompt cache clock, as in Claude Code's VS Code extension: the minutes the conversation's cache has left
|
|
2614
|
-
// ("◷ 12m"), or the icon alone in red once it has run out or right after a compaction, until the next response:
|
|
2615
|
-
// the next message then writes the whole conversation to the cache again. Nothing before a response reported
|
|
2616
|
-
// cache use.
|
|
2617
|
-
cacheClock() {
|
|
2618
|
-
const clock = this.agent?.cache.clock();
|
|
2619
|
-
return !clock ? '' : clock.cold ? c.red(glyphs.clock) : c.dim(`${glyphs.clock} ${clock.minutes}m`);
|
|
2620
|
-
}
|
|
2621
|
-
|
|
2622
|
-
footer(w) {
|
|
2623
|
-
let left;
|
|
2624
|
-
const flash = this.flashMessage && Date.now() < this.flashMessage.until ? this.flashMessage : null;
|
|
2625
|
-
if (this.exitArmed && Date.now() - this.exitArmed < 1500) left = c.dim(' Press Ctrl-C again to exit');
|
|
2626
|
-
else if (flash) left = (flash.kind === 'warn' ? c.yellow : c.dim)(' ' + truncate(flash.text, w - 4));
|
|
2627
|
-
else if (this.screen.full && this.screen.selection) left = c.dim(' ctrl+c to copy · ctrl+q to quote it in your message');
|
|
2628
|
-
else if (this.editor.selection) left = c.dim(' ctrl+c to copy · esc to clear');
|
|
2629
|
-
else if (this.restartRequest) left = c.dim(` ${glyphs.restart} restarting when this turn ends`);
|
|
2630
|
-
else if (this.editor.mode === 'bash') left = c.magenta(' ! for bash mode');
|
|
2631
|
-
else if (this.editor.mode === 'memory') left = c.blue(' # to memorize');
|
|
2632
|
-
else left = c.dim(' ? for shortcuts');
|
|
2633
|
-
if (this.remote?.online && this.remote.viewers && !flash && !(this.exitArmed && Date.now() - this.exitArmed < 1500)) {
|
|
2634
|
-
left += c.dim(' · ') + c.green(`⇄ ${this.remote.viewers} watching`);
|
|
2635
|
-
}
|
|
2636
|
-
if (!flash) {
|
|
2637
|
-
if (this.updating) left += c.dim(' · ') + c.blue(`${glyphs.update} updating ${APP_NAME} to ${this.updating}…`);
|
|
2638
|
-
else if (this.updateRestart && this.sourceChanged && !this.restartRequest) left += c.dim(' · ') + c.blue(`${glyphs.restart} ${this.updateRestart} installed: restarts ${this.working() ? 'when the work is done' : 'now'}`);
|
|
2639
|
-
else if (this.sourceChanged && !this.sourceChangedInTurn && !this.restartRequest && !this.reloading && !this.working() && this.sourceQuietAt > Date.now()) left += c.dim(' · ') + c.dim(`${glyphs.restart} source changed: restarts once it is left alone (/restart: now)`);
|
|
2640
|
-
else if (this.pendingUpdate) left += c.dim(' · ') + c.dim(`update ${this.pendingUpdate} ready · ${this.updateWaitingFor ? `installs when @${this.updateWaitingFor.split(',')[0]} is idle` : 'installs when idle'}`);
|
|
2641
|
-
}
|
|
2642
|
-
const cfg = this.config;
|
|
2643
|
-
const threshold = cfg.compactWindow();
|
|
2644
|
-
const used = this.agent.contextEstimate;
|
|
2645
|
-
let notice = '';
|
|
2646
|
-
const pctLeft = Math.max(0, Math.round((1 - used / threshold) * 100));
|
|
2647
|
-
if (pctLeft <= 30) notice = c.yellow(`Context left until auto-compact: ${pctLeft}%`);
|
|
2648
|
-
else if (this.runtime.tasks.running().length) notice = c.dim(`${this.runtime.tasks.running().length} background agent${this.runtime.tasks.running().length === 1 ? '' : 's'} running · /tasks`);
|
|
2649
|
-
else if (this.verbose) notice = c.dim('verbose');
|
|
2650
|
-
// The model and effort in use always have a place at the right: with the notice after it when both fit,
|
|
2651
|
-
// and the notice alone when they do not (a context warning matters more than the model's name).
|
|
2652
|
-
const { model, effort } = modelInfo(cfg);
|
|
2653
|
-
// An effort that is not set is not sent: the API then uses the model's default, which is shown instead.
|
|
2654
|
-
const level = effort || defaultEffort(cfg.model.id, cfg);
|
|
2655
|
-
const info = c.dim(level ? `${model} · ${level}` : model);
|
|
2656
|
-
const version = c.dim(`v${VERSION}`);
|
|
2657
|
-
const compactTokens = (n) => formatTokens(n).replace(/\.0([kM])$/, '$1');
|
|
2658
|
-
const context = c.dim(`ctx ${compactTokens(used)}/${compactTokens(cfg.model.contextWindow)}`);
|
|
2659
|
-
// Before the context, version and model: the prompt cache clock, then what the conversation has cost so far;
|
|
2660
|
-
// when room is short the cost goes first, then the clock.
|
|
2661
|
-
const spent = this.cost > 0 ? c.dim(formatUsd(this.cost)) : '';
|
|
2662
|
-
const clock = this.cacheClock();
|
|
2663
|
-
const join = (...parts) => parts.filter(Boolean).join(c.dim(' · '));
|
|
2664
|
-
const room = w - stringWidth(left) - 1;
|
|
2665
|
-
const right = [
|
|
2666
|
-
join(notice, clock, spent, context, version, info),
|
|
2667
|
-
join(notice, clock, context, version, info),
|
|
2668
|
-
join(notice, context, version, info),
|
|
2669
|
-
join(notice, context, version),
|
|
2670
|
-
join(notice, version),
|
|
2671
|
-
version,
|
|
2672
|
-
].find((r) => r && stringWidth(r) < room) || '';
|
|
2673
|
-
const gap = room - stringWidth(right);
|
|
2674
|
-
return right ? left + ' '.repeat(gap) + right : left;
|
|
2656
|
+
return { lines, cursor };
|
|
2657
|
+
}
|
|
2658
|
+
|
|
2659
|
+
|
|
2660
|
+
// A line under the input, only while there is something to say that cannot wait for the end of the turn.
|
|
2661
|
+
hint() {
|
|
2662
|
+
if (this.exitArmed && Date.now() - this.exitArmed < 1500) return c.dim(' Press Ctrl-C again to exit');
|
|
2663
|
+
if (this.restartRequest) return c.dim(` ${glyphs.restart} restarting when this turn ends`);
|
|
2664
|
+
if (this.updating) return c.blue(` ${glyphs.update} updating ${APP_NAME} to ${this.updating}…`);
|
|
2665
|
+
if (this.updateRestart && this.sourceChanged) return c.blue(` ${glyphs.restart} ${this.updateRestart} installed: restarts ${this.working() ? 'when the work is done' : 'now'}`);
|
|
2666
|
+
if (this.sourceChanged && !this.sourceChangedInTurn && !this.reloading && !this.working() && this.sourceQuietAt > Date.now()) return c.dim(` ${glyphs.restart} source changed: restarts once it is left alone (/restart: now)`);
|
|
2667
|
+
return '';
|
|
2675
2668
|
}
|
|
2676
2669
|
}
|
|
2677
2670
|
|