@yanzc/claude-pro 0.8.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 -318
- package/package.json +1 -2
- package/src/agent.js +80 -14
- 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 +145 -144
- package/src/context.js +45 -18
- package/src/filestate.js +3 -2
- 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 +7 -63
- package/src/ratelimit.js +2 -4
- package/src/remote.js +76 -14
- 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 +368 -45
- package/src/tools/index.js +9 -1
- 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 +335 -101
- package/src/ui/screen.js +139 -31
- package/src/updater.js +135 -165
- package/src/utils/clipboard.js +5 -3
- package/src/utils/dirs.js +136 -0
- package/src/utils/encoding.js +23 -2
- 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}.` };
|