@yanzc/claude-pro 0.9.0 → 0.9.2
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 +240 -62
- package/src/agents.js +3 -2
- package/src/api.js +83 -41
- 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 +177 -71
- package/src/compaction.js +75 -0
- package/src/config.js +153 -153
- 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 +6 -62
- package/src/ratelimit.js +3 -5
- package/src/remote.js +26 -10
- package/src/restart.js +3 -0
- 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 +19 -18
- 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 +104 -21
- 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 +246 -119
- 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 +75 -21
- package/.env.example +0 -29
- package/src/verify.js +0 -57
package/src/tools/notebook.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import { resolvePath, displayPath } from '../utils/paths.js';
|
|
6
|
-
import { checkFreshness, mtime } from './files.js';
|
|
6
|
+
import { checkFreshness, mtime, hashOf } from './files.js';
|
|
7
7
|
|
|
8
8
|
// Jupyter stores cell source as an array of lines, each keeping its trailing newline.
|
|
9
9
|
function toSource(text) {
|
|
@@ -52,7 +52,12 @@ export const NotebookEditTool = {
|
|
|
52
52
|
if (err) return { isError: true, content: err };
|
|
53
53
|
const file = resolvePath(input.notebook_path, ctx.cwd);
|
|
54
54
|
let nb;
|
|
55
|
-
|
|
55
|
+
let bom = false; // a BOM in front made the notebook unreadable here; it is kept when the notebook is written
|
|
56
|
+
try {
|
|
57
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
58
|
+
bom = text.startsWith('\uFEFF');
|
|
59
|
+
nb = JSON.parse(bom ? text.slice(1) : text);
|
|
60
|
+
} catch (e) { return { isError: true, content: `Could not parse notebook: ${e.message}` }; }
|
|
56
61
|
nb.cells ||= [];
|
|
57
62
|
const mode = input.edit_mode || 'replace';
|
|
58
63
|
let summary;
|
|
@@ -84,8 +89,10 @@ export const NotebookEditTool = {
|
|
|
84
89
|
summary = `Updated cell ${input.cell_id}`;
|
|
85
90
|
}
|
|
86
91
|
}
|
|
87
|
-
|
|
88
|
-
|
|
92
|
+
const out = Buffer.from(`${bom ? '\uFEFF' : ''}${JSON.stringify(nb, null, 1)}\n`, 'utf8');
|
|
93
|
+
fs.writeFileSync(file, out);
|
|
94
|
+
// with its hash, as after a Read: a later change of its time alone (a sync, a scan) is not taken for an edit
|
|
95
|
+
ctx.fileState.set(file, { mtimeMs: mtime(file), hash: hashOf(out) });
|
|
89
96
|
return { content: summary, display: { summary } };
|
|
90
97
|
},
|
|
91
98
|
};
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
// Processes: the processes on this machine (pid, parent, start time, memory, the ports they use, command line),
|
|
2
|
+
// found by name, command line, pid, tree or port, and killed by pid with their children. On Windows it is one
|
|
3
|
+
// PowerShell query (CIM, for the command lines) and netstat; the model did the same through Bash about a thousand
|
|
4
|
+
// times in two weeks, where PowerShell's $_ inside bash quoting made one call in ten fail.
|
|
5
|
+
|
|
6
|
+
import { spawn } from 'node:child_process';
|
|
7
|
+
import { OutputDecoder } from '../utils/encoding.js';
|
|
8
|
+
|
|
9
|
+
const isWin = process.platform === 'win32';
|
|
10
|
+
export const processLimits = { rows: 40, maxRows: 200, commandChars: 220, queryMs: 30_000 };
|
|
11
|
+
|
|
12
|
+
function capture(cmd, args, { timeoutMs = processLimits.queryMs, signal } = {}) {
|
|
13
|
+
return new Promise((resolve) => {
|
|
14
|
+
let child;
|
|
15
|
+
try {
|
|
16
|
+
child = spawn(cmd, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
17
|
+
} catch (e) {
|
|
18
|
+
resolve({ code: null, out: '', err: e.message });
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const outDec = new OutputDecoder();
|
|
22
|
+
const errDec = new OutputDecoder();
|
|
23
|
+
let out = '';
|
|
24
|
+
let err = '';
|
|
25
|
+
const timer = setTimeout(() => { try { child.kill(); } catch { /* gone */ } }, timeoutMs);
|
|
26
|
+
const onAbort = () => { try { child.kill(); } catch { /* gone */ } };
|
|
27
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
28
|
+
child.stdout.on('data', (c) => { out += outDec.write(c); });
|
|
29
|
+
child.stderr.on('data', (c) => { err += errDec.write(c); });
|
|
30
|
+
const done = (code, e) => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); resolve({ code, out: out + outDec.end(), err: err + errDec.end() + (e ? e.message : '') }); };
|
|
31
|
+
child.on('error', (e) => done(null, e));
|
|
32
|
+
child.on('close', (code) => done(code));
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ---- Reading the process table
|
|
37
|
+
|
|
38
|
+
// Select-Object, not a ForEach-Object that builds objects: half a second faster on 650 processes (PowerShell's own
|
|
39
|
+
// start takes 1.3 s of the 2.7). The dates come as "/Date(ms)/".
|
|
40
|
+
const PS_SCRIPT = '[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine,CreationDate,WorkingSetSize | ConvertTo-Json -Compress';
|
|
41
|
+
|
|
42
|
+
async function windowsProcesses(signal) {
|
|
43
|
+
const r = await capture('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', PS_SCRIPT], { signal });
|
|
44
|
+
if (r.code !== 0) throw new Error(`PowerShell could not list the processes: ${(r.err || r.out).trim().slice(0, 300)}`);
|
|
45
|
+
let rows;
|
|
46
|
+
try { rows = JSON.parse(r.out.replace(/^\uFEFF/, '').trim()); } catch { throw new Error(`PowerShell gave no process list: ${r.out.slice(0, 200)}`); }
|
|
47
|
+
const date = (d) => Number(/\/Date\((-?\d+)/.exec(String(d ?? ''))?.[1]) || (d ? Date.parse(d) || null : null);
|
|
48
|
+
return (Array.isArray(rows) ? rows : [rows]).map((x) => ({ pid: x.ProcessId, ppid: x.ParentProcessId, name: x.Name || '', command: x.CommandLine || '', started: date(x.CreationDate), memory: x.WorkingSetSize || 0 }));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// ps on Linux and macOS: pid ppid rss lstart (five words) args. (Not run on this project's own machine, which has
|
|
52
|
+
// no POSIX system to try it on.)
|
|
53
|
+
async function posixProcesses(signal) {
|
|
54
|
+
const r = await capture('ps', ['-axo', 'pid=,ppid=,rss=,lstart=,args='], { signal });
|
|
55
|
+
if (r.code !== 0) throw new Error(`ps failed: ${r.err.trim().slice(0, 300)}`);
|
|
56
|
+
const out = [];
|
|
57
|
+
for (const line of r.out.split('\n')) {
|
|
58
|
+
const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w+\s+\w+\s+\d+\s+[\d:]+\s+\d+)\s+(.*)$/.exec(line);
|
|
59
|
+
if (!m) continue;
|
|
60
|
+
const command = m[5].trim();
|
|
61
|
+
const exe = command.split(/\s+/)[0] || '';
|
|
62
|
+
out.push({ pid: Number(m[1]), ppid: Number(m[2]), name: exe.split('/').pop(), command, started: Date.parse(m[4]) || null, memory: Number(m[3]) * 1024 });
|
|
63
|
+
}
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Sockets: [{proto, local, remote, state, pid}] from netstat -ano (Windows) or lsof (elsewhere).
|
|
68
|
+
async function sockets(signal) {
|
|
69
|
+
if (isWin) {
|
|
70
|
+
const r = await capture('netstat', ['-ano'], { signal });
|
|
71
|
+
const out = [];
|
|
72
|
+
for (const line of r.out.split('\n')) {
|
|
73
|
+
const t = line.trim().split(/\s+/);
|
|
74
|
+
if (t[0] === 'TCP' && t.length >= 5) out.push({ proto: 'TCP', local: t[1], remote: t[2], state: t[3], pid: Number(t[4]) });
|
|
75
|
+
else if (t[0] === 'UDP' && t.length >= 4) out.push({ proto: 'UDP', local: t[1], remote: t[2], state: '', pid: Number(t[3]) });
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
const r = await capture('lsof', ['-nP', '-i', '-FpPnT'], { signal });
|
|
80
|
+
const out = [];
|
|
81
|
+
let pid = 0;
|
|
82
|
+
let proto = '';
|
|
83
|
+
for (const line of r.out.split('\n')) {
|
|
84
|
+
const k = line[0];
|
|
85
|
+
const v = line.slice(1);
|
|
86
|
+
if (k === 'p') pid = Number(v);
|
|
87
|
+
else if (k === 'P') proto = v;
|
|
88
|
+
else if (k === 'n') {
|
|
89
|
+
const [local, remote = ''] = v.split('->');
|
|
90
|
+
out.push({ proto, local, remote, state: '', pid });
|
|
91
|
+
} else if (k === 'T' && v.startsWith('ST=') && out.length) out[out.length - 1].state = v.slice(3);
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const portOf = (address) => Number(/:(\d+)$/.exec(address || '')?.[1] || NaN);
|
|
97
|
+
|
|
98
|
+
// ---- What may not be killed
|
|
99
|
+
|
|
100
|
+
const CRITICAL = new Set(['system', 'system idle process', 'registry', 'memory compression', 'secure system', 'smss.exe', 'csrss.exe', 'wininit.exe', 'winlogon.exe', 'services.exe', 'lsass.exe', 'lsaiso.exe', 'svchost.exe', 'dwm.exe', 'fontdrvhost.exe', 'init', 'systemd', 'launchd', 'kernel_task', 'loginwindow', 'windowserver']);
|
|
101
|
+
const NEEDS_FORCE = new Set(['explorer.exe', 'finder']);
|
|
102
|
+
|
|
103
|
+
// claude-pro and everything it runs under (its supervisor, the shell, the terminal): never killed from here.
|
|
104
|
+
function ownLine(byPid) {
|
|
105
|
+
const out = new Set();
|
|
106
|
+
for (let pid = process.pid, guard = 0; pid && byPid.has(pid) && guard < 64; pid = byPid.get(pid).ppid, guard++) out.add(pid);
|
|
107
|
+
out.add(process.pid);
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function descendants(list, root) {
|
|
112
|
+
const children = new Map();
|
|
113
|
+
for (const p of list) {
|
|
114
|
+
if (p.pid === p.ppid) continue;
|
|
115
|
+
if (!children.has(p.ppid)) children.set(p.ppid, []);
|
|
116
|
+
children.get(p.ppid).push(p);
|
|
117
|
+
}
|
|
118
|
+
const out = [];
|
|
119
|
+
// A process that started before the one its parent id names is not its child: Windows gives no new parent to an
|
|
120
|
+
// orphan, and its parent's id may be another process's by now (a tree listed or killed unrelated processes).
|
|
121
|
+
const walk = (pid, depth, started) => {
|
|
122
|
+
for (const c of children.get(pid) || []) {
|
|
123
|
+
if (out.length > 2000) return;
|
|
124
|
+
if (started && c.started && c.started < started) continue;
|
|
125
|
+
out.push({ ...c, depth });
|
|
126
|
+
walk(c.pid, depth + 1, c.started);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
walk(root, 1, list.find((p) => p.pid === root)?.started);
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ---- Showing them
|
|
134
|
+
|
|
135
|
+
const pad = (s, n) => (String(s).length >= n ? String(s) : String(s) + ' '.repeat(n - String(s).length));
|
|
136
|
+
const cut = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
|
|
137
|
+
const mb = (bytes) => (bytes >= 1024 ** 3 ? `${(bytes / 1024 ** 3).toFixed(1)}G` : `${Math.round(bytes / 1024 ** 2)}M`);
|
|
138
|
+
function when(ms) {
|
|
139
|
+
if (!ms) return '?';
|
|
140
|
+
const d = new Date(ms);
|
|
141
|
+
const two = (n) => String(n).padStart(2, '0');
|
|
142
|
+
return `${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}:${two(d.getSeconds())}`;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function table(rows, socketsByPid, { mine, portFilter } = {}) {
|
|
146
|
+
const lines = [`${pad('PID', 7)} ${pad('PPID', 7)} ${pad('started', 14)} ${pad('mem', 6)} name — ports — command line`];
|
|
147
|
+
for (const p of rows) {
|
|
148
|
+
const socks = socketsByPid.get(p.pid) || [];
|
|
149
|
+
const shown = (portFilter ? socks.filter((s) => portOf(s.local) === portFilter || portOf(s.remote) === portFilter) : socks.filter((s) => s.state === 'LISTENING' || s.state === 'LISTEN' || s.proto === 'UDP'))
|
|
150
|
+
.slice(0, 6).map((s) => portFilter ? `${s.proto} ${s.local}${s.remote && !/^(\*:\*|0\.0\.0\.0:0|\[::\]:0)$/.test(s.remote) ? ` → ${s.remote}` : ''}${s.state ? ` ${s.state}` : ''}` : `${s.proto === 'UDP' ? 'udp ' : ''}${s.local}`);
|
|
151
|
+
const extra = socks.length > 6 && !portFilter ? ' …' : '';
|
|
152
|
+
const indent = p.depth ? `${' '.repeat(p.depth)}└ ` : '';
|
|
153
|
+
const tag = mine?.has(p.pid) ? ' [claude-pro]' : '';
|
|
154
|
+
lines.push(`${pad(p.pid, 7)} ${pad(p.ppid, 7)} ${pad(when(p.started), 14)} ${pad(mb(p.memory), 6)} ${indent}${p.name}${tag}${shown.length ? ` — ${shown.join(', ')}${extra}` : ''}${p.command ? ` — ${cut(p.command.replace(/\s+/g, ' '), processLimits.commandChars)}` : ''}`);
|
|
155
|
+
}
|
|
156
|
+
return lines.join('\n');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function killPid(pid, tree) {
|
|
160
|
+
if (isWin) {
|
|
161
|
+
const r = await capture('taskkill', ['/F', ...(tree ? ['/T'] : []), '/PID', String(pid)], { timeoutMs: 15_000 });
|
|
162
|
+
return r.code === 0 ? null : (r.err || r.out).trim().split('\n').pop();
|
|
163
|
+
}
|
|
164
|
+
try { process.kill(pid, 'SIGTERM'); } catch (e) { return e.code === 'ESRCH' ? 'no such process' : e.message; }
|
|
165
|
+
for (let i = 0; i < 20; i++) {
|
|
166
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
167
|
+
try { process.kill(pid, 0); } catch { return null; }
|
|
168
|
+
}
|
|
169
|
+
try { process.kill(pid, 'SIGKILL'); } catch { /* gone */ }
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const exists = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
|
|
174
|
+
|
|
175
|
+
export const ProcessesTool = {
|
|
176
|
+
name: 'Processes',
|
|
177
|
+
description: `Lists the processes on this machine, or kills some. Each row: PID, parent PID, start time, memory, name, the ports it listens on, command line.
|
|
178
|
+
|
|
179
|
+
- action "list" (default), filtered by name (part of the program name), command (part of the command line), pid, port (what listens on or is connected to that port, with the connections), and tree: true with pid for the process and all its descendants. Filters combine. Without one, the most recently started processes. limit: rows (default ${processLimits.rows}).
|
|
180
|
+
- action "kill": pids, with their child processes (tree: false for only the process itself). claude-pro and what it runs under (its terminal, shell, supervisor) and system-critical processes are refused; explorer.exe needs force: true.
|
|
181
|
+
- Use it instead of ps, tasklist, netstat, taskkill or PowerShell through Bash. Before killing what the user did not start for this task, check what it is.`,
|
|
182
|
+
input_schema: {
|
|
183
|
+
type: 'object',
|
|
184
|
+
properties: {
|
|
185
|
+
action: { type: 'string', enum: ['list', 'kill'] },
|
|
186
|
+
name: { type: 'string', description: 'Part of the program name (case-insensitive)' },
|
|
187
|
+
command: { type: 'string', description: 'Part of the command line (case-insensitive)' },
|
|
188
|
+
pid: { type: 'number' },
|
|
189
|
+
port: { type: 'number', description: 'A local or remote port' },
|
|
190
|
+
tree: { type: 'boolean', description: 'list: the pid and all its descendants; kill: with child processes (default true)' },
|
|
191
|
+
pids: { type: 'array', items: { type: 'number' }, description: 'For kill' },
|
|
192
|
+
force: { type: 'boolean' },
|
|
193
|
+
limit: { type: 'number' },
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
readOnly: false,
|
|
197
|
+
summarize(input) {
|
|
198
|
+
if (input.action === 'kill') return `kill ${(input.pids || [input.pid]).filter(Boolean).join(', ')}${input.tree === false ? ' (not its children)' : ''}`;
|
|
199
|
+
return ['name', 'command', 'pid', 'port'].filter((k) => input[k] !== undefined && input[k] !== '').map((k) => `${k} ${input[k]}`).join(', ') + (input.tree ? ' tree' : '') || 'recent';
|
|
200
|
+
},
|
|
201
|
+
async call(input, ctx) {
|
|
202
|
+
const signal = ctx?.signal;
|
|
203
|
+
const action = input.action || 'list';
|
|
204
|
+
let list;
|
|
205
|
+
let socks;
|
|
206
|
+
try {
|
|
207
|
+
[list, socks] = await Promise.all([isWin ? windowsProcesses(signal) : posixProcesses(signal), sockets(signal).catch(() => [])]);
|
|
208
|
+
} catch (e) {
|
|
209
|
+
if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError' });
|
|
210
|
+
return { isError: true, content: e.message };
|
|
211
|
+
}
|
|
212
|
+
const byPid = new Map(list.map((p) => [p.pid, p]));
|
|
213
|
+
const mine = ownLine(byPid);
|
|
214
|
+
const socketsByPid = new Map();
|
|
215
|
+
for (const s of socks) {
|
|
216
|
+
if (!socketsByPid.has(s.pid)) socketsByPid.set(s.pid, []);
|
|
217
|
+
socketsByPid.get(s.pid).push(s);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (action === 'kill') {
|
|
221
|
+
const pids = [...new Set((Array.isArray(input.pids) && input.pids.length ? input.pids : [input.pid]).map(Number).filter((n) => Number.isInteger(n) && n > 0))];
|
|
222
|
+
if (!pids.length) return { isError: true, content: 'kill needs pids (the process ids, from a list)' };
|
|
223
|
+
const tree = input.tree !== false;
|
|
224
|
+
const lines = [];
|
|
225
|
+
let failed = false;
|
|
226
|
+
for (const pid of pids) {
|
|
227
|
+
const p = byPid.get(pid);
|
|
228
|
+
if (!p) { lines.push(`${pid}: no such process`); failed = true; continue; }
|
|
229
|
+
const victims = [p, ...(tree ? descendants(list, pid) : [])];
|
|
230
|
+
const label = `${pid} ${p.name}`;
|
|
231
|
+
const own = victims.find((v) => mine.has(v.pid));
|
|
232
|
+
const critical = victims.find((v) => CRITICAL.has(v.name.toLowerCase()) || v.pid <= 4);
|
|
233
|
+
const guarded = victims.find((v) => NEEDS_FORCE.has(v.name.toLowerCase()));
|
|
234
|
+
if (own) { lines.push(`${label}: refused, ${own.pid === pid ? 'it is' : `its tree holds ${own.pid} ${own.name}, which is`} claude-pro or what it runs under`); failed = true; continue; }
|
|
235
|
+
if (critical) { lines.push(`${label}: refused, ${critical.pid === pid ? 'it is' : `its tree holds ${critical.pid} ${critical.name},`} a system process`); failed = true; continue; }
|
|
236
|
+
if (guarded && !input.force) { lines.push(`${label}: refused without force: true (${guarded.name} is the desktop shell)`); failed = true; continue; }
|
|
237
|
+
const err = await killPid(pid, tree);
|
|
238
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
239
|
+
const left = victims.filter((v) => exists(v.pid));
|
|
240
|
+
if (!left.length) lines.push(`${label}: killed${victims.length > 1 ? ` with ${victims.length - 1} child process${victims.length === 2 ? '' : 'es'}` : ''}`);
|
|
241
|
+
else { failed = true; lines.push(`${label}: ${left.length} of ${victims.length} still running (${left.slice(0, 5).map((v) => `${v.pid} ${v.name}`).join(', ')})${err ? `: ${err}` : ''}`); }
|
|
242
|
+
}
|
|
243
|
+
return { isError: failed, content: lines.join('\n'), display: { summary: lines.length === 1 ? lines[0] : `${lines.filter((l) => /killed/.test(l)).length} of ${lines.length} killed` } };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (action !== 'list') return { isError: true, content: `unknown action "${action}": use list or kill` };
|
|
247
|
+
const limit = Math.min(Math.max(1, Number(input.limit) || processLimits.rows), processLimits.maxRows);
|
|
248
|
+
let rows = list;
|
|
249
|
+
const filters = [];
|
|
250
|
+
if (input.pid !== undefined) {
|
|
251
|
+
const root = byPid.get(Number(input.pid));
|
|
252
|
+
if (!root) return { isError: true, content: `no process ${input.pid}` };
|
|
253
|
+
rows = input.tree ? [root, ...descendants(list, root.pid)] : [root];
|
|
254
|
+
filters.push(`pid ${input.pid}${input.tree ? ' and its descendants' : ''}`);
|
|
255
|
+
}
|
|
256
|
+
if (input.name) { const q = String(input.name).toLowerCase(); rows = rows.filter((p) => p.name.toLowerCase().includes(q)); filters.push(`name ~ ${input.name}`); }
|
|
257
|
+
if (input.command) { const q = String(input.command).toLowerCase(); rows = rows.filter((p) => p.command.toLowerCase().includes(q)); filters.push(`command ~ ${input.command}`); }
|
|
258
|
+
const portFilter = input.port !== undefined ? Number(input.port) : null;
|
|
259
|
+
if (portFilter !== null) {
|
|
260
|
+
const using = new Set(socks.filter((s) => portOf(s.local) === portFilter || portOf(s.remote) === portFilter).map((s) => s.pid));
|
|
261
|
+
rows = rows.filter((p) => using.has(p.pid));
|
|
262
|
+
filters.push(`port ${portFilter}`);
|
|
263
|
+
}
|
|
264
|
+
const total = rows.length;
|
|
265
|
+
if (!filters.length) rows = [...rows].sort((a, b) => (b.started || 0) - (a.started || 0));
|
|
266
|
+
else if (!input.tree) rows = [...rows].sort((a, b) => (a.started || 0) - (b.started || 0));
|
|
267
|
+
const shown = rows.slice(0, limit);
|
|
268
|
+
const head = filters.length
|
|
269
|
+
? `${total} process${total === 1 ? '' : 'es'} with ${filters.join(', ')}${total > shown.length ? ` (first ${shown.length}; limit shows more)` : ''}:`
|
|
270
|
+
: `${list.length} processes; the ${shown.length} started last (filter by name, command, pid or port):`;
|
|
271
|
+
if (!total) return { content: `No process with ${filters.join(', ')}.`, display: { summary: 'None found' } };
|
|
272
|
+
return { content: `${head}\n${table(shown, socketsByPid, { mine, portFilter })}`, display: { summary: `${total} process${total === 1 ? '' : 'es'}` } };
|
|
273
|
+
},
|
|
274
|
+
};
|
package/src/tools/search.js
CHANGED
|
@@ -11,6 +11,28 @@ import { decodeText as decodeFile } from '../utils/encoding.js';
|
|
|
11
11
|
|
|
12
12
|
const IGNORED_DIRS = new Set(['node_modules', '.git', '.svn', '.hg', '__pycache__', '.venv', 'dist-newstyle']);
|
|
13
13
|
|
|
14
|
+
// How long a search may take. A search of a home directory or a drive (a million files and more) does not end in
|
|
15
|
+
// any useful time: in a month of traces 31 calls took 50 minutes together, a Grep up to 14 minutes, with the turn
|
|
16
|
+
// waiting. Past the limit the search stops and gives what it found, saying that it is not all (Claude Code stops
|
|
17
|
+
// ripgrep after 20 seconds).
|
|
18
|
+
export const searchLimits = { ms: 30_000 };
|
|
19
|
+
const stoppedNote = (what) => `(The search was stopped after ${Math.round(searchLimits.ms / 1000)} s without finishing, so ${what} Search a narrower path${what.includes('match') ? ', or add a glob or type' : ' or use a more specific pattern'}.)`;
|
|
20
|
+
|
|
21
|
+
// When each file was last changed (ms; null: it cannot be read), without blocking: statSync for 20,000 files held
|
|
22
|
+
// the program for a second.
|
|
23
|
+
async function mtimes(files) {
|
|
24
|
+
const out = new Array(files.length).fill(null);
|
|
25
|
+
let next = 0;
|
|
26
|
+
const worker = async () => {
|
|
27
|
+
while (next < files.length) {
|
|
28
|
+
const i = next++;
|
|
29
|
+
try { out[i] = (await fs.promises.stat(files[i])).mtimeMs; } catch { /* vanished */ }
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
await Promise.all(Array.from({ length: Math.min(32, files.length) }, worker));
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
|
|
14
36
|
export const GlobTool = {
|
|
15
37
|
name: 'Glob',
|
|
16
38
|
readOnly: true,
|
|
@@ -43,30 +65,77 @@ export const GlobTool = {
|
|
|
43
65
|
const name = path.basename(p);
|
|
44
66
|
return IGNORED_DIRS.has(name) && !explicit.includes(name);
|
|
45
67
|
};
|
|
46
|
-
|
|
68
|
+
let files = [];
|
|
69
|
+
let stopped = false;
|
|
47
70
|
const start = Date.now();
|
|
48
71
|
try {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const st = fs.statSync(abs);
|
|
54
|
-
if (st.isFile()) files.push({ abs, mtime: st.mtimeMs });
|
|
55
|
-
} catch { /* vanished */ }
|
|
56
|
-
if (files.length >= 20_000) break;
|
|
57
|
-
}
|
|
72
|
+
const walked = await globFiles(base, pattern, { skip: exclude, signal: ctx.signal, max: 20_000, deadline: start + searchLimits.ms });
|
|
73
|
+
stopped = walked.stopped;
|
|
74
|
+
const times = await mtimes(walked.files);
|
|
75
|
+
files = walked.files.map((abs, i) => ({ abs, mtime: times[i] })).filter((f) => f.mtime !== null);
|
|
58
76
|
} catch (e) {
|
|
59
77
|
return { isError: true, content: `Glob failed: ${e.message}` };
|
|
60
78
|
}
|
|
61
79
|
files.sort((a, b) => b.mtime - a.mtime);
|
|
62
80
|
const limit = 1000;
|
|
63
81
|
const shown = files.slice(0, limit).map((f) => f.abs);
|
|
64
|
-
let content = shown.length ? shown.join('\n') : 'No files found';
|
|
82
|
+
let content = shown.length ? shown.join('\n') : stopped ? 'No files found so far' : 'No files found';
|
|
65
83
|
if (files.length > limit) content += `\n(Results are truncated: showing ${limit} of ${files.length}. Consider using a more specific path or pattern.)`;
|
|
66
|
-
|
|
84
|
+
if (stopped) content += `\n${stoppedNote('there may be more files than these.')}`;
|
|
85
|
+
return { content, display: { summary: `Found ${files.length} file${files.length === 1 ? '' : 's'} in ${Date.now() - start}ms${stopped ? ' (stopped: not finished)' : ''}` } };
|
|
67
86
|
},
|
|
68
87
|
};
|
|
69
88
|
|
|
89
|
+
// The files under `base` that `pattern` matches, as fs.glob finds them (in any case on Windows) but with dotfiles and
|
|
90
|
+
// dot directories too: fs.glob leaves those out of * and ** and has no option for them, so "**/*.yml" missed
|
|
91
|
+
// .github/workflows/ci.yml, which Grep (searching hidden files) found. `skip(name)`: a directory not to go into. The
|
|
92
|
+
// walk starts at the pattern's fixed leading directories, and goes no deeper than its segments without a "**". A
|
|
93
|
+
// linked directory is not entered (it can make a loop). Directories are read several at a time; past `deadline`
|
|
94
|
+
// (ms since epoch) the walk ends with what it has. Returns {files, stopped: it ended at the deadline}.
|
|
95
|
+
async function globFiles(base, pattern, { skip, signal, max, deadline = Infinity }) {
|
|
96
|
+
const parts = pattern.replace(/^(?:\.\/)+/, '').split('/');
|
|
97
|
+
const fixed = [];
|
|
98
|
+
while (parts.length > 1 && !/[*?[\]{}]/.test(parts[0])) fixed.push(parts.shift());
|
|
99
|
+
const rest = parts.join('/');
|
|
100
|
+
const re = globToRegExp(rest, process.platform === 'win32');
|
|
101
|
+
const maxDepth = /\*\*|[{}]/.test(rest) ? Infinity : parts.length;
|
|
102
|
+
const found = [];
|
|
103
|
+
let stopped = false;
|
|
104
|
+
const done = () => signal?.aborted || found.length >= max || (stopped ||= Date.now() > deadline);
|
|
105
|
+
// at most this many directories are being read at once
|
|
106
|
+
let reading = 0;
|
|
107
|
+
const waiting = []; // a stack: the deepest directories first, which keeps it short in a wide tree
|
|
108
|
+
const readDir = async (dir) => {
|
|
109
|
+
if (reading >= 16) await new Promise((go) => waiting.push(go));
|
|
110
|
+
reading++;
|
|
111
|
+
try {
|
|
112
|
+
return done() ? null : await fs.promises.readdir(dir, { withFileTypes: true });
|
|
113
|
+
} catch {
|
|
114
|
+
return null;
|
|
115
|
+
} finally {
|
|
116
|
+
reading--;
|
|
117
|
+
waiting.pop()?.();
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
const walk = async (dir, rel, depth) => {
|
|
121
|
+
const entries = await readDir(dir);
|
|
122
|
+
if (!entries) return;
|
|
123
|
+
const below = [];
|
|
124
|
+
for (const e of entries) {
|
|
125
|
+
if (done()) break;
|
|
126
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
127
|
+
const abs = path.join(dir, e.name);
|
|
128
|
+
let isFile = e.isFile();
|
|
129
|
+
if (e.isSymbolicLink()) { try { isFile = (await fs.promises.stat(abs)).isFile(); } catch { /* a broken link */ } }
|
|
130
|
+
if (isFile) { if (re.test(r) && found.length < max) found.push(abs); }
|
|
131
|
+
else if (e.isDirectory() && depth < maxDepth && !skip(e.name)) below.push(walk(abs, r, depth + 1));
|
|
132
|
+
}
|
|
133
|
+
await Promise.all(below);
|
|
134
|
+
};
|
|
135
|
+
await walk(path.join(base, ...fixed), '', 1);
|
|
136
|
+
return { files: found, stopped: stopped && !signal?.aborted };
|
|
137
|
+
}
|
|
138
|
+
|
|
70
139
|
// rg --type names (plus a few aliases) → file extensions, for the JS scanner.
|
|
71
140
|
const TYPE_EXT = {
|
|
72
141
|
js: ['js', 'jsx', 'mjs', 'cjs'], ts: ['ts', 'tsx', 'mts', 'cts'], py: ['py', 'pyi'], rust: ['rs'], go: ['go'],
|
|
@@ -247,10 +316,13 @@ const decodeText = (buf) => decodeFile(buf, { writable: false })?.text ?? null;
|
|
|
247
316
|
|
|
248
317
|
const clip = (line) => (line.length > MAX_COLUMNS ? `${line.slice(0, MAX_COLUMNS)} [... omitted end of long line]` : line);
|
|
249
318
|
|
|
250
|
-
|
|
319
|
+
// `timeoutMs`: rg is stopped then, and what it had found by then is given, with `timedOut`.
|
|
320
|
+
function runRg(bin, args, cwd, signal, timeoutMs = searchLimits.ms) {
|
|
251
321
|
return new Promise((resolve) => {
|
|
252
322
|
const child = spawn(bin, args, { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
253
323
|
let out = '', err = '';
|
|
324
|
+
let timedOut = false;
|
|
325
|
+
const timer = setTimeout(() => { timedOut = true; child.kill(); }, timeoutMs);
|
|
254
326
|
// Decoded as a stream (a Chinese path or line can be split between two chunks), and rg is stopped once
|
|
255
327
|
// there is more than will ever be shown instead of scanning on.
|
|
256
328
|
child.stdout.setEncoding('utf8');
|
|
@@ -263,8 +335,13 @@ function runRg(bin, args, cwd, signal) {
|
|
|
263
335
|
child.stderr.on('data', (d) => { if (err.length < 100_000) err += d; });
|
|
264
336
|
const onAbort = () => child.kill();
|
|
265
337
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
266
|
-
child.on('close', (code) => {
|
|
267
|
-
|
|
338
|
+
child.on('close', (code) => {
|
|
339
|
+
clearTimeout(timer);
|
|
340
|
+
signal?.removeEventListener('abort', onAbort);
|
|
341
|
+
// the last line may have been cut where rg was stopped
|
|
342
|
+
resolve(timedOut ? { code: 0, out: out.slice(0, out.lastIndexOf('\n') + 1), err, timedOut } : { code, out, err });
|
|
343
|
+
});
|
|
344
|
+
child.on('error', (e) => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); resolve({ code: 2, out: '', err: e.message, spawnError: true }); });
|
|
268
345
|
});
|
|
269
346
|
}
|
|
270
347
|
|
|
@@ -416,6 +493,7 @@ Usage:
|
|
|
416
493
|
const mode = input.output_mode || 'files_with_matches';
|
|
417
494
|
let lines = null;
|
|
418
495
|
let note = '';
|
|
496
|
+
let stopped = false;
|
|
419
497
|
const rg = ripgrepPath(ctx.config);
|
|
420
498
|
if (rg) {
|
|
421
499
|
// --crlf lets `$` match before \r\n, so line-end anchors also work in Windows (CRLF) files.
|
|
@@ -437,11 +515,14 @@ Usage:
|
|
|
437
515
|
if (!r.spawnError) {
|
|
438
516
|
if (r.code === 2 && !r.out) return { isError: true, content: `ripgrep error: ${r.err.trim()}` };
|
|
439
517
|
lines = r.out.split(/\r?\n/).filter(Boolean);
|
|
518
|
+
stopped = Boolean(r.timedOut);
|
|
440
519
|
}
|
|
441
520
|
}
|
|
442
521
|
if (!lines) {
|
|
443
522
|
try {
|
|
444
|
-
const
|
|
523
|
+
const limit = AbortSignal.timeout(searchLimits.ms);
|
|
524
|
+
const found = await jsGrep(input, base, mode, ctx.signal ? AbortSignal.any([ctx.signal, limit]) : limit);
|
|
525
|
+
stopped = limit.aborted && !ctx.signal?.aborted;
|
|
445
526
|
lines = found.lines;
|
|
446
527
|
if (found.skipped) note = `\n\n(${found.skipped} file${found.skipped === 1 ? '' : 's'} larger than ${MAX_FILE_BYTES / 1024 / 1024}MB not searched; install ripgrep to search them)`;
|
|
447
528
|
} catch (e) {
|
|
@@ -449,9 +530,10 @@ Usage:
|
|
|
449
530
|
}
|
|
450
531
|
}
|
|
451
532
|
if (mode === 'files_with_matches') {
|
|
452
|
-
|
|
453
|
-
|
|
533
|
+
const times = await mtimes(lines);
|
|
534
|
+
lines = lines.map((f, i) => ({ f, t: times[i] ?? 0 })).sort((a, b) => b.t - a.t).map((x) => x.f);
|
|
454
535
|
}
|
|
536
|
+
if (stopped) note += `\n\n${stoppedNote('there may be more matches than these.')}`;
|
|
455
537
|
const total = lines.length;
|
|
456
538
|
const offset = Math.max(0, input.offset || 0);
|
|
457
539
|
const limit = input.head_limit === 0 ? Infinity : (input.head_limit || 1000);
|
|
@@ -459,16 +541,17 @@ Usage:
|
|
|
459
541
|
let content;
|
|
460
542
|
let summary;
|
|
461
543
|
if (mode === 'files_with_matches') {
|
|
462
|
-
content = total ? `Found ${total} file${total === 1 ? '' : 's'}\n${page.join('\n')}` : 'No files found';
|
|
544
|
+
content = total ? `Found ${total} file${total === 1 ? '' : 's'}\n${page.join('\n')}` : stopped ? 'No files found so far' : 'No files found';
|
|
463
545
|
summary = `Found ${total} file${total === 1 ? '' : 's'}`;
|
|
464
546
|
} else if (mode === 'count') {
|
|
465
547
|
const sum = lines.reduce((n, l) => n + (parseInt(l.split(':').pop(), 10) || 0), 0);
|
|
466
|
-
content = total ? page.join('\n') + `\n\nFound ${sum} total occurrences across ${total} files.` : 'No matches found';
|
|
548
|
+
content = total ? page.join('\n') + `\n\nFound ${sum} total occurrences across ${total} files.` : stopped ? 'No matches found so far' : 'No matches found';
|
|
467
549
|
summary = `Found ${sum} match${sum === 1 ? '' : 'es'} in ${total} file${total === 1 ? '' : 's'}`;
|
|
468
550
|
} else {
|
|
469
|
-
content = total ? page.join('\n') : 'No matches found';
|
|
551
|
+
content = total ? page.join('\n') : stopped ? 'No matches found so far' : 'No matches found';
|
|
470
552
|
summary = `Found ${total} line${total === 1 ? '' : 's'}`;
|
|
471
553
|
}
|
|
554
|
+
if (stopped) summary += ' (stopped: not finished)';
|
|
472
555
|
if (total > offset + page.length) content += `\n\n(Showing ${page.length} of ${total} results. Use offset/head_limit to page, or narrow the search.)`;
|
|
473
556
|
return { content: content + note, display: { summary } };
|
|
474
557
|
},
|