@yanzc/claude-pro 0.11.0 → 0.12.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 +55 -36
- package/package.json +1 -1
- package/src/agent.js +4 -3
- package/src/browser/session.js +21 -1
- package/src/commands.js +103 -18
- package/src/config.js +1 -2
- package/src/live.js +148 -0
- package/src/main.js +5 -3
- package/src/peers.js +41 -4
- package/src/remote.js +73 -267
- package/src/runtime.js +36 -11
- package/src/selfcheck.js +3 -3
- package/src/session.js +116 -7
- 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 +399 -456
- package/src/ui/screen.js +47 -674
- package/src/updater.js +5 -4
- package/src/web/api.js +787 -0
- package/src/web/app.css +412 -0
- package/src/web/app.js +1850 -0
- package/src/web/data.js +424 -0
- package/src/web/host.js +334 -0
- package/src/web/login.html +66 -0
- package/src/web/page.html +41 -0
- package/src/web/remote-access.js +232 -0
- package/src/web/server.js +459 -0
package/src/runtime.js
CHANGED
|
@@ -13,25 +13,21 @@ import { isAbort } from './api.js';
|
|
|
13
13
|
import { McpManager } from './mcp.js';
|
|
14
14
|
import { HookRunner } from './hooks.js';
|
|
15
15
|
import { BackgroundTasks, taskNotification } from './tasks.js';
|
|
16
|
-
import { autoMemoryDir, sweepOldData, projectDir } from './session.js';
|
|
16
|
+
import { autoMemoryDir, claimSession, sweepOldData, projectDir } from './session.js';
|
|
17
17
|
import { loadAutoMemoryIndex, takeEnvSnapshot, takeEnvSnapshotAsync, localDate } from './context.js';
|
|
18
18
|
import { canRestart } from './restart.js';
|
|
19
19
|
import { RuntimeTrace } from './trace.js';
|
|
20
20
|
|
|
21
21
|
export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
|
|
22
22
|
const config = loadConfig({ cwd, flags });
|
|
23
|
+
// Whose background shells, interpreters and browser tabs are whose (tools/bash.js, code.js, browser.js): the web
|
|
24
|
+
// console runs several sessions in one process.
|
|
25
|
+
config.owner = crypto.randomUUID();
|
|
23
26
|
const trace = new RuntimeTrace({ cwd, sessionId, enabled: config.traceEnabled });
|
|
24
27
|
applyRememberedChoices(config, flags); // what /model and /effort chose last time
|
|
28
|
+
if (flags.initialChoices && 'model' in flags.initialChoices) config.modelOverride = flags.initialChoices.model;
|
|
29
|
+
if (flags.initialChoices && 'effort' in flags.initialChoices) config.effortOverride = flags.initialChoices.effort;
|
|
25
30
|
if (flags.verify) config.verifyOverride = flags.verify;
|
|
26
|
-
// Old conversations and what goes with them, in the background a while after the start (not in the self-check's
|
|
27
|
-
// throwaway process, nor a test's: CLAUDE_PRO_CONFIG_DIR points elsewhere then anyway)
|
|
28
|
-
if (process.env.CLAUDE_PRO_SELF_CHECK !== '1') {
|
|
29
|
-
setTimeout(() => {
|
|
30
|
-
sweepOldData({ days: config.setting('cleanupPeriodDays'), keep: [sessionId, config.sessionId] })
|
|
31
|
-
.then((done) => { if (done.files) trace.append('cleanup', { conversations: done.conversations, files: done.files, bytes: done.bytes }); })
|
|
32
|
-
.catch(() => {});
|
|
33
|
-
}, 15_000).unref();
|
|
34
|
-
}
|
|
35
31
|
pruneStaleShellFiles();
|
|
36
32
|
// Full access: nothing is ever asked.
|
|
37
33
|
const checkpoints = new CheckpointStore(path.join(projectDir(cwd), 'checkpoints', `${Date.now()}-${crypto.randomBytes(3).toString('hex')}`));
|
|
@@ -47,7 +43,7 @@ export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
|
|
|
47
43
|
const runtime = { config, checkpoints, agents, mcp, shell, io, cwd, hooks, tasks, memoryDir, trace };
|
|
48
44
|
runtime.skills = loadSkills(cwd);
|
|
49
45
|
// The self-check builds the Restart tool too, so that a mistake in it is found before a restart relies on it.
|
|
50
|
-
const restartable = canRestart() || process.env.CLAUDE_PRO_SELF_CHECK === '1';
|
|
46
|
+
const restartable = (io?.canRestart ? io.canRestart() : canRestart()) || process.env.CLAUDE_PRO_SELF_CHECK === '1';
|
|
51
47
|
// The agent fixes its own code (and restarts for it) only in a source checkout: an installed copy is replaced by
|
|
52
48
|
// the next update, so there it reports its defects instead.
|
|
53
49
|
const selfEdit = restartable && SOURCE_CHECKOUT;
|
|
@@ -202,5 +198,34 @@ export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
|
|
|
202
198
|
runtime.agent.notifications.push({ taskId: task.id, text: taskNotification(task) });
|
|
203
199
|
io.backgroundTaskDone?.(task);
|
|
204
200
|
});
|
|
201
|
+
|
|
202
|
+
// A /resume must claim the new id before it reads the old transcript. If loading fails, keep the previous claim.
|
|
203
|
+
let ownedId, release;
|
|
204
|
+
runtime.useSession = (id, load = () => {}) => {
|
|
205
|
+
if (!id || id === ownedId) return load();
|
|
206
|
+
const next = claimSession(id);
|
|
207
|
+
let value;
|
|
208
|
+
try { value = load(); } catch (e) { next(); throw e; }
|
|
209
|
+
release?.();
|
|
210
|
+
ownedId = id;
|
|
211
|
+
release = next;
|
|
212
|
+
return value;
|
|
213
|
+
};
|
|
214
|
+
runtime.releaseSession = () => { release?.(); ownedId = release = undefined; };
|
|
215
|
+
// The REPL switches via useSession; print mode can only resume the id given at startup.
|
|
216
|
+
try { runtime.useSession(!io?.store && flags.resumeFile ? (flags.resumeId || sessionId) : sessionId); }
|
|
217
|
+
catch (e) { mcp.close(); throw e; }
|
|
218
|
+
|
|
219
|
+
if (process.env.CLAUDE_PRO_SELF_CHECK !== '1') {
|
|
220
|
+
setTimeout(() => {
|
|
221
|
+
if (io?.exiting) return;
|
|
222
|
+
// Read live state at the deletion point, also covering local Apps still in startup.
|
|
223
|
+
const isOwned = (id) => id === config.sessionId || id === io?.store?.id || [...(io?.host?.apps || [])].some((app) =>
|
|
224
|
+
!app.exiting && (id === app.store?.id || (!app.runtime && (id === app.flags?.resumeId || id === app.flags?.restart?.sessionId))));
|
|
225
|
+
sweepOldData({ days: config.setting('cleanupPeriodDays'), isOwned })
|
|
226
|
+
.then((done) => { if (done.files) trace.append('cleanup', { conversations: done.conversations, files: done.files, bytes: done.bytes }); })
|
|
227
|
+
.catch(() => {});
|
|
228
|
+
}, 15_000).unref();
|
|
229
|
+
}
|
|
205
230
|
return runtime;
|
|
206
231
|
}
|
package/src/selfcheck.js
CHANGED
|
@@ -10,14 +10,14 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
|
10
10
|
async function check() {
|
|
11
11
|
const problems = [];
|
|
12
12
|
const fail = (text) => problems.push(text);
|
|
13
|
-
// The App starts as a session does
|
|
13
|
+
// The App starts as a session does, so that code only a real start runs is checked
|
|
14
14
|
// too, but this process must not show up as a session or go online.
|
|
15
15
|
Object.assign(process.env, { CLAUDE_PRO_PEERS: '0', CLAUDE_PRO_ONLINE: '0' });
|
|
16
16
|
|
|
17
17
|
let App;
|
|
18
18
|
try {
|
|
19
19
|
({ App } = await import('./ui/repl.js'));
|
|
20
|
-
for (const file of ['./main.js', './print.js', './restart.js', './supervisor.js']) await import(file);
|
|
20
|
+
for (const file of ['./main.js', './print.js', './restart.js', './supervisor.js', './web/server.js', './web/api.js', './web/host.js']) await import(file);
|
|
21
21
|
} catch (e) {
|
|
22
22
|
return [`A module does not load: ${e?.stack || e}`];
|
|
23
23
|
}
|
|
@@ -34,7 +34,7 @@ async function check() {
|
|
|
34
34
|
exited = app.start('');
|
|
35
35
|
exited.catch((e) => fail(`Starting failed: ${e?.stack || e}`));
|
|
36
36
|
const began = Date.now();
|
|
37
|
-
while (!(screen.includes('Welcome to') && screen.includes('
|
|
37
|
+
while (!(screen.includes('Welcome to') && (screen.includes('explain this codebase') || screen.includes('Enter to confirm')))) {
|
|
38
38
|
if (problems.length) return problems;
|
|
39
39
|
if (Date.now() - began > STARTUP_LIMIT_MS) return [`The interface did not come up within ${STARTUP_LIMIT_MS / 1000} seconds.\n${screen.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').slice(-800)}`];
|
|
40
40
|
await sleep(25);
|
package/src/session.js
CHANGED
|
@@ -7,6 +7,8 @@ import path from 'node:path';
|
|
|
7
7
|
import crypto from 'node:crypto';
|
|
8
8
|
import { CONFIG_DIR } from './config.js';
|
|
9
9
|
import { PROMPT_CODE_VERSION } from './prompts.js';
|
|
10
|
+
import { processAlive } from './utils/shell.js';
|
|
11
|
+
import { listPeers } from './peers.js';
|
|
10
12
|
|
|
11
13
|
// The directory of a project's state (conversations, memory, checkpoints, traces): its path with every character
|
|
12
14
|
// but a-z, A-Z and 0-9 made '-', as Claude Code names it. A path with characters beyond ASCII in it also gets a hash
|
|
@@ -93,23 +95,117 @@ export function checkpointsDir(cwd) {
|
|
|
93
95
|
return path.join(projectDir(cwd), 'checkpoints');
|
|
94
96
|
}
|
|
95
97
|
|
|
98
|
+
// 归档 (archived) conversations: put away from the web console's workspace, kept whole, and never deleted by age
|
|
99
|
+
// (sweepOldData). A mark in CONFIG_DIR/archived.json ({id: {at}}); the conversation's file stays where it is, so
|
|
100
|
+
// /resume and --resume still find it.
|
|
101
|
+
const archivedFile = () => path.join(CONFIG_DIR, 'archived.json');
|
|
102
|
+
export function archivedSessions() {
|
|
103
|
+
try {
|
|
104
|
+
const data = JSON.parse(fs.readFileSync(archivedFile(), 'utf8'));
|
|
105
|
+
return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
|
|
106
|
+
} catch { return {}; }
|
|
107
|
+
}
|
|
108
|
+
export function setArchived(ids, archived = true) {
|
|
109
|
+
const data = archivedSessions();
|
|
110
|
+
const at = Date.now();
|
|
111
|
+
for (const id of ids) {
|
|
112
|
+
if (typeof id !== 'string' || !id) continue;
|
|
113
|
+
if (archived) data[id] = { at };
|
|
114
|
+
else delete data[id];
|
|
115
|
+
}
|
|
116
|
+
fs.mkdirSync(path.dirname(archivedFile()), { recursive: true });
|
|
117
|
+
const tmp = `${archivedFile()}.${process.pid}.tmp`;
|
|
118
|
+
fs.writeFileSync(tmp, JSON.stringify(data));
|
|
119
|
+
fs.renameSync(tmp, archivedFile());
|
|
120
|
+
return data;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Ownership is independent of peer servers: even --print and CLAUDE_PRO_PEERS=0 can own a transcript.
|
|
124
|
+
// Both sides publish their intent before checking the other's marks. If a sweep got there first, the resume
|
|
125
|
+
// must not read the transcript until it can claim it; if the owner got there first, the sweep leaves it alone.
|
|
126
|
+
function markSession(id, kind) {
|
|
127
|
+
const key = crypto.createHash('sha256').update(process.platform === 'win32' ? id.toLowerCase() : id).digest('hex');
|
|
128
|
+
const dir = path.join(CONFIG_DIR, 'session-owners', key);
|
|
129
|
+
const file = path.join(dir, `${kind}-${process.pid}-${crypto.randomUUID()}`);
|
|
130
|
+
const create = () => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file, '', { flag: 'wx' }); };
|
|
131
|
+
try { create(); } catch (e) { if (e.code !== 'ENOENT') throw e; create(); } // a concurrent release removed the empty dir
|
|
132
|
+
return {
|
|
133
|
+
dir,
|
|
134
|
+
close() {
|
|
135
|
+
try { fs.unlinkSync(file); } catch { /* already gone, or still protected */ }
|
|
136
|
+
try { fs.rmdirSync(dir); } catch { /* still in use */ }
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function hasSessionMark(dir, kind) {
|
|
142
|
+
return fs.readdirSync(dir).some((name) => {
|
|
143
|
+
const [, type, pid] = /^(owner|sweep)-(\d+)-/.exec(name) || [];
|
|
144
|
+
if (!type) return false;
|
|
145
|
+
if (processAlive(Number(pid))) return type === kind;
|
|
146
|
+
try { fs.unlinkSync(path.join(dir, name)); } catch { /* already gone */ }
|
|
147
|
+
return false;
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function claimSession(id) {
|
|
152
|
+
const mark = markSession(id, 'owner');
|
|
153
|
+
try {
|
|
154
|
+
if (hasSessionMark(mark.dir, 'sweep')) throw new Error(`Session ${id} is being checked for expiration; try again.`);
|
|
155
|
+
return mark.close;
|
|
156
|
+
} catch (e) {
|
|
157
|
+
mark.close();
|
|
158
|
+
throw e;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// During an upgrade an older process may not publish ownership marks yet. Peer IDs aren't transcript IDs,
|
|
163
|
+
// and /status can time out or change after a /resume. Conservatively keep its project's transcripts and traces.
|
|
164
|
+
// (A process of this version says so in its peer file and is covered by its marks.)
|
|
165
|
+
function foreignPeerIn(dir) {
|
|
166
|
+
return listPeers().some(({ pid, cwd, sessionClaims }) => {
|
|
167
|
+
if (pid === process.pid || sessionClaims) return false;
|
|
168
|
+
if (typeof cwd !== 'string' || !cwd) return true;
|
|
169
|
+
const abs = path.resolve(cwd);
|
|
170
|
+
const name = abs.replace(/[^a-zA-Z0-9]/g, '-');
|
|
171
|
+
const key = pathKey(dir);
|
|
172
|
+
const legacy = path.join(path.dirname(dir), name);
|
|
173
|
+
return key === pathKey(legacy) || key === pathKey(`${legacy}-${pathHash(abs)}`);
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
96
177
|
// Delete what is older than `days` (the cleanupPeriodDays setting, as in Claude Code: 30 by default), in every
|
|
97
178
|
// project: conversations not written to since (they no longer appear in /resume), their traces, saved tool outputs
|
|
98
179
|
// (at most 7 days) and /rewind snapshots (at most 14 days). The memory is never touched. Conversations were kept
|
|
99
180
|
// for good before: 646 MB in 176 files in a month (2026-11-11), of which only the current project's tool outputs,
|
|
100
181
|
// snapshots and traces were deleted, and only when a session started there. Runs in the background, at most once
|
|
101
|
-
// an hour on the machine (`marker`); `keep`: conversation ids not to delete whatever their age
|
|
102
|
-
|
|
182
|
+
// an hour on the machine (`marker`); `keep`: conversation ids not to delete whatever their age (and the archived
|
|
183
|
+
// ones are never deleted). `isOwned` is a synchronous fallback for owners without a claim. Returns what went.
|
|
184
|
+
export async function sweepOldData({ days, keep = [], isOwned = () => false, root = path.join(CONFIG_DIR, 'projects'), now = Date.now() } = {}) {
|
|
103
185
|
const done = { conversations: 0, files: 0, bytes: 0 };
|
|
104
186
|
if (!(days >= 1)) return done;
|
|
105
187
|
const marker = path.join(root, '.last-sweep');
|
|
106
188
|
try { if (now - fs.statSync(marker).mtimeMs < 3600_000) return done; } catch { /* never swept */ }
|
|
107
189
|
try { fs.mkdirSync(root, { recursive: true }); fs.writeFileSync(marker, ''); } catch { return done; }
|
|
108
190
|
const day = 24 * 3600_000;
|
|
109
|
-
const keepIds = new Set(keep.filter(Boolean));
|
|
191
|
+
const keepIds = new Set([...keep.filter(Boolean), ...Object.keys(archivedSessions())]);
|
|
110
192
|
const fsp = fs.promises;
|
|
111
193
|
const list = async (dir) => { try { return await fsp.readdir(dir, { withFileTypes: true }); } catch { return []; } };
|
|
112
194
|
const old = async (file, maxAgeMs) => { try { return now - (await fsp.stat(file)).mtimeMs > maxAgeMs; } catch { return false; } };
|
|
195
|
+
const removeSessionFile = (file, id, dir) => {
|
|
196
|
+
let mark;
|
|
197
|
+
try {
|
|
198
|
+
mark = markSession(id, 'sweep');
|
|
199
|
+
// Check after the async age test, then keep the ownership check, final stat and unlink together.
|
|
200
|
+
if (hasSessionMark(mark.dir, 'owner') || isOwned(id, dir) || foreignPeerIn(dir) || Object.hasOwn(archivedSessions(), id)) return false;
|
|
201
|
+
const stats = fs.statSync(file);
|
|
202
|
+
if (now - stats.mtimeMs <= days * day) return false;
|
|
203
|
+
fs.unlinkSync(file);
|
|
204
|
+
done.files++;
|
|
205
|
+
done.bytes += stats.size;
|
|
206
|
+
return true;
|
|
207
|
+
} catch { return false; } finally { mark?.close(); }
|
|
208
|
+
};
|
|
113
209
|
const remove = async (file, isDir = false) => {
|
|
114
210
|
try {
|
|
115
211
|
const size = isDir ? 0 : (await fsp.stat(file)).size;
|
|
@@ -119,17 +215,26 @@ export async function sweepOldData({ days, keep = [], root = path.join(CONFIG_DI
|
|
|
119
215
|
return true;
|
|
120
216
|
} catch { return false; }
|
|
121
217
|
};
|
|
218
|
+
// marks left by processes that ended without releasing them (a crash): nothing else removes them
|
|
219
|
+
const owners = path.join(CONFIG_DIR, 'session-owners');
|
|
220
|
+
for (const d of await list(owners)) {
|
|
221
|
+
if (!d.isDirectory()) continue;
|
|
222
|
+
try { hasSessionMark(path.join(owners, d.name), 'owner'); } catch { /* gone meanwhile */ }
|
|
223
|
+
try { fs.rmdirSync(path.join(owners, d.name)); } catch { /* still in use */ }
|
|
224
|
+
}
|
|
122
225
|
for (const project of await list(root)) {
|
|
123
226
|
if (!project.isDirectory()) continue;
|
|
124
227
|
const dir = path.join(root, project.name);
|
|
125
228
|
for (const e of await list(dir)) {
|
|
126
229
|
const id = e.name.replace(/\.jsonl$/, '');
|
|
127
230
|
if (!e.isFile() || id === e.name || keepIds.has(id)) continue;
|
|
128
|
-
|
|
231
|
+
const f = path.join(dir, e.name);
|
|
232
|
+
if (await old(f, days * day) && removeSessionFile(f, id, dir)) done.conversations++;
|
|
129
233
|
}
|
|
130
234
|
for (const e of await list(path.join(dir, 'traces'))) { // a conversation's trace is written with it
|
|
131
235
|
const f = path.join(dir, 'traces', e.name);
|
|
132
|
-
|
|
236
|
+
const id = e.name.replace(/\.jsonl(\.\d+)?$/, '');
|
|
237
|
+
if (!keepIds.has(id) && (await old(f, days * day))) removeSessionFile(f, id, dir);
|
|
133
238
|
}
|
|
134
239
|
for (const e of await list(path.join(dir, 'tool-results'))) {
|
|
135
240
|
const f = path.join(dir, 'tool-results', e.name);
|
|
@@ -174,6 +279,7 @@ export function moveSession(file, id, cwd) {
|
|
|
174
279
|
|
|
175
280
|
export class SessionStore {
|
|
176
281
|
static onError = null; // (error, store): a write of the conversation failed (the first time for a store)
|
|
282
|
+
onError = null; // the same for this store alone (its session's: the web console runs several in one process)
|
|
177
283
|
|
|
178
284
|
constructor(cwd, id = crypto.randomUUID()) {
|
|
179
285
|
this.cwd = cwd;
|
|
@@ -195,7 +301,7 @@ export class SessionStore {
|
|
|
195
301
|
// Best effort, but a message that did not get in leaves the file without it, and a restart or /resume would go
|
|
196
302
|
// on from a conversation that lacks it: noted (`lost`, see App.restartNow), and said once (SessionStore.onError).
|
|
197
303
|
this.lost = true;
|
|
198
|
-
if (!this.warned) { this.warned = true; try { SessionStore.onError?.(e, this); } catch { /* ignore */ } }
|
|
304
|
+
if (!this.warned) { this.warned = true; try { (this.onError || SessionStore.onError)?.(e, this); } catch { /* ignore */ } }
|
|
199
305
|
}
|
|
200
306
|
}
|
|
201
307
|
|
|
@@ -312,5 +418,8 @@ const SESSION_INDEX = 'sessions-index.json';
|
|
|
312
418
|
export function firstUserText(message) {
|
|
313
419
|
const blocks = typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : message.content;
|
|
314
420
|
const t = blocks.find((b) => b.type === 'text' && !b.text.startsWith('<system-reminder>') && !b.text.startsWith('['));
|
|
315
|
-
|
|
421
|
+
if (!t) return null;
|
|
422
|
+
// a command of bash mode (!cmd): the command, as it was typed
|
|
423
|
+
const bash = /^<bash-input>([\s\S]*?)<\/bash-input>/.exec(t.text);
|
|
424
|
+
return (bash ? `! ${bash[1]}` : t.text).replace(/\s+/g, ' ').trim().slice(0, 100);
|
|
316
425
|
}
|
package/src/supervisor.js
CHANGED
|
@@ -41,7 +41,7 @@ export function sessionEntry(entry, platform = process.platform) {
|
|
|
41
41
|
// Whether this invocation is an interactive session that should run under the supervisor.
|
|
42
42
|
export function shouldSupervise(argv, env = process.env, isTty = (fd) => tty.isatty(fd)) {
|
|
43
43
|
if (env[ENV_SUPERVISED] || /^(1|true|yes)$/i.test(env.CLAUDE_PRO_NO_SUPERVISOR || '')) return false;
|
|
44
|
-
if (['config', 'host', 'attach', 'connect'].includes(argv[0])) return false; // a command, or a removed one (see main.js)
|
|
44
|
+
if (['config', 'web', 'host', 'attach', 'connect'].includes(argv[0])) return false; // a command, or a removed one (see main.js)
|
|
45
45
|
if (!isTty(0) || !isTty(1)) return false;
|
|
46
46
|
return !argv.some((a) => NOT_INTERACTIVE.has(a));
|
|
47
47
|
}
|
package/src/tools/bash.js
CHANGED
|
@@ -8,7 +8,11 @@ import { stripAnsi } from '../ui/ansi.js';
|
|
|
8
8
|
import { OutputDecoder } from '../utils/encoding.js';
|
|
9
9
|
import { toolResultsDir } from '../session.js';
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
// id -> {owner, child, command, output, readPos, status, exitCode, startedAt}. `owner`: the session's (config.owner):
|
|
12
|
+
// the web console runs several sessions in one process, and each sees and stops only its own shells.
|
|
13
|
+
const background = new Map();
|
|
14
|
+
const ownedBy = (bg, owner) => !owner || !bg.owner || bg.owner === owner;
|
|
15
|
+
const shellOf = (id, owner) => { const bg = background.get(id); return bg && ownedBy(bg, owner) ? bg : null; };
|
|
12
16
|
let bgCounter = 0;
|
|
13
17
|
const PROGRESS_CHARS = 8192; // the end of the output the live view gets while a command runs
|
|
14
18
|
|
|
@@ -46,13 +50,18 @@ export function appendOutput(bg, text, max = 5_000_000, keep = 2_000_000) {
|
|
|
46
50
|
|
|
47
51
|
export { childEnv };
|
|
48
52
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
for (const bg of background
|
|
53
|
+
// The session `owner` ends (every session when not given: the program is exiting).
|
|
54
|
+
export function shutdownBackgroundShells(owner) {
|
|
55
|
+
for (const [id, bg] of background) {
|
|
56
|
+
if (!ownedBy(bg, owner)) continue;
|
|
57
|
+
// `orphans`: a shell that has ended but is still "running" left something holding its output
|
|
58
|
+
if (bg.status === 'running') killTreeSync(bg.child, { orphans: true });
|
|
59
|
+
if (owner) background.delete(id);
|
|
60
|
+
}
|
|
52
61
|
}
|
|
53
62
|
|
|
54
|
-
export function listBackgroundShells() {
|
|
55
|
-
return [...background.entries()].map(([id, bg]) => ({ id, command: bg.command, description: bg.description || '', status: bg.status, exitCode: bg.exitCode, startedAt: bg.startedAt }));
|
|
63
|
+
export function listBackgroundShells(owner) {
|
|
64
|
+
return [...background.entries()].filter(([, bg]) => ownedBy(bg, owner)).map(([id, bg]) => ({ id, command: bg.command, description: bg.description || '', status: bg.status, exitCode: bg.exitCode, startedAt: bg.startedAt }));
|
|
56
65
|
}
|
|
57
66
|
|
|
58
67
|
export function makeBashTool(config) {
|
|
@@ -98,10 +107,10 @@ When you commit (the system prompt says when): run git status, git diff and git
|
|
|
98
107
|
if (input.run_in_background) {
|
|
99
108
|
const child = spawnShell(shell, command, { cwd, env: childEnv(), stdin: stdinText });
|
|
100
109
|
const id = `bash_${++bgCounter}`;
|
|
101
|
-
const bg = { child, command, description: String(input.description || ''), output: '', readPos: 0, status: 'running', exitCode: null, startedAt: Date.now() };
|
|
110
|
+
const bg = { owner: config.owner || null, child, command, description: String(input.description || ''), output: '', readPos: 0, status: 'running', exitCode: null, startedAt: Date.now() };
|
|
102
111
|
background.set(id, bg);
|
|
103
112
|
// the shells that ended stay listed, with what was not read of their output: the oldest go past 50
|
|
104
|
-
const ended = [...background].filter(([, b]) => b.status !== 'running');
|
|
113
|
+
const ended = [...background].filter(([, b]) => b.status !== 'running' && b.owner === bg.owner);
|
|
105
114
|
for (const [old] of ended.slice(0, Math.max(0, ended.length - 50))) background.delete(old);
|
|
106
115
|
// Line by line, UTF-8 or the console code page (GBK here), never cutting a character (see OutputDecoder).
|
|
107
116
|
for (const stream of [child.stdout, child.stderr]) {
|
|
@@ -189,8 +198,8 @@ export const BashOutputTool = {
|
|
|
189
198
|
},
|
|
190
199
|
summarize(input) { return input.bash_id; },
|
|
191
200
|
async call(input, ctx = {}) {
|
|
192
|
-
const bg =
|
|
193
|
-
if (!bg) return { isError: true, content: `No background shell with id ${input.bash_id}. Known: ${
|
|
201
|
+
const bg = shellOf(input.bash_id, ctx.config?.owner);
|
|
202
|
+
if (!bg) return { isError: true, content: `No background shell with id ${input.bash_id}. Known: ${listBackgroundShells(ctx.config?.owner).map((s) => s.id).join(', ') || 'none'}` };
|
|
194
203
|
let fresh = bg.output.slice(bg.readPos);
|
|
195
204
|
bg.output = ''; // what was read is not read again (up to 5 MB a shell, kept for good before)
|
|
196
205
|
bg.readPos = 0;
|
|
@@ -222,8 +231,8 @@ export const KillShellTool = {
|
|
|
222
231
|
required: ['shell_id'],
|
|
223
232
|
},
|
|
224
233
|
summarize(input) { return input.shell_id; },
|
|
225
|
-
async call(input) {
|
|
226
|
-
const bg =
|
|
234
|
+
async call(input, ctx = {}) {
|
|
235
|
+
const bg = shellOf(input.shell_id, ctx.config?.owner);
|
|
227
236
|
if (!bg) return { isError: true, content: `No background shell with id ${input.shell_id}` };
|
|
228
237
|
if (bg.status !== 'running') return { content: `Shell ${input.shell_id} is not running (status: ${bg.status})` };
|
|
229
238
|
bg.status = 'killed';
|
package/src/tools/browser.js
CHANGED
|
@@ -4,11 +4,16 @@
|
|
|
4
4
|
|
|
5
5
|
import fs from 'node:fs';
|
|
6
6
|
import path from 'node:path';
|
|
7
|
-
import {
|
|
7
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
8
|
+
import { browserSessionFor, BrowserError, CdpError, refId, safeUrl } from '../browser/session.js';
|
|
8
9
|
import { snapshotLines, renderLines, diffLines, renderDiff, findLines } from '../browser/snapshot.js';
|
|
9
10
|
import { CONFIG_DIR } from '../config.js';
|
|
10
11
|
import { resolvePath } from '../utils/paths.js';
|
|
11
12
|
|
|
13
|
+
// The browser session of the call being run: the session's own (see browserSessionFor), passed down the call.
|
|
14
|
+
const current = new AsyncLocalStorage();
|
|
15
|
+
const session = () => current.getStore();
|
|
16
|
+
|
|
12
17
|
export const browserToolLimits = { snapshotChars: 10_000, diffLines: 60, diffChars: 5_000, textChars: 30_000, evalChars: 20_000, findMatches: 30 };
|
|
13
18
|
|
|
14
19
|
const ACTIONS = ['tabs', 'open', 'switch', 'navigate', 'back', 'forward', 'reload', 'close', 'snapshot', 'find', 'text', 'click', 'type', 'press', 'hover', 'scroll', 'select', 'upload', 'wait', 'eval', 'screenshot', 'dialog', 'disconnect'];
|
|
@@ -78,7 +83,7 @@ const header = (tab) => `${tab.id} ${cut(tab.url || '', 200)}${tab.title ? ` —
|
|
|
78
83
|
// text and the links' addresses too (what find searches, and what the changes after an action are taken from, so
|
|
79
84
|
// that a message or a counter that changes shows up).
|
|
80
85
|
async function readPage(tab) {
|
|
81
|
-
const trees = await
|
|
86
|
+
const trees = await session().trees(tab);
|
|
82
87
|
const title = trees.main?.find((n) => !n.parentId)?.name?.value; // the document's title, before the browser reports it
|
|
83
88
|
if (title) tab.title = title;
|
|
84
89
|
return {
|
|
@@ -104,7 +109,7 @@ function named(tab, ref) {
|
|
|
104
109
|
|
|
105
110
|
// A tab by id (t3f9a; see BrowserSession.relabel) or by words of its title or address.
|
|
106
111
|
function findTab(spec) {
|
|
107
|
-
const s =
|
|
112
|
+
const s = session();
|
|
108
113
|
const want = String(spec ?? '').trim();
|
|
109
114
|
if (!want) throw new BrowserError('switch needs tab: an id from tabs, or words of its title or address');
|
|
110
115
|
if (/^t(?:\d+|[0-9a-f]{4,})$/i.test(want)) return s.tab(want);
|
|
@@ -116,7 +121,7 @@ function findTab(spec) {
|
|
|
116
121
|
}
|
|
117
122
|
|
|
118
123
|
async function step(input, ctx) {
|
|
119
|
-
const s =
|
|
124
|
+
const s = session();
|
|
120
125
|
const a = input.action;
|
|
121
126
|
const need = (field) => {
|
|
122
127
|
if (input[field] === undefined || input[field] === null || input[field] === '') throw new BrowserError(`${a} needs ${field}`);
|
|
@@ -234,7 +239,7 @@ async function step(input, ctx) {
|
|
|
234
239
|
|
|
235
240
|
// The page after what was done: what changed since the last snapshot, or the page itself.
|
|
236
241
|
async function pageState(tab, kind) {
|
|
237
|
-
const s =
|
|
242
|
+
const s = session();
|
|
238
243
|
await s.settle(tab);
|
|
239
244
|
if (tab.dialog) return `A ${tab.dialog.type} dialog is open: ${JSON.stringify(tab.dialog.message)}. Answer it with dialog (accept: true or false${tab.dialog.type === 'prompt' ? ', text' : ''}).`;
|
|
240
245
|
const page = await readPage(tab);
|
|
@@ -254,13 +259,13 @@ async function pageState(tab, kind) {
|
|
|
254
259
|
// When the last step read the page (switch, then find): only where the tab is, the page not shown again. It is
|
|
255
260
|
// still recorded, so that the next action shows what it changed instead of the whole page.
|
|
256
261
|
async function quietState(tab, unsettled) {
|
|
257
|
-
if (unsettled) await
|
|
262
|
+
if (unsettled) await session().settle(tab);
|
|
258
263
|
if (!tab.dialog) remember(tab, await readPage(tab));
|
|
259
264
|
return header(tab);
|
|
260
265
|
}
|
|
261
266
|
|
|
262
267
|
async function run(input, ctx) {
|
|
263
|
-
const s =
|
|
268
|
+
const s = session();
|
|
264
269
|
const steps = Array.isArray(input.steps) && input.steps.length ? input.steps : [input];
|
|
265
270
|
if (steps.some((x) => !x || typeof x !== 'object' || !x.action)) {
|
|
266
271
|
return { isError: true, content: 'Each call needs an action (or steps: a list of {action, …}).' };
|
|
@@ -359,7 +364,8 @@ export function makeBrowserTool() {
|
|
|
359
364
|
return one(input);
|
|
360
365
|
},
|
|
361
366
|
async call(input, ctx) {
|
|
362
|
-
|
|
367
|
+
const s = browserSessionFor(ctx.config?.owner);
|
|
368
|
+
return s.run(ctx.signal, () => current.run(s, () => run(input, ctx)));
|
|
363
369
|
},
|
|
364
370
|
};
|
|
365
371
|
}
|
package/src/tools/code.js
CHANGED
|
@@ -329,11 +329,17 @@ class Interpreter {
|
|
|
329
329
|
}
|
|
330
330
|
}
|
|
331
331
|
|
|
332
|
-
|
|
332
|
+
// "<owner> <language>" -> Interpreter. The owner is the session's (config.owner): the web console runs several
|
|
333
|
+
// sessions in one process, and each has its own interpreters.
|
|
334
|
+
const interpreters = new Map();
|
|
333
335
|
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
interpreters
|
|
336
|
+
// The session `owner` ends (all of them when not given: the program is exiting).
|
|
337
|
+
export function shutdownInterpreters(owner) {
|
|
338
|
+
for (const [key, i] of interpreters) {
|
|
339
|
+
if (owner && !key.startsWith(`${owner} `)) continue;
|
|
340
|
+
i.kill(true);
|
|
341
|
+
interpreters.delete(key);
|
|
342
|
+
}
|
|
337
343
|
}
|
|
338
344
|
|
|
339
345
|
const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
|
|
@@ -367,15 +373,16 @@ Use it to work with data: load a log, a JSON or CSV file, a database or an API r
|
|
|
367
373
|
if (!lang) return { isError: true, content: 'language must be python or node' };
|
|
368
374
|
const { label } = LANGUAGES[lang];
|
|
369
375
|
const code = typeof input.code === 'string' ? input.code : '';
|
|
370
|
-
|
|
376
|
+
const key = `${config?.owner || ''} ${lang}`;
|
|
377
|
+
let interp = interpreters.get(key);
|
|
371
378
|
const notes = [];
|
|
372
379
|
if (input.reset && interp) {
|
|
373
380
|
interp.kill();
|
|
374
|
-
interpreters.delete(
|
|
381
|
+
interpreters.delete(key);
|
|
375
382
|
interp = null;
|
|
376
383
|
notes.push(`(a new ${label} process: the old one's variables are gone)`);
|
|
377
384
|
} else if (interp && !interp.alive) {
|
|
378
|
-
interpreters.delete(
|
|
385
|
+
interpreters.delete(key);
|
|
379
386
|
interp = null;
|
|
380
387
|
notes.push(`(the ${label} process had ended, so this is a new one: earlier variables are gone)`);
|
|
381
388
|
}
|
|
@@ -386,24 +393,24 @@ Use it to work with data: load a log, a JSON or CSV file, a database or an API r
|
|
|
386
393
|
const cwd = fs.existsSync(ctx.cwd) ? ctx.cwd : ctx.projectRoot;
|
|
387
394
|
if (!interp) {
|
|
388
395
|
interp = new Interpreter(lang, { cwd, env: ctx.config?.env });
|
|
389
|
-
interpreters.set(
|
|
396
|
+
interpreters.set(key, interp);
|
|
390
397
|
}
|
|
391
398
|
const timeoutMs = Math.min(Math.max(1000, Number(input.timeout) || replLimits.defaultTimeoutMs), replLimits.maxTimeoutMs);
|
|
392
399
|
const started = Date.now();
|
|
393
400
|
const r = await interp.run(lang === 'node' ? rewriteDynamicImports(code) : code, { cwd, timeoutMs, signal: ctx.signal });
|
|
394
401
|
if (r.startError) {
|
|
395
|
-
interpreters.delete(
|
|
402
|
+
interpreters.delete(key);
|
|
396
403
|
const hint = lang === 'python' ? ` Is Python installed and on PATH? CLAUDE_PRO_PYTHON can name the interpreter (now: ${pythonCommand(ctx.config?.env)}).` : '';
|
|
397
404
|
return { isError: true, content: `Cannot start ${label}: ${r.startError.message}.${hint}` };
|
|
398
405
|
}
|
|
399
406
|
if (r.aborted || ctx.signal?.aborted) {
|
|
400
|
-
interpreters.delete(
|
|
407
|
+
interpreters.delete(key);
|
|
401
408
|
throw Object.assign(new Error('aborted'), { name: 'AbortError', partialOutput: r.output });
|
|
402
409
|
}
|
|
403
410
|
let text = stripAnsi([r.output, r.stderr ? `[stderr]\n${r.stderr.replace(/\s+$/, '')}` : ''].filter(Boolean).join('\n')).replace(/\r\n/g, '\n').replace(/\s+$/, '');
|
|
404
411
|
let isError = false;
|
|
405
412
|
if (r.died) {
|
|
406
|
-
interpreters.delete(
|
|
413
|
+
interpreters.delete(key);
|
|
407
414
|
isError = true;
|
|
408
415
|
const why = r.timedOut ? `timed out after ${timeoutMs / 1000} s and was stopped` : `ended (exit code ${interp.exited?.code ?? '?'})`;
|
|
409
416
|
text += `${text ? '\n' : ''}The ${label} process ${why}: its variables are gone, and the next call starts a new one.`;
|
package/src/tools/restart.js
CHANGED
|
@@ -28,7 +28,7 @@ How it works:
|
|
|
28
28
|
summarize(input) { return input.reason || ''; },
|
|
29
29
|
async call(input, ctx) {
|
|
30
30
|
const io = ctx.io;
|
|
31
|
-
if (!canRestart() || typeof io?.requestRestart !== 'function') {
|
|
31
|
+
if (!(io?.canRestart ? io.canRestart() : canRestart()) || typeof io?.requestRestart !== 'function') {
|
|
32
32
|
return { isError: true, content: `Restart is not available here: it needs an interactive session started with \`${APP_NAME}\` (not -p, and not with CLAUDE_PRO_NO_SUPERVISOR set). Ask the user to restart the program themselves.` };
|
|
33
33
|
}
|
|
34
34
|
const blockers = io.restartBlockers?.() || [];
|
package/src/ui/dialogs.js
CHANGED
|
@@ -1,25 +1,18 @@
|
|
|
1
1
|
// Modal dialogs rendered in the live region: selection menus (questions, the model and session pickers, /rewind),
|
|
2
2
|
// with a typed answer of their own when they offer "Other", and a text field (/connect asks for a key or an address).
|
|
3
3
|
|
|
4
|
-
import { c, glyphs,
|
|
4
|
+
import { c, glyphs, stringWidth, truncate, wordWrap } from './ansi.js';
|
|
5
5
|
import { Editor } from './editor.js';
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
for (const part of stringWidth(l) > inner ? wordWrap(l, inner) : [l]) {
|
|
13
|
-
out.push(color('│') + ' ' + padEnd(part, inner) + ' ' + color('│'));
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
out.push(color(glyphs.bottomLeft + '─'.repeat(w - 2) + glyphs.bottomRight));
|
|
17
|
-
return out;
|
|
7
|
+
// A dialog is drawn without a frame: its lines, the long ones wrapped between words.
|
|
8
|
+
const innerWidth = (width) => Math.max(20, width - 1);
|
|
9
|
+
function wrapAll(lines, width) {
|
|
10
|
+
const inner = innerWidth(width);
|
|
11
|
+
return lines.flatMap((l) => (stringWidth(l) > inner ? wordWrap(l, inner) : [l]));
|
|
18
12
|
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
const inner = Math.max(20, width - 1) - 4;
|
|
13
|
+
// The rows `lines` take once wrapAll() has wrapped the long ones.
|
|
14
|
+
function rowsOf(lines, width) {
|
|
15
|
+
const inner = innerWidth(width);
|
|
23
16
|
return lines.reduce((n, l) => n + (stringWidth(l) > inner ? wordWrap(l, inner).length : 1), 0);
|
|
24
17
|
}
|
|
25
18
|
|
|
@@ -100,10 +93,10 @@ export class SelectDialog {
|
|
|
100
93
|
lines.push(...this.body);
|
|
101
94
|
if (this.body.length) lines.push('');
|
|
102
95
|
if (this.question) lines.push(this.question);
|
|
103
|
-
const inner =
|
|
96
|
+
const inner = innerWidth(width);
|
|
104
97
|
// Show a window of options around the selection when they don't all fit.
|
|
105
98
|
const perOption = this.options.some((o) => o.description) ? 2 : 1;
|
|
106
|
-
const room = Math.max(3, Math.floor((maxHeight -
|
|
99
|
+
const room = Math.max(3, Math.floor((maxHeight - rowsOf(lines, width) - 2 - (this.other ? 3 : 0)) / perOption));
|
|
107
100
|
let first = 0;
|
|
108
101
|
if (this.options.length > room) first = Math.min(Math.max(0, this.selected - Math.floor(room / 2)), this.options.length - room);
|
|
109
102
|
const last = Math.min(this.options.length, first + room);
|
|
@@ -120,12 +113,12 @@ export class SelectDialog {
|
|
|
120
113
|
let cursor = null;
|
|
121
114
|
if (this.other) {
|
|
122
115
|
lines.push('');
|
|
123
|
-
const r = this.other.render(width
|
|
124
|
-
const top =
|
|
116
|
+
const r = this.other.render(width, { placeholder: 'Type your answer, Enter to submit, Esc to go back' });
|
|
117
|
+
const top = rowsOf(lines, width); // the rows above it once wrapAll() has wrapped the long ones
|
|
125
118
|
lines.push(...r.lines.map((l) => truncate(l, inner)));
|
|
126
|
-
if (r.cursor) cursor = { row: top + r.cursor.row, col:
|
|
119
|
+
if (r.cursor) cursor = { row: top + r.cursor.row, col: r.cursor.col };
|
|
127
120
|
}
|
|
128
|
-
const out =
|
|
121
|
+
const out = wrapAll(lines, width);
|
|
129
122
|
const hint = this.footer ?? (this.multi ? 'Space to toggle · Enter to confirm · Esc to cancel' : 'Enter to confirm · Esc to cancel');
|
|
130
123
|
out.push(c.dim(' ' + hint));
|
|
131
124
|
return { lines: out, cursor };
|
|
@@ -186,23 +179,23 @@ export class TextInputDialog {
|
|
|
186
179
|
lines.push(...this.body);
|
|
187
180
|
if (this.body.length) lines.push('');
|
|
188
181
|
if (this.question) lines.push(this.question);
|
|
189
|
-
const inner =
|
|
182
|
+
const inner = innerWidth(width);
|
|
190
183
|
let cursor = null;
|
|
191
184
|
if (this.secret) {
|
|
192
185
|
const n = this.value().length;
|
|
193
186
|
const room = Math.max(4, inner - 20);
|
|
194
187
|
const stars = n ? `${'*'.repeat(Math.min(n, room))}${n > room ? '...' : ''}` : '';
|
|
195
|
-
const row =
|
|
196
|
-
lines.push(
|
|
197
|
-
cursor = { row, col: 2 +
|
|
188
|
+
const row = rowsOf(lines, width); // the row it takes once wrapAll() has wrapped the long ones
|
|
189
|
+
lines.push(`${c.claude('>')} ${stars}${n ? c.dim(` (${n} characters)`) : c.dim(this.placeholder)}`);
|
|
190
|
+
cursor = { row, col: 2 + stringWidth(stars) };
|
|
198
191
|
} else {
|
|
199
|
-
const r = this.editor.render(width
|
|
200
|
-
const top =
|
|
192
|
+
const r = this.editor.render(width, { placeholder: this.placeholder });
|
|
193
|
+
const top = rowsOf(lines, width);
|
|
201
194
|
lines.push(...r.lines.map((l) => truncate(l, inner)));
|
|
202
|
-
if (r.cursor) cursor = { row: top + r.cursor.row, col:
|
|
195
|
+
if (r.cursor) cursor = { row: top + r.cursor.row, col: r.cursor.col };
|
|
203
196
|
}
|
|
204
197
|
if (this.error) lines.push('', c.red(this.error));
|
|
205
|
-
const out =
|
|
198
|
+
const out = wrapAll(lines, width);
|
|
206
199
|
out.push(c.dim(` Enter to confirm · Esc to cancel${this.secret ? ' · Ctrl+V pastes' : ''}`));
|
|
207
200
|
return { lines: out, cursor };
|
|
208
201
|
}
|