@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
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
// REPL: runs code in a Python or Node.js process that stays alive for the session, so that imports, variables and
|
|
2
|
+
// loaded data are there for the next call. The model loads a log or a JSON file once and asks it questions in small
|
|
3
|
+
// steps, and only what the code prints comes back: no quoting through Bash, no reloading for every question.
|
|
4
|
+
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import crypto from 'node:crypto';
|
|
9
|
+
import { spawn } from 'node:child_process';
|
|
10
|
+
import { killTree, killTreeSync } from '../utils/shell.js';
|
|
11
|
+
import { OutputDecoder } from '../utils/encoding.js';
|
|
12
|
+
import { stripAnsi } from '../ui/ansi.js';
|
|
13
|
+
import { childEnv, truncateOutput, saveFullOutput } from './bash.js';
|
|
14
|
+
|
|
15
|
+
export const replLimits = { defaultTimeoutMs: 120_000, maxTimeoutMs: 600_000, outputChars: 20_000 };
|
|
16
|
+
// A run's output kept in memory: past OUTPUT_MAX characters only the newest OUTPUT_KEEP stay, as in Bash.
|
|
17
|
+
const OUTPUT_MAX = 10_000_000;
|
|
18
|
+
const OUTPUT_KEEP = 5_000_000;
|
|
19
|
+
|
|
20
|
+
// The driver each interpreter runs: it reads one JSON request per line on stdin ({id, code, cwd}), runs the code in
|
|
21
|
+
// one namespace that lives as long as the process, and after what the code printed writes a line that starts with
|
|
22
|
+
// the process's random token and carries {id, error}. The value of a last expression is printed, as in a notebook.
|
|
23
|
+
const PYTHON_DRIVER = String.raw`import sys, os, json, ast, traceback, pprint
|
|
24
|
+
TOKEN = sys.argv[1]
|
|
25
|
+
_proto_in = sys.stdin
|
|
26
|
+
sys.stdin = open(os.devnull)
|
|
27
|
+
ns = {'__name__': '__main__', '__builtins__': __builtins__}
|
|
28
|
+
|
|
29
|
+
def run(code, cwd):
|
|
30
|
+
if cwd:
|
|
31
|
+
try:
|
|
32
|
+
os.chdir(cwd)
|
|
33
|
+
except OSError:
|
|
34
|
+
pass
|
|
35
|
+
try:
|
|
36
|
+
tree = ast.parse(code, '<cell>', 'exec')
|
|
37
|
+
last = None
|
|
38
|
+
if tree.body and isinstance(tree.body[-1], ast.Expr):
|
|
39
|
+
last = ast.Expression(tree.body.pop().value)
|
|
40
|
+
exec(compile(tree, '<cell>', 'exec'), ns)
|
|
41
|
+
if last is not None:
|
|
42
|
+
value = eval(compile(last, '<cell>', 'eval'), ns)
|
|
43
|
+
if value is not None:
|
|
44
|
+
print(pprint.pformat(value, width=120, compact=True, sort_dicts=False))
|
|
45
|
+
return None
|
|
46
|
+
except SyntaxError as e:
|
|
47
|
+
return ''.join(traceback.format_exception_only(type(e), e))
|
|
48
|
+
except BaseException as e:
|
|
49
|
+
return ''.join(traceback.format_exception(type(e), e, e.__traceback__.tb_next))
|
|
50
|
+
finally:
|
|
51
|
+
try:
|
|
52
|
+
sys.stdout.flush()
|
|
53
|
+
sys.stderr.flush()
|
|
54
|
+
except Exception:
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
while True:
|
|
58
|
+
line = _proto_in.readline()
|
|
59
|
+
if not line:
|
|
60
|
+
break
|
|
61
|
+
req = json.loads(line)
|
|
62
|
+
error = run(req['code'], req.get('cwd'))
|
|
63
|
+
sys.stdout.write('\n' + TOKEN + json.dumps({'id': req['id'], 'error': error}) + '\n')
|
|
64
|
+
sys.stdout.flush()
|
|
65
|
+
`;
|
|
66
|
+
|
|
67
|
+
// Node: the code is evaluated as the DevTools console does it, through the process's own inspector with replMode,
|
|
68
|
+
// which takes top-level await and lets let, const and class be declared again in a later call (node:repl's
|
|
69
|
+
// evaluator never calls back for that: "Identifier has already been declared" hung the call). require() resolves
|
|
70
|
+
// from the working directory. Code evaluated through the inspector has no dynamic import of its own ("A dynamic
|
|
71
|
+
// import callback was not specified", with any flag): its import(...) calls are rewritten (rewriteDynamicImports)
|
|
72
|
+
// to the driver's, which resolves from the working directory too.
|
|
73
|
+
const NODE_DRIVER = String.raw`const inspector = require('node:inspector');
|
|
74
|
+
const util = require('node:util');
|
|
75
|
+
const path = require('node:path');
|
|
76
|
+
const readline = require('node:readline');
|
|
77
|
+
const { pathToFileURL } = require('node:url');
|
|
78
|
+
const { createRequire, isBuiltin } = require('node:module');
|
|
79
|
+
const TOKEN = process.argv[2];
|
|
80
|
+
function importFrom(spec, options) {
|
|
81
|
+
let target = spec;
|
|
82
|
+
if (typeof spec === 'string') {
|
|
83
|
+
if (/^[a-zA-Z]:[\\/]/.test(spec) || /^[\\/]/.test(spec) || /^\.\.?([\\/]|$)/.test(spec)) {
|
|
84
|
+
target = pathToFileURL(path.resolve(process.cwd(), spec)).href;
|
|
85
|
+
} else if (!isBuiltin(spec) && !/^[a-z][a-z0-9+.-]*:/i.test(spec)) {
|
|
86
|
+
try {
|
|
87
|
+
const resolved = createRequire(path.join(process.cwd(), '[repl]')).resolve(spec);
|
|
88
|
+
if (path.isAbsolute(resolved)) target = pathToFileURL(resolved).href;
|
|
89
|
+
} catch {}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return options === undefined ? import(target) : import(target, options);
|
|
93
|
+
}
|
|
94
|
+
Object.defineProperty(globalThis, '__claudeProImport', { value: importFrom });
|
|
95
|
+
const session = new inspector.Session();
|
|
96
|
+
session.connect();
|
|
97
|
+
const post = (method, params) => new Promise((resolve, reject) => session.post(method, params, (e, r) => (e ? reject(e) : resolve(r))));
|
|
98
|
+
const show = (v) => util.inspect(v, { depth: 4, maxArrayLength: 100, maxStringLength: 10000, breakLength: 120 });
|
|
99
|
+
Object.defineProperty(globalThis, '__claudeProShow', { value: show });
|
|
100
|
+
process.on('uncaughtException', (e) => process.stderr.write('Uncaught ' + ((e && e.stack) || e) + '\n'));
|
|
101
|
+
process.on('unhandledRejection', (e) => process.stderr.write('Unhandled rejection ' + ((e && e.stack) || e) + '\n'));
|
|
102
|
+
async function evaluate(code) {
|
|
103
|
+
const r = await post('Runtime.evaluate', { expression: code, replMode: true, awaitPromise: true, objectGroup: 'cell' });
|
|
104
|
+
if (r.exceptionDetails) {
|
|
105
|
+
const ex = r.exceptionDetails.exception;
|
|
106
|
+
const text = (ex && (ex.description || String(ex.value))) || r.exceptionDetails.text || 'Error';
|
|
107
|
+
// the stack down to the code's own frames: the rest is this driver and the inspector
|
|
108
|
+
const lines = String(text).split('\n');
|
|
109
|
+
const cut = lines.findIndex((l, i) => i > 0 && /node:inspector|claude-pro-repl-node/.test(l));
|
|
110
|
+
return (cut > 0 ? lines.slice(0, cut) : lines).join('\n');
|
|
111
|
+
}
|
|
112
|
+
const v = r.result;
|
|
113
|
+
if (v.type === 'undefined') return null;
|
|
114
|
+
if (v.objectId) {
|
|
115
|
+
const s = await post('Runtime.callFunctionOn', { objectId: v.objectId, functionDeclaration: 'function() { return globalThis.__claudeProShow(this); }', returnByValue: true });
|
|
116
|
+
process.stdout.write(s.result.value + '\n');
|
|
117
|
+
} else {
|
|
118
|
+
process.stdout.write((v.unserializableValue !== undefined ? v.unserializableValue : show(v.value)) + '\n');
|
|
119
|
+
}
|
|
120
|
+
await post('Runtime.releaseObjectGroup', { objectGroup: 'cell' });
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
const queue = [];
|
|
124
|
+
let busy = false;
|
|
125
|
+
readline.createInterface({ input: process.stdin }).on('line', (line) => { queue.push(JSON.parse(line)); next(); });
|
|
126
|
+
async function next() {
|
|
127
|
+
if (busy || !queue.length) return;
|
|
128
|
+
busy = true;
|
|
129
|
+
const req = queue.shift();
|
|
130
|
+
if (req.cwd) { try { process.chdir(req.cwd); } catch {} }
|
|
131
|
+
globalThis.require = createRequire(path.join(process.cwd(), '[repl]'));
|
|
132
|
+
let error = null;
|
|
133
|
+
try { error = await evaluate(req.code); } catch (e) { error = String((e && e.stack) || e); }
|
|
134
|
+
process.stdout.write('\n' + TOKEN + JSON.stringify({ id: req.id, error }) + '\n', () => { busy = false; next(); });
|
|
135
|
+
}
|
|
136
|
+
`;
|
|
137
|
+
|
|
138
|
+
// The code's dynamic import(...) calls, made calls of the Node driver's importFrom. Strings, template literals and
|
|
139
|
+
// comments are left alone; import.meta and a method named import are not calls of import().
|
|
140
|
+
export function rewriteDynamicImports(code) {
|
|
141
|
+
let out = '';
|
|
142
|
+
let i = 0;
|
|
143
|
+
const n = code.length;
|
|
144
|
+
while (i < n) {
|
|
145
|
+
const ch = code[i];
|
|
146
|
+
let end = -1;
|
|
147
|
+
if (ch === '/' && code[i + 1] === '/') { end = code.indexOf('\n', i); if (end < 0) end = n; }
|
|
148
|
+
else if (ch === '/' && code[i + 1] === '*') { end = code.indexOf('*/', i + 2); end = end < 0 ? n : end + 2; }
|
|
149
|
+
else if (ch === '"' || ch === "'") {
|
|
150
|
+
end = i + 1;
|
|
151
|
+
while (end < n && code[end] !== ch && code[end] !== '\n') end += code[end] === '\\' ? 2 : 1;
|
|
152
|
+
end = Math.min(n, end + 1);
|
|
153
|
+
} else if (ch === '`') {
|
|
154
|
+
end = i + 1;
|
|
155
|
+
let depth = 0;
|
|
156
|
+
while (end < n && (depth > 0 || code[end] !== '`')) {
|
|
157
|
+
if (code[end] === '\\') { end += 2; continue; }
|
|
158
|
+
if (code[end] === '$' && code[end + 1] === '{') { depth++; end += 2; continue; }
|
|
159
|
+
if (depth > 0 && code[end] === '}') depth--;
|
|
160
|
+
end++;
|
|
161
|
+
}
|
|
162
|
+
end = Math.min(n, end + 1);
|
|
163
|
+
}
|
|
164
|
+
if (end > i) { out += code.slice(i, end); i = end; continue; }
|
|
165
|
+
if (ch === 'i' && code.startsWith('import', i) && !/[\w$.]/.test(code[i - 1] || '')) {
|
|
166
|
+
let j = i + 6;
|
|
167
|
+
while (j < n && /\s/.test(code[j])) j++;
|
|
168
|
+
if (code[j] === '(') { out += '__claudeProImport('; i = j + 1; continue; }
|
|
169
|
+
}
|
|
170
|
+
out += ch;
|
|
171
|
+
i++;
|
|
172
|
+
}
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const LANGUAGES = {
|
|
177
|
+
python: { label: 'Python', driver: PYTHON_DRIVER, ext: 'py' },
|
|
178
|
+
node: { label: 'Node.js', driver: NODE_DRIVER, ext: 'cjs' },
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
// The driver as a file (named by its content, so that two versions of claude-pro do not overwrite each other's).
|
|
182
|
+
function driverFile(lang) {
|
|
183
|
+
const { driver, ext } = LANGUAGES[lang];
|
|
184
|
+
const hash = crypto.createHash('sha256').update(driver).digest('hex').slice(0, 12);
|
|
185
|
+
const file = path.join(os.tmpdir(), `claude-pro-repl-${lang}-${hash}.${ext}`);
|
|
186
|
+
if (!fs.existsSync(file)) fs.writeFileSync(file, driver);
|
|
187
|
+
return file;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function pythonCommand(env) {
|
|
191
|
+
const configured = String(env?.CLAUDE_PRO_PYTHON ?? process.env.CLAUDE_PRO_PYTHON ?? '').trim();
|
|
192
|
+
if (configured) return configured;
|
|
193
|
+
return process.platform === 'win32' ? 'python' : 'python3';
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
class Interpreter {
|
|
197
|
+
constructor(lang, { cwd, env }) {
|
|
198
|
+
this.lang = lang;
|
|
199
|
+
this.token = `@@claude-pro-repl-${crypto.randomBytes(8).toString('hex')}@@`;
|
|
200
|
+
this.clearOutput();
|
|
201
|
+
this.waiting = null; // {resolve, id}
|
|
202
|
+
this.nextId = 1;
|
|
203
|
+
this.queue = Promise.resolve();
|
|
204
|
+
this.exited = null;
|
|
205
|
+
this.dead = false; // stopped by a timeout or an interrupt: never used again, whether or not it has exited yet
|
|
206
|
+
const file = driverFile(lang);
|
|
207
|
+
const cmd = lang === 'python' ? pythonCommand(env) : process.execPath;
|
|
208
|
+
const args = lang === 'python' ? ['-u', file, this.token] : [file, this.token];
|
|
209
|
+
const childEnvironment = { ...childEnv(), PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1', PYTHONUNBUFFERED: '1', PYTHONDONTWRITEBYTECODE: '1' };
|
|
210
|
+
this.child = spawn(cmd, args, { cwd, env: childEnvironment, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
|
|
211
|
+
this.started = new Promise((resolve) => {
|
|
212
|
+
this.child.once('spawn', () => resolve(null));
|
|
213
|
+
this.child.once('error', (e) => resolve(e));
|
|
214
|
+
});
|
|
215
|
+
const out = new OutputDecoder();
|
|
216
|
+
const err = new OutputDecoder();
|
|
217
|
+
this.child.stdout.on('data', (c) => this.onStdout(out.write(c)));
|
|
218
|
+
this.child.stderr.on('data', (c) => {
|
|
219
|
+
this.stderr += err.write(c);
|
|
220
|
+
if (this.stderr.length > OUTPUT_MAX) this.stderr = this.stderr.slice(-OUTPUT_KEEP);
|
|
221
|
+
});
|
|
222
|
+
this.child.on('close', (code, signal) => {
|
|
223
|
+
this.exited = { code, signal };
|
|
224
|
+
const w = this.waiting;
|
|
225
|
+
this.waiting = null;
|
|
226
|
+
w?.resolve({ died: true });
|
|
227
|
+
});
|
|
228
|
+
this.child.stdin.on('error', () => {}); // a dead interpreter: reported by 'close'
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
clearOutput() {
|
|
232
|
+
this.stdout = '';
|
|
233
|
+
this.stderr = '';
|
|
234
|
+
this.carry = ''; // the end of stdout so far, the token's length less one: a token split between two chunks
|
|
235
|
+
this.tokenAt = -1; // where the token is in stdout, once it came
|
|
236
|
+
this.endAt = -1; // where the line after it ends
|
|
237
|
+
this.droppedHead = false; // the start of the output was not kept (OUTPUT_MAX)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// What the code prints, then the end of the run: the token and a line of JSON. Each chunk is looked at once, with
|
|
241
|
+
// the end of the one before it, and stdout itself is not touched until the run is over: searching all of it again
|
|
242
|
+
// for every chunk was quadratic (160 MB of output took over a minute, with the program frozen).
|
|
243
|
+
onStdout(text) {
|
|
244
|
+
if (!text) return;
|
|
245
|
+
const start = this.stdout.length; // where `text` goes in stdout
|
|
246
|
+
this.stdout += text;
|
|
247
|
+
if (this.tokenAt < 0) {
|
|
248
|
+
const win = this.carry + text;
|
|
249
|
+
const at = win.indexOf(this.token);
|
|
250
|
+
if (at >= 0) this.tokenAt = start - this.carry.length + at;
|
|
251
|
+
else {
|
|
252
|
+
this.carry = win.slice(-(this.token.length - 1));
|
|
253
|
+
if (this.stdout.length > OUTPUT_MAX) { this.stdout = this.stdout.slice(-OUTPUT_KEEP); this.droppedHead = true; }
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (this.endAt < 0) { // the JSON line after the token has no newline of its own
|
|
258
|
+
const nl = text.indexOf('\n', Math.max(0, this.tokenAt + this.token.length - start));
|
|
259
|
+
if (nl >= 0) this.endAt = start + nl;
|
|
260
|
+
}
|
|
261
|
+
this.check();
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
check() {
|
|
265
|
+
const w = this.waiting;
|
|
266
|
+
if (!w || this.endAt < 0) return;
|
|
267
|
+
const all = this.stdout;
|
|
268
|
+
let meta = {};
|
|
269
|
+
try { meta = JSON.parse(all.slice(this.tokenAt + this.token.length, this.endAt)); } catch { /* reported as no error */ }
|
|
270
|
+
const output = all.slice(0, this.tokenAt).replace(/\n$/, '');
|
|
271
|
+
const droppedHead = this.droppedHead;
|
|
272
|
+
this.stdout = '';
|
|
273
|
+
this.carry = '';
|
|
274
|
+
this.tokenAt = -1;
|
|
275
|
+
this.endAt = -1;
|
|
276
|
+
this.waiting = null;
|
|
277
|
+
// stderr comes on its own pipe: what the code wrote there before it finished arrives a moment later at most
|
|
278
|
+
setTimeout(() => w.resolve({ output, error: meta.error || null, droppedHead }), 30);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
get alive() { return !this.dead && !this.exited && this.child.exitCode === null; }
|
|
282
|
+
|
|
283
|
+
// Stop the run in progress for good: the call returns now, and the process is killed behind it (with its
|
|
284
|
+
// children; plain TerminateProcess when that did not work).
|
|
285
|
+
stop() {
|
|
286
|
+
this.dead = true;
|
|
287
|
+
const w = this.waiting;
|
|
288
|
+
this.waiting = null;
|
|
289
|
+
w?.resolve({ died: true });
|
|
290
|
+
killTree(this.child).then(() => { if (this.child.exitCode === null) { try { this.child.kill('SIGKILL'); } catch { /* gone */ } } });
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// One run at a time (the main agent and sub-agents share an interpreter).
|
|
294
|
+
run(code, opts) {
|
|
295
|
+
const next = this.queue.then(() => this.runNow(code, opts));
|
|
296
|
+
this.queue = next.catch(() => {});
|
|
297
|
+
return next;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async runNow(code, { cwd, timeoutMs, signal }) {
|
|
301
|
+
const failed = await this.started;
|
|
302
|
+
if (failed) return { startError: failed };
|
|
303
|
+
if (!this.alive) return { died: true };
|
|
304
|
+
this.clearOutput();
|
|
305
|
+
const id = this.nextId++;
|
|
306
|
+
const done = new Promise((resolve) => { this.waiting = { resolve, id }; });
|
|
307
|
+
let timedOut = false;
|
|
308
|
+
let aborted = false;
|
|
309
|
+
const timer = setTimeout(() => { timedOut = true; this.stop(); }, timeoutMs);
|
|
310
|
+
const onAbort = () => { aborted = true; this.stop(); };
|
|
311
|
+
if (signal?.aborted) onAbort(); else signal?.addEventListener('abort', onAbort, { once: true });
|
|
312
|
+
try {
|
|
313
|
+
this.child.stdin.write(`${JSON.stringify({ id, code, cwd })}\n`);
|
|
314
|
+
const r = await done;
|
|
315
|
+
const stderr = this.stderr;
|
|
316
|
+
this.stderr = '';
|
|
317
|
+
if (r.died) return { died: true, timedOut, aborted, output: this.stdout, stderr, droppedHead: this.droppedHead };
|
|
318
|
+
return { ...r, stderr };
|
|
319
|
+
} finally {
|
|
320
|
+
clearTimeout(timer);
|
|
321
|
+
signal?.removeEventListener('abort', onAbort);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
kill(sync = false) {
|
|
326
|
+
this.dead = true;
|
|
327
|
+
if (this.exited || this.child.exitCode !== null) return;
|
|
328
|
+
if (sync) killTreeSync(this.child); else killTree(this.child);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const interpreters = new Map(); // language -> Interpreter
|
|
333
|
+
|
|
334
|
+
export function shutdownInterpreters() {
|
|
335
|
+
for (const i of interpreters.values()) i.kill(true); // the program is exiting
|
|
336
|
+
interpreters.clear();
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
|
|
340
|
+
|
|
341
|
+
export function makeReplTool(config) {
|
|
342
|
+
return {
|
|
343
|
+
name: 'REPL',
|
|
344
|
+
description: `Runs code in a persistent Python or Node.js process: imports, variables and loaded data stay between calls (one process per language, for the whole session; sub-agents share it). Only what the code prints comes back, and the value of a last expression, as in a notebook.
|
|
345
|
+
|
|
346
|
+
Use it to work with data: load a log, a JSON or CSV file, a database or an API response once, then ask it questions in small steps, printing only results (counts, a few matching records, a summary), instead of reading big files into the conversation or re-running a script through Bash for every question. Bash stays the tool for commands, builds and tests; Read for reading a file you need to see.
|
|
347
|
+
|
|
348
|
+
- It runs in the current working directory, with the user's own Python (CLAUDE_PRO_PYTHON picks another) or claude-pro's Node. Node takes top-level await and require(), and a later call may declare a let or const again.
|
|
349
|
+
- Print little: the output is cut at ${replLimits.outputChars} characters (the whole of it is saved to a file). Print with limits (df.head(), [:20], len()).
|
|
350
|
+
- A timeout (default ${replLimits.defaultTimeoutMs / 1000} s, timeout in ms up to ${replLimits.maxTimeoutMs / 1000} s) or an interrupt ends the process: its state is gone, and the next call starts a new one. reset: true does that on purpose.`,
|
|
351
|
+
input_schema: {
|
|
352
|
+
type: 'object',
|
|
353
|
+
properties: {
|
|
354
|
+
language: { type: 'string', enum: ['python', 'node'] },
|
|
355
|
+
code: { type: 'string', description: 'The code to run' },
|
|
356
|
+
timeout: { type: 'number', description: `Optional timeout in milliseconds (default ${replLimits.defaultTimeoutMs}, max ${replLimits.maxTimeoutMs})` },
|
|
357
|
+
reset: { type: 'boolean', description: 'Start a new process first (all variables are lost)' },
|
|
358
|
+
},
|
|
359
|
+
required: ['language'],
|
|
360
|
+
},
|
|
361
|
+
summarize(input) {
|
|
362
|
+
const first = String(input.code || '').split('\n').find((l) => l.trim()) || '';
|
|
363
|
+
return `${input.language === 'node' ? 'node' : 'python'}${input.reset ? ', reset' : ''}: ${first.trim().slice(0, 80)}`;
|
|
364
|
+
},
|
|
365
|
+
async call(input, ctx) {
|
|
366
|
+
const lang = input.language === 'node' ? 'node' : input.language === 'python' ? 'python' : null;
|
|
367
|
+
if (!lang) return { isError: true, content: 'language must be python or node' };
|
|
368
|
+
const { label } = LANGUAGES[lang];
|
|
369
|
+
const code = typeof input.code === 'string' ? input.code : '';
|
|
370
|
+
let interp = interpreters.get(lang);
|
|
371
|
+
const notes = [];
|
|
372
|
+
if (input.reset && interp) {
|
|
373
|
+
interp.kill();
|
|
374
|
+
interpreters.delete(lang);
|
|
375
|
+
interp = null;
|
|
376
|
+
notes.push(`(a new ${label} process: the old one's variables are gone)`);
|
|
377
|
+
} else if (interp && !interp.alive) {
|
|
378
|
+
interpreters.delete(lang);
|
|
379
|
+
interp = null;
|
|
380
|
+
notes.push(`(the ${label} process had ended, so this is a new one: earlier variables are gone)`);
|
|
381
|
+
}
|
|
382
|
+
if (!code.trim()) {
|
|
383
|
+
if (input.reset) return { content: notes.join('\n') || `Started a new ${label} process.` };
|
|
384
|
+
return { isError: true, content: 'code is empty' };
|
|
385
|
+
}
|
|
386
|
+
const cwd = fs.existsSync(ctx.cwd) ? ctx.cwd : ctx.projectRoot;
|
|
387
|
+
if (!interp) {
|
|
388
|
+
interp = new Interpreter(lang, { cwd, env: ctx.config?.env });
|
|
389
|
+
interpreters.set(lang, interp);
|
|
390
|
+
}
|
|
391
|
+
const timeoutMs = Math.min(Math.max(1000, Number(input.timeout) || replLimits.defaultTimeoutMs), replLimits.maxTimeoutMs);
|
|
392
|
+
const started = Date.now();
|
|
393
|
+
const r = await interp.run(lang === 'node' ? rewriteDynamicImports(code) : code, { cwd, timeoutMs, signal: ctx.signal });
|
|
394
|
+
if (r.startError) {
|
|
395
|
+
interpreters.delete(lang);
|
|
396
|
+
const hint = lang === 'python' ? ` Is Python installed and on PATH? CLAUDE_PRO_PYTHON can name the interpreter (now: ${pythonCommand(ctx.config?.env)}).` : '';
|
|
397
|
+
return { isError: true, content: `Cannot start ${label}: ${r.startError.message}.${hint}` };
|
|
398
|
+
}
|
|
399
|
+
if (r.aborted || ctx.signal?.aborted) {
|
|
400
|
+
interpreters.delete(lang);
|
|
401
|
+
throw Object.assign(new Error('aborted'), { name: 'AbortError', partialOutput: r.output });
|
|
402
|
+
}
|
|
403
|
+
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
|
+
let isError = false;
|
|
405
|
+
if (r.died) {
|
|
406
|
+
interpreters.delete(lang);
|
|
407
|
+
isError = true;
|
|
408
|
+
const why = r.timedOut ? `timed out after ${timeoutMs / 1000} s and was stopped` : `ended (exit code ${interp.exited?.code ?? '?'})`;
|
|
409
|
+
text += `${text ? '\n' : ''}The ${label} process ${why}: its variables are gone, and the next call starts a new one.`;
|
|
410
|
+
} else if (r.error) {
|
|
411
|
+
isError = true;
|
|
412
|
+
text += `${text ? '\n' : ''}${String(r.error).replace(/\s+$/, '')}`;
|
|
413
|
+
}
|
|
414
|
+
if (text.length > replLimits.outputChars) {
|
|
415
|
+
const saved = saveFullOutput(ctx.projectRoot, text);
|
|
416
|
+
const size = text.length;
|
|
417
|
+
text = truncateOutput(text, replLimits.outputChars);
|
|
418
|
+
const kept = r.droppedHead ? `over ${OUTPUT_MAX.toLocaleString('en-US')} characters and has been cut${saved ? `; the last ${size} are in ${saved}` : ''}` : `${size} characters and has been cut${saved ? `; all of it is in ${saved}` : ''}`;
|
|
419
|
+
text += `\n\n(The output was ${kept}. Print less: a count, the first rows, a summary.)`;
|
|
420
|
+
}
|
|
421
|
+
const lines = text ? text.split('\n').length : 0;
|
|
422
|
+
const secs = ((Date.now() - started) / 1000).toFixed(1);
|
|
423
|
+
return {
|
|
424
|
+
isError,
|
|
425
|
+
content: [...notes, text || '(no output)'].join('\n'),
|
|
426
|
+
display: { summary: `${isError ? 'Failed' : 'Ran'} in ${secs} s${lines ? `, ${plural(lines, 'line')} of output` : ', no output'}` },
|
|
427
|
+
};
|
|
428
|
+
},
|
|
429
|
+
};
|
|
430
|
+
}
|
package/src/tools/effort.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
// Effort: the model changes its own reasoning effort in the middle of a request, typically raising it for a hard
|
|
2
2
|
// problem. The change lasts until the user's next message, which goes back to the effort the user chose.
|
|
3
3
|
|
|
4
|
-
import { defaultEffort } from '../api.js';
|
|
4
|
+
import { defaultEffort, CLAUDE_EFFORTS } from '../api.js';
|
|
5
5
|
|
|
6
|
-
export const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
|
|
7
6
|
|
|
8
7
|
export function makeEffortTool(config) {
|
|
9
8
|
return {
|
|
@@ -16,7 +15,7 @@ Do not raise it for routine work, and do not switch back and forth: the prompt c
|
|
|
16
15
|
input_schema: {
|
|
17
16
|
type: 'object',
|
|
18
17
|
properties: {
|
|
19
|
-
level: { type: 'string', enum:
|
|
18
|
+
level: { type: 'string', enum: CLAUDE_EFFORTS, description: 'The new effort level' },
|
|
20
19
|
reason: { type: 'string', description: 'Why, in a few words. Shown to the user.' },
|
|
21
20
|
},
|
|
22
21
|
required: ['level', 'reason'],
|
|
@@ -24,7 +23,7 @@ Do not raise it for routine work, and do not switch back and forth: the prompt c
|
|
|
24
23
|
summarize(input) { return `${input.level}${input.reason ? `: ${input.reason}` : ''}`; },
|
|
25
24
|
async call(input) {
|
|
26
25
|
const level = String(input.level || '').trim().toLowerCase();
|
|
27
|
-
if (!
|
|
26
|
+
if (!CLAUDE_EFFORTS.includes(level)) return { isError: true, content: `Unknown effort "${input.level}". Use one of: ${CLAUDE_EFFORTS.join(', ')}.` };
|
|
28
27
|
const shown = () => config.effort || defaultEffort(config.model.id, config) || 'the model default';
|
|
29
28
|
const before = shown();
|
|
30
29
|
if (level === before) return { content: `The effort is already ${level}.` };
|
package/src/tools/files.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import crypto from 'node:crypto';
|
|
7
|
+
import { isUtf8 } from 'node:buffer';
|
|
7
8
|
import { resolvePath, displayPath } from '../utils/paths.js';
|
|
8
9
|
import { diffLines, makeHunks, countChanges, splitLines } from '../utils/diff.js';
|
|
9
10
|
import { fitImage } from '../utils/images.js';
|
|
@@ -155,7 +156,7 @@ Usage:
|
|
|
155
156
|
if (ext === '.ipynb') {
|
|
156
157
|
try {
|
|
157
158
|
const raw = fs.readFileSync(file);
|
|
158
|
-
const nb = JSON.parse(raw.toString('utf8'));
|
|
159
|
+
const nb = JSON.parse(raw.toString('utf8').replace(/^\uFEFF/, ''));
|
|
159
160
|
const rendered = renderNotebook(nb);
|
|
160
161
|
if (rendered.length > MAX_OUTPUT_CHARS || tooManyTokens(rendered)) {
|
|
161
162
|
return { isError: true, content: `Notebook content (${Math.round(rendered.length / 1024)}KB, about ${tokensOf(rendered).toLocaleString('en-US')} tokens) exceeds the maximum allowed size. Look at parts of it with the Bash tool (python or jq on its JSON), or use Grep to search it.` };
|
|
@@ -166,28 +167,40 @@ Usage:
|
|
|
166
167
|
return { isError: true, content: `Could not parse notebook: ${e.message}` };
|
|
167
168
|
}
|
|
168
169
|
}
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const
|
|
173
|
-
|
|
170
|
+
const start = Math.max(1, Math.floor(input.offset || 1));
|
|
171
|
+
// allow_large: no line, character or line length limit, only the room left in the context (see Agent.takeContext).
|
|
172
|
+
const large = input.allow_large === true;
|
|
173
|
+
const limit = Math.max(1, Math.floor(input.limit || (large ? Infinity : MAX_LINES)));
|
|
174
|
+
// `total`: the file's lines; `slice`: those asked for; `hash` of its bytes. A big UTF-8 file is read in chunks for
|
|
175
|
+
// the lines asked for (see readLineRange); the rest is read whole, decoded and split.
|
|
176
|
+
let total, slice, hash, note = '';
|
|
177
|
+
const streamed = stat.size > STREAM_READ_BYTES && Number.isFinite(limit) ? await readLineRange(file, start, limit) : null;
|
|
178
|
+
if (streamed?.binary) return { isError: true, content: `This appears to be a binary file (${stat.size} bytes) and cannot be displayed as text.` };
|
|
179
|
+
if (streamed) ({ total, slice, hash } = streamed);
|
|
180
|
+
else {
|
|
181
|
+
const buf = fs.readFileSync(file);
|
|
182
|
+
const decoded = readText(file, buf);
|
|
183
|
+
if (!decoded) return { isError: true, content: `This appears to be a binary file (${stat.size} bytes) and cannot be displayed as text.` };
|
|
184
|
+
note = encodingNote(decoded);
|
|
185
|
+
const lines = splitLines(decoded.text);
|
|
186
|
+
total = lines.length;
|
|
187
|
+
slice = lines.slice(start - 1, start - 1 + limit);
|
|
188
|
+
hash = hashOf(buf);
|
|
189
|
+
}
|
|
174
190
|
// `partial` records that part of the file was not shown, so Write can refuse to overwrite it; `hash` tells a
|
|
175
191
|
// later change of its time without a change of its bytes from a real one (see fileStanding).
|
|
176
|
-
const seen = (partial) => ctx.fileState.set(file, { mtimeMs: stat.mtimeMs, partial, hash
|
|
177
|
-
if (
|
|
192
|
+
const seen = (partial) => ctx.fileState.set(file, { mtimeMs: stat.mtimeMs, partial, hash });
|
|
193
|
+
if (total === 0) {
|
|
178
194
|
seen(false);
|
|
179
195
|
return { content: '<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>', display: { summary: 'Read 0 lines (empty file)' } };
|
|
180
196
|
}
|
|
181
|
-
|
|
182
|
-
if (start > lines.length) {
|
|
197
|
+
if (start > total) {
|
|
183
198
|
seen(true);
|
|
184
|
-
return { content: `<system-reminder>Warning: the file exists but is shorter than the provided offset (${start}). The file has ${
|
|
199
|
+
return { content: `<system-reminder>Warning: the file exists but is shorter than the provided offset (${start}). The file has ${total} lines.</system-reminder>`, display: { summary: 'Read 0 lines' } };
|
|
185
200
|
}
|
|
186
|
-
// allow_large: no line, character or line length limit, only the room left in the context (see Agent.takeContext).
|
|
187
|
-
const large = input.allow_large === true;
|
|
188
|
-
const limit = Math.max(1, Math.floor(input.limit || (large ? Infinity : MAX_LINES)));
|
|
189
|
-
const slice = lines.slice(start - 1, start - 1 + limit);
|
|
190
201
|
let content = numberLines(slice, start, large ? Infinity : MAX_LINE_CHARS);
|
|
202
|
+
// a line cut short is not seen whole either: a Write from what was shown would put "… [line truncated]" in the file
|
|
203
|
+
const longLines = !large && slice.some((l) => l.length > MAX_LINE_CHARS);
|
|
191
204
|
if (large) {
|
|
192
205
|
const fit = ctx.agent?.takeContext?.(content);
|
|
193
206
|
if (fit && !fit.ok) {
|
|
@@ -208,14 +221,74 @@ Usage:
|
|
|
208
221
|
content = `${kept}${whole ? '' : '\n'}… [output cut at ${why}: line ${end} is the last one shown${whole ? '' : ', and only in part'}; read on from there with offset/limit, or pass allow_large: true to read it all at once]`;
|
|
209
222
|
cut = true;
|
|
210
223
|
}
|
|
211
|
-
seen(cut || start > 1 || end <
|
|
212
|
-
if (end <
|
|
224
|
+
seen(cut || longLines || start > 1 || end < total);
|
|
225
|
+
if (end < total) content += `\n\n(File has ${total} lines total; showing lines ${start}-${end}. Use offset/limit to read more.)`;
|
|
213
226
|
content += note;
|
|
214
227
|
return { content, display: { summary: `Read ${slice.length} line${slice.length === 1 ? '' : 's'}` } };
|
|
215
228
|
},
|
|
216
229
|
};
|
|
217
230
|
|
|
218
|
-
const hashOf = (buf) => crypto.createHash('sha1').update(buf).digest('hex');
|
|
231
|
+
export const hashOf = (buf) => crypto.createHash('sha1').update(buf).digest('hex');
|
|
232
|
+
|
|
233
|
+
const STREAM_READ_BYTES = 8 * 1024 * 1024;
|
|
234
|
+
|
|
235
|
+
// Lines [start, start + limit) of a big file, read in chunks without blocking and without the whole file in memory
|
|
236
|
+
// (a Read of 20 lines of a 183 MB log took 0.7 s, blocked, and 768 MB): {total, slice, hash}, as the whole read
|
|
237
|
+
// gives them (splitLines: \r\n is a line end, no line after the last end; the BOM is not text). {binary: true} for
|
|
238
|
+
// a binary file; null when the file is not UTF-8 as a whole (UTF-16, GBK): it is read whole then.
|
|
239
|
+
async function readLineRange(file, start, limit) {
|
|
240
|
+
const hash = crypto.createHash('sha1');
|
|
241
|
+
const slice = [];
|
|
242
|
+
const end = start + limit;
|
|
243
|
+
let ended = 0; // the lines ended so far (by a \n)
|
|
244
|
+
let parts = null; // the bytes of the line going on, when it is one asked for
|
|
245
|
+
let carry = null; // a character the last chunk did not finish, checked with the next one
|
|
246
|
+
let first = true;
|
|
247
|
+
let last = -1; // the file's last byte
|
|
248
|
+
for await (let chunk of fs.createReadStream(file, { highWaterMark: 1 << 20 })) {
|
|
249
|
+
hash.update(chunk);
|
|
250
|
+
if (first) {
|
|
251
|
+
first = false;
|
|
252
|
+
if ((chunk[0] === 0xff && chunk[1] === 0xfe) || (chunk[0] === 0xfe && chunk[1] === 0xff)) return null;
|
|
253
|
+
if (chunk[0] === 0xef && chunk[1] === 0xbb && chunk[2] === 0xbf) chunk = chunk.subarray(3);
|
|
254
|
+
if (chunk.subarray(0, 8000).includes(0)) return { binary: true };
|
|
255
|
+
}
|
|
256
|
+
if (!chunk.length) continue;
|
|
257
|
+
const data = carry ? Buffer.concat([carry, chunk]) : chunk;
|
|
258
|
+
const keep = unfinishedTail(data);
|
|
259
|
+
if (!isUtf8(data.subarray(0, data.length - keep))) return null;
|
|
260
|
+
carry = keep ? Buffer.from(data.subarray(data.length - keep)) : null;
|
|
261
|
+
let from = 0;
|
|
262
|
+
for (let nl = chunk.indexOf(10); nl >= 0; nl = chunk.indexOf(10, from)) {
|
|
263
|
+
const n = ++ended;
|
|
264
|
+
if (n >= start && n < end) {
|
|
265
|
+
let line = parts ? Buffer.concat([...parts, chunk.subarray(from, nl)]) : chunk.subarray(from, nl);
|
|
266
|
+
if (line[line.length - 1] === 13) line = line.subarray(0, -1);
|
|
267
|
+
slice.push(line.toString('utf8'));
|
|
268
|
+
}
|
|
269
|
+
parts = null;
|
|
270
|
+
from = nl + 1;
|
|
271
|
+
}
|
|
272
|
+
if (from < chunk.length && ended + 1 >= start && ended + 1 < end) (parts ??= []).push(Buffer.from(chunk.subarray(from)));
|
|
273
|
+
last = chunk[chunk.length - 1];
|
|
274
|
+
}
|
|
275
|
+
if (carry) return null; // a character cut off at the end
|
|
276
|
+
const total = ended + (last !== -1 && last !== 10 ? 1 : 0);
|
|
277
|
+
if (parts && total >= start && total < end) slice.push(Buffer.concat(parts).toString('utf8'));
|
|
278
|
+
return { total, slice, hash: hash.digest('hex') };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// How many bytes at the end of `buf` start a UTF-8 character it does not finish (0 to 3).
|
|
282
|
+
function unfinishedTail(buf) {
|
|
283
|
+
const n = buf.length;
|
|
284
|
+
for (let k = 1; k <= Math.min(3, n); k++) {
|
|
285
|
+
const b = buf[n - k];
|
|
286
|
+
if ((b & 0xc0) === 0x80) continue; // a continuation byte: its lead is further back
|
|
287
|
+
const need = b >= 0xf0 ? 4 : b >= 0xe0 ? 3 : b >= 0xc0 ? 2 : 1;
|
|
288
|
+
return need > k ? k : 0;
|
|
289
|
+
}
|
|
290
|
+
return 0;
|
|
291
|
+
}
|
|
219
292
|
|
|
220
293
|
// How a file stands against what the model has seen of it: null (read or written by it, unchanged since),
|
|
221
294
|
// 'unread', or 'modified' (changed on disk since). A time that moved while the bytes stayed the same (git, a
|
|
@@ -240,7 +313,7 @@ export function checkFreshness(file, ctx, { full = false } = {}) {
|
|
|
240
313
|
const standing = fileStanding(file, ctx);
|
|
241
314
|
if (standing === 'unread') return 'File has not been read yet. Read it first before writing to it.';
|
|
242
315
|
if (full && ctx.fileState.get(file).partial) {
|
|
243
|
-
return 'Only part of this file has been seen (a Read with offset/limit, or edits without a whole Read), so Write would overwrite content you have not seen. Read the whole file first, or use Edit for targeted changes.';
|
|
316
|
+
return 'Only part of this file has been seen (a Read with offset/limit or one that cut long lines short, or edits without a whole Read), so Write would overwrite content you have not seen. Read the whole file first (allow_large: true shows long lines whole), or use Edit for targeted changes.';
|
|
244
317
|
}
|
|
245
318
|
if (standing === 'modified') {
|
|
246
319
|
return 'File has been modified since it was last read, either by the user or by a linter. Read it again before attempting to write it.';
|
package/src/tools/index.js
CHANGED
|
@@ -2,6 +2,9 @@ import { ReadTool, WriteTool, EditTool, MultiEditTool } from './files.js';
|
|
|
2
2
|
import { makeBashTool, BashOutputTool, KillShellTool } from './bash.js';
|
|
3
3
|
import { GlobTool, GrepTool } from './search.js';
|
|
4
4
|
import { makeWebFetchTool, WebSearchTool } from './web.js';
|
|
5
|
+
import { makeBrowserTool, browserToolEnabled } from './browser.js';
|
|
6
|
+
import { makeReplTool } from './code.js';
|
|
7
|
+
import { ProcessesTool } from './processes.js';
|
|
5
8
|
import { TodoWriteTool, AskUserQuestionTool } from './interaction.js';
|
|
6
9
|
import { makeTaskTool, TaskOutputTool, TaskStopTool } from './task.js';
|
|
7
10
|
import { NotebookEditTool } from './notebook.js';
|
|
@@ -20,6 +23,8 @@ export function buildTools(config, { agents, skills, mcpTools = [], restart = fa
|
|
|
20
23
|
TaskOutputTool,
|
|
21
24
|
TaskStopTool,
|
|
22
25
|
makeBashTool(config),
|
|
26
|
+
makeReplTool(config),
|
|
27
|
+
ProcessesTool,
|
|
23
28
|
GlobTool,
|
|
24
29
|
GrepTool,
|
|
25
30
|
ReadTool,
|
|
@@ -29,6 +34,7 @@ export function buildTools(config, { agents, skills, mcpTools = [], restart = fa
|
|
|
29
34
|
NotebookEditTool,
|
|
30
35
|
makeWebFetchTool(config),
|
|
31
36
|
WebSearchTool,
|
|
37
|
+
...(browserToolEnabled(config) ? [makeBrowserTool()] : []),
|
|
32
38
|
TodoWriteTool,
|
|
33
39
|
BashOutputTool,
|
|
34
40
|
KillShellTool,
|