@babylonjs-toolkit/agent 1.1.44 → 1.1.48
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 +46 -1
- package/bin/bt-agent.js +19 -0
- package/lib/diskinfo/cli.js +104 -0
- package/lib/diskinfo/locations.js +213 -0
- package/lib/diskinfo/report.js +271 -0
- package/lib/diskinfo/scan.js +193 -0
- package/lib/kill/cli.js +227 -0
- package/lib/kill/ports.js +254 -0
- package/package.json +1 -1
- package/skills/bt-convert/SKILL.md +7 -3
- package/skills/bt-design/SKILL.md +2 -0
- package/skills/bt-execute/SKILL.md +3 -3
- package/skills/bt-gauntlet/SKILL.md +2 -1
- package/skills/bt-gauntlet/references/critic-rubrics.md +1 -0
- package/skills/bt-plan/SKILL.md +6 -5
- package/skills/bt-prototype/SKILL.md +2 -1
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { spawnSync } = require('child_process');
|
|
7
|
+
|
|
8
|
+
const { Scanner, keyOf } = require('./scan');
|
|
9
|
+
const { systemRoots, breakdowns, hogs, suggestions, glob } = require('./locations');
|
|
10
|
+
const { prettyPath } = require('../paths');
|
|
11
|
+
|
|
12
|
+
const MB = 1024 ** 2;
|
|
13
|
+
const HOG_MIN = 50 * MB;
|
|
14
|
+
|
|
15
|
+
/** 1536 -> "1.5 KB", using 1024 steps like Finder's "About This Mac" used to. */
|
|
16
|
+
function human(bytes) {
|
|
17
|
+
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
|
18
|
+
let n = Number(bytes) || 0;
|
|
19
|
+
let i = 0;
|
|
20
|
+
while (n >= 1024 && i < units.length - 1) {
|
|
21
|
+
n /= 1024;
|
|
22
|
+
i += 1;
|
|
23
|
+
}
|
|
24
|
+
return i === 0 ? `${n} B` : `${n.toFixed(1)} ${units[i]}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function localStamp(d) {
|
|
28
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
29
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function run(cmd, args) {
|
|
33
|
+
const r = spawnSync(cmd, args, { encoding: 'utf8', timeout: 20000, windowsHide: true });
|
|
34
|
+
return r.status === 0 ? r.stdout : '';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function statVolume(mount) {
|
|
38
|
+
if (typeof fs.statfsSync !== 'function') return null; // Node < 18.15
|
|
39
|
+
try {
|
|
40
|
+
const s = fs.statfsSync(mount);
|
|
41
|
+
const total = s.blocks * s.bsize;
|
|
42
|
+
return { mount, total, used: total - s.bfree * s.bsize, free: s.bavail * s.bsize };
|
|
43
|
+
} catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The volume holding the user's data, plus every other fixed drive on Windows. */
|
|
49
|
+
function volumes(ctx) {
|
|
50
|
+
if (ctx.platform === 'win32') {
|
|
51
|
+
const out = [];
|
|
52
|
+
for (let c = 67; c <= 90; c += 1) {
|
|
53
|
+
const root = `${String.fromCharCode(c)}:\\`;
|
|
54
|
+
const v = fs.existsSync(root) ? statVolume(root) : null;
|
|
55
|
+
if (v && v.total > 0) out.push(v);
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
const data = ctx.platform === 'darwin' && fs.existsSync('/System/Volumes/Data') ? '/System/Volumes/Data' : '/';
|
|
60
|
+
const v = statVolume(data);
|
|
61
|
+
return v ? [v] : [];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** macOS only: space consumed by each APFS volume (simulator runtimes show up here). */
|
|
65
|
+
function apfsVolumes() {
|
|
66
|
+
const out = [];
|
|
67
|
+
let name = null;
|
|
68
|
+
for (const line of run('diskutil', ['apfs', 'list']).split('\n')) {
|
|
69
|
+
const n = /Name:\s+(.+?)(\s+\(Case-.*\))?\s*$/.exec(line);
|
|
70
|
+
if (n) name = n[1];
|
|
71
|
+
const c = /Capacity Consumed:\s+(\d+) B/.exec(line);
|
|
72
|
+
if (c && name) out.push({ name, bytes: Number(c[1]) });
|
|
73
|
+
}
|
|
74
|
+
return out.sort((a, b) => b.bytes - a.bytes);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function snapshotCount() {
|
|
78
|
+
return run('tmutil', ['listlocalsnapshots', '/']).split('\n').filter((l) => l.includes('com.apple')).length;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const top = (list, n) => [...list].sort((a, b) => b.bytes - a.bytes).slice(0, n);
|
|
82
|
+
const sum = (list) => list.reduce((n, x) => n + x.bytes, 0);
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Scan the disk and return the report data. Read-only: nothing is moved or deleted.
|
|
86
|
+
* The walk itself is synchronous (see Scanner); this stays async for callers' convenience.
|
|
87
|
+
* @param {object} [opts]
|
|
88
|
+
* @param {(msg: string) => void} [opts.onStage] A new phase started.
|
|
89
|
+
* @param {(p: {files:number, bytes:number, dir:string}) => void} [opts.onProgress]
|
|
90
|
+
* @param {object} [opts.ctx] { platform, home, env } — injectable for tests.
|
|
91
|
+
* @param {string[]} [opts.roots] Override the system folders to walk (tests).
|
|
92
|
+
*/
|
|
93
|
+
async function buildReport(opts = {}) {
|
|
94
|
+
const started = Date.now();
|
|
95
|
+
const ctx = opts.ctx || { platform: process.platform, home: os.homedir(), env: process.env };
|
|
96
|
+
const stage = opts.onStage || (() => {});
|
|
97
|
+
const scanner = new Scanner({ onProgress: opts.onProgress });
|
|
98
|
+
|
|
99
|
+
stage('volume overview');
|
|
100
|
+
const vols = volumes(ctx);
|
|
101
|
+
const mac = ctx.platform === 'darwin' && !opts.ctx;
|
|
102
|
+
const apfs = mac ? apfsVolumes() : [];
|
|
103
|
+
const snapshots = mac ? snapshotCount() : 0;
|
|
104
|
+
|
|
105
|
+
stage(`home folder ${prettyPath(ctx.home)}`);
|
|
106
|
+
const homeBytes = scanner.measure(ctx.home) || 0;
|
|
107
|
+
|
|
108
|
+
const roots = [{ path: ctx.home, bytes: homeBytes, home: true }];
|
|
109
|
+
const homeKey = keyOf(ctx.home);
|
|
110
|
+
for (const root of opts.roots || systemRoots(ctx)) {
|
|
111
|
+
const k = keyOf(root);
|
|
112
|
+
if (k === homeKey || k.startsWith(homeKey + path.sep) || homeKey.startsWith(k + path.sep)) continue;
|
|
113
|
+
if (!fs.existsSync(root)) continue;
|
|
114
|
+
stage(prettyPath(root));
|
|
115
|
+
const bytes = scanner.measure(root);
|
|
116
|
+
if (bytes !== null) roots.push({ path: root, bytes });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
stage('known space hogs');
|
|
120
|
+
const hogRows = [];
|
|
121
|
+
const hogTotals = {};
|
|
122
|
+
for (const hog of hogs(ctx)) {
|
|
123
|
+
const found = hog.paths.flatMap(glob).filter((p) => fs.existsSync(p));
|
|
124
|
+
const rows = hog.each ? found.map((p) => ({ paths: [p], label: `${hog.label} ${path.basename(p)}` })) : [{ paths: found, label: hog.label }];
|
|
125
|
+
for (const row of rows) {
|
|
126
|
+
let bytes = 0;
|
|
127
|
+
for (const p of row.paths) bytes += scanner.sizeOf(p) || 0;
|
|
128
|
+
hogTotals[hog.id] = (hogTotals[hog.id] || 0) + bytes;
|
|
129
|
+
if (bytes >= HOG_MIN) hogRows.push({ id: hog.id, group: hog.group, label: row.label, bytes, paths: row.paths });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const worthListing = (p) => p.bytes >= HOG_MIN;
|
|
134
|
+
const unity = top(scanner.unityProjects.filter(worthListing), 50);
|
|
135
|
+
const unreal = top(scanner.unrealProjects.filter(worthListing), 50);
|
|
136
|
+
hogTotals['node-modules'] = sum(scanner.nodeModules);
|
|
137
|
+
hogTotals['unity-projects'] = unity.reduce((n, p) => n + p.regenerable, 0);
|
|
138
|
+
hogTotals['unreal-projects'] = unreal.reduce((n, p) => n + p.regenerable, 0);
|
|
139
|
+
hogTotals.snapshots = snapshots;
|
|
140
|
+
hogTotals.always = 0;
|
|
141
|
+
|
|
142
|
+
const vol = vols.find((v) => keyOf(ctx.home).startsWith(keyOf(v.mount))) || vols[0] || null;
|
|
143
|
+
const measured = sum(roots);
|
|
144
|
+
const other = vol ? Math.max(0, vol.used - measured) : null;
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
generatedAt: new Date().toISOString(),
|
|
148
|
+
localTime: localStamp(new Date()),
|
|
149
|
+
computer: os.hostname(),
|
|
150
|
+
platform: ctx.platform,
|
|
151
|
+
elapsedMs: Date.now() - started,
|
|
152
|
+
volumes: vols,
|
|
153
|
+
apfs,
|
|
154
|
+
snapshots,
|
|
155
|
+
roots: top(roots, roots.length),
|
|
156
|
+
other,
|
|
157
|
+
home: { path: ctx.home, children: top(scanner.children(ctx.home), 25) },
|
|
158
|
+
breakdowns: breakdowns(ctx)
|
|
159
|
+
.filter((d) => scanner.lookup(d) !== null)
|
|
160
|
+
.map((d) => ({ path: d, bytes: scanner.lookup(d), children: top(scanner.children(d), d === breakdowns(ctx)[0] ? 15 : 10) })),
|
|
161
|
+
hogs: hogRows,
|
|
162
|
+
nodeModules: { count: scanner.nodeModules.length, bytes: hogTotals['node-modules'], top: top(scanner.nodeModules, 15) },
|
|
163
|
+
unityProjects: unity,
|
|
164
|
+
unrealProjects: unreal,
|
|
165
|
+
bigFiles: top(scanner.bigFiles, 30),
|
|
166
|
+
suggestions: suggestions(ctx).filter((s) => (hogTotals[s.id] ?? -1) >= s.min).map((s) => s.text),
|
|
167
|
+
unreadable: scanner.unreadable,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Plain-text rendering of buildReport()'s result. */
|
|
172
|
+
function formatReport(r) {
|
|
173
|
+
const out = [];
|
|
174
|
+
const line = (s = '') => out.push(s);
|
|
175
|
+
const row = (bytes, label) => line(` ${human(bytes).padStart(10)} ${label}`);
|
|
176
|
+
const header = (title) => {
|
|
177
|
+
line();
|
|
178
|
+
line('='.repeat(70));
|
|
179
|
+
line(` ${title}`);
|
|
180
|
+
line('='.repeat(70));
|
|
181
|
+
};
|
|
182
|
+
const win = r.platform === 'win32';
|
|
183
|
+
|
|
184
|
+
line(`Disk space report — ${r.localTime} — ${r.computer}`);
|
|
185
|
+
line('(read-only scan; nothing was deleted)');
|
|
186
|
+
|
|
187
|
+
header('1. VOLUMES');
|
|
188
|
+
for (const v of r.volumes) {
|
|
189
|
+
const pct = v.total ? Math.round((v.used / v.total) * 100) : 0;
|
|
190
|
+
line(` ${v.mount.padEnd(24)} ${human(v.used)} used of ${human(v.total)} (${pct}%) — ${human(v.free)} free`);
|
|
191
|
+
}
|
|
192
|
+
if (r.apfs.length) {
|
|
193
|
+
line();
|
|
194
|
+
line(' APFS volumes on this Mac (space consumed):');
|
|
195
|
+
for (const a of r.apfs) line(` ${human(a.bytes).padStart(10)} ${a.name}`);
|
|
196
|
+
}
|
|
197
|
+
if (r.platform === 'darwin') {
|
|
198
|
+
line();
|
|
199
|
+
line(` Local Time Machine snapshots: ${r.snapshots}`);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
header('2. TOP-LEVEL BREAKDOWN (largest first)');
|
|
203
|
+
for (const root of r.roots) row(root.bytes, root.home ? `${prettyPath(root.path)} (your home folder)` : root.path);
|
|
204
|
+
if (r.other !== null) {
|
|
205
|
+
row(r.other, win ? 'Everything else (Windows, page file, restore points, unreadable folders)' : 'Everything else (system files, snapshots, unreadable folders)');
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
header(`3. HOME FOLDER — ${r.home.children.length} largest items`);
|
|
209
|
+
for (const c of r.home.children) row(c.bytes, prettyPath(c.path));
|
|
210
|
+
for (const b of r.breakdowns) {
|
|
211
|
+
line();
|
|
212
|
+
line(` -- ${prettyPath(b.path)} (${human(b.bytes)}) --`);
|
|
213
|
+
if (!b.children.length) line(' (empty or unreadable)');
|
|
214
|
+
for (const c of b.children) row(c.bytes, prettyPath(c.path));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
header('4. KNOWN SPACE HOGS (50 MB and up)');
|
|
218
|
+
let group = null;
|
|
219
|
+
for (const h of r.hogs) {
|
|
220
|
+
if (h.group !== group) line(` [${(group = h.group)}]`);
|
|
221
|
+
row(h.bytes, h.label);
|
|
222
|
+
}
|
|
223
|
+
if (!r.hogs.length) line(' none found');
|
|
224
|
+
|
|
225
|
+
header('5. DEVELOPER CLUTTER (folders that rebuild themselves)');
|
|
226
|
+
if (r.nodeModules.count) {
|
|
227
|
+
line(` node_modules: ${r.nodeModules.count} folders, ${human(r.nodeModules.bytes)} total. Largest:`);
|
|
228
|
+
for (const n of r.nodeModules.top) row(n.bytes, prettyPath(n.path));
|
|
229
|
+
} else {
|
|
230
|
+
line(' node_modules: none found');
|
|
231
|
+
}
|
|
232
|
+
for (const [title, list, folder] of [
|
|
233
|
+
['Unity projects', r.unityProjects, 'Library'],
|
|
234
|
+
['Unreal projects', r.unrealProjects, 'Intermediate etc.'],
|
|
235
|
+
]) {
|
|
236
|
+
if (!list.length) continue;
|
|
237
|
+
line();
|
|
238
|
+
line(` ${title} (whole project / regenerable ${folder}):`);
|
|
239
|
+
for (const p of list) line(` ${human(p.bytes).padStart(10)} (${folder}: ${human(p.regenerable).padStart(8)}) ${prettyPath(p.path)}`);
|
|
240
|
+
line(` Total regenerable: ${human(list.reduce((n, p) => n + p.regenerable, 0))}`);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
header('6. LARGEST INDIVIDUAL FILES (1 GB and up)');
|
|
244
|
+
for (const f of r.bigFiles) row(f.bytes, prettyPath(f.path));
|
|
245
|
+
if (!r.bigFiles.length) line(' none');
|
|
246
|
+
|
|
247
|
+
header('7. SUGGESTED NEXT STEPS (review first; nothing has been run)');
|
|
248
|
+
for (const s of r.suggestions) line(` • ${s}`);
|
|
249
|
+
|
|
250
|
+
if (r.unreadable > 0) {
|
|
251
|
+
line();
|
|
252
|
+
line(` Note: ${r.unreadable.toLocaleString()} folders or files could not be read, so some totals are partial.`);
|
|
253
|
+
line(
|
|
254
|
+
win
|
|
255
|
+
? ' Run the terminal as Administrator for a fuller picture.'
|
|
256
|
+
: r.platform === 'darwin'
|
|
257
|
+
? ' Give your terminal app Full Disk Access (System Settings > Privacy & Security) and rerun for a fuller picture.'
|
|
258
|
+
: ' Run with sudo for a fuller picture.'
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
if (win) {
|
|
262
|
+
line();
|
|
263
|
+
line(' OneDrive / iCloud files that are online-only are counted at full size here, though they use no local space.');
|
|
264
|
+
}
|
|
265
|
+
line();
|
|
266
|
+
line(` Scanned in ${Math.round(r.elapsedMs / 1000)}s.`);
|
|
267
|
+
line();
|
|
268
|
+
return out.join('\n');
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
module.exports = { buildReport, formatReport, human };
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* One-pass disk-usage walker.
|
|
8
|
+
*
|
|
9
|
+
* Every root is walked once. Along the way it records the size of each folder
|
|
10
|
+
* down to `recordDepth`, every `node_modules`, every Unity / Unreal project and
|
|
11
|
+
* every file over `bigFile` bytes — so the report is lookups, not re-walks.
|
|
12
|
+
*
|
|
13
|
+
* Sizes are allocated bytes (st.blocks * 512) where the platform reports them, so
|
|
14
|
+
* sparse files (Docker.raw) count what they really use, like `du`. Windows has no
|
|
15
|
+
* st.blocks, so it falls back to st.size. Hard links count once (like `du`),
|
|
16
|
+
* symlinks and junctions are never followed, and a walk never crosses onto
|
|
17
|
+
* another volume.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const GB = 1024 ** 3;
|
|
21
|
+
|
|
22
|
+
function allocated(st) {
|
|
23
|
+
return typeof st.blocks === 'number' && st.blocks >= 0 && process.platform !== 'win32' ? st.blocks * 512 : st.size;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Normalised key for the size map, so lookups are case-insensitive on Windows and macOS. */
|
|
27
|
+
function keyOf(p) {
|
|
28
|
+
const resolved = path.resolve(p);
|
|
29
|
+
return process.platform === 'linux' ? resolved : resolved.toLowerCase();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
class Scanner {
|
|
33
|
+
/**
|
|
34
|
+
* @param {object} [opts]
|
|
35
|
+
* @param {number} [opts.recordDepth=4] Folder sizes are kept for this many levels below each root.
|
|
36
|
+
* @param {number} [opts.bigFile=1 GiB] Files at least this big are listed individually.
|
|
37
|
+
* @param {(s: {files: number, bytes: number, dir: string}) => void} [opts.onProgress]
|
|
38
|
+
*/
|
|
39
|
+
constructor(opts = {}) {
|
|
40
|
+
this.recordDepth = opts.recordDepth ?? 4;
|
|
41
|
+
this.bigFile = opts.bigFile ?? GB;
|
|
42
|
+
this.onProgress = opts.onProgress || null;
|
|
43
|
+
|
|
44
|
+
this.sizes = new Map(); // keyOf(dir) -> bytes, for folders within recordDepth of a root
|
|
45
|
+
this.kids = new Map(); // keyOf(dir) -> [{ path, bytes }] recorded subfolders
|
|
46
|
+
this.seenInodes = new Set();
|
|
47
|
+
this.nodeModules = []; // { path, bytes }
|
|
48
|
+
this.unityProjects = []; // { path, bytes, regenerable }
|
|
49
|
+
this.unrealProjects = []; // { path, bytes, regenerable }
|
|
50
|
+
this.bigFiles = []; // { path, bytes }
|
|
51
|
+
this.unreadable = 0;
|
|
52
|
+
this.files = 0;
|
|
53
|
+
this.bytes = 0;
|
|
54
|
+
this._lastProgress = 0;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Walk a folder (or measure a file). Returns its size in bytes, or null when it does not exist. */
|
|
58
|
+
measure(target) {
|
|
59
|
+
const known = this.lookup(target);
|
|
60
|
+
if (known !== null) return known;
|
|
61
|
+
let st;
|
|
62
|
+
try {
|
|
63
|
+
st = fs.lstatSync(target);
|
|
64
|
+
} catch (err) {
|
|
65
|
+
if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') this.unreadable += 1;
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
if (st.isSymbolicLink()) return 0;
|
|
69
|
+
if (!st.isDirectory()) return this._countFile(target, st);
|
|
70
|
+
return this._walkDir(target, st.dev, 0, false);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Size of any path, for one-off lookups like the known-hogs table. Folders recorded
|
|
75
|
+
* by a walk are free; anything else is measured by a throwaway scanner, so a lookup
|
|
76
|
+
* never adds to the totals, the big-file list, the hard-link set or the project lists.
|
|
77
|
+
*/
|
|
78
|
+
sizeOf(target) {
|
|
79
|
+
const known = this.lookup(target);
|
|
80
|
+
if (known !== null) return known;
|
|
81
|
+
const probe = new Scanner({ recordDepth: 0, bigFile: Infinity });
|
|
82
|
+
const bytes = probe.measure(target);
|
|
83
|
+
this.unreadable += probe.unreadable;
|
|
84
|
+
return bytes;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Size of a folder already covered by a walk, without touching the disk; null if unknown. */
|
|
88
|
+
lookup(target) {
|
|
89
|
+
const k = keyOf(target);
|
|
90
|
+
return this.sizes.has(k) ? this.sizes.get(k) : null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Recorded subfolders of a walked folder, largest first: [{ path, bytes }]. */
|
|
94
|
+
children(dir) {
|
|
95
|
+
return [...(this.kids.get(keyOf(dir)) || [])].sort((a, b) => b.bytes - a.bytes);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
_record(dir, depth, bytes) {
|
|
99
|
+
if (depth > this.recordDepth) return;
|
|
100
|
+
this.sizes.set(keyOf(dir), bytes);
|
|
101
|
+
if (depth === 0) return;
|
|
102
|
+
const parent = keyOf(path.dirname(dir));
|
|
103
|
+
if (!this.kids.has(parent)) this.kids.set(parent, []);
|
|
104
|
+
this.kids.get(parent).push({ path: dir, bytes });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
_countFile(file, st) {
|
|
108
|
+
if (st.nlink > 1) {
|
|
109
|
+
const id = `${st.dev}:${st.ino}`;
|
|
110
|
+
if (this.seenInodes.has(id)) return 0;
|
|
111
|
+
this.seenInodes.add(id);
|
|
112
|
+
}
|
|
113
|
+
const bytes = allocated(st);
|
|
114
|
+
this.files += 1;
|
|
115
|
+
this.bytes += bytes;
|
|
116
|
+
if (bytes >= this.bigFile) this.bigFiles.push({ path: file, bytes });
|
|
117
|
+
if (this.onProgress && (this.files & 0x3fff) === 0) {
|
|
118
|
+
const now = Date.now();
|
|
119
|
+
if (now - this._lastProgress > 250) {
|
|
120
|
+
this._lastProgress = now;
|
|
121
|
+
this.onProgress({ files: this.files, bytes: this.bytes, dir: path.dirname(file) });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return bytes;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Synchronous on purpose: on a 690k-file tree it is ~3.4x faster than a promise-per-entry
|
|
129
|
+
* walk, which spends its time in promise bookkeeping rather than on the disk.
|
|
130
|
+
* `quiet` = inside node_modules or a project's rebuildable folder: count, but detect nothing.
|
|
131
|
+
*/
|
|
132
|
+
_walkDir(dir, rootDev, depth, quiet) {
|
|
133
|
+
let entries;
|
|
134
|
+
try {
|
|
135
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
136
|
+
} catch (err) {
|
|
137
|
+
if (err.code !== 'ENOENT') this.unreadable += 1;
|
|
138
|
+
this._record(dir, depth, 0);
|
|
139
|
+
return 0;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const isNodeModules = !quiet && path.basename(dir) === 'node_modules';
|
|
143
|
+
const engine = quiet || isNodeModules ? null : detectProject(dir, entries);
|
|
144
|
+
const rebuildable = new Set(engine ? engine.regenerable : []);
|
|
145
|
+
|
|
146
|
+
let total = 0;
|
|
147
|
+
let regenerable = 0;
|
|
148
|
+
for (const entry of entries) {
|
|
149
|
+
if (entry.isSymbolicLink()) continue;
|
|
150
|
+
const full = path.join(dir, entry.name);
|
|
151
|
+
let st;
|
|
152
|
+
try {
|
|
153
|
+
st = fs.lstatSync(full);
|
|
154
|
+
} catch (err) {
|
|
155
|
+
if (err.code !== 'ENOENT') this.unreadable += 1;
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (st.isSymbolicLink()) continue; // Windows junctions surface here
|
|
159
|
+
if (st.isDirectory()) {
|
|
160
|
+
if (st.dev !== rootDev) continue; // another volume
|
|
161
|
+
const inRebuildable = rebuildable.has(entry.name);
|
|
162
|
+
const bytes = this._walkDir(full, rootDev, depth + 1, quiet || isNodeModules || inRebuildable);
|
|
163
|
+
total += bytes;
|
|
164
|
+
if (inRebuildable) regenerable += bytes;
|
|
165
|
+
} else {
|
|
166
|
+
total += this._countFile(full, st);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
this._record(dir, depth, total);
|
|
171
|
+
if (isNodeModules) this.nodeModules.push({ path: dir, bytes: total });
|
|
172
|
+
if (engine) (engine.kind === 'unity' ? this.unityProjects : this.unrealProjects).push({ path: dir, bytes: total, regenerable });
|
|
173
|
+
return total;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* A Unity project has Assets/ and ProjectSettings/ProjectVersion.txt (packages and test
|
|
179
|
+
* fixtures often have the two folders but never the version file). An Unreal project has
|
|
180
|
+
* a *.uproject file next to Config/ (VS Code's file history alone keeps stray *.uproject copies).
|
|
181
|
+
*/
|
|
182
|
+
function detectProject(dir, entries) {
|
|
183
|
+
const dirs = new Set(entries.filter((e) => e.isDirectory()).map((e) => e.name));
|
|
184
|
+
if (dirs.has('Assets') && dirs.has('ProjectSettings') && fs.existsSync(path.join(dir, 'ProjectSettings', 'ProjectVersion.txt'))) {
|
|
185
|
+
return { kind: 'unity', regenerable: ['Library', 'Temp', 'Obj', 'Logs'] };
|
|
186
|
+
}
|
|
187
|
+
if (dirs.has('Config') && entries.some((e) => e.isFile() && e.name.toLowerCase().endsWith('.uproject'))) {
|
|
188
|
+
return { kind: 'unreal', regenerable: ['Intermediate', 'DerivedDataCache', 'Binaries'] };
|
|
189
|
+
}
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
module.exports = { Scanner, detectProject, allocated, keyOf, GB };
|
package/lib/kill/cli.js
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { parsePortSpecs, parsePids, findListeners, processName, stopProcesses, isAlive } = require('./ports');
|
|
4
|
+
|
|
5
|
+
const USAGE = `
|
|
6
|
+
bt-agent kill — free ports and stop processes (macOS, Windows, Linux)
|
|
7
|
+
|
|
8
|
+
Stops whatever is listening on the given TCP ports, or the given process ids, so
|
|
9
|
+
a dev server can be restarted. --port matches only processes *listening* on a
|
|
10
|
+
port — a browser that is merely connected to your dev server is left alone. On
|
|
11
|
+
macOS and Linux each process is asked to exit (SIGTERM) and force-killed if it is
|
|
12
|
+
still running after 3 seconds; Windows always force-kills the process and its
|
|
13
|
+
children (taskkill /T /F).
|
|
14
|
+
|
|
15
|
+
Usage
|
|
16
|
+
bt-agent kill --port <port|range> [...] stop whatever listens on these ports
|
|
17
|
+
bt-agent kill --pid <id> [...] stop these processes
|
|
18
|
+
bt-agent kill --list [port|range ...] list listening ports (all, or just these)
|
|
19
|
+
bt-agent kill --list --pid <id> [...] list the ports these processes listen on
|
|
20
|
+
|
|
21
|
+
4444 one port
|
|
22
|
+
8000-8010 an inclusive range
|
|
23
|
+
4444,8888 a list (separate arguments work too; the same for process ids)
|
|
24
|
+
|
|
25
|
+
Options
|
|
26
|
+
--port The values are ports or port ranges
|
|
27
|
+
--pid The values are process ids
|
|
28
|
+
--list, -l Show listening ports with their process id and name; stop nothing
|
|
29
|
+
(--dry-run is the same)
|
|
30
|
+
--force, -9 Force-kill at once (SIGKILL) instead of asking first
|
|
31
|
+
--json Machine-readable output
|
|
32
|
+
-h, --help Show this help
|
|
33
|
+
|
|
34
|
+
Examples
|
|
35
|
+
bt-agent kill --port 4444
|
|
36
|
+
bt-agent kill --port 4444 8888
|
|
37
|
+
bt-agent kill --port 3000-3010
|
|
38
|
+
bt-agent kill --pid 51234
|
|
39
|
+
bt-agent kill --pid 51234 --force
|
|
40
|
+
bt-agent kill --list
|
|
41
|
+
bt-agent kill --list 3000-3999
|
|
42
|
+
`;
|
|
43
|
+
|
|
44
|
+
const MODE_HINT = 'Say what to stop: `bt-agent kill --port 4444`, `bt-agent kill --pid 51234` or `bt-agent kill --list`';
|
|
45
|
+
|
|
46
|
+
function parseKillArgs(argv) {
|
|
47
|
+
const opts = { specs: [], ports: [], pids: [], by: null, list: false, force: false, json: false, help: false };
|
|
48
|
+
const setBy = (by) => {
|
|
49
|
+
if (opts.by && opts.by !== by) throw new Error('Use --port or --pid, not both');
|
|
50
|
+
opts.by = by;
|
|
51
|
+
};
|
|
52
|
+
for (const arg of argv) {
|
|
53
|
+
if (arg === '-h' || arg === '--help') opts.help = true;
|
|
54
|
+
else if (arg === '--list' || arg === '-l' || arg === '--dry-run') opts.list = true;
|
|
55
|
+
else if (arg === '--force' || arg === '-9') opts.force = true;
|
|
56
|
+
else if (arg === '--json') opts.json = true;
|
|
57
|
+
else if (arg === '--port' || arg === '--pid') setBy(arg.slice(2));
|
|
58
|
+
else if (arg.startsWith('--port=') || arg.startsWith('--pid=')) {
|
|
59
|
+
const [flag, value] = arg.split('=');
|
|
60
|
+
setBy(flag.slice(2));
|
|
61
|
+
opts.specs.push(value);
|
|
62
|
+
} else if (arg.startsWith('-')) throw new Error(`Unknown option: ${arg}`);
|
|
63
|
+
else opts.specs.push(arg);
|
|
64
|
+
}
|
|
65
|
+
if (opts.help) return opts;
|
|
66
|
+
|
|
67
|
+
if (opts.list && opts.force) throw new Error('--force stops processes; --list never does — drop one of them');
|
|
68
|
+
|
|
69
|
+
// --list on its own filters by port, the thing it lists.
|
|
70
|
+
if (!opts.by && opts.list) opts.by = 'port';
|
|
71
|
+
if (!opts.by) throw new Error(opts.specs.length ? `${MODE_HINT} — is ${opts.specs[0]} a port or a process id?` : MODE_HINT);
|
|
72
|
+
if (!opts.list && !opts.specs.length) {
|
|
73
|
+
throw new Error(opts.by === 'port' ? '--port needs a port or range, e.g. --port 4444' : '--pid needs a process id, e.g. --pid 51234');
|
|
74
|
+
}
|
|
75
|
+
if (opts.by === 'port') opts.ports = parsePortSpecs(opts.specs);
|
|
76
|
+
else opts.pids = parsePids(opts.specs);
|
|
77
|
+
return opts;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function describe(r) {
|
|
81
|
+
if (r.pid == null) return 'a process owned by another user';
|
|
82
|
+
return `${r.command || 'process'} (pid ${r.pid})`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const STATUS_TEXT = {
|
|
86
|
+
stopped: 'stopped',
|
|
87
|
+
killed: 'force-killed',
|
|
88
|
+
'not-running': 'not running',
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/** Unique listeners, sorted by port then pid. */
|
|
92
|
+
function uniqueListeners(listeners) {
|
|
93
|
+
const seen = new Set();
|
|
94
|
+
return listeners
|
|
95
|
+
.filter((l) => {
|
|
96
|
+
const key = `${l.port}/${l.pid}`;
|
|
97
|
+
if (seen.has(key)) return false;
|
|
98
|
+
seen.add(key);
|
|
99
|
+
return true;
|
|
100
|
+
})
|
|
101
|
+
.sort((a, b) => a.port - b.port || (a.pid || 0) - (b.pid || 0));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function printList(rows, idle, opts, platform) {
|
|
105
|
+
console.log('');
|
|
106
|
+
if (!rows.length && !idle.length) {
|
|
107
|
+
console.log(opts.ports.length || opts.pids.length ? 'Nothing is listening there.' : 'Nothing is listening.');
|
|
108
|
+
} else {
|
|
109
|
+
console.log(` ${'PORT'.padStart(5)} ${'PID'.padStart(7)} PROCESS`);
|
|
110
|
+
for (const l of rows) {
|
|
111
|
+
const who = l.pid == null ? '(another user)' : l.command || '?';
|
|
112
|
+
console.log(` ${String(l.port).padStart(5)} ${String(l.pid == null ? '?' : l.pid).padStart(7)} ${who}`);
|
|
113
|
+
}
|
|
114
|
+
for (const p of idle) {
|
|
115
|
+
console.log(` ${'-'.padStart(5)} ${String(p.pid).padStart(7)} ${p.alive ? `${p.command || '?'} — no listening ports` : 'not running'}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (platform !== 'win32') console.log('\n(Processes owned by other users are only fully visible with sudo.)');
|
|
119
|
+
console.log('');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function printResults(results, respawned, opts, platform) {
|
|
123
|
+
const lines = [];
|
|
124
|
+
for (const r of results) {
|
|
125
|
+
const outcome = STATUS_TEXT[r.status] || `FAILED — ${r.error}`;
|
|
126
|
+
const ports = r.ports.length ? r.ports : ['-'];
|
|
127
|
+
for (const port of ports) lines.push([port === '-' ? Infinity : port, ` ${String(port).padStart(5)} ${describe(r)} ${outcome}`]);
|
|
128
|
+
}
|
|
129
|
+
for (const l of respawned) {
|
|
130
|
+
lines.push([l.port, ` ${String(l.port).padStart(5)} listening again: ${describe(l)} — a watcher or supervisor restarted it`]);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
console.log('');
|
|
134
|
+
if (!lines.length) {
|
|
135
|
+
console.log(`Nothing is listening on ${opts.specs.join(', ')}.`);
|
|
136
|
+
if (platform !== 'win32') console.log('(A process owned by another user is only visible with sudo.)');
|
|
137
|
+
} else {
|
|
138
|
+
for (const [, line] of lines.sort((a, b) => a[0] - b[0])) console.log(line);
|
|
139
|
+
}
|
|
140
|
+
console.log('');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** `--list`: show listeners, kill nothing. */
|
|
144
|
+
function runList(opts, listeners, platform) {
|
|
145
|
+
const wantedPorts = new Set(opts.ports);
|
|
146
|
+
const wantedPids = new Set(opts.pids);
|
|
147
|
+
const all = !opts.ports.length && !opts.pids.length;
|
|
148
|
+
const rows = uniqueListeners(listeners.filter((l) => all || wantedPorts.has(l.port) || wantedPids.has(l.pid)));
|
|
149
|
+
const idle = opts.pids
|
|
150
|
+
.filter((pid) => !rows.some((l) => l.pid === pid))
|
|
151
|
+
.map((pid) => {
|
|
152
|
+
const alive = isAlive(pid);
|
|
153
|
+
return { pid, alive, command: alive ? processName(pid, platform) : '' };
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
if (opts.json) console.log(JSON.stringify({ listeners: rows, processes: idle }, null, 2));
|
|
157
|
+
else printList(rows, idle, opts, platform);
|
|
158
|
+
return 0;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Entry point for `bt-agent kill`. Resolves to the process exit code. */
|
|
162
|
+
async function runKillCli(argv, platform = process.platform) {
|
|
163
|
+
let opts;
|
|
164
|
+
try {
|
|
165
|
+
opts = parseKillArgs(argv);
|
|
166
|
+
} catch (err) {
|
|
167
|
+
console.error(`${err.message}\n\nRun \`bt-agent kill --help\` for usage.`);
|
|
168
|
+
return 2;
|
|
169
|
+
}
|
|
170
|
+
if (opts.help) {
|
|
171
|
+
console.log(USAGE);
|
|
172
|
+
return 0;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const listeners = findListeners(platform);
|
|
176
|
+
if (opts.list) return runList(opts, listeners, platform);
|
|
177
|
+
|
|
178
|
+
const wanted = new Set(opts.ports);
|
|
179
|
+
const byPid = new Map();
|
|
180
|
+
const unknown = new Set();
|
|
181
|
+
const target = (pid, command) => {
|
|
182
|
+
if (!byPid.has(pid)) byPid.set(pid, { pid, command, ports: [] });
|
|
183
|
+
return byPid.get(pid);
|
|
184
|
+
};
|
|
185
|
+
for (const l of listeners) {
|
|
186
|
+
if (!wanted.has(l.port)) continue;
|
|
187
|
+
if (l.pid == null) unknown.add(l.port);
|
|
188
|
+
else if (!target(l.pid, l.command).ports.includes(l.port)) byPid.get(l.pid).ports.push(l.port);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const missing = [];
|
|
192
|
+
for (const pid of opts.pids) {
|
|
193
|
+
if (byPid.has(pid)) continue;
|
|
194
|
+
if (!isAlive(pid)) {
|
|
195
|
+
missing.push({ pid, command: '', ports: [], status: 'not-running', error: null });
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
const own = listeners.filter((l) => l.pid === pid);
|
|
199
|
+
const t = target(pid, (own[0] && own[0].command) || processName(pid, platform));
|
|
200
|
+
for (const l of own) if (!t.ports.includes(l.port)) t.ports.push(l.port);
|
|
201
|
+
}
|
|
202
|
+
for (const t of byPid.values()) t.ports.sort((a, b) => a - b);
|
|
203
|
+
|
|
204
|
+
const results = await stopProcesses([...byPid.values()], { force: opts.force, platform });
|
|
205
|
+
results.push(...missing);
|
|
206
|
+
for (const port of unknown) {
|
|
207
|
+
results.push({ pid: null, command: '', ports: [port], status: 'failed', error: 'owned by another user — retry with sudo' });
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// A dev server run under a watcher (nodemon, pm2, a supervisor) can come straight back.
|
|
211
|
+
let respawned = [];
|
|
212
|
+
const freed = new Set(results.filter((r) => r.status === 'stopped' || r.status === 'killed').flatMap((r) => r.ports));
|
|
213
|
+
if (freed.size) {
|
|
214
|
+
respawned = uniqueListeners(findListeners(platform).filter((l) => freed.has(l.port) && !byPid.has(l.pid)));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
if (opts.json) {
|
|
218
|
+
console.log(JSON.stringify({ ports: opts.specs, pids: opts.pids, results, respawned }, null, 2));
|
|
219
|
+
} else {
|
|
220
|
+
printResults(results, respawned, opts, platform);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const failed = results.some((r) => r.status === 'failed' || r.status === 'protected');
|
|
224
|
+
return failed || respawned.length ? 1 : 0;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
module.exports = { runKillCli, parseKillArgs };
|