@yanzc/claude-pro 0.9.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +342 -320
- package/package.json +1 -2
- package/src/agent.js +79 -13
- package/src/agents.js +3 -2
- package/src/api.js +39 -34
- package/src/browser/broker.js +367 -0
- package/src/browser/cdp.js +114 -0
- package/src/browser/render.js +242 -0
- package/src/browser/session.js +948 -0
- package/src/browser/snapshot.js +212 -0
- package/src/cache.js +1 -1
- package/src/checkpoints.js +1 -0
- package/src/commands.js +169 -67
- package/src/compaction.js +75 -0
- package/src/config.js +143 -143
- package/src/context.js +45 -18
- package/src/filestate.js +2 -1
- package/src/gateway.js +208 -164
- package/src/hooks.js +2 -2
- package/src/keepalive.js +1 -1
- package/src/main.js +52 -40
- package/src/mcp.js +2 -2
- package/src/peers.js +1 -10
- package/src/print.js +9 -3
- package/src/prompt-profiles.js +0 -6
- package/src/prompts.js +5 -61
- package/src/ratelimit.js +2 -4
- package/src/remote.js +26 -10
- package/src/runtime.js +33 -10
- package/src/selfcheck.js +3 -3
- package/src/session.js +93 -3
- package/src/supervisor.js +10 -1
- package/src/tools/bash.js +18 -17
- package/src/tools/browser.js +365 -0
- package/src/tools/code.js +430 -0
- package/src/tools/effort.js +3 -4
- package/src/tools/files.js +92 -19
- package/src/tools/index.js +6 -0
- package/src/tools/notebook.js +11 -4
- package/src/tools/processes.js +274 -0
- package/src/tools/search.js +33 -8
- package/src/tools/web.js +316 -46
- package/src/trace.js +0 -4
- package/src/ui/ansi.js +92 -13
- package/src/ui/dialogs.js +16 -54
- package/src/ui/editor.js +231 -34
- package/src/ui/markdown.js +1 -2
- package/src/ui/render.js +1 -2
- package/src/ui/repl.js +185 -104
- package/src/ui/screen.js +139 -31
- package/src/updater.js +135 -165
- package/src/utils/clipboard.js +5 -3
- package/src/utils/paths.js +15 -17
- package/src/utils/shell.js +66 -11
- package/.env.example +0 -29
package/src/ui/repl.js
CHANGED
|
@@ -8,7 +8,7 @@ import readline from 'node:readline';
|
|
|
8
8
|
import { spawn } from 'node:child_process';
|
|
9
9
|
import { c, ESC, stringWidth, stripAnsi, truncate, padEnd, wordWrap } from './ansi.js';
|
|
10
10
|
import { Screen, queryCursorRow, mouseFilter } from './screen.js';
|
|
11
|
-
import { Editor, topBorder } from './editor.js';
|
|
11
|
+
import { Editor, topBorder, shownQuotes } from './editor.js';
|
|
12
12
|
import { SelectDialog } from './dialogs.js';
|
|
13
13
|
import { MarkdownStream, renderMarkdown } from './markdown.js';
|
|
14
14
|
import {
|
|
@@ -18,7 +18,7 @@ import { createRuntime } from '../runtime.js';
|
|
|
18
18
|
import { SessionStore, firstUserText, moveSession } from '../session.js';
|
|
19
19
|
import { defaultEffort, effortSupported, effortToSend, quickQuery } from '../api.js';
|
|
20
20
|
import { CONFIG_DIR, VERSION, APP_NAME, INSTALL_DIR } from '../config.js';
|
|
21
|
-
import { gatewayLogin, normalizeGatewayUrl, formatUsd } from '../gateway.js';
|
|
21
|
+
import { gatewayLogin, loadGatewayModels, normalizeGatewayUrl, formatUsd } from '../gateway.js';
|
|
22
22
|
import { TOPIC_TITLE_SYSTEM, topicTitlePrompt } from '../prompts.js';
|
|
23
23
|
import { buildCommands, modelChoices, effortChoices } from '../commands.js';
|
|
24
24
|
import { canRestart, writeRestartState, runSelfCheck, watchSource, restartNote, RESTART_EXIT_CODE, MAX_RESTARTS, RESTART_WINDOW_MS } from '../restart.js';
|
|
@@ -27,6 +27,8 @@ import { listDirectory, recentDirectories } from '../utils/dirs.js';
|
|
|
27
27
|
import { ripgrepPath } from '../utils/shell.js';
|
|
28
28
|
import { describePause, formatClock, humanDuration, resumeText, shouldAnnounce } from '../ratelimit.js';
|
|
29
29
|
import { shutdownBackgroundShells, listBackgroundShells } from '../tools/bash.js';
|
|
30
|
+
import { shutdownInterpreters } from '../tools/code.js';
|
|
31
|
+
import { browserSession } from '../browser/session.js';
|
|
30
32
|
import { estimateTokens } from '../agent.js';
|
|
31
33
|
import { readClipboardImage, imageFromFile, writeClipboard, readClipboardText } from '../utils/clipboard.js';
|
|
32
34
|
import { fitImagesIn, imageSize } from '../utils/images.js';
|
|
@@ -68,6 +70,9 @@ const imageBlock = (img) => ({ type: 'image', source: { type: 'base64', media_ty
|
|
|
68
70
|
// The images the remote page sends with a message ({media_type, data: base64}), checked as the API would: at most
|
|
69
71
|
// REMOTE_MAX_IMAGES, each a PNG, JPEG, GIF or WebP of at most 5 MB. Throws what to tell the page.
|
|
70
72
|
const REMOTE_IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
|
|
73
|
+
// What the page may not send (see App.remoteSend): ending or restarting the session, or updating claude-pro (which
|
|
74
|
+
// restarts it), with or without arguments. The gateway uses the same pattern.
|
|
75
|
+
const TERMINAL_ONLY = /^\s*\/(exit|quit|restart|reload|update)(?:\s|$)/i;
|
|
71
76
|
const REMOTE_MAX_IMAGES = 6;
|
|
72
77
|
const REMOTE_MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
73
78
|
export function remoteImages(images) {
|
|
@@ -91,17 +96,49 @@ const SPINNER = ['·', '✢', '✳', '✶', '✻', '✽', '✽', '✻', '✶', '
|
|
|
91
96
|
const VERBS = ['Thinking', 'Pondering', 'Crafting', 'Brewing', 'Computing', 'Conjuring', 'Cooking', 'Musing', 'Noodling', 'Percolating', 'Ruminating', 'Synthesizing', 'Working', 'Tinkering', 'Mulling', 'Deliberating', 'Churning', 'Forging', 'Hatching', 'Simmering'];
|
|
92
97
|
const HISTORY_FILE = path.join(CONFIG_DIR, 'history.jsonl');
|
|
93
98
|
|
|
99
|
+
const HISTORY_KEEP = 500; // entries a project's history loads (and keeps, see loadHistory)
|
|
100
|
+
const HISTORY_PRUNE_CHARS = 5_000_000;
|
|
101
|
+
const HISTORY_PASTE_CHARS = 100_000; // pasted text kept with an entry in the file, at most (images are not kept)
|
|
102
|
+
|
|
103
|
+
// The input history of the project, oldest first: the text, or {text, parts} with the pasted text and quotes its
|
|
104
|
+
// placeholders stand for (see Editor.submit). A file past HISTORY_PRUNE_CHARS is written again with the last
|
|
105
|
+
// HISTORY_KEEP entries of each project: it grew for good (every message of every project), read whole at each start.
|
|
94
106
|
function loadHistory(cwd) {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
107
|
+
let text;
|
|
108
|
+
try { text = fs.readFileSync(HISTORY_FILE, 'utf8'); } catch { return []; }
|
|
109
|
+
const entries = text.split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter((e) => e && typeof e.display === 'string');
|
|
110
|
+
if (text.length > HISTORY_PRUNE_CHARS) pruneHistory(entries);
|
|
111
|
+
return entries.filter((e) => e.project === cwd).slice(-HISTORY_KEEP).map((e) => (Array.isArray(e.pastes) && e.pastes.length
|
|
112
|
+
? { text: e.display, parts: { pastes: e.pastes, quotes: Array.isArray(e.quotes) ? e.quotes : [] } }
|
|
113
|
+
: e.display));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function pruneHistory(entries) {
|
|
117
|
+
const count = new Map();
|
|
118
|
+
const keep = [];
|
|
119
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
120
|
+
const n = count.get(entries[i].project) || 0;
|
|
121
|
+
if (n >= HISTORY_KEEP) continue;
|
|
122
|
+
count.set(entries[i].project, n + 1);
|
|
123
|
+
keep.push(entries[i]);
|
|
124
|
+
}
|
|
125
|
+
try { // whole or not at all; an entry another window adds meanwhile may be lost, which costs an up-arrow
|
|
126
|
+
const tmp = `${HISTORY_FILE}.${process.pid}.tmp`;
|
|
127
|
+
fs.writeFileSync(tmp, keep.reverse().map((e) => JSON.stringify(e)).join('\n') + '\n');
|
|
128
|
+
fs.renameSync(tmp, HISTORY_FILE);
|
|
129
|
+
} catch { /* pruned another time */ }
|
|
99
130
|
}
|
|
100
131
|
|
|
101
|
-
function appendHistory(cwd, text) {
|
|
132
|
+
function appendHistory(cwd, text, parts = null) {
|
|
133
|
+
const entry = { display: text, project: cwd, timestamp: Date.now() };
|
|
134
|
+
const pastes = (parts?.pastes || []).filter(([label]) => text.includes(label));
|
|
135
|
+
if (pastes.length && pastes.reduce((n, [, content]) => n + String(content).length, 0) <= HISTORY_PASTE_CHARS) {
|
|
136
|
+
entry.pastes = pastes;
|
|
137
|
+
if (parts.quotes?.length) entry.quotes = parts.quotes;
|
|
138
|
+
}
|
|
102
139
|
try {
|
|
103
140
|
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
104
|
-
fs.appendFileSync(HISTORY_FILE, JSON.stringify(
|
|
141
|
+
fs.appendFileSync(HISTORY_FILE, JSON.stringify(entry) + '\n');
|
|
105
142
|
} catch { /* ignore */ }
|
|
106
143
|
}
|
|
107
144
|
|
|
@@ -232,6 +269,7 @@ export class App {
|
|
|
232
269
|
this.cost = 0; // what this conversation's requests have cost so far (USD at list prices): the footer and /cost
|
|
233
270
|
this.fileIndex = new FileIndex(cwd, () => this.runtime?.config);
|
|
234
271
|
this.store = new SessionStore(cwd);
|
|
272
|
+
SessionStore.onError = (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');
|
|
235
273
|
// What the terminal prints goes to the remote page too, except what it is told about as events.
|
|
236
274
|
this.screen.onLog = (items) => {
|
|
237
275
|
const lines = () => items.flatMap((i) => (Array.isArray(i) ? i : [i])).flatMap((l) => String(l).split(/\r?\n/));
|
|
@@ -240,7 +278,7 @@ export class App {
|
|
|
240
278
|
};
|
|
241
279
|
this.editor = new Editor({
|
|
242
280
|
history: loadHistory(cwd),
|
|
243
|
-
onSubmit: (value, raw, images) => { try { this.onSubmit(value, raw, images); } catch (e) { this.logError(e); } },
|
|
281
|
+
onSubmit: (value, raw, images, display, parts) => { try { this.onSubmit(value, raw, images, display, parts); } catch (e) { this.logError(e); } },
|
|
244
282
|
onDoubleEscape: () => this.openRewind(),
|
|
245
283
|
imageFromPath: (p) => {
|
|
246
284
|
const r = imageFromFile(resolvePath(p, this.cwd));
|
|
@@ -284,6 +322,10 @@ export class App {
|
|
|
284
322
|
this.screen.schedule();
|
|
285
323
|
};
|
|
286
324
|
this.commands = buildCommands(this);
|
|
325
|
+
// The window of the model in use may come from the gateway's model list (see Config.resolveModel): asked for now,
|
|
326
|
+
// so that the footer shows it before the first request.
|
|
327
|
+
// not in the self-check a restart runs first: that would ask the gateway once more for every restart
|
|
328
|
+
if (!this.driven && !this.selfCheck) loadGatewayModels(this.runtime.config).then(() => this.screen.schedule());
|
|
287
329
|
// What the session showed before a restart: scrolled back to in fullscreen, repainted after a resize otherwise.
|
|
288
330
|
if (Array.isArray(this.flags.restart?.screenHistory)) this.screen.history = this.flags.restart.screenHistory.filter((l) => typeof l === 'string');
|
|
289
331
|
if (this.fullscreenWanted()) this.screen.setFull(true);
|
|
@@ -320,7 +362,7 @@ export class App {
|
|
|
320
362
|
if (restart) this.continueAfterRestart(restart);
|
|
321
363
|
else if (initialPrompt?.trim()) this.onSubmit(initialPrompt, initialPrompt);
|
|
322
364
|
// Nothing configured yet: the gateway is the default, and its browser login starts first.
|
|
323
|
-
else if (
|
|
365
|
+
else if (!gatewayLogin(this.config.gatewayUrl)) {
|
|
324
366
|
Promise.resolve(this.commands.get('login').run('')).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
|
|
325
367
|
}
|
|
326
368
|
this.fileIndex.refresh();
|
|
@@ -413,6 +455,7 @@ export class App {
|
|
|
413
455
|
clearInterval(this.spinnerTimer);
|
|
414
456
|
this.sourceWatch?.close();
|
|
415
457
|
shutdownBackgroundShells();
|
|
458
|
+
shutdownInterpreters();
|
|
416
459
|
this.runtime?.tasks.killAll();
|
|
417
460
|
this.runtime?.mcp.close();
|
|
418
461
|
this.peers?.close();
|
|
@@ -602,7 +645,7 @@ export class App {
|
|
|
602
645
|
const env = this.config.env;
|
|
603
646
|
if (!onlineEnabled(env)) return false;
|
|
604
647
|
if (this.driven && !/^(1|true|yes|on)$/i.test(env.CLAUDE_PRO_ONLINE || '')) return false;
|
|
605
|
-
return Boolean(gatewayLogin(this.config.gatewayUrl
|
|
648
|
+
return Boolean(gatewayLogin(this.config.gatewayUrl));
|
|
606
649
|
}
|
|
607
650
|
|
|
608
651
|
// Online at the gateway from the start when this computer is logged in, and after a restart with the same
|
|
@@ -617,7 +660,7 @@ export class App {
|
|
|
617
660
|
}
|
|
618
661
|
|
|
619
662
|
// Connect this session to the gateway (see remote.js): the web page and the sessions on the account's other
|
|
620
|
-
// computers reach it from then on. Needs the gateway login from /login
|
|
663
|
+
// computers reach it from then on. Needs the gateway login from /login; throws
|
|
621
664
|
// {code: 'NO_GATEWAY_LOGIN'} without it. A gateway that cannot be reached now is tried again in the background;
|
|
622
665
|
// one that refuses the key throws, and that key is not tried again (see syncRemote).
|
|
623
666
|
startRemote({ id } = {}) {
|
|
@@ -631,7 +674,7 @@ export class App {
|
|
|
631
674
|
syncRemote() {
|
|
632
675
|
if (this.exiting) return Promise.resolve(null);
|
|
633
676
|
if (this.remoteStarting) return this.remoteStarting.catch(() => null);
|
|
634
|
-
const login = gatewayLogin(this.config.gatewayUrl
|
|
677
|
+
const login = gatewayLogin(this.config.gatewayUrl);
|
|
635
678
|
const r = this.remote;
|
|
636
679
|
// logged out, or another account: not this account's session any more
|
|
637
680
|
if (r && (!login || login.apiKey !== r.apiKey || normalizeGatewayUrl(login.url || this.config.gatewayUrl) !== normalizeGatewayUrl(r.base))) this.stopRemote();
|
|
@@ -644,7 +687,7 @@ export class App {
|
|
|
644
687
|
}
|
|
645
688
|
|
|
646
689
|
async connectRemote({ id }) {
|
|
647
|
-
const login = gatewayLogin(this.config.gatewayUrl
|
|
690
|
+
const login = gatewayLogin(this.config.gatewayUrl);
|
|
648
691
|
if (!login) throw Object.assign(new Error(`this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login logs in)`), { code: 'NO_GATEWAY_LOGIN' });
|
|
649
692
|
// What the page may do here, besides watching (see remote.js): nothing with CLAUDE_PRO_REMOTE_COMMANDS=0.
|
|
650
693
|
const commands = remoteCommandsEnabled(this.config.env) ? {
|
|
@@ -718,7 +761,7 @@ export class App {
|
|
|
718
761
|
return { text };
|
|
719
762
|
}
|
|
720
763
|
if (this.remoteStarting) return { text: 'connecting…' };
|
|
721
|
-
const login = gatewayLogin(this.config.gatewayUrl
|
|
764
|
+
const login = gatewayLogin(this.config.gatewayUrl);
|
|
722
765
|
if (!login) return { text: c.dim(`offline: this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login)`) };
|
|
723
766
|
if (login.apiKey === this.remoteRefused) return { text: c.red('offline: the gateway refused this computer\'s key (/logout, then /login)') };
|
|
724
767
|
if (!onlineEnabled(this.config.env)) return { text: c.dim('offline (CLAUDE_PRO_ONLINE=0)') };
|
|
@@ -769,10 +812,13 @@ export class App {
|
|
|
769
812
|
contextUsed() {
|
|
770
813
|
const a = this.agent;
|
|
771
814
|
if (a.lastContextTokens) return a.contextEstimate;
|
|
772
|
-
|
|
815
|
+
// not built yet: the prompt is counted once git has answered in the background (building it here blocked on git)
|
|
816
|
+
const ready = this.runtime.systemPromptReady?.() ?? true;
|
|
817
|
+
const key = `${a.messages.length}|${this.runtime.tools.length}|${ready}`;
|
|
773
818
|
if (this.contextGuess?.key !== key) {
|
|
819
|
+
if (!ready) this.runtime.prepareSnapshot().then(() => this.screen.schedule());
|
|
774
820
|
let used = 0;
|
|
775
|
-
try { used = estimateTokens(this.runtime.systemPrompt()) + estimateTokens(a.toolSchemas()) + estimateTokens(a.messages); } catch { /* 0 */ }
|
|
821
|
+
try { used = (ready ? estimateTokens(this.runtime.systemPrompt()) : 0) + estimateTokens(a.toolSchemas()) + estimateTokens(a.messages); } catch { /* 0 */ }
|
|
776
822
|
this.contextGuess = { key, used };
|
|
777
823
|
}
|
|
778
824
|
return this.contextGuess.used;
|
|
@@ -791,8 +837,6 @@ export class App {
|
|
|
791
837
|
if (!d) return null;
|
|
792
838
|
d.remoteId ??= ++this.remoteDialogs;
|
|
793
839
|
const base = { id: d.remoteId, title: d.title || '', question: d.question || '', body: d.body || [], markdown: d.markdown || null };
|
|
794
|
-
// a question answered with typed text (TextDialog): a text box on the page, answered with {id, text}
|
|
795
|
-
if (d.input) return { ...base, input: { placeholder: d.input.placeholder || '', value: d.value || '', multiline: Boolean(d.input.multiline) } };
|
|
796
840
|
if (!Array.isArray(d.options)) return base;
|
|
797
841
|
return { ...base, multi: Boolean(d.multi), options: d.options.map((o) => ({ label: String(o.label ?? ''), description: o.description || '', other: o.value === '__other__' })) };
|
|
798
842
|
}
|
|
@@ -800,17 +844,11 @@ export class App {
|
|
|
800
844
|
// ---------------------------------------------------------------- the page's commands (see remote.js)
|
|
801
845
|
|
|
802
846
|
// The answer to the dialog the status showed the page (remoteDialog): {id, index}, {id, indices}, {id, text,
|
|
803
|
-
// indices?} (its "other" option)
|
|
847
|
+
// indices?} (its "other" option) or {id, cancel: true}.
|
|
804
848
|
answerDialog({ id, index, indices, text, cancel } = {}) {
|
|
805
849
|
const d = this.dialogs[0];
|
|
806
850
|
if (!d || d.remoteId !== id) throw new Error('That question is no longer open.');
|
|
807
851
|
if (cancel) { d.resolve(d.cancelValue); return {}; }
|
|
808
|
-
if (d.input) {
|
|
809
|
-
if (typeof text !== 'string') throw new Error('Type an answer first.');
|
|
810
|
-
d.resolve(text);
|
|
811
|
-
this.screen.schedule();
|
|
812
|
-
return {};
|
|
813
|
-
}
|
|
814
852
|
if (!Array.isArray(d.options)) throw new Error('This dialog cannot be answered from the page.');
|
|
815
853
|
const valueAt = (i) => {
|
|
816
854
|
const o = d.options[i];
|
|
@@ -838,6 +876,10 @@ export class App {
|
|
|
838
876
|
let value = String(text ?? '').replace(/\r\n/g, '\n');
|
|
839
877
|
if (!value.trim() && pictures.length) value = pictures.map((_, i) => `[Image #${i + 1}]`).join(' ');
|
|
840
878
|
if (!value.trim()) throw new Error('The message is empty.');
|
|
879
|
+
// The user's rule: the page does not end or restart the session, nor update claude-pro; only the terminal does
|
|
880
|
+
// (the automatic update goes on as before: it is not a command of the page). The gateway refuses these too, with
|
|
881
|
+
// the same pattern and message; this holds when it does not (another gateway, or one that misses them).
|
|
882
|
+
if (TERMINAL_ONLY.test(value)) throw new Error('结束、重启会话和更新 claude-pro 只能在终端里操作');
|
|
841
883
|
if (this.exiting) throw new Error('The session is ending.');
|
|
842
884
|
if (this.isTurnRunning() && value.trim().startsWith('/')) throw new Error('Commands wait until the current task is done (or stopped).');
|
|
843
885
|
if (this.dialogs.length && !this.isTurnRunning()) throw new Error('A question is open: answer it first.');
|
|
@@ -983,12 +1025,19 @@ export class App {
|
|
|
983
1025
|
if (request.cwd) {
|
|
984
1026
|
try { moved = moveSession(this.store.file, this.store.id, request.cwd); } catch (e) { this.notice(`Could not change the directory: ${e.message}`, 'warn'); return; }
|
|
985
1027
|
}
|
|
1028
|
+
// a write of the conversation failed at some point: the file lacks part of it, and the next process goes on from it
|
|
1029
|
+
if (this.store.lost) { this.store.lost = false; this.store.reset(this.agent.messages); }
|
|
986
1030
|
const state = {
|
|
987
1031
|
at: now,
|
|
988
1032
|
reason: request.reason || '',
|
|
989
1033
|
continueWith: request.continueTurn ? restartNote(request) : '',
|
|
990
1034
|
cwd: request.cwd || this.cwd,
|
|
991
1035
|
changedDirectory: Boolean(request.cwd),
|
|
1036
|
+
// where the agent's shell is (a `cd` in Bash moves it): the next process goes on there, not at the project's root
|
|
1037
|
+
agentCwd: request.cwd ? null : this.agent.cwd,
|
|
1038
|
+
// the browser instance in use (one picked with /tabs may be any of several): the next process connects to it
|
|
1039
|
+
// again, where the tab ids in the conversation are still its tabs'
|
|
1040
|
+
browser: browserSession.preferred || null,
|
|
992
1041
|
sessionId: this.store.id,
|
|
993
1042
|
sessionFile: moved?.file || this.store.file,
|
|
994
1043
|
modelOverride: cfg.modelOverride,
|
|
@@ -998,7 +1047,9 @@ export class App {
|
|
|
998
1047
|
draft: this.editor.text,
|
|
999
1048
|
screenHistory: this.screen.history.slice(-3000),
|
|
1000
1049
|
draftCursor: this.editor.cursor,
|
|
1001
|
-
|
|
1050
|
+
draftParts: this.editor.draftParts(),
|
|
1051
|
+
// `peer`: a task of another session, which gets the answer of the turn that handles it
|
|
1052
|
+
queue: this.queue.map((q) => ({ text: q.text, images: q.images || [], display: q.display ?? null, peer: q.peer || null })),
|
|
1002
1053
|
checkpoints: this.runtime.checkpoints.snapshot(),
|
|
1003
1054
|
// a /cd is the user's: it does not count towards the restarts that look like a loop
|
|
1004
1055
|
restarts: [...this.restarts.filter((t) => now - t < RESTART_WINDOW_MS), ...(request.cwd ? [] : [now])],
|
|
@@ -1043,8 +1094,12 @@ export class App {
|
|
|
1043
1094
|
this.loadSession(state.sessionFile, state.sessionId, { quiet: true });
|
|
1044
1095
|
if (Array.isArray(state.todos)) this.agent.todos = state.todos;
|
|
1045
1096
|
if (state.checkpoints) this.runtime.checkpoints.adopt(state.checkpoints);
|
|
1097
|
+
if (typeof state.agentCwd === 'string' && state.agentCwd !== this.cwd) {
|
|
1098
|
+
try { if (fs.statSync(state.agentCwd).isDirectory()) this.agent.cwd = state.agentCwd; } catch { /* gone: the project's root */ }
|
|
1099
|
+
}
|
|
1046
1100
|
}
|
|
1047
|
-
if (typeof state.
|
|
1101
|
+
if (state.browser && typeof state.browser === 'object' && typeof state.browser.dir === 'string') browserSession.preferred = state.browser;
|
|
1102
|
+
if (typeof state.draft === 'string' && state.draft) this.editor.restoreDraft(state.draft, state.draftCursor, state.draftParts);
|
|
1048
1103
|
// Fullscreen starts on an empty screen: without what the process before showed (an older version, or one
|
|
1049
1104
|
// that ran classic), the conversation is drawn again from the session.
|
|
1050
1105
|
if (this.screen.full && resumable && !Array.isArray(state.screenHistory)) this.printTranscript(this.agent.messages.slice(-80));
|
|
@@ -1063,13 +1118,20 @@ export class App {
|
|
|
1063
1118
|
const queued = (Array.isArray(state.queue) ? state.queue : []).filter((q) => q && typeof q.text === 'string' && q.text.trim());
|
|
1064
1119
|
if (!state.continueWith && !queued.length) return;
|
|
1065
1120
|
const typed = queued.map((q) => q.text).join('\n\n');
|
|
1066
|
-
|
|
1121
|
+
const shown = queued.map((q) => (typeof q.display === 'string' ? q.display : q.text)).join('\n\n');
|
|
1122
|
+
this.startTurn([state.continueWith, typed].filter(Boolean).join('\n\n'), {
|
|
1123
|
+
echo: queued.length > 0,
|
|
1124
|
+
display: shown,
|
|
1125
|
+
topic: shown,
|
|
1126
|
+
images: queued.flatMap((q) => (Array.isArray(q.images) ? q.images : [])),
|
|
1127
|
+
peers: queued.map((q) => q.peer).filter((p) => p && typeof p === 'object' && p.from),
|
|
1128
|
+
});
|
|
1067
1129
|
}
|
|
1068
1130
|
|
|
1069
1131
|
// Follow the program's own source: once a turn is over (or at once when idle) a change to it is loaded by
|
|
1070
1132
|
// a restart, if the new code starts.
|
|
1071
1133
|
startSourceWatch() {
|
|
1072
|
-
if (!canRestart()
|
|
1134
|
+
if (!canRestart()) return;
|
|
1073
1135
|
this.sourceWatch = watchSource(INSTALL_DIR, (file) => {
|
|
1074
1136
|
this.sourceChanged = file || true;
|
|
1075
1137
|
// another window (or npm) installed a new version: say so, and load it once this session is idle. In a
|
|
@@ -1100,18 +1162,18 @@ export class App {
|
|
|
1100
1162
|
return;
|
|
1101
1163
|
}
|
|
1102
1164
|
if (this.isTurnRunning() || this.dialogs.length) { this.sourceChanged = changed; return; } // something started meanwhile: later
|
|
1103
|
-
this.requestRestart({ reason: this.updateRestart ? `updated to ${APP_NAME} ${this.updateRestart}` : 'source changed', force: true });
|
|
1165
|
+
const r = this.requestRestart({ reason: this.updateRestart ? `updated to ${APP_NAME} ${this.updateRestart}` : 'source changed', force: true });
|
|
1166
|
+
// refused (too many restarts in a row): say so, or later changes would go unloaded without a word
|
|
1167
|
+
if (!r.ok) this.notice(`The program's source changed, but it was not restarted to load it: ${r.message.replace(/ That looks like a loop:.*$/, '')} A change after that window loads it, or /restart once it has passed.`, 'warn');
|
|
1104
1168
|
}
|
|
1105
1169
|
|
|
1106
|
-
//
|
|
1107
|
-
// loaded by a restart (this session's; the others restart when they see the files change).
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
async autoUpdate({ force = false, quiet = false } = {}) {
|
|
1111
|
-
if (this.updating) { if (force) this.notice(`${APP_NAME} ${this.updating} is being installed.`); return; }
|
|
1170
|
+
// /update: a newer version on npm (see updater.js) is installed once no session of this machine is working, and
|
|
1171
|
+
// then loaded by a restart (this session's; the others restart when they see the files change).
|
|
1172
|
+
async updateFromNpm() {
|
|
1173
|
+
if (this.updating) { this.notice(`${APP_NAME} ${this.updating} is being installed.`); return; }
|
|
1112
1174
|
let r;
|
|
1113
1175
|
try {
|
|
1114
|
-
r = await checkForUpdate(
|
|
1176
|
+
r = await checkForUpdate();
|
|
1115
1177
|
} catch (e) {
|
|
1116
1178
|
r = { status: 'failed', error: e.message };
|
|
1117
1179
|
}
|
|
@@ -1119,18 +1181,17 @@ export class App {
|
|
|
1119
1181
|
if (r.status === 'available') {
|
|
1120
1182
|
if (this.pendingUpdate !== r.version) {
|
|
1121
1183
|
this.pendingUpdate = r.version;
|
|
1122
|
-
this.updateQuiet = quiet;
|
|
1123
1184
|
this.screen.schedule();
|
|
1124
1185
|
}
|
|
1125
|
-
if (
|
|
1126
|
-
await this.maybeInstallUpdate({ force });
|
|
1186
|
+
if (this.working()) this.notice(`${APP_NAME} ${r.version} is out: it is installed as soon as this session's work is done.`);
|
|
1187
|
+
await this.maybeInstallUpdate({ force: true });
|
|
1127
1188
|
} else if (r.status === 'installed') {
|
|
1128
|
-
|
|
1189
|
+
this.notice(`${APP_NAME} ${r.version} is installed already; this session restarts to load it ${this.working() ? 'once its work is done' : 'now'}.`);
|
|
1129
1190
|
this.updateRestart = r.version;
|
|
1130
1191
|
if (canRestart()) { this.sourceChanged ||= true; if (!this.isTurnRunning()) this.maybeAutoReload(); }
|
|
1131
1192
|
} else if (r.status === 'failed') {
|
|
1132
|
-
|
|
1133
|
-
} else
|
|
1193
|
+
this.notice(`Could not update ${APP_NAME}${r.version ? ` to ${r.version}` : ''}: ${r.error}`, 'warn');
|
|
1194
|
+
} else {
|
|
1134
1195
|
this.notice(r.status === 'dev' ? `This copy runs from a source checkout (${INSTALL_DIR}): update it with git.` : `${APP_NAME} ${VERSION} is the latest version.`);
|
|
1135
1196
|
}
|
|
1136
1197
|
}
|
|
@@ -1184,7 +1245,7 @@ export class App {
|
|
|
1184
1245
|
}
|
|
1185
1246
|
return;
|
|
1186
1247
|
}
|
|
1187
|
-
|
|
1248
|
+
this.notice(`Could not update ${APP_NAME} to ${version}: ${r.error}`, 'warn');
|
|
1188
1249
|
}
|
|
1189
1250
|
|
|
1190
1251
|
printWelcome() {
|
|
@@ -1205,7 +1266,7 @@ export class App {
|
|
|
1205
1266
|
c.claude('╰' + '─'.repeat(w - 2) + '╯'),
|
|
1206
1267
|
];
|
|
1207
1268
|
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).'));
|
|
1208
|
-
if (!gatewayLogin(cfg.gatewayUrl
|
|
1269
|
+
if (!gatewayLogin(cfg.gatewayUrl)) lines.push('', c.yellow(` ⚠ Not logged in to the gateway ${cfg.gatewayUrl}. Run /login.`));
|
|
1209
1270
|
const mcp = this.runtime.mcp.status();
|
|
1210
1271
|
if (mcp.length) {
|
|
1211
1272
|
const ok = mcp.filter((m) => m.status === 'connected').length;
|
|
@@ -1217,15 +1278,15 @@ export class App {
|
|
|
1217
1278
|
|
|
1218
1279
|
// ---------------------------------------------------------------- input
|
|
1219
1280
|
|
|
1220
|
-
// Fullscreen
|
|
1221
|
-
// bottom of the window, the conversation scrolled inside the program. Not in the tests that drive the App.
|
|
1281
|
+
// Fullscreen unless settings.tui selects the classic renderer; a driven test defaults to classic.
|
|
1222
1282
|
fullscreenWanted() {
|
|
1223
|
-
const mode =
|
|
1283
|
+
const mode = this.driven && this.config.settings.tui == null ? 'default' : this.config.setting('tui');
|
|
1224
1284
|
return mode === 'fullscreen' && this.stdout.isTTY !== false;
|
|
1225
1285
|
}
|
|
1226
1286
|
|
|
1227
1287
|
// Fullscreen: the wheel scrolls the conversation (3 rows a notch); a drag,
|
|
1228
1288
|
// a double or a triple click selects text. Selection is copied only with Ctrl+C.
|
|
1289
|
+
// In the input box a click moves the cursor and a drag selects its text (see Editor.mouse).
|
|
1229
1290
|
onMouse(m) {
|
|
1230
1291
|
if (!this.screen.full || this.exiting) return;
|
|
1231
1292
|
if (m.button & 64) {
|
|
@@ -1235,7 +1296,30 @@ export class App {
|
|
|
1235
1296
|
return;
|
|
1236
1297
|
}
|
|
1237
1298
|
// Right-click is intentionally inert. Clipboard operations use Ctrl+C and Ctrl+V only.
|
|
1238
|
-
this.screen.
|
|
1299
|
+
const had = this.screen.selection;
|
|
1300
|
+
const hadInput = this.editor.selection;
|
|
1301
|
+
const r = this.screen.mouse(m);
|
|
1302
|
+
if (r?.input) this.editor.mouse(r.input);
|
|
1303
|
+
else if ((m.button & 3) === 0 && !(m.button & 32) && !m.release) this.editor.clearSelection(); // a press elsewhere
|
|
1304
|
+
if ((this.screen.selection && this.screen.selection !== had) || (this.editor.selection && this.editor.selection !== hadInput)) {
|
|
1305
|
+
this.flashMessage = null; // the footer says what a selection takes
|
|
1306
|
+
this.screen.schedule();
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
// Quote what is selected in the conversation in the message being written, as ChatGPT's "Ask ChatGPT" does:
|
|
1311
|
+
// ctrl+q (alt+q where the terminal keeps ctrl+q), as the footer says while there is a selection. The box shows
|
|
1312
|
+
// "[Quote #1 +12 lines]"; the model gets the text and the line of the conversation it is under (see
|
|
1313
|
+
// Editor.insertQuote), so that it knows which part, and which file or command, the question is about.
|
|
1314
|
+
quoteSelection() {
|
|
1315
|
+
if (!this.screen.full) { this.flash('Quoting works in fullscreen (/tui fullscreen): select text with the mouse, then ctrl+q', 'warn'); return; }
|
|
1316
|
+
const quote = this.screen.selectionQuote();
|
|
1317
|
+
if (!quote?.text.trim()) { this.flash('Select part of the conversation first (drag over it, or double/triple-click), then ctrl+q', 'warn'); return; }
|
|
1318
|
+
if (this.dialogs.length) { this.flash('Answer the open question first, then quote', 'warn'); return; }
|
|
1319
|
+
if (this.finder) this.closeFind();
|
|
1320
|
+
this.screen.clearSelection();
|
|
1321
|
+
const label = this.editor.insertQuote(quote.text, quote.source);
|
|
1322
|
+
this.flash(`${label}${quote.source ? ` from ${quote.source}` : ''}: type your question below it`);
|
|
1239
1323
|
}
|
|
1240
1324
|
|
|
1241
1325
|
copyText(text) {
|
|
@@ -1342,10 +1426,19 @@ export class App {
|
|
|
1342
1426
|
// then does what it does.
|
|
1343
1427
|
if (this.screen.selection) {
|
|
1344
1428
|
if (key.ctrl && key.name === 'c') { this.copyText(this.screen.selectedText()); this.screen.clearSelection(); return; }
|
|
1429
|
+
if ((key.ctrl || key.meta) && key.name === 'q') { this.quoteSelection(); return; }
|
|
1345
1430
|
this.screen.clearSelection();
|
|
1346
1431
|
if (key.name === 'escape') return;
|
|
1347
1432
|
}
|
|
1348
1433
|
}
|
|
1434
|
+
// A selection in the input box (see Editor.mouse), the same way: ctrl+c copies it (and neither interrupts nor
|
|
1435
|
+
// clears the message), esc only clears it, any other key clears it and then does what it does.
|
|
1436
|
+
if (this.editor.selection) {
|
|
1437
|
+
const shown = !this.dialogs.length && !this.finder; // else the box is not on screen, and the key is not for it
|
|
1438
|
+
if (shown && key.ctrl && key.name === 'c') { this.copyText(this.editor.selectedText()); this.editor.clearSelection(); return; }
|
|
1439
|
+
this.editor.clearSelection();
|
|
1440
|
+
if (shown && key.name === 'escape') return;
|
|
1441
|
+
}
|
|
1349
1442
|
if (key.name === 'paste-start' || key.sequence === '\x1b[200~') {
|
|
1350
1443
|
this.bracketedPaste = { raw: '' };
|
|
1351
1444
|
return;
|
|
@@ -1353,6 +1446,7 @@ export class App {
|
|
|
1353
1446
|
if (key.ctrl && key.name === 'c' && this.finder && !this.dialogs.length) { this.closeFind(); return; } // not the hidden input's text
|
|
1354
1447
|
if (key.ctrl && key.name === 'c') { this.onCtrlC(); return; }
|
|
1355
1448
|
if ((key.ctrl || key.meta) && key.name === 'v') { this.pasteClipboard(); return; } // alt+v: the clipboard's image
|
|
1449
|
+
if ((key.ctrl || key.meta) && key.name === 'q') { this.quoteSelection(); return; } // nothing selected: says how
|
|
1356
1450
|
const dialog = this.dialogs[0];
|
|
1357
1451
|
if (dialog) {
|
|
1358
1452
|
dialog.handleKey(str, key);
|
|
@@ -1361,15 +1455,11 @@ export class App {
|
|
|
1361
1455
|
}
|
|
1362
1456
|
if (key.ctrl && key.name === 'f') { this.openFind(); return; }
|
|
1363
1457
|
if (this.finder) { this.findKey(str, key); this.screen.schedule(); return; }
|
|
1364
|
-
if (key.ctrl && key.name === 'o') {
|
|
1365
|
-
this.verbose = !this.verbose;
|
|
1366
|
-
this.notice(this.verbose ? 'Verbose mode on: showing thinking and full tool output' : 'Verbose mode off', 'info');
|
|
1367
|
-
return;
|
|
1368
|
-
}
|
|
1369
1458
|
if (key.ctrl && key.name === 't') { this.showTodos = !this.showTodos; this.screen.schedule(); return; }
|
|
1370
1459
|
if (key.ctrl && key.name === 'l') { if (this.screen.full) this.screen.repaint(); else this.screen.clearScreen(); return; }
|
|
1371
1460
|
if (key.ctrl && key.name === 'd' && !this.editor.text) { this.keyboardExit(); return; }
|
|
1372
|
-
|
|
1461
|
+
// esc closes an open completion list first (the editor does that), and only then stops the turn
|
|
1462
|
+
if (key.name === 'escape' && this.isTurnRunning() && !this.editor.suggestions) { this.interrupt(); return; }
|
|
1373
1463
|
this.exitArmed = 0;
|
|
1374
1464
|
this.editor.handleKey(str, key);
|
|
1375
1465
|
this.screen.schedule();
|
|
@@ -1478,19 +1568,20 @@ export class App {
|
|
|
1478
1568
|
];
|
|
1479
1569
|
}
|
|
1480
1570
|
|
|
1481
|
-
|
|
1571
|
+
// `display`: how the message shows in the transcript when that is not `value` (a quote shows its first lines).
|
|
1572
|
+
onSubmit(value, raw, images = [], display = undefined, parts = null) {
|
|
1482
1573
|
const text = value.trim();
|
|
1483
1574
|
if (!text) { this.screen.schedule(); return; }
|
|
1484
1575
|
if (this.screen.scrolledUp) this.screen.scrollBy('bottom'); // what was sent, and what comes of it, is in view
|
|
1485
|
-
appendHistory(this.cwd, raw);
|
|
1576
|
+
appendHistory(this.cwd, raw, parts);
|
|
1486
1577
|
if (this.sendTypedToPeer(text)) return;
|
|
1487
1578
|
if (this.isTurnRunning()) {
|
|
1488
1579
|
if (text.startsWith('/')) { this.notice('Wait for the current task to finish (or press Esc) before running commands.', 'warn'); return; }
|
|
1489
|
-
this.queue.push({ text: value, images });
|
|
1580
|
+
this.queue.push({ text: value, images, ...(display ? { display } : {}) });
|
|
1490
1581
|
this.screen.schedule();
|
|
1491
1582
|
return;
|
|
1492
1583
|
}
|
|
1493
|
-
if (images.length) { this.startTurn(value, { images }); return; }
|
|
1584
|
+
if (images.length) { this.startTurn(value, { images, display }); return; }
|
|
1494
1585
|
if (text === '?') { this.screen.log(this.shortcutsHelp()); return; }
|
|
1495
1586
|
if (raw.startsWith('!')) { this.runBashMode(value.slice(1).trim()); return; }
|
|
1496
1587
|
if (raw.startsWith('#')) { this.addMemory(value.slice(1).trim()); return; }
|
|
@@ -1503,11 +1594,11 @@ export class App {
|
|
|
1503
1594
|
Promise.resolve(cmd.run(args, rest)).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
|
|
1504
1595
|
return;
|
|
1505
1596
|
}
|
|
1506
|
-
if (!/^\/[\w:-]+$/.test(text.split(/\s/)[0])) { this.startTurn(value); return; } // e.g. a path like /usr/bin
|
|
1597
|
+
if (!/^\/[\w:-]+$/.test(text.split(/\s/)[0])) { this.startTurn(value, { display }); return; } // e.g. a path like /usr/bin
|
|
1507
1598
|
this.notice(`Unknown command: /${name}. Type /help for the list of commands.`, 'warn');
|
|
1508
1599
|
return;
|
|
1509
1600
|
}
|
|
1510
|
-
this.startTurn(value);
|
|
1601
|
+
this.startTurn(value, { display });
|
|
1511
1602
|
}
|
|
1512
1603
|
|
|
1513
1604
|
// `@name message`: the message goes to that session, as a task for it. A session on another computer of the
|
|
@@ -1543,12 +1634,13 @@ export class App {
|
|
|
1543
1634
|
shortcutsHelp() {
|
|
1544
1635
|
const rows = [
|
|
1545
1636
|
['! for bash mode', 'double tap esc to clear input'],
|
|
1546
|
-
['/ for commands', '
|
|
1637
|
+
['/ for commands', '/verbose for detailed tool output'],
|
|
1547
1638
|
['@ for files and sessions', 'ctrl + f to find in the conversation'],
|
|
1548
1639
|
['PgUp/PgDn, wheel to scroll', 'ctrl + home/end to the top/bottom'],
|
|
1549
1640
|
['# to memorize', 'ctrl + t to toggle todos'],
|
|
1550
1641
|
['\\⏎ or alt+⏎ for newline', 'ctrl + l to redraw, ctrl + d to exit'],
|
|
1551
|
-
['ctrl + c to copy selection', 'ctrl +
|
|
1642
|
+
['ctrl + c to copy selection', 'ctrl + q to quote it in your message'],
|
|
1643
|
+
['ctrl + v to paste text or an image', ''],
|
|
1552
1644
|
];
|
|
1553
1645
|
return rows.map(([a, b]) => c.dim(' ' + padEnd(a, 30) + b));
|
|
1554
1646
|
}
|
|
@@ -1567,7 +1659,7 @@ export class App {
|
|
|
1567
1659
|
if (this.finder && !seed.trim()) { this.finder.selected = Boolean(this.finder.text); this.screen.schedule(); return; } // open: select what is typed
|
|
1568
1660
|
const text = (seed.split('\n').find((l) => l.trim()) || '').trim() || this.lastFind || '';
|
|
1569
1661
|
if (!this.finder) this.screen.openFind();
|
|
1570
|
-
this.finder = { text, cursor: text.length, selected: Boolean(text)
|
|
1662
|
+
this.finder = { text, cursor: text.length, selected: Boolean(text) };
|
|
1571
1663
|
this.screen.setFind(text);
|
|
1572
1664
|
this.screen.schedule();
|
|
1573
1665
|
}
|
|
@@ -1593,13 +1685,7 @@ export class App {
|
|
|
1593
1685
|
if (f.selected) edit(t, t.length);
|
|
1594
1686
|
else edit(f.text.slice(0, f.cursor) + t + f.text.slice(f.cursor), f.cursor + t.length);
|
|
1595
1687
|
};
|
|
1596
|
-
|
|
1597
|
-
if (f.pasting !== null) {
|
|
1598
|
-
if (name === 'paste-end') { const t = f.pasting.split(/\r?\n/).find((l) => l.trim()) || ''; f.pasting = null; insert(t.trim()); }
|
|
1599
|
-
else if (name === 'return' || name === 'enter') f.pasting += '\n';
|
|
1600
|
-
else if (str) f.pasting += str;
|
|
1601
|
-
return;
|
|
1602
|
-
}
|
|
1688
|
+
// a bracketed paste never gets here: App.onKey takes it whole (see insertFindText)
|
|
1603
1689
|
if (name === 'escape') { this.closeFind(); return; }
|
|
1604
1690
|
const back = (name === 'return' && (key.meta || key.shift)) || name === 'enter' || key.sequence === '\x1b[13;2u' || (name === 'f3' && key.shift);
|
|
1605
1691
|
if (back || name === 'down' || (key.ctrl && name === 'n')) { f.selected = false; this.screen.findStep(-1); return; }
|
|
@@ -1969,7 +2055,8 @@ export class App {
|
|
|
1969
2055
|
for (const b of blocks) {
|
|
1970
2056
|
const bash = m.role === 'user' && b.type === 'text' ? bashModeLines(b.text) : null;
|
|
1971
2057
|
if (bash) this.screen.log(bash, '');
|
|
1972
|
-
else if (m.role === 'user' && b.type === 'text' && !b.text.startsWith('<system-reminder>')) this.screen.log(renderUserMessage(b.text.slice(0, 2000), this.width));
|
|
2058
|
+
else if (m.role === 'user' && b.type === 'text' && !b.text.startsWith('<system-reminder>')) this.screen.log(renderUserMessage(shownQuotes(b.text).slice(0, 2000), this.width));
|
|
2059
|
+
if (m.role === 'assistant' && b.type === 'thinking' && b.thinking) this.screen.log(renderMarkdown(b.thinking, { width: this.width - 1, firstPrefix: c.dim('✻ '), indent: ' ', style: (s) => c.dim(c.italic(s)) }), '');
|
|
1973
2060
|
if (m.role === 'assistant' && b.type === 'text') this.screen.log(renderMarkdown(b.text, { width: this.width - 1, firstPrefix: `${DOT} `, indent: ' ' }), '');
|
|
1974
2061
|
if (m.role === 'assistant' && b.type === 'tool_use') {
|
|
1975
2062
|
const tool = toolMap.get(b.name) || { name: b.name };
|
|
@@ -2035,7 +2122,7 @@ export class App {
|
|
|
2035
2122
|
this.remote?.emit({ t: 'start', kind: 'text' });
|
|
2036
2123
|
} else if (ev.block.type === 'thinking') {
|
|
2037
2124
|
this.remote?.emit({ t: 'start', kind: 'thinking' });
|
|
2038
|
-
this.thinking =
|
|
2125
|
+
this.thinking = new MarkdownStream({ width: w, firstPrefix: c.dim('✻ '), indent: ' ', style: (s) => c.dim(c.italic(s)) });
|
|
2039
2126
|
} else if (ev.block.type === 'tool_use') {
|
|
2040
2127
|
this.flushThinking();
|
|
2041
2128
|
this.pendingToolBlocks.set(ev.index, { name: ev.block.name, partial: '' });
|
|
@@ -2052,12 +2139,9 @@ export class App {
|
|
|
2052
2139
|
case 'thinking':
|
|
2053
2140
|
this.turnTokens += estimateTokens(ev.text);
|
|
2054
2141
|
if (this.thinking) {
|
|
2055
|
-
this.thinking.text += ev.text;
|
|
2056
2142
|
this.remote?.emit({ t: 'delta', kind: 'thinking', text: ev.text });
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
if (lines.length) this.logLocal({ soon: true }, lines);
|
|
2060
|
-
}
|
|
2143
|
+
const lines = this.thinking.write(ev.text);
|
|
2144
|
+
if (lines.length) this.logLocal({ soon: true }, lines);
|
|
2061
2145
|
}
|
|
2062
2146
|
break;
|
|
2063
2147
|
case 'tool_input': {
|
|
@@ -2117,14 +2201,9 @@ export class App {
|
|
|
2117
2201
|
if (!t) return;
|
|
2118
2202
|
this.thinking = null;
|
|
2119
2203
|
this.remote?.emit({ t: 'stop' });
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
this.logLocal('');
|
|
2124
|
-
} else if (t.text.trim()) {
|
|
2125
|
-
const secs = Math.max(1, Math.round((Date.now() - t.start) / 1000));
|
|
2126
|
-
this.logLocal(c.dim(c.italic(`✻ Thought for ${secs}s (ctrl+o to show thinking)`)), '');
|
|
2127
|
-
}
|
|
2204
|
+
const lines = t.end();
|
|
2205
|
+
if (lines.length) this.logLocal(lines);
|
|
2206
|
+
if (t.emittedAny) this.logLocal('');
|
|
2128
2207
|
}
|
|
2129
2208
|
|
|
2130
2209
|
flushStreaming() {
|
|
@@ -2252,7 +2331,6 @@ export class App {
|
|
|
2252
2331
|
if (!this.isMain(agent)) return;
|
|
2253
2332
|
this.flushStreaming();
|
|
2254
2333
|
this.status = auto ? 'Auto-compacting conversation' : 'Compacting conversation';
|
|
2255
|
-
this.compactTokens = 0;
|
|
2256
2334
|
this.screen.schedule();
|
|
2257
2335
|
}
|
|
2258
2336
|
|
|
@@ -2262,11 +2340,10 @@ export class App {
|
|
|
2262
2340
|
else if (ev.type === 'rate_limit_wait' || ev.type === 'rate_limit_resume') this.rateLimitEvent(ev);
|
|
2263
2341
|
}
|
|
2264
2342
|
|
|
2265
|
-
compactEnd(
|
|
2343
|
+
compactEnd(_summary, agent, err, { part } = {}) {
|
|
2266
2344
|
if (!this.isMain(agent)) return;
|
|
2267
2345
|
this.status = null;
|
|
2268
2346
|
if (err) return;
|
|
2269
|
-
this.lastSummary = summary;
|
|
2270
2347
|
this.store.setCacheUntil(agent.cache.clockUntil, agent.cacheState());
|
|
2271
2348
|
const what = part === 'before' ? 'The earlier part of the conversation was summarized' : part === 'after' ? 'The conversation from that message on was summarized' : 'Conversation compacted';
|
|
2272
2349
|
this.screen.log(c.dim(`✻ ${what} (the summary is in context; /context to see usage)`), '');
|
|
@@ -2347,12 +2424,7 @@ export class App {
|
|
|
2347
2424
|
const partial = this.md.partial();
|
|
2348
2425
|
lines.push(...partial.slice(-Math.floor(this.screen.height / 2)));
|
|
2349
2426
|
}
|
|
2350
|
-
if (this.thinking
|
|
2351
|
-
else if (this.thinking && this.thinking.text) {
|
|
2352
|
-
const text = this.thinking.text.trimEnd();
|
|
2353
|
-
const last = text.slice(text.lastIndexOf('\n') + 1); // not split(): this runs every frame on all of it
|
|
2354
|
-
lines.push(c.dim(c.italic(truncate(`✻ ${last}`, w))));
|
|
2355
|
-
}
|
|
2427
|
+
if (this.thinking) lines.push(...this.thinking.partial().slice(-Math.floor(this.screen.height / 2)));
|
|
2356
2428
|
for (const [, p] of this.pendingToolBlocks) {
|
|
2357
2429
|
// The start of the input is enough for a one-line preview (a streaming Bash heredoc can be very long).
|
|
2358
2430
|
const m = /"(?:file_path|command|pattern|url|description|query)"\s*:\s*"((?:\\.|[^"\\])*)/.exec(p.partial.slice(0, 4000));
|
|
@@ -2383,15 +2455,19 @@ export class App {
|
|
|
2383
2455
|
}
|
|
2384
2456
|
if (lines.length) lines.push('');
|
|
2385
2457
|
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"');
|
|
2386
|
-
const
|
|
2458
|
+
const after = this.finder ? [c.dim(truncate(' ⏎ or ↑ older · shift+⏎ or ↓ newer · PgUp/PgDn scroll · esc to close', w))]
|
|
2459
|
+
: this.editor.suggestions ? this.editor.renderSuggestions(w)
|
|
2460
|
+
: this.editor.text === '?' ? this.shortcutsHelp()
|
|
2461
|
+
: [this.footer(w)];
|
|
2462
|
+
// the box's text gets the screen less what is above and below it, its borders, and two rows of the conversation
|
|
2463
|
+
const maxRows = Math.max(3, this.screen.height - 1 - lines.length - after.length - 2 - 2);
|
|
2464
|
+
const r = this.finder ? this.renderFind(width) : this.editor.render(width, { placeholder, title: this.boxTitle(), maxRows });
|
|
2387
2465
|
const top = lines.length;
|
|
2388
2466
|
lines.push(...r.lines);
|
|
2389
2467
|
if (r.cursor) cursor = { row: top + r.cursor.row, col: r.cursor.col };
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
else lines.push(this.footer(w));
|
|
2394
|
-
return { lines, cursor };
|
|
2468
|
+
const input = r.text ? { ...r.text, row: top + r.text.row } : null; // where the mouse reaches the input box's text
|
|
2469
|
+
lines.push(...after);
|
|
2470
|
+
return { lines, cursor, input };
|
|
2395
2471
|
}
|
|
2396
2472
|
|
|
2397
2473
|
// In the input box's top border: the directory the agent is in now (a `cd` moves it), and this
|
|
@@ -2418,6 +2494,8 @@ export class App {
|
|
|
2418
2494
|
const flash = this.flashMessage && Date.now() < this.flashMessage.until ? this.flashMessage : null;
|
|
2419
2495
|
if (this.exitArmed && Date.now() - this.exitArmed < 1500) left = c.dim(' Press Ctrl-C again to exit');
|
|
2420
2496
|
else if (flash) left = (flash.kind === 'warn' ? c.yellow : c.dim)(' ' + truncate(flash.text, w - 4));
|
|
2497
|
+
else if (this.screen.full && this.screen.selection) left = c.dim(' ctrl+c to copy · ctrl+q to quote it in your message');
|
|
2498
|
+
else if (this.editor.selection) left = c.dim(' ctrl+c to copy · esc to clear');
|
|
2421
2499
|
else if (this.restartRequest) left = c.dim(' ↻ restarting when this turn ends');
|
|
2422
2500
|
else if (this.editor.mode === 'bash') left = c.magenta(' ! for bash mode');
|
|
2423
2501
|
else if (this.editor.mode === 'memory') left = c.blue(' # to memorize');
|
|
@@ -2431,11 +2509,11 @@ export class App {
|
|
|
2431
2509
|
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'}`);
|
|
2432
2510
|
}
|
|
2433
2511
|
const cfg = this.config;
|
|
2434
|
-
const threshold = cfg.
|
|
2512
|
+
const threshold = cfg.compactWindow();
|
|
2435
2513
|
const used = this.agent.contextEstimate;
|
|
2436
2514
|
let notice = '';
|
|
2437
2515
|
const pctLeft = Math.max(0, Math.round((1 - used / threshold) * 100));
|
|
2438
|
-
if (pctLeft <= 30
|
|
2516
|
+
if (pctLeft <= 30) notice = c.yellow(`Context left until auto-compact: ${pctLeft}%`);
|
|
2439
2517
|
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`);
|
|
2440
2518
|
else if (this.verbose) notice = c.dim('verbose');
|
|
2441
2519
|
// The model and effort in use always have a place at the right: with the notice after it when both fit,
|
|
@@ -2473,5 +2551,8 @@ export async function runRepl({ flags, cwd, initialPrompt }) {
|
|
|
2473
2551
|
process.stderr.write(`\nUnexpected error: ${e?.stack || e}\n`);
|
|
2474
2552
|
process.exit(1);
|
|
2475
2553
|
});
|
|
2554
|
+
// A promise without a handler that rejects is a bug to show, not a reason to end the session: Node ends the process
|
|
2555
|
+
// on one by default (through the handler above, with exit code 1, which the supervisor does not restart).
|
|
2556
|
+
process.on('unhandledRejection', (e) => { try { app.logError(e); } catch { /* the screen is gone */ } });
|
|
2476
2557
|
return await app.start(initialPrompt);
|
|
2477
2558
|
}
|