@yanzc/claude-pro 0.10.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 +66 -35
- package/package.json +1 -1
- package/src/agent.js +16 -6
- package/src/browser/session.js +32 -2
- package/src/commands.js +160 -11
- package/src/config.js +42 -10
- package/src/live.js +148 -0
- package/src/main.js +5 -3
- package/src/peers.js +64 -10
- package/src/providers.js +10 -1
- package/src/remote.js +90 -243
- 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 +23 -20
- package/src/tools/browser.js +14 -8
- package/src/tools/code.js +18 -11
- package/src/tools/peers.js +6 -5
- 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 +470 -449
- package/src/ui/screen.js +47 -674
- package/src/updater.js +5 -4
- package/src/utils/shell.js +4 -5
- 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/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) {
|
|
@@ -60,7 +69,7 @@ export function makeBashTool(config) {
|
|
|
60
69
|
const isCmd = shell.kind === 'cmd';
|
|
61
70
|
return {
|
|
62
71
|
name: 'Bash',
|
|
63
|
-
description: `Executes a given ${isCmd ? 'cmd.exe' : 'bash'} command with an optional timeout.
|
|
72
|
+
description: `Executes a given ${isCmd ? 'cmd.exe' : 'bash'} command with an optional timeout. Every command starts in the session's working directory: a \`cd\` lasts for that command only, and shell state (variables, functions) does not persist either.
|
|
64
73
|
|
|
65
74
|
This tool is for terminal operations like git, npm, docker, running builds and tests. For file work use the dedicated tools instead of shell commands: Read, not cat/head/tail; Edit, not sed/awk; Write, not echo or heredoc redirection; Glob and Grep, not find and grep. An edit made with Edit, MultiEdit or Write can be undone with /rewind and is shown to the user as a diff; one made by a command (a script that rewrites the file, sed -i) is neither. To edit and then build or test in one step, put the edit calls and the Bash call in the same response: they run in that order. A script is fine for a mechanical change across many files, once you know git can bring them back.
|
|
66
75
|
|
|
@@ -92,17 +101,16 @@ When you commit (the system prompt says when): run git status, git diff and git
|
|
|
92
101
|
const command = String(input.command || '').trim();
|
|
93
102
|
if (!command) return { isError: true, content: 'Empty command' };
|
|
94
103
|
const stdinText = typeof input.stdin === 'string' ? input.stdin : undefined;
|
|
95
|
-
const cwdFile = path.join(os.tmpdir(), `claude-pro-cwd-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
|
96
104
|
let cwd = ctx.cwd;
|
|
97
105
|
if (!fs.existsSync(cwd)) cwd = ctx.projectRoot;
|
|
98
106
|
|
|
99
107
|
if (input.run_in_background) {
|
|
100
108
|
const child = spawnShell(shell, command, { cwd, env: childEnv(), stdin: stdinText });
|
|
101
109
|
const id = `bash_${++bgCounter}`;
|
|
102
|
-
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() };
|
|
103
111
|
background.set(id, bg);
|
|
104
112
|
// the shells that ended stay listed, with what was not read of their output: the oldest go past 50
|
|
105
|
-
const ended = [...background].filter(([, b]) => b.status !== 'running');
|
|
113
|
+
const ended = [...background].filter(([, b]) => b.status !== 'running' && b.owner === bg.owner);
|
|
106
114
|
for (const [old] of ended.slice(0, Math.max(0, ended.length - 50))) background.delete(old);
|
|
107
115
|
// Line by line, UTF-8 or the console code page (GBK here), never cutting a character (see OutputDecoder).
|
|
108
116
|
for (const stream of [child.stdout, child.stderr]) {
|
|
@@ -122,7 +130,7 @@ When you commit (the system prompt says when): run git status, git diff and git
|
|
|
122
130
|
let timedOut = false;
|
|
123
131
|
let child;
|
|
124
132
|
try {
|
|
125
|
-
child = spawnShell(shell, command, { cwd, env: childEnv(),
|
|
133
|
+
child = spawnShell(shell, command, { cwd, env: childEnv(), stdin: stdinText });
|
|
126
134
|
} catch (e) {
|
|
127
135
|
resolve({ isError: true, content: `Failed to start shell: ${e.message}` });
|
|
128
136
|
return;
|
|
@@ -133,11 +141,6 @@ When you commit (the system prompt says when): run git status, git diff and git
|
|
|
133
141
|
const finish = (code, err) => {
|
|
134
142
|
clearTimeout(timer);
|
|
135
143
|
ctx.signal?.removeEventListener('abort', onAbort);
|
|
136
|
-
try {
|
|
137
|
-
const newCwd = fs.readFileSync(cwdFile, 'utf8').trim();
|
|
138
|
-
if (newCwd && fs.existsSync(newCwd)) ctx.setCwd(path.resolve(newCwd));
|
|
139
|
-
} catch { /* command may have exited early */ }
|
|
140
|
-
fs.rm(cwdFile, { force: true }, () => {});
|
|
141
144
|
if (ctx.signal?.aborted) {
|
|
142
145
|
reject(Object.assign(new Error('aborted'), { name: 'AbortError', partialOutput: output }));
|
|
143
146
|
return;
|
|
@@ -195,8 +198,8 @@ export const BashOutputTool = {
|
|
|
195
198
|
},
|
|
196
199
|
summarize(input) { return input.bash_id; },
|
|
197
200
|
async call(input, ctx = {}) {
|
|
198
|
-
const bg =
|
|
199
|
-
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'}` };
|
|
200
203
|
let fresh = bg.output.slice(bg.readPos);
|
|
201
204
|
bg.output = ''; // what was read is not read again (up to 5 MB a shell, kept for good before)
|
|
202
205
|
bg.readPos = 0;
|
|
@@ -228,8 +231,8 @@ export const KillShellTool = {
|
|
|
228
231
|
required: ['shell_id'],
|
|
229
232
|
},
|
|
230
233
|
summarize(input) { return input.shell_id; },
|
|
231
|
-
async call(input) {
|
|
232
|
-
const bg =
|
|
234
|
+
async call(input, ctx = {}) {
|
|
235
|
+
const bg = shellOf(input.shell_id, ctx.config?.owner);
|
|
233
236
|
if (!bg) return { isError: true, content: `No background shell with id ${input.shell_id}` };
|
|
234
237
|
if (bg.status !== 'running') return { content: `Shell ${input.shell_id} is not running (status: ${bg.status})` };
|
|
235
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/peers.js
CHANGED
|
@@ -5,31 +5,32 @@ const unavailable = { isError: true, content: 'Talking to other sessions is only
|
|
|
5
5
|
|
|
6
6
|
export const ListPeersTool = {
|
|
7
7
|
name: 'ListPeers',
|
|
8
|
-
description: 'List the other claude-pro sessions (each is an agent with its own conversation, working in its own directory): those running on this machine,
|
|
8
|
+
description: 'List the other claude-pro sessions (each is an agent with its own conversation, working in its own directory): those running on this machine, those on the user\'s other computers that are online at the gateway, and those of the user\'s contacts (other people), with the name to send them a message with MessagePeer.',
|
|
9
9
|
input_schema: { type: 'object', properties: {} },
|
|
10
10
|
summarize() { return ''; },
|
|
11
11
|
async call(input, ctx) {
|
|
12
12
|
if (!ctx.io?.listAllPeers) return unavailable;
|
|
13
|
-
const { me, local, remote, online } = await ctx.io.listAllPeers();
|
|
13
|
+
const { me, local, remote, contacts = [], online } = await ctx.io.listAllPeers();
|
|
14
14
|
const head = `You are "${me.name}" (${me.cwd})${online ? `; sessions on other computers know you as "${me.label}"` : ''}.`;
|
|
15
|
-
const count = local.length + remote.length;
|
|
15
|
+
const count = local.length + remote.length + contacts.length;
|
|
16
16
|
if (!count) return { content: `${head}\nNo other session is running${online ? '' : ' on this machine (this session is not online at the gateway, so sessions on other computers are not listed)'}.`, display: { summary: 'No other session' } };
|
|
17
17
|
const lines = [head];
|
|
18
18
|
if (local.length) lines.push('On this machine:', ...local.map((p) => `- ${p.name}: working in ${p.cwd}`));
|
|
19
19
|
if (remote.length) lines.push('On the user\'s other computers (through the gateway):', ...remote.map((p) => `- ${p.label}: working in ${p.cwd} on the computer "${p.machine}"${p.busy ? ' (busy now)' : ''}`));
|
|
20
|
+
if (contacts.length) lines.push('Of the user\'s contacts, other people (message them only when the user asks you to):', ...contacts.map((p) => `- ${p.label}: a session of ${p.account}${p.busy ? ' (busy now)' : ''}`));
|
|
20
21
|
return { content: lines.join('\n'), display: { summary: `${count} other session${count === 1 ? '' : 's'}` } };
|
|
21
22
|
},
|
|
22
23
|
};
|
|
23
24
|
|
|
24
25
|
export const MessagePeerTool = {
|
|
25
26
|
name: 'MessagePeer',
|
|
26
|
-
description: `Send a task or a question to another claude-pro session, on this machine
|
|
27
|
+
description: `Send a task or a question to another claude-pro session, on this machine, on one of the user's other computers, or of one of the user's contacts (ListPeers lists them). A contact's session belongs to another person: message it only when the user asks you to, and send it nothing private. The other session's agent works on it in its own conversation and directory, and the final text of its answer comes back to you later as a <peer-message kind="reply"> message: you do not wait for it here. Use it to delegate work that belongs to another session's project or context, or to ask it something only it knows. Write the message so that it stands on its own: the other agent has not seen your conversation.
|
|
27
28
|
|
|
28
29
|
Send it once and wait for the answer: do not send reminders or "please report" follow-ups while the other session works. Messages that arrive while it is busy are handled together after what it is doing, so they only add to its work; the answer comes by itself when it is done.`,
|
|
29
30
|
input_schema: {
|
|
30
31
|
type: 'object',
|
|
31
32
|
properties: {
|
|
32
|
-
to: { type: 'string', description: 'The name of the session as ListPeers shows it (computer/name for one on another computer)' },
|
|
33
|
+
to: { type: 'string', description: 'The name of the session as ListPeers shows it (computer/name for one on another computer, contact:computer/name for a contact\'s)' },
|
|
33
34
|
message: { type: 'string', description: 'The task or question to send, written so it stands on its own' },
|
|
34
35
|
},
|
|
35
36
|
required: ['to', 'message'],
|
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
|
}
|