@babylonjs-toolkit/agent 1.1.66 → 1.1.68

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.
@@ -0,0 +1,517 @@
1
+ /**
2
+ * bt-profile capture: opens a Babylon Toolkit web game in a real Chrome (GPU on, fresh profile = cold shader and HTTP
3
+ * caches), runs a scenario (a small module that drives the game: open the page, wait for phases, hold keys, mark
4
+ * phases, take screenshots), and records everything needed to name the code behind every slow frame:
5
+ *
6
+ * - a V8 sampling CPU profile of the whole scenario (`cpu.cpuprofile`, opens in DevTools too);
7
+ * - a sampling allocation profile that includes collected objects (`heap.heapprofile`) — who feeds the GC;
8
+ * - the in-page probe's per-frame CPU work, Babylon timers, scene counters, phase marks and long animation frames;
9
+ * - the source text and source map of every script the profile hit (`scripts/`), so analysis can map minified or
10
+ * transformed positions back to original files offline;
11
+ * - optional: a full DevTools performance trace (`--trace true`), and a second, warm load in the same browser
12
+ * (`--warm true`) to separate first-use costs (shader compiles, decoding) from steady per-frame work;
13
+ * - optional (`--snapshots true`): the scenario's phase screenshots plus a filmstrip — about one small frame per
14
+ * second from Chrome's screencast, timed on the same clock as the frames. Off by default: a full-size screenshot
15
+ * stalls the game for a moment and would show up in the very profile it is meant to explain.
16
+ *
17
+ * Usage (from `.agents/profile/<slug>/data`, whose profile.config.json supplies the defaults for --url and --scenario):
18
+ * node ../../.tools/profile.mjs --out runs/baseline [--url http://localhost:5173/play] [--scenario scenario.mjs]
19
+ * [--seconds 150] [--dpr 2] [--width 1600] [--height 900] [--headed true] [--interval 250] [--warm true]
20
+ * [--trace true] [--uncapped true] [--heap false] [--snapshots true] [--filmstrip-interval 1] [--autoplay gesture] [--args key=value,key2=value2]
21
+ */
22
+ import fs from "node:fs";
23
+ import os from "node:os";
24
+ import path from "node:path";
25
+ import { pathToFileURL } from "node:url";
26
+ import puppeteer from "puppeteer-core";
27
+ import { installProbe } from "./lib/probe.mjs";
28
+
29
+ /** Default sampling interval of the CPU profiler, in microseconds (DevTools uses 100–1000). */
30
+ const DEFAULT_SAMPLING_INTERVAL_US = 250;
31
+ /** Console lines a dev server's client prints when it hot-patches or reloads the page (Vite, webpack, Parcel, Next). */
32
+ const DEV_SERVER_UPDATE = /^\[vite\] (hot updated|page reload|.*full reload)|^\[HMR\]|^\[webpack-dev-server\].*(reload|updated)|^\[parcel\].*(updated|reload)|^\[Fast Refresh\]/i;
33
+ /** Allocation sampling interval, in bytes: one sample per this many bytes allocated, on average. */
34
+ const HEAP_SAMPLING_INTERVAL_BYTES = 32768;
35
+ /** Hard ceiling on one scenario run, in seconds, so a stuck scenario never hangs the capture. */
36
+ const DEFAULT_MAX_SECONDS = 240;
37
+ /** Name of the busy-wait function that ties CPU-profile timestamps to page epoch time. */
38
+ const SYNC_MARKER_NAME = "__btProfileSyncMarker";
39
+ /** How long the sync marker busy-waits, in milliseconds — long enough to be sampled many times. */
40
+ const SYNC_MARKER_MS = 4;
41
+ /** Trace categories DevTools' Performance panel records, so `trace.json` opens there with a flame chart. */
42
+ const TRACE_CATEGORIES = [
43
+ "-*", "devtools.timeline", "disabled-by-default-devtools.timeline", "disabled-by-default-devtools.timeline.frame",
44
+ "v8.execute", "blink.user_timing", "loading", "latencyInfo", "disabled-by-default-v8.cpu_profiler", "v8", "gpu",
45
+ "disabled-by-default-devtools.timeline.stack",
46
+ ];
47
+
48
+ /**
49
+ * Reads `--name value` pairs from the command line.
50
+ * @param {string[]} argv - process.argv.slice(2)
51
+ * @returns {Record<string, string>} the parsed flags
52
+ */
53
+ function parseArguments(argv) {
54
+ const flags = {};
55
+ for (let i = 0; i < argv.length; i += 2) flags[argv[i].replace(/^--/, "")] = argv[i + 1];
56
+ return flags;
57
+ }
58
+
59
+ /**
60
+ * Parses `key=value,key2=value2` into an object of strings, for scenario options.
61
+ * @param {string|undefined} text - the raw `--args` value
62
+ * @returns {Record<string, string>} the options
63
+ */
64
+ function parseScenarioArguments(text) {
65
+ const options = {};
66
+ for (const pair of (text || "").split(",").filter(Boolean)) {
67
+ const [key, ...rest] = pair.split("=");
68
+ options[key.trim()] = rest.join("=").trim();
69
+ }
70
+ return options;
71
+ }
72
+
73
+ /**
74
+ * Finds a Chrome or Chromium executable: CHROME_PATH, the usual install locations, then puppeteer's own cache.
75
+ * @returns {string} absolute path of the browser executable
76
+ * @throws {Error} when no browser can be found
77
+ */
78
+ function findChrome() {
79
+ const candidates = [
80
+ process.env.CHROME_PATH,
81
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
82
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
83
+ "/usr/bin/google-chrome",
84
+ "/usr/bin/chromium",
85
+ "/usr/bin/chromium-browser",
86
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
87
+ "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
88
+ ].filter(Boolean);
89
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
90
+ if (found) return found;
91
+ throw new Error("No Chrome found. Set CHROME_PATH to a Chrome or Chromium executable.");
92
+ }
93
+
94
+ /** Pauses for the given number of seconds. */
95
+ const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
96
+
97
+ /**
98
+ * Runs the sync marker in the page: a named function that busy-waits a few milliseconds. Its first sample in the CPU
99
+ * profile and the epoch time it returns pin the profile's clock to the page's clock.
100
+ * @param {import("puppeteer-core").Page} page - the profiled page
101
+ * @returns {Promise<number>} epoch milliseconds at which the marker started
102
+ */
103
+ async function runSyncMarker(page) {
104
+ return page.evaluate(`(function ${SYNC_MARKER_NAME}() {
105
+ const startedAt = performance.timeOrigin + performance.now();
106
+ const until = performance.now() + ${SYNC_MARKER_MS};
107
+ let spins = 0;
108
+ while (performance.now() < until) spins++;
109
+ return startedAt;
110
+ })()`);
111
+ }
112
+
113
+ /**
114
+ * Loads the scenario module. A scenario exports `meta` ({ name, description }) and `async run(context)`.
115
+ * @param {string|undefined} scenarioPath - path of the scenario module, or undefined for the built-in idle scenario
116
+ * @returns {Promise<{meta: object, run: Function}>} the scenario
117
+ */
118
+ async function loadScenario(scenarioPath) {
119
+ if (!scenarioPath) {
120
+ return {
121
+ meta: { name: "idle", description: "Opens the URL and records for --idle seconds (default 60) after the first frame." },
122
+ run: async (context) => {
123
+ await context.open();
124
+ await context.waitForFrames();
125
+ context.mark("running");
126
+ await context.sleep(Number(context.options.idle || 60));
127
+ },
128
+ };
129
+ }
130
+ const module = await import(pathToFileURL(path.resolve(scenarioPath)).href);
131
+ if (typeof module.run !== "function") throw new Error(`Scenario ${scenarioPath} must export an async run(context) function.`);
132
+ return { meta: module.meta || { name: path.basename(scenarioPath, path.extname(scenarioPath)) }, run: module.run };
133
+ }
134
+
135
+ /**
136
+ * Says whether the game restarted under the capture without the scenario asking: a document load after the first
137
+ * open() with no open() since the previous load, or the dev server hot-patching the page.
138
+ * @returns {{reason: string, unexpectedNavigations: object[], devServerUpdates: object[], scenesSeen: number}|null}
139
+ */
140
+ function disturbance(context, navigations, devServerUpdates, probe) {
141
+ const opens = context.openTimes;
142
+ const unexpectedNavigations = [];
143
+ let previousLoad = opens.length ? opens[0] : Infinity;
144
+ for (const navigation of navigations) {
145
+ if (navigation.at < previousLoad) continue; // the start page, or the first load the scenario asked for
146
+ if (!opens.some((at) => at >= previousLoad && at <= navigation.at)) unexpectedNavigations.push(navigation);
147
+ previousLoad = navigation.at;
148
+ }
149
+ if (unexpectedNavigations.length === 0 && devServerUpdates.length === 0) return null;
150
+ const parts = [];
151
+ if (unexpectedNavigations.length) parts.push(`${unexpectedNavigations.length} page reload(s) the scenario did not ask for`);
152
+ if (devServerUpdates.length) parts.push(`${devServerUpdates.length} dev-server update(s) (${devServerUpdates[0].text})`);
153
+ return { reason: parts.join(", "), unexpectedNavigations, devServerUpdates: devServerUpdates.slice(0, 40), scenesSeen: probe ? probe.scenesSeen : null };
154
+ }
155
+
156
+ /**
157
+ * Builds the object a scenario drives the game through.
158
+ * @returns {object} the scenario context
159
+ */
160
+ function createScenarioContext(page, targetUrl, shotsDir, options, log, snapshots, onMark) {
161
+ const nodeMarks = [];
162
+ const context = {
163
+ nodeMarks,
164
+ /** When the scenario asked for a navigation (a document load no open() asked for is a dev-server reload). */
165
+ openTimes: [],
166
+ page,
167
+ options,
168
+ url: targetUrl,
169
+ log,
170
+ sleep,
171
+ /** Navigates to the target URL (or another URL / path on the same origin). */
172
+ open: async (urlOrPath) => {
173
+ const destination = urlOrPath ? new URL(urlOrPath, targetUrl).href : targetUrl;
174
+ log(`open ${destination}`);
175
+ context.openTimes.push(Date.now());
176
+ await page.goto(destination, { waitUntil: "domcontentloaded", timeout: 600000 });
177
+ },
178
+ /**
179
+ * Says the next page load is the scenario's own doing (a click on a link or button that navigates), so the
180
+ * capture does not report it as a dev-server reload. Call it just before the click.
181
+ */
182
+ expectNavigation: () => { context.openTimes.push(Date.now()); },
183
+ /** Records a phase boundary in the page's clock. */
184
+ mark: async (name) => {
185
+ log(`mark ${name}`);
186
+ // Kept on this side too: a mark sent while a navigation commits can miss the page's recorder.
187
+ nodeMarks.push({ name, at: Date.now() });
188
+ await page.evaluate((markName) => window.__btProfile && window.__btProfile.mark(markName), name);
189
+ if (onMark) await onMark(name);
190
+ },
191
+ /** Waits until a page function returns truthy (polls every 100 ms). */
192
+ waitFor: (pageFunction, { timeout = 600000, polling = 100, args = [] } = {}) =>
193
+ page.waitForFunction(pageFunction, { timeout, polling }, ...args),
194
+ /** Waits until the Babylon engine has rendered at least `count` frames. */
195
+ waitForFrames: (count = 10, timeout = 600000) =>
196
+ page.waitForFunction((minimum) => window.__btProfile && window.__btProfile.frames.length >= minimum, { timeout, polling: 100 }, count),
197
+ evaluate: (pageFunction, ...args) => page.evaluate(pageFunction, ...args),
198
+ keyDown: (key) => page.keyboard.down(key),
199
+ keyUp: (key) => page.keyboard.up(key),
200
+ press: (key) => page.keyboard.press(key),
201
+ /** Saves a screenshot under shots/<name>.png — only with --snapshots true; otherwise a no-op returning null. */
202
+ shot: async (name) => {
203
+ if (!snapshots) return null;
204
+ const file = path.join(shotsDir, `${name}.png`);
205
+ await page.screenshot({ path: file });
206
+ log(`shot ${path.basename(file)}`);
207
+ return file;
208
+ },
209
+ };
210
+ return context;
211
+ }
212
+
213
+ /**
214
+ * Fetches a script's source map: inline `data:` URLs are decoded, anything else is fetched relative to the script.
215
+ * @returns {Promise<string|null>} the source map JSON text, or null when there is none or it cannot be fetched
216
+ */
217
+ async function fetchSourceMap(scriptUrl, sourceMapUrl) {
218
+ if (!sourceMapUrl) return null;
219
+ try {
220
+ if (sourceMapUrl.startsWith("data:")) {
221
+ const comma = sourceMapUrl.indexOf(",");
222
+ const header = sourceMapUrl.slice(0, comma);
223
+ const body = sourceMapUrl.slice(comma + 1);
224
+ return header.includes(";base64") ? Buffer.from(body, "base64").toString("utf8") : decodeURIComponent(body);
225
+ }
226
+ const absolute = new URL(sourceMapUrl, scriptUrl).href;
227
+ const response = await fetch(absolute);
228
+ return response.ok ? await response.text() : null;
229
+ } catch {
230
+ return null;
231
+ }
232
+ }
233
+
234
+ /**
235
+ * Saves the source and source map of every script the CPU profile sampled. Enabling the debugger after the profile
236
+ * stops replays `scriptParsed` for every live script, so the profiled run itself never ran with the debugger on.
237
+ * @returns {Promise<object[]>} the script index written to scripts/index.json
238
+ */
239
+ async function saveProfiledScripts(session, profile, scriptsDir) {
240
+ const sampledIds = new Set(profile.nodes.map((node) => node.callFrame.scriptId).filter((id) => id && id !== "0"));
241
+ const parsed = new Map();
242
+ session.on("Debugger.scriptParsed", (event) => parsed.set(event.scriptId, event));
243
+ await session.send("Debugger.enable");
244
+ await sleep(1);
245
+ const index = [];
246
+ for (const scriptId of sampledIds) {
247
+ const info = parsed.get(scriptId);
248
+ const entry = { scriptId, url: info ? info.url : "", sourceMapUrl: info ? info.sourceMapURL || "" : "", hasSource: false, hasMap: false };
249
+ try {
250
+ const { scriptSource } = await session.send("Debugger.getScriptSource", { scriptId });
251
+ fs.writeFileSync(path.join(scriptsDir, `${scriptId}.js`), scriptSource);
252
+ entry.hasSource = true;
253
+ if (!entry.sourceMapUrl) {
254
+ const inline = scriptSource.match(/\/\/[#@] sourceMappingURL=([^\s'"]+)\s*$/);
255
+ if (inline) entry.sourceMapUrl = inline[1];
256
+ }
257
+ } catch {
258
+ // Wasm modules and scripts from a navigated-away document have no retrievable source.
259
+ }
260
+ const mapText = entry.url ? await fetchSourceMap(entry.url, entry.sourceMapUrl) : null;
261
+ if (mapText) {
262
+ fs.writeFileSync(path.join(scriptsDir, `${scriptId}.map.json`), mapText);
263
+ entry.hasMap = true;
264
+ }
265
+ index.push(entry);
266
+ }
267
+ await session.send("Debugger.disable");
268
+ fs.writeFileSync(path.join(scriptsDir, "index.json"), JSON.stringify(index, null, 1));
269
+ return index;
270
+ }
271
+
272
+ /**
273
+ * Starts the allocation sampler, including objects the GC already collected, so short-lived per-frame garbage counts.
274
+ * Older Chrome versions reject the include flags; the sampler then reports only objects still alive at the end.
275
+ * @returns {Promise<boolean>} true when collected objects are included
276
+ */
277
+ async function startHeapSampling(session) {
278
+ await session.send("HeapProfiler.enable");
279
+ try {
280
+ await session.send("HeapProfiler.startSampling", {
281
+ samplingInterval: HEAP_SAMPLING_INTERVAL_BYTES, includeObjectsCollectedByMajorGC: true, includeObjectsCollectedByMinorGC: true,
282
+ });
283
+ return true;
284
+ } catch {
285
+ await session.send("HeapProfiler.startSampling", { samplingInterval: HEAP_SAMPLING_INTERVAL_BYTES });
286
+ return false;
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Records a DevTools trace into trace.json (streamed, it can be large).
292
+ * @returns {Promise<() => Promise<void>>} a function that stops the trace and writes the file
293
+ */
294
+ async function startTrace(session, traceFile) {
295
+ await session.send("Tracing.start", { traceConfig: { includedCategories: TRACE_CATEGORIES.filter((category) => category !== "-*"), excludedCategories: ["*"] }, transferMode: "ReturnAsStream" });
296
+ return async () => {
297
+ const complete = new Promise((resolve) => session.once("Tracing.tracingComplete", resolve));
298
+ await session.send("Tracing.end");
299
+ const { stream } = await complete;
300
+ const output = fs.createWriteStream(traceFile);
301
+ for (;;) {
302
+ const chunk = await session.send("IO.read", { handle: stream });
303
+ output.write(chunk.base64Encoded ? Buffer.from(chunk.data, "base64") : chunk.data);
304
+ if (chunk.eof) break;
305
+ }
306
+ await session.send("IO.close", { handle: stream });
307
+ await new Promise((resolve) => output.end(resolve));
308
+ };
309
+ }
310
+
311
+ /**
312
+ * Records a filmstrip with Chrome's screencast: the compositor hands over frames it already produced, encoded off
313
+ * the page's main thread, and every `intervalSeconds` one is kept as a small JPEG under filmstrip/.
314
+ * @returns {Promise<() => Promise<object[]>>} a function that stops the screencast and returns [{ at, file }]
315
+ */
316
+ async function startFilmstrip(session, runDir, intervalSeconds) {
317
+ const filmstripDir = path.join(runDir, "filmstrip");
318
+ fs.mkdirSync(filmstripDir, { recursive: true });
319
+ const frames = [];
320
+ let lastKeptAt = 0;
321
+ const onFrame = (event) => {
322
+ session.send("Page.screencastFrameAck", { sessionId: event.sessionId }).catch(() => {});
323
+ const at = event.metadata.timestamp * 1000;
324
+ if (at - lastKeptAt < intervalSeconds * 1000) return;
325
+ lastKeptAt = at;
326
+ const file = `${String(frames.length).padStart(4, "0")}.jpg`;
327
+ fs.writeFileSync(path.join(filmstripDir, file), Buffer.from(event.data, "base64"));
328
+ frames.push({ at, file: `filmstrip/${file}` });
329
+ };
330
+ session.on("Page.screencastFrame", onFrame);
331
+ await session.send("Page.startScreencast", { format: "jpeg", quality: 55, maxWidth: 480, maxHeight: 270, everyNthFrame: 4 });
332
+ return async () => {
333
+ await session.send("Page.stopScreencast").catch(() => {});
334
+ session.off("Page.screencastFrame", onFrame);
335
+ fs.writeFileSync(path.join(runDir, "filmstrip.json"), JSON.stringify(frames));
336
+ return frames;
337
+ };
338
+ }
339
+
340
+ /**
341
+ * Runs the scenario once in a new page of the given browser and writes the whole capture into runDir.
342
+ * @returns {Promise<object>} the capture summary (also written to capture.json)
343
+ */
344
+ async function captureOnce(browser, flags, scenario, runDir, label) {
345
+ const shotsDir = path.join(runDir, "shots");
346
+ const scriptsDir = path.join(runDir, "scripts");
347
+ fs.mkdirSync(shotsDir, { recursive: true });
348
+ fs.mkdirSync(scriptsDir, { recursive: true });
349
+ const log = (message) => process.stderr.write(`[bt-profile ${label} +${((Date.now() - startedAt) / 1000).toFixed(1)}s] ${message}\n`);
350
+ const startedAt = Date.now();
351
+ const targetUrl = flags.url;
352
+ const deviceScaleFactor = Number(flags.dpr || 2);
353
+ const page = await browser.newPage();
354
+ await page.setViewport({ width: Number(flags.width || 1600), height: Number(flags.height || 900), deviceScaleFactor });
355
+ const consoleErrors = [];
356
+ // A dev server that watches files reloads or hot-patches the game when anyone edits the project (another agent session,
357
+ // an editor's save): the scene restarts mid-capture and the numbers are worthless. Both are recorded and flagged.
358
+ const devServerUpdates = [];
359
+ const navigations = [];
360
+ page.on("console", (message) => {
361
+ const text = message.text();
362
+ if (DEV_SERVER_UPDATE.test(text)) devServerUpdates.push({ at: Date.now(), text: text.slice(0, 200) });
363
+ if (message.type() === "error" || message.type() === "warning") consoleErrors.push({ type: message.type(), text: text.slice(0, 600) });
364
+ });
365
+ // Document loads only: a router's history.pushState / replaceState is a same-document "navigation" and is not a reload.
366
+ page.on("domcontentloaded", () => navigations.push({ at: Date.now(), url: page.url() }));
367
+ page.on("pageerror", (error) => consoleErrors.push({ type: "pageerror", text: String(error).slice(0, 600) }));
368
+ await page.evaluateOnNewDocument(installProbe);
369
+
370
+ // Start on a same-origin document so the renderer process (and the V8 isolate the profiler is attached to)
371
+ // stays the same when the scenario navigates to the game.
372
+ const origin = new URL(targetUrl).origin;
373
+ await page.goto(`${origin}/favicon.ico`, { waitUntil: "load" }).catch(() => page.goto("about:blank"));
374
+
375
+ const session = await page.createCDPSession();
376
+ await session.send("Profiler.enable");
377
+ await session.send("Profiler.setSamplingInterval", { interval: Number(flags.interval || DEFAULT_SAMPLING_INTERVAL_US) });
378
+ const heapEnabled = flags.heap !== "false";
379
+ const heapIncludesCollected = heapEnabled ? await startHeapSampling(session) : false;
380
+ const stopTrace = flags.trace === "true" ? await startTrace(session, path.join(runDir, "trace.json")) : null;
381
+ await session.send("Profiler.start");
382
+ const syncEpochMs = await runSyncMarker(page);
383
+ const snapshots = flags.snapshots === "true";
384
+ const stopFilmstrip = snapshots ? await startFilmstrip(session, runDir, Number(flags["filmstrip-interval"] || 1)) : null;
385
+
386
+ // The allocation sampler has no timestamps, so it is restarted at every phase mark: one profile per phase
387
+ // (heap/<index>-<phase>.heapprofile) separates load-time buffers from per-frame garbage.
388
+ const heapDir = path.join(runDir, "heap");
389
+ if (heapEnabled) fs.mkdirSync(heapDir, { recursive: true });
390
+ let heapPhase = "start";
391
+ let heapIndex = 0;
392
+ const rotateHeap = async (nextPhase) => {
393
+ if (!heapEnabled) return;
394
+ const { profile: phaseProfile } = await session.send("HeapProfiler.stopSampling");
395
+ const safeName = heapPhase.replace(/[^\w+.-]+/g, "_");
396
+ fs.writeFileSync(path.join(heapDir, `${String(heapIndex).padStart(2, "0")}-${safeName}.heapprofile`), JSON.stringify(phaseProfile));
397
+ heapIndex++;
398
+ heapPhase = nextPhase;
399
+ if (nextPhase !== "end") await startHeapSampling(session);
400
+ };
401
+ const context = createScenarioContext(page, targetUrl, shotsDir, parseScenarioArguments(flags.args), log, snapshots, rotateHeap);
402
+ const maxSeconds = Number(flags.seconds || DEFAULT_MAX_SECONDS);
403
+ let scenarioError = null;
404
+ let timedOut = false;
405
+ try {
406
+ await Promise.race([
407
+ scenario.run(context),
408
+ sleep(maxSeconds).then(() => { timedOut = true; }),
409
+ ]);
410
+ } catch (error) {
411
+ scenarioError = String(error && error.stack ? error.stack : error);
412
+ log(`scenario failed: ${scenarioError.split("\n")[0]}`);
413
+ }
414
+ if (timedOut) log(`scenario still running after --seconds ${maxSeconds}; stopping the capture there`);
415
+ await context.mark("end").catch(() => {});
416
+
417
+ const filmstrip = stopFilmstrip ? await stopFilmstrip() : [];
418
+ const { profile } = await session.send("Profiler.stop");
419
+ fs.writeFileSync(path.join(runDir, "cpu.cpuprofile"), JSON.stringify(profile));
420
+ if (heapEnabled && heapPhase !== "end") await rotateHeap("end");
421
+ if (stopTrace) await stopTrace();
422
+ const probe = await page.evaluate(() => (window.__btProfile ? window.__btProfile.dump() : null));
423
+ if (probe) {
424
+ const recorded = new Set(probe.marks.map((mark) => mark.name));
425
+ for (const mark of context.nodeMarks) if (!recorded.has(mark.name)) probe.marks.push({ ...mark, fromNode: true });
426
+ probe.marks.sort((first, second) => first.at - second.at);
427
+ }
428
+ const census = await page.evaluate(() => (window.__btProfile ? window.__btProfile.census() : null)).catch(() => null);
429
+ if (snapshots) await page.screenshot({ path: path.join(shotsDir, "end.png") }).catch(() => {});
430
+ const scripts = await saveProfiledScripts(session, profile, scriptsDir);
431
+ await session.detach();
432
+ await page.close();
433
+
434
+ const capture = {
435
+ label,
436
+ url: targetUrl,
437
+ scenario: scenario.meta,
438
+ scenarioOptions: context.options,
439
+ scenarioError,
440
+ timedOut,
441
+ capturedAt: new Date().toISOString(),
442
+ browser: await browser.version(),
443
+ platform: `${os.platform()} ${os.release()} ${os.arch()}`,
444
+ viewport: { width: Number(flags.width || 1600), height: Number(flags.height || 900), deviceScaleFactor },
445
+ samplingIntervalUs: Number(flags.interval || DEFAULT_SAMPLING_INTERVAL_US),
446
+ heapIncludesCollected,
447
+ snapshots,
448
+ filmstripFrames: filmstrip.length,
449
+ sync: { markerName: SYNC_MARKER_NAME, epochMs: syncEpochMs },
450
+ census,
451
+ probe,
452
+ scripts: scripts.length,
453
+ consoleErrors: consoleErrors.slice(0, 60),
454
+ disturbed: disturbance(context, navigations, devServerUpdates, probe),
455
+ wallSeconds: +((Date.now() - startedAt) / 1000).toFixed(1),
456
+ };
457
+ fs.writeFileSync(path.join(runDir, "capture.json"), JSON.stringify(capture));
458
+ if (capture.disturbed) log(`WARNING: ${capture.disturbed.reason} — this capture is not comparable; profile a server with file watching off (SKILL.md › Other sessions)`);
459
+ log(`done: ${probe ? probe.frames.length : 0} frames, ${profile.samples.length} CPU samples, ${scripts.length} scripts, engine ${probe && probe.engine}`);
460
+ return capture;
461
+ }
462
+
463
+ /**
464
+ * Entry point: launches Chrome, runs the cold capture and, with --warm true, a warm one in the same browser.
465
+ */
466
+ async function main() {
467
+ const flags = parseArguments(process.argv.slice(2));
468
+ // The slug's config (in the working folder, `.agents/profile/<slug>/data`) supplies the URL and scenario by default.
469
+ const configPath = path.resolve("profile.config.json");
470
+ const config = fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, "utf8")) : {};
471
+ if (!flags.url && config.url) flags.url = config.url;
472
+ if (!flags.scenario && config.scenario) flags.scenario = config.scenario;
473
+ if (!flags.url) throw new Error("Pass --url <game URL>, e.g. --url http://localhost:5173/play");
474
+ if (!flags.out) throw new Error("Pass --out <run folder>");
475
+ const runDir = path.resolve(flags.out);
476
+ fs.mkdirSync(runDir, { recursive: true });
477
+ const scenario = await loadScenario(flags.scenario);
478
+ const width = Number(flags.width || 1600);
479
+ const height = Number(flags.height || 900);
480
+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "bt-profile-chrome-"));
481
+ const args = [
482
+ "--use-angle=metal", "--enable-gpu", "--ignore-gpu-blocklist", "--enable-unsafe-webgpu",
483
+ "--disable-background-timer-throttling", "--disable-renderer-backgrounding", "--disable-backgrounding-occluded-windows",
484
+ "--enable-precise-memory-info", `--window-size=${width},${height}`,
485
+ ];
486
+ // Audio: by default it may start without a user gesture, so it starts during the load. `--autoplay gesture` keeps a real
487
+ // browser's rule — audio stays locked until the first key or click — when the slow moment may be the audio unlock itself.
488
+ if (flags.autoplay !== "gesture") args.push("--autoplay-policy=no-user-gesture-required");
489
+ if (flags.uncapped === "true") args.push("--disable-frame-rate-limit", "--disable-gpu-vsync");
490
+ const browser = await puppeteer.launch({
491
+ executablePath: findChrome(),
492
+ headless: flags.headed === "true" ? false : "new",
493
+ defaultViewport: null,
494
+ userDataDir,
495
+ args,
496
+ });
497
+ try {
498
+ const cold = await captureOnce(browser, flags, scenario, path.join(runDir, "cold"), "cold");
499
+ const summary = { runDir, cold: path.join(runDir, "cold") };
500
+ if (flags.warm === "true") {
501
+ await captureOnce(browser, flags, scenario, path.join(runDir, "warm"), "warm");
502
+ summary.warm = path.join(runDir, "warm");
503
+ }
504
+ if (cold.probe && cold.probe.engine == null) process.stderr.write("WARNING: the probe never found a Babylon engine (window.BABYLON.EngineStore). Frame data is empty.\n");
505
+ if (cold.census && /swiftshader|llvmpipe|software/i.test(cold.census.adapter || "")) process.stderr.write("WARNING: Chrome rendered with a software adapter — GPU numbers are not representative.\n");
506
+ fs.writeFileSync(path.join(runDir, "run.json"), JSON.stringify({ ...summary, flags, scenario: scenario.meta }, null, 2));
507
+ process.stdout.write(JSON.stringify(summary) + "\n");
508
+ } finally {
509
+ await browser.close();
510
+ fs.rmSync(userDataDir, { recursive: true, force: true });
511
+ }
512
+ }
513
+
514
+ main().catch((error) => {
515
+ process.stderr.write(String(error && error.stack ? error.stack : error) + "\n");
516
+ process.exit(1);
517
+ });