@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,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
|
@@ -46,14 +46,8 @@ export const GlobTool = {
|
|
|
46
46
|
const files = [];
|
|
47
47
|
const start = Date.now();
|
|
48
48
|
try {
|
|
49
|
-
for
|
|
50
|
-
|
|
51
|
-
const abs = path.resolve(base, f);
|
|
52
|
-
try {
|
|
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;
|
|
49
|
+
for (const abs of await globFiles(base, pattern, { skip: exclude, signal: ctx.signal, max: 20_000 })) {
|
|
50
|
+
try { files.push({ abs, mtime: fs.statSync(abs).mtimeMs }); } catch { /* vanished */ }
|
|
57
51
|
}
|
|
58
52
|
} catch (e) {
|
|
59
53
|
return { isError: true, content: `Glob failed: ${e.message}` };
|
|
@@ -67,6 +61,37 @@ export const GlobTool = {
|
|
|
67
61
|
},
|
|
68
62
|
};
|
|
69
63
|
|
|
64
|
+
// The files under `base` that `pattern` matches, as fs.glob finds them (in any case on Windows) but with dotfiles and
|
|
65
|
+
// dot directories too: fs.glob leaves those out of * and ** and has no option for them, so "**/*.yml" missed
|
|
66
|
+
// .github/workflows/ci.yml, which Grep (searching hidden files) found. `skip(name)`: a directory not to go into. The
|
|
67
|
+
// walk starts at the pattern's fixed leading directories, and goes no deeper than its segments without a "**". A
|
|
68
|
+
// linked directory is not entered (it can make a loop).
|
|
69
|
+
async function globFiles(base, pattern, { skip, signal, max }) {
|
|
70
|
+
const parts = pattern.replace(/^(?:\.\/)+/, '').split('/');
|
|
71
|
+
const fixed = [];
|
|
72
|
+
while (parts.length > 1 && !/[*?[\]{}]/.test(parts[0])) fixed.push(parts.shift());
|
|
73
|
+
const rest = parts.join('/');
|
|
74
|
+
const re = globToRegExp(rest, process.platform === 'win32');
|
|
75
|
+
const maxDepth = /\*\*|[{}]/.test(rest) ? Infinity : parts.length;
|
|
76
|
+
const found = [];
|
|
77
|
+
const walk = async (dir, rel, depth) => {
|
|
78
|
+
if (signal?.aborted || found.length >= max) return;
|
|
79
|
+
let entries;
|
|
80
|
+
try { entries = await fs.promises.readdir(dir, { withFileTypes: true }); } catch { return; }
|
|
81
|
+
for (const e of entries) {
|
|
82
|
+
if (found.length >= max) return;
|
|
83
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
84
|
+
const abs = path.join(dir, e.name);
|
|
85
|
+
let isFile = e.isFile();
|
|
86
|
+
if (e.isSymbolicLink()) { try { isFile = (await fs.promises.stat(abs)).isFile(); } catch { /* a broken link */ } }
|
|
87
|
+
if (isFile) { if (re.test(r)) found.push(abs); }
|
|
88
|
+
else if (e.isDirectory() && depth < maxDepth && !skip(e.name)) await walk(abs, r, depth + 1);
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
await walk(path.join(base, ...fixed), '', 1);
|
|
92
|
+
return found;
|
|
93
|
+
}
|
|
94
|
+
|
|
70
95
|
// rg --type names (plus a few aliases) → file extensions, for the JS scanner.
|
|
71
96
|
const TYPE_EXT = {
|
|
72
97
|
js: ['js', 'jsx', 'mjs', 'cjs'], ts: ['ts', 'tsx', 'mts', 'cts'], py: ['py', 'pyi'], rust: ['rs'], go: ['go'],
|