@a2f0/agent-tool 0.1.72 → 0.1.74
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 +10 -8
- package/package.json +2 -1
- package/skills/performance-pass/SKILL.md +107 -0
- package/skills/performance-pass/agents/openai.yaml +4 -0
- package/skills/performance-pass/references/lessons.md +30 -0
- package/skills/space-cleanup/SKILL.md +96 -0
- package/skills/space-cleanup/agents/openai.yaml +4 -0
- package/skills/take-screenshots/SKILL.md +103 -0
- package/skills/take-screenshots/agents/openai.yaml +4 -0
- package/skills/take-screenshots/references/adding-capture.md +121 -0
- package/src/cli.ts +14 -1
- package/src/perf/browser.ts +269 -0
- package/src/perf/command.ts +82 -0
- package/src/perf/diff.ts +115 -0
- package/src/perf/graph.ts +110 -0
- package/src/perf/options.ts +107 -0
- package/src/perf/serve.ts +163 -0
- package/src/permissions/catalog.ts +6 -1
- package/src/screenshots/build.ts +4 -3
- package/src/screenshots/store/capture.ts +317 -0
- package/src/screenshots/store/clones.ts +145 -0
- package/src/screenshots/store/command.ts +317 -0
- package/src/screenshots/store/git.ts +14 -0
- package/src/screenshots/store/link.ts +201 -0
- package/src/screenshots/store/lock.ts +94 -0
- package/src/screenshots/store/namespace.ts +311 -0
- package/src/screenshots/store/record.ts +157 -0
- package/src/screenshots/store/store.ts +47 -0
- package/src/screenshots/store/targets.ts +68 -0
- package/src/skills/bundled.ts +14 -0
- package/src/space/candidates.ts +228 -0
- package/src/space/command.ts +325 -0
- package/src/space/machine.ts +303 -0
- package/src/space/processes.ts +186 -0
- package/src/space/targets.ts +24 -0
- package/src/system/checkouts.ts +135 -0
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `perf measure` and `perf shot`: cold loads and seeded screenshots in Chrome,
|
|
3
|
+
* driven through the measured repository's own `playwright`. Playwright is
|
|
4
|
+
* imported for its types only, which Bun erases, so agent-tool needs no
|
|
5
|
+
* Playwright of its own at run time.
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
8
|
+
import { createRequire } from "node:module";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import type { Browser, BrowserContext, BrowserType, Page } from "playwright";
|
|
11
|
+
import { toplevel } from "../system/checkouts";
|
|
12
|
+
import type { Options } from "./options";
|
|
13
|
+
|
|
14
|
+
/** Median and spread of repeated samples; the median is what rounds compare. */
|
|
15
|
+
export function summarize(samples: number[]): { median: number; min: number; max: number; runs: number } {
|
|
16
|
+
if (samples.length === 0) throw new Error("No samples.");
|
|
17
|
+
const sorted = [...samples].sort((a, b) => a - b);
|
|
18
|
+
const middle = sorted.length >> 1;
|
|
19
|
+
const median = sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;
|
|
20
|
+
return { median: Math.round(median), min: sorted[0]!, max: sorted.at(-1)!, runs: sorted.length };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// A deterministic Math.random for screenshots, so randomly placed decoration matches between rounds.
|
|
24
|
+
const SEED_SCRIPT = "{ let s = 0x2545f491; Math.random = () => { s ^= s << 13; s ^= s >>> 17; s ^= s << 5; return (s >>> 0) / 4294967296; }; }";
|
|
25
|
+
|
|
26
|
+
/** Whether a URL names this machine, as `perf serve`'s do. */
|
|
27
|
+
export function loopback(url: string): boolean {
|
|
28
|
+
try {
|
|
29
|
+
return ["127.0.0.1", "localhost", "[::1]"].includes(new URL(url).hostname);
|
|
30
|
+
} catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Whether `child` is `parent` or inside it. */
|
|
36
|
+
function within(child: string, parent: string): boolean {
|
|
37
|
+
const relative = path.relative(parent, child);
|
|
38
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The `playwright` entry the measured repository installs: the nearest
|
|
43
|
+
* `node_modules/playwright` at or above `from`, searching no higher than the
|
|
44
|
+
* checkout holding the working directory. `from` must be inside that checkout
|
|
45
|
+
* (a matrix workspace's checkouts are inside it), so the command never loads
|
|
46
|
+
* Playwright from an arbitrary directory, and never through Bun's
|
|
47
|
+
* auto-install, which fetches the newest release when no node_modules is found.
|
|
48
|
+
*/
|
|
49
|
+
export function installedPlaywright(from: string, cwd = process.cwd()): string | undefined {
|
|
50
|
+
const top = toplevel(cwd);
|
|
51
|
+
if (!top) throw new Error("agent-tool perf measures from the measured repository's checkout; run it inside one.");
|
|
52
|
+
const boundary = realpathSync(top);
|
|
53
|
+
if (!existsSync(path.resolve(cwd, from))) throw new Error(`--from ${from} does not exist.`);
|
|
54
|
+
const start = realpathSync(path.resolve(cwd, from));
|
|
55
|
+
if (!within(start, boundary)) throw new Error(`--from ${from} is outside the checkout ${boundary}; run agent-tool perf from the checkout that holds it.`);
|
|
56
|
+
for (let directory = start; ; directory = path.dirname(directory)) {
|
|
57
|
+
if (existsSync(path.join(directory, "node_modules", "playwright", "package.json"))) {
|
|
58
|
+
let resolved: string;
|
|
59
|
+
try {
|
|
60
|
+
resolved = createRequire(path.join(directory, "package.json")).resolve("playwright");
|
|
61
|
+
} catch {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
// Resolution can fall through to NODE_PATH or a global folder; only an install inside the checkout counts,
|
|
65
|
+
// including a linker's store such as node_modules/.bun or .pnpm at the workspace root.
|
|
66
|
+
return within(realpathSync(resolved), boundary) ? resolved : undefined;
|
|
67
|
+
}
|
|
68
|
+
if (directory === boundary || path.dirname(directory) === directory) return undefined;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function chromium(from = process.cwd()): Promise<Browser> {
|
|
73
|
+
const resolved = installedPlaywright(from);
|
|
74
|
+
if (!resolved) {
|
|
75
|
+
throw new Error(
|
|
76
|
+
`agent-tool perf drives Chrome through the measured repository's \`playwright\`, which ${path.resolve(from)} does not install; run it there or pass --from <repository>.`,
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
const playwright = (await import(resolved)) as { chromium?: BrowserType; default?: { chromium?: BrowserType } };
|
|
80
|
+
const browserType = playwright.chromium ?? playwright.default?.chromium;
|
|
81
|
+
if (!browserType) throw new Error(`${resolved} does not export Playwright's chromium; reinstall the measured repository's playwright.`);
|
|
82
|
+
// Playwright's default launch, which runs Chrome without its sandbox: measure only pages you trust.
|
|
83
|
+
return browserType.launch({ channel: "chrome", args: ["--ignore-gpu-blocklist", "--enable-gpu"] });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
interface Request {
|
|
87
|
+
url: string;
|
|
88
|
+
start: number;
|
|
89
|
+
end?: number;
|
|
90
|
+
bytes?: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The parts of a CDP CPU profile node that profileTable reads. */
|
|
94
|
+
interface ProfileNode {
|
|
95
|
+
id: number;
|
|
96
|
+
callFrame: { functionName: string; url: string; lineNumber: number };
|
|
97
|
+
children?: number[];
|
|
98
|
+
}
|
|
99
|
+
interface CpuProfile {
|
|
100
|
+
nodes: ProfileNode[];
|
|
101
|
+
samples?: number[];
|
|
102
|
+
timeDeltas?: number[];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Opens the page and returns once its navigation commits, so a ready signal that comes before
|
|
107
|
+
* the `load` event is timed when it comes, and slow unrelated assets cannot hold the wait.
|
|
108
|
+
*/
|
|
109
|
+
export function navigate(page: { goto(url: string, options: { waitUntil: "commit" }): Promise<unknown> }, url: string): Promise<unknown> {
|
|
110
|
+
return page.goto(url, { waitUntil: "commit" });
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function load(
|
|
114
|
+
browser: Browser,
|
|
115
|
+
url: string,
|
|
116
|
+
options: Options,
|
|
117
|
+
capture: { profile?: boolean; seed?: boolean } = {},
|
|
118
|
+
): Promise<{ page: Page; context: BrowserContext; ready: number; requests: Request[]; profile?: CpuProfile }> {
|
|
119
|
+
// The local server's certificate is self-signed.
|
|
120
|
+
// `perf serve`'s certificate is self-signed. Playwright's setting covers the whole context, so a loopback page's
|
|
121
|
+
// other requests skip the check too; a page on any other host is checked as usual.
|
|
122
|
+
const context = await browser.newContext({ viewport: { width: options.width, height: options.height }, ignoreHTTPSErrors: loopback(url) });
|
|
123
|
+
try {
|
|
124
|
+
if (capture.seed) await context.addInitScript(SEED_SCRIPT);
|
|
125
|
+
const page = await context.newPage();
|
|
126
|
+
const cdp = await context.newCDPSession(page);
|
|
127
|
+
await cdp.send("Network.enable");
|
|
128
|
+
await cdp.send("Network.setCacheDisabled", { cacheDisabled: true });
|
|
129
|
+
if (options.latency > 0 || options.mbps > 0) {
|
|
130
|
+
await cdp.send("Network.emulateNetworkConditions", {
|
|
131
|
+
offline: false,
|
|
132
|
+
latency: options.latency,
|
|
133
|
+
downloadThroughput: options.mbps > 0 ? options.mbps * 125_000 : -1,
|
|
134
|
+
uploadThroughput: -1,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
if (options.cpu > 1) await cdp.send("Emulation.setCPUThrottlingRate", { rate: options.cpu });
|
|
138
|
+
const requests = new Map<string, Request>();
|
|
139
|
+
// A redirect repeats requestWillBeSent with the same id; the request started at its first hop.
|
|
140
|
+
cdp.on("Network.requestWillBeSent", event => {
|
|
141
|
+
const first = requests.get(event.requestId);
|
|
142
|
+
requests.set(event.requestId, { url: event.request.url, start: first?.start ?? event.timestamp });
|
|
143
|
+
});
|
|
144
|
+
cdp.on("Network.loadingFinished", event => {
|
|
145
|
+
const request = requests.get(event.requestId);
|
|
146
|
+
if (request) Object.assign(request, { end: event.timestamp, bytes: event.encodedDataLength });
|
|
147
|
+
});
|
|
148
|
+
if (capture.profile) {
|
|
149
|
+
await cdp.send("Profiler.enable");
|
|
150
|
+
await cdp.send("Profiler.setSamplingInterval", { interval: 200 });
|
|
151
|
+
await cdp.send("Profiler.start");
|
|
152
|
+
}
|
|
153
|
+
const started = performance.now();
|
|
154
|
+
await navigate(page, url);
|
|
155
|
+
await page.waitForFunction(options.ready, null, { timeout: 180_000, polling: 20 });
|
|
156
|
+
const ready = Math.round(performance.now() - started);
|
|
157
|
+
// Copied at ready: requests that finish while the profile stops or the context closes are not part of the load.
|
|
158
|
+
const atReady = [...requests.values()].map(request => ({ ...request }));
|
|
159
|
+
const profile = capture.profile ? (await cdp.send("Profiler.stop")).profile : undefined;
|
|
160
|
+
return { page, context, ready, requests: atReady, profile };
|
|
161
|
+
} catch (error) {
|
|
162
|
+
await context.close();
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Self and inclusive milliseconds per function from a CPU profile, heaviest first. */
|
|
168
|
+
export function profileTable(profile: CpuProfile, limit = 25) {
|
|
169
|
+
const nodes = new Map(profile.nodes.map(node => [node.id, node]));
|
|
170
|
+
const parent = new Map<number, number>();
|
|
171
|
+
for (const node of profile.nodes) for (const child of node.children ?? []) parent.set(child, node.id);
|
|
172
|
+
const name = (node: ProfileNode) =>
|
|
173
|
+
`${node.callFrame.functionName || "(anonymous)"} ${node.callFrame.url.split("/").slice(-2).join("/")}${node.callFrame.url ? `:${node.callFrame.lineNumber + 1}` : ""}`;
|
|
174
|
+
const self = new Map<string, number>(),
|
|
175
|
+
total = new Map<string, number>();
|
|
176
|
+
(profile.samples ?? []).forEach((id, index) => {
|
|
177
|
+
const time = (profile.timeDeltas?.[index] ?? 0) / 1000;
|
|
178
|
+
self.set(name(nodes.get(id)!), (self.get(name(nodes.get(id)!)) ?? 0) + time);
|
|
179
|
+
const counted = new Set<string>();
|
|
180
|
+
for (let current: number | undefined = id; current !== undefined; current = parent.get(current)) {
|
|
181
|
+
const label = name(nodes.get(current)!);
|
|
182
|
+
if (counted.has(label)) continue;
|
|
183
|
+
counted.add(label);
|
|
184
|
+
total.set(label, (total.get(label) ?? 0) + time);
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
const top = (map: Map<string, number>) =>
|
|
188
|
+
[...map]
|
|
189
|
+
.sort((a, b) => b[1] - a[1])
|
|
190
|
+
.slice(0, limit)
|
|
191
|
+
.map(([fn, ms]) => ({ fn, ms: Math.round(ms * 10) / 10 }));
|
|
192
|
+
return { self: top(self), inclusive: top(total) };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Times cold loads of `options.args[0]` and reports them; `measure` prints the report. */
|
|
196
|
+
export async function measureLoad(options: Options) {
|
|
197
|
+
const url = options.args[0];
|
|
198
|
+
if (!url) throw new Error("measure needs a URL.");
|
|
199
|
+
const browser = await chromium(options.from);
|
|
200
|
+
try {
|
|
201
|
+
const samples: number[] = [];
|
|
202
|
+
let first: { requests: Request[]; profile: CpuProfile | undefined } | undefined;
|
|
203
|
+
// The profiler slows the load it records, so --profile adds an unsampled run of its own.
|
|
204
|
+
let profile: CpuProfile | undefined;
|
|
205
|
+
if (options.profile) {
|
|
206
|
+
const profiled = await load(browser, url, options, { profile: true, seed: options.seed });
|
|
207
|
+
profile = profiled.profile;
|
|
208
|
+
await profiled.context.close();
|
|
209
|
+
}
|
|
210
|
+
for (let run = 0; run < options.runs; run += 1) {
|
|
211
|
+
const result = await load(browser, url, options, { seed: options.seed });
|
|
212
|
+
samples.push(result.ready);
|
|
213
|
+
first ??= { requests: result.requests, profile };
|
|
214
|
+
await result.context.close();
|
|
215
|
+
}
|
|
216
|
+
const requests = first!.requests;
|
|
217
|
+
const origin = Math.min(...requests.map(request => request.start));
|
|
218
|
+
const report = {
|
|
219
|
+
url,
|
|
220
|
+
conditions: { latencyMs: options.latency, mbps: options.mbps || "unthrottled", cpuSlowdown: options.cpu, viewport: `${options.width}x${options.height}` },
|
|
221
|
+
readyMs: summarize(samples),
|
|
222
|
+
samples,
|
|
223
|
+
requests: requests.length,
|
|
224
|
+
transferredBytes: requests.reduce((sum, request) => sum + (request.bytes ?? 0), 0),
|
|
225
|
+
networkDoneMs: Math.round((Math.max(origin, ...requests.flatMap(request => (request.end === undefined ? [] : [request.end]))) - origin) * 1000),
|
|
226
|
+
// Requests still loading, or failed, when the page was ready: network-done excludes them.
|
|
227
|
+
pendingRequests: requests.filter(request => request.end === undefined).length,
|
|
228
|
+
waterfall: options.waterfall
|
|
229
|
+
? requests
|
|
230
|
+
.sort((a, b) => a.start - b.start)
|
|
231
|
+
.map(request => ({
|
|
232
|
+
start: Math.round((request.start - origin) * 1000),
|
|
233
|
+
end: request.end === undefined ? null : Math.round((request.end - origin) * 1000),
|
|
234
|
+
bytes: request.bytes ?? null,
|
|
235
|
+
path: request.url.replace(/^https?:\/\/[^/]+/, ""),
|
|
236
|
+
}))
|
|
237
|
+
: undefined,
|
|
238
|
+
cpu: first!.profile ? profileTable(first!.profile) : undefined,
|
|
239
|
+
};
|
|
240
|
+
return report;
|
|
241
|
+
} finally {
|
|
242
|
+
await browser.close();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export async function shot(options: Options): Promise<void> {
|
|
247
|
+
const url = options.args[0];
|
|
248
|
+
if (!url || !options.out) throw new Error("shot needs a URL and --out <png>.");
|
|
249
|
+
const browser = await chromium(options.from);
|
|
250
|
+
try {
|
|
251
|
+
const result = await load(browser, url, { ...options, latency: 0, mbps: 0, cpu: 1 }, { seed: options.seed });
|
|
252
|
+
// An interaction to compare after, such as switching a mode on; it may return a promise.
|
|
253
|
+
if (options.eval) await result.page.evaluate(options.eval);
|
|
254
|
+
// Let a frame or two settle after the ready signal or the interaction.
|
|
255
|
+
await result.page.waitForTimeout(500);
|
|
256
|
+
// Decoration that is random by design, hidden by a CSS selector that reaches into open shadow roots.
|
|
257
|
+
if (options.hide)
|
|
258
|
+
await result.page.locator(options.hide).evaluateAll((elements: HTMLElement[]) =>
|
|
259
|
+
elements.forEach(element => {
|
|
260
|
+
element.style.visibility = "hidden";
|
|
261
|
+
}),
|
|
262
|
+
);
|
|
263
|
+
await result.page.screenshot({ path: options.out, animations: "disabled" });
|
|
264
|
+
await result.context.close();
|
|
265
|
+
console.log(`Wrote ${options.out}`);
|
|
266
|
+
} finally {
|
|
267
|
+
await browser.close();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** `agent-tool perf`: measures how fast a page becomes usable; PERF_USAGE lists the commands. */
|
|
2
|
+
import { writeFileSync, writeSync } from "node:fs";
|
|
3
|
+
import { measureLoad, shot } from "./browser";
|
|
4
|
+
import { compareImages } from "./diff";
|
|
5
|
+
import { moduleGraph } from "./graph";
|
|
6
|
+
import { type Options, PERF_USAGE, parseOptions } from "./options";
|
|
7
|
+
import { serve } from "./serve";
|
|
8
|
+
|
|
9
|
+
const print = (text: string) => {
|
|
10
|
+
writeSync(1, `${text}\n`);
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
async function measure(options: Options): Promise<void> {
|
|
14
|
+
const report = await measureLoad(options);
|
|
15
|
+
if (options.json) {
|
|
16
|
+
print(JSON.stringify(report, null, 2));
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
const { url, readyMs } = report;
|
|
20
|
+
print(`${url} ready median ${readyMs.median} ms (min ${readyMs.min}, max ${readyMs.max}, ${readyMs.runs} runs)`);
|
|
21
|
+
print(
|
|
22
|
+
` ${report.requests} requests, ${report.transferredBytes} bytes, network done at ${report.networkDoneMs} ms${report.pendingRequests ? ` (${report.pendingRequests} still pending)` : ""}; ${JSON.stringify(report.conditions)}`,
|
|
23
|
+
);
|
|
24
|
+
for (const row of report.waterfall ?? [])
|
|
25
|
+
print(` ${String(row.start).padStart(6)} ${String(row.end ?? "-").padStart(6)} ${String(row.bytes ?? "").padStart(8)} ${row.path}`);
|
|
26
|
+
if (report.cpu) {
|
|
27
|
+
printCpuRows("self", report.cpu.self);
|
|
28
|
+
printCpuRows("inclusive", report.cpu.inclusive);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function printCpuRows(title: string, rows: { fn: string; ms: number }[]): void {
|
|
33
|
+
print(` CPU ${title} (ms):`);
|
|
34
|
+
for (const row of rows) print(` ${row.ms.toFixed(1).padStart(8)} ${row.fn}`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Runs one perf command. `serve` returns once it is listening and keeps the
|
|
39
|
+
* process alive; `diff` exits 1 when any pixel differs. Usage errors throw.
|
|
40
|
+
*/
|
|
41
|
+
export async function perfCommand(argv: string[]): Promise<number> {
|
|
42
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
43
|
+
print(PERF_USAGE);
|
|
44
|
+
return 0;
|
|
45
|
+
}
|
|
46
|
+
const options = parseOptions(argv);
|
|
47
|
+
switch (options.command) {
|
|
48
|
+
case "serve": {
|
|
49
|
+
if (!options.args[0]) throw new Error("serve needs a directory.");
|
|
50
|
+
const server = serve(options.args[0], options.port, options.http1);
|
|
51
|
+
// Listening keeps the process alive; a port already in use ends it with 1.
|
|
52
|
+
return new Promise(resolve => {
|
|
53
|
+
server.once("listening", () => resolve(0));
|
|
54
|
+
server.once("error", () => resolve(1));
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
case "measure":
|
|
58
|
+
await measure(options);
|
|
59
|
+
return 0;
|
|
60
|
+
case "shot":
|
|
61
|
+
await shot(options);
|
|
62
|
+
return 0;
|
|
63
|
+
case "diff": {
|
|
64
|
+
const result = compareImages(options);
|
|
65
|
+
print(JSON.stringify(result));
|
|
66
|
+
return result.differing === 0 ? 0 : 1;
|
|
67
|
+
}
|
|
68
|
+
case "graph": {
|
|
69
|
+
const [root, ...entries] = options.args;
|
|
70
|
+
if (!root || entries.length === 0) throw new Error("graph needs a directory and at least one entry.");
|
|
71
|
+
const graph = moduleGraph(root, entries);
|
|
72
|
+
if (options.out) writeFileSync(options.out, `${JSON.stringify(graph, null, 2)}\n`);
|
|
73
|
+
print(JSON.stringify(graph));
|
|
74
|
+
return 0;
|
|
75
|
+
}
|
|
76
|
+
case "help":
|
|
77
|
+
print(PERF_USAGE);
|
|
78
|
+
return 0;
|
|
79
|
+
default:
|
|
80
|
+
throw new Error(`Unknown perf command '${options.command}'.\n\n${PERF_USAGE}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
package/src/perf/diff.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/** `perf diff`: pixel differences between two PNG screenshots, without a browser. */
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { inflateSync } from "node:zlib";
|
|
4
|
+
import type { Options } from "./options";
|
|
5
|
+
|
|
6
|
+
/** An 8-bit RGB or RGBA, non-interlaced PNG, as Chrome writes screenshots, decoded to RGBA. */
|
|
7
|
+
function decodePng(file: Buffer): { width: number; height: number; data: Uint8Array } {
|
|
8
|
+
const { width, height, channels, compressed } = readPngChunks(file);
|
|
9
|
+
const raw = inflateSync(compressed);
|
|
10
|
+
if (raw.length !== (width * channels + 1) * height) throw new Error("The PNG's image data is truncated or the wrong size.");
|
|
11
|
+
const pixels = unfilterRows(raw, width, height, channels);
|
|
12
|
+
return { width, height, data: toRgba(pixels, width * height, channels) };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The header fields and concatenated image data of a PNG, rejecting formats `decodePng` cannot read. */
|
|
16
|
+
function readPngChunks(file: Buffer): { width: number; height: number; channels: number; compressed: Buffer } {
|
|
17
|
+
if (file.subarray(0, 8).toString("hex") !== "89504e470d0a1a0a") throw new Error("Not a PNG.");
|
|
18
|
+
let header = { width: 0, height: 0, channels: 0 };
|
|
19
|
+
const chunks: Buffer[] = [];
|
|
20
|
+
for (let at = 8; at < file.length; ) {
|
|
21
|
+
const length = file.readUInt32BE(at),
|
|
22
|
+
type = file.toString("latin1", at + 4, at + 8),
|
|
23
|
+
body = file.subarray(at + 8, at + 8 + length);
|
|
24
|
+
if (type === "IHDR") header = pngHeader(body);
|
|
25
|
+
else if (type === "IDAT") chunks.push(body);
|
|
26
|
+
at += 12 + length;
|
|
27
|
+
}
|
|
28
|
+
return { ...header, compressed: Buffer.concat(chunks) };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The size and channel count an IHDR chunk gives, rejecting what `decodePng` cannot read. */
|
|
32
|
+
function pngHeader(body: Buffer): { width: number; height: number; channels: number } {
|
|
33
|
+
const width = body.readUInt32BE(0);
|
|
34
|
+
const height = body.readUInt32BE(4);
|
|
35
|
+
const [depth, colour, , , interlace] = [body[8], body[9], body[10], body[11], body[12]];
|
|
36
|
+
const channels = colour === 6 ? 4 : colour === 2 ? 3 : 0;
|
|
37
|
+
if (depth !== 8 || !channels || interlace !== 0) throw new Error("Only 8-bit RGB or RGBA, non-interlaced PNGs are supported.");
|
|
38
|
+
return { width, height, channels };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Reverses each scanline's filter, giving `channels` bytes per pixel. */
|
|
42
|
+
function unfilterRows(raw: Buffer, width: number, height: number, channels: number): Uint8Array {
|
|
43
|
+
const stride = width * channels;
|
|
44
|
+
const pixels = new Uint8Array(stride * height);
|
|
45
|
+
for (let y = 0; y < height; y += 1) unfilterRow(raw, pixels, y, stride, channels);
|
|
46
|
+
return pixels;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Reverses scanline `y`'s filter into `pixels`, reading the already decoded row above. */
|
|
50
|
+
function unfilterRow(raw: Buffer, pixels: Uint8Array, y: number, stride: number, channels: number): void {
|
|
51
|
+
const filter = raw[y * (stride + 1)]!,
|
|
52
|
+
row = y * stride;
|
|
53
|
+
if (filter > 4) throw new Error(`Unknown PNG row filter ${filter}.`);
|
|
54
|
+
for (let x = 0; x < stride; x += 1) {
|
|
55
|
+
const value = raw[y * (stride + 1) + 1 + x]!;
|
|
56
|
+
const left = x >= channels ? pixels[row + x - channels]! : 0,
|
|
57
|
+
up = y ? pixels[row - stride + x]! : 0;
|
|
58
|
+
const corner = x >= channels && y ? pixels[row - stride + x - channels]! : 0;
|
|
59
|
+
pixels[row + x] = (value + predictor(filter, left, up, corner)) & 255;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The byte a PNG filter type predicts from the left, upper and upper-left neighbours. */
|
|
64
|
+
function predictor(filter: number, left: number, up: number, corner: number): number {
|
|
65
|
+
if (filter === 1) return left;
|
|
66
|
+
if (filter === 2) return up;
|
|
67
|
+
if (filter === 3) return (left + up) >> 1;
|
|
68
|
+
if (filter !== 4) return 0;
|
|
69
|
+
const estimate = left + up - corner,
|
|
70
|
+
a = Math.abs(estimate - left),
|
|
71
|
+
b = Math.abs(estimate - up),
|
|
72
|
+
c = Math.abs(estimate - corner);
|
|
73
|
+
return a <= b && a <= c ? left : b <= c ? up : corner;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Widens RGB or RGBA pixels to RGBA, opaque where the image has no alpha. */
|
|
77
|
+
function toRgba(pixels: Uint8Array, count: number, channels: number): Uint8Array {
|
|
78
|
+
const data = new Uint8Array(count * 4);
|
|
79
|
+
for (let pixel = 0; pixel < count; pixel += 1) {
|
|
80
|
+
for (let c = 0; c < channels; c += 1) data[pixel * 4 + c] = pixels[pixel * channels + c]!;
|
|
81
|
+
if (channels === 3) data[pixel * 4 + 3] = 255;
|
|
82
|
+
}
|
|
83
|
+
return data;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Counts the pixels that differ between two PNG screenshots; `diff` prints the result. */
|
|
87
|
+
export function compareImages(options: Options) {
|
|
88
|
+
const [a, b] = options.args;
|
|
89
|
+
if (!a || !b) throw new Error("diff needs two PNG paths.");
|
|
90
|
+
const x = decodePng(readFileSync(a)),
|
|
91
|
+
y = decodePng(readFileSync(b));
|
|
92
|
+
if (x.width !== y.width || x.height !== y.height)
|
|
93
|
+
return { sizeMismatch: true, differing: -1, total: 0, maxChannelDelta: 255, cells: [] as { at: string; pixels: number }[] };
|
|
94
|
+
// Differences per 50-pixel cell, so a few moved stars read differently from a changed building.
|
|
95
|
+
const CELL = 50,
|
|
96
|
+
cells = new Map<string, number>();
|
|
97
|
+
let differing = 0,
|
|
98
|
+
maxChannelDelta = 0;
|
|
99
|
+
for (let i = 0; i < x.data.length; i += 4) {
|
|
100
|
+
let pixel = 0;
|
|
101
|
+
for (let c = 0; c < 4; c += 1) pixel = Math.max(pixel, Math.abs(x.data[i + c]! - y.data[i + c]!));
|
|
102
|
+
if (pixel > 0) {
|
|
103
|
+
differing += 1;
|
|
104
|
+
const index = i / 4,
|
|
105
|
+
key = `${Math.floor((index % x.width) / CELL) * CELL},${Math.floor(index / x.width / CELL) * CELL}`;
|
|
106
|
+
cells.set(key, (cells.get(key) ?? 0) + 1);
|
|
107
|
+
}
|
|
108
|
+
maxChannelDelta = Math.max(maxChannelDelta, pixel);
|
|
109
|
+
}
|
|
110
|
+
const busiest = [...cells]
|
|
111
|
+
.sort((first, second) => second[1] - first[1])
|
|
112
|
+
.slice(0, 20)
|
|
113
|
+
.map(([at, pixels]) => ({ at, pixels }));
|
|
114
|
+
return { sizeMismatch: false, differing, total: x.width * x.height, maxChannelDelta, cells: busiest };
|
|
115
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/** `perf graph`: the relative import closure of ES modules, for preload lists generated from built files. */
|
|
2
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The source with comments blanked and every string literal's contents replaced by a
|
|
7
|
+
* placeholder, keeping its quotes, so a scan for imports sees neither commented-out imports nor
|
|
8
|
+
* text that only looks like one. Specifiers are kept in `strings`, indexed by placeholder.
|
|
9
|
+
* Regular expression literals are not recognised: a quote inside one can hide later imports.
|
|
10
|
+
*/
|
|
11
|
+
function tokens(source: string): { code: string; strings: string[] } {
|
|
12
|
+
let code = "",
|
|
13
|
+
i = 0;
|
|
14
|
+
const strings: string[] = [];
|
|
15
|
+
while (i < source.length) {
|
|
16
|
+
const char = source[i]!;
|
|
17
|
+
const skipped = comment(source, i);
|
|
18
|
+
if (skipped) {
|
|
19
|
+
code += skipped.text;
|
|
20
|
+
i = skipped.end;
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
if (char === "'" || char === '"' || char === "`") {
|
|
24
|
+
const literal = stringLiteral(source, i);
|
|
25
|
+
code += `${char}${strings.length}${char}`;
|
|
26
|
+
strings.push(literal.text);
|
|
27
|
+
i = literal.end;
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
code += char;
|
|
31
|
+
i += 1;
|
|
32
|
+
}
|
|
33
|
+
return { code, strings };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The comment starting at `start`, if one does: the index just past it (a line comment's newline stays) and what replaces it in the code. */
|
|
37
|
+
function comment(source: string, start: number): { end: number; text: string } | undefined {
|
|
38
|
+
if (source[start] !== "/") return undefined;
|
|
39
|
+
if (source[start + 1] === "/") {
|
|
40
|
+
const end = source.indexOf("\n", start);
|
|
41
|
+
return { end: end < 0 ? source.length : end, text: "" };
|
|
42
|
+
}
|
|
43
|
+
if (source[start + 1] !== "*") return undefined;
|
|
44
|
+
const end = source.indexOf("*/", start + 2);
|
|
45
|
+
return { end: end < 0 ? source.length : end + 2, text: " " };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The contents of the string literal whose quote is at `start`, escapes kept, and the index just past its closing quote. */
|
|
49
|
+
function stringLiteral(source: string, start: number): { text: string; end: number } {
|
|
50
|
+
const quote = source[start];
|
|
51
|
+
let j = start + 1,
|
|
52
|
+
text = "";
|
|
53
|
+
while (j < source.length && source[j] !== quote) {
|
|
54
|
+
if (source[j] === "\\") {
|
|
55
|
+
text += source[j]! + (source[j + 1] ?? "");
|
|
56
|
+
j += 2;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
text += source[j]!;
|
|
60
|
+
j += 1;
|
|
61
|
+
}
|
|
62
|
+
return { text, end: j + 1 };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Relative imports of an ES module's source: static `import`/`export from`, bare `import "x"`, and literal `import("x")`. */
|
|
66
|
+
export function importsOf(source: string): string[] {
|
|
67
|
+
const { code, strings } = tokens(source);
|
|
68
|
+
const found = new Set<string>();
|
|
69
|
+
const patterns = [
|
|
70
|
+
/(?:^|[^\w$.])(?:import|export)\b[^;'"`]*?\bfrom\s*["'](\d+)["']/g,
|
|
71
|
+
/(?:^|[^\w$.])import\s*["'](\d+)["']/g,
|
|
72
|
+
/(?:^|[^\w$.])import\s*\(\s*["'](\d+)["']\s*\)/g,
|
|
73
|
+
];
|
|
74
|
+
for (const pattern of patterns)
|
|
75
|
+
for (const match of code.matchAll(pattern)) {
|
|
76
|
+
const specifier = strings[Number(match[1])]!;
|
|
77
|
+
if (specifier.startsWith(".")) found.add(specifier);
|
|
78
|
+
}
|
|
79
|
+
return [...found];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Every module reachable from the entries through relative imports, as paths within `root`, entries first. */
|
|
83
|
+
export function moduleGraph(root: string, entries: string[]): string[] {
|
|
84
|
+
const seen = new Set<string>();
|
|
85
|
+
let base: string;
|
|
86
|
+
try {
|
|
87
|
+
base = realpathSync(root);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
throw new Error(`Cannot read ${root}: ${(error as NodeJS.ErrnoException).code ?? (error as Error).message}.`);
|
|
90
|
+
}
|
|
91
|
+
const walk = (rel: string, from: string | undefined) => {
|
|
92
|
+
const where = from === undefined ? `entry ${rel}` : `${rel}, imported by ${from}`;
|
|
93
|
+
if (rel === ".." || rel.startsWith("../") || path.posix.isAbsolute(rel)) throw new Error(`The graph leaves ${root} at ${where}.`);
|
|
94
|
+
if (seen.has(rel)) return;
|
|
95
|
+
seen.add(rel);
|
|
96
|
+
let source: string;
|
|
97
|
+
try {
|
|
98
|
+
// A symbolic link inside the directory can lead out of it, as `..` can.
|
|
99
|
+
const real = realpathSync(path.join(root, rel));
|
|
100
|
+
if (!real.startsWith(`${base}${path.sep}`)) throw new Error(`The graph leaves ${root} at ${where}, through a symbolic link.`);
|
|
101
|
+
source = readFileSync(real, "utf8");
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (!(error as NodeJS.ErrnoException).code) throw error;
|
|
104
|
+
throw new Error(`Cannot read ${where}: ${(error as NodeJS.ErrnoException).code}.`);
|
|
105
|
+
}
|
|
106
|
+
for (const spec of importsOf(source)) walk(path.posix.normalize(path.posix.join(path.posix.dirname(rel), spec)), rel);
|
|
107
|
+
};
|
|
108
|
+
for (const entry of entries) walk(path.posix.normalize(entry), undefined);
|
|
109
|
+
return [...seen];
|
|
110
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/** `agent-tool perf` arguments: a command, its positional arguments, and its measuring conditions. */
|
|
2
|
+
|
|
3
|
+
export const PERF_USAGE = `Usage: agent-tool perf <command> [args...] [options]
|
|
4
|
+
|
|
5
|
+
Measures how fast a page becomes usable, so a performance pass compares
|
|
6
|
+
rounds by numbers rather than impressions. Chrome is driven through the
|
|
7
|
+
measured repository's own \`playwright\` dependency, found from the working
|
|
8
|
+
directory or --from <repository>.
|
|
9
|
+
|
|
10
|
+
serve <dir> [--port 8765] [--http1] serve a production build, compressed, revalidating
|
|
11
|
+
measure <url> --ready <js> [...] cold loads: median time to ready, requests, bytes
|
|
12
|
+
--waterfall, --profile, --json
|
|
13
|
+
shot <url> --ready <js> --out <png> a seeded screenshot of the ready state; --eval <js>, --hide <css>
|
|
14
|
+
diff <a.png> <b.png> count differing pixels between two screenshots; exit 1 on any
|
|
15
|
+
graph <dir> <entry...> [--out file] an ES module's relative static and dynamic imports
|
|
16
|
+
|
|
17
|
+
Conditions: --runs 5, --latency 40 (ms), --mbps 20, --cpu 1 (slowdown),
|
|
18
|
+
--width 1600, --height 900; --no-seed leaves Math.random unseeded.`;
|
|
19
|
+
|
|
20
|
+
export interface Options {
|
|
21
|
+
command: string;
|
|
22
|
+
args: string[];
|
|
23
|
+
ready: string;
|
|
24
|
+
runs: number;
|
|
25
|
+
latency: number;
|
|
26
|
+
mbps: number;
|
|
27
|
+
cpu: number;
|
|
28
|
+
width: number;
|
|
29
|
+
height: number;
|
|
30
|
+
port: number;
|
|
31
|
+
out: string | undefined;
|
|
32
|
+
hide: string | undefined;
|
|
33
|
+
eval: string | undefined;
|
|
34
|
+
from: string | undefined;
|
|
35
|
+
waterfall: boolean;
|
|
36
|
+
profile: boolean;
|
|
37
|
+
json: boolean;
|
|
38
|
+
seed: boolean;
|
|
39
|
+
http1: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type NumberOption = "runs" | "latency" | "mbps" | "cpu" | "width" | "height" | "port";
|
|
43
|
+
type StringOption = "ready" | "out" | "hide" | "eval" | "from";
|
|
44
|
+
type FlagOption = "waterfall" | "profile" | "json" | "seed" | "http1";
|
|
45
|
+
const NUMBERS = new Set<string>(["runs", "latency", "mbps", "cpu", "width", "height", "port"] satisfies NumberOption[]);
|
|
46
|
+
const STRINGS = new Set<string>(["ready", "out", "hide", "eval", "from"] satisfies StringOption[]);
|
|
47
|
+
const FLAGS = new Set<string>(["waterfall", "profile", "json", "seed", "http1"] satisfies FlagOption[]);
|
|
48
|
+
const isNumber = (name: string): name is NumberOption => NUMBERS.has(name);
|
|
49
|
+
const isString = (name: string): name is StringOption => STRINGS.has(name);
|
|
50
|
+
const isFlag = (name: string): name is FlagOption => FLAGS.has(name);
|
|
51
|
+
|
|
52
|
+
export function parseOptions(argv: string[]): Options {
|
|
53
|
+
const options: Options = {
|
|
54
|
+
command: argv[0] ?? "help",
|
|
55
|
+
args: [],
|
|
56
|
+
ready: "document.readyState === 'complete'",
|
|
57
|
+
runs: 5,
|
|
58
|
+
latency: 40,
|
|
59
|
+
mbps: 20,
|
|
60
|
+
cpu: 1,
|
|
61
|
+
width: 1600,
|
|
62
|
+
height: 900,
|
|
63
|
+
port: 8765,
|
|
64
|
+
out: undefined,
|
|
65
|
+
hide: undefined,
|
|
66
|
+
eval: undefined,
|
|
67
|
+
from: undefined,
|
|
68
|
+
waterfall: false,
|
|
69
|
+
profile: false,
|
|
70
|
+
json: false,
|
|
71
|
+
seed: true,
|
|
72
|
+
http1: false,
|
|
73
|
+
};
|
|
74
|
+
for (let i = 1; i < argv.length; i += 1) i = readArgument(options, argv, i);
|
|
75
|
+
if (options.runs < 1) throw new Error("--runs needs at least 1.");
|
|
76
|
+
for (const name of ["runs", "width", "height", "port"] as const) if (!Number.isInteger(options[name])) throw new Error(`--${name} needs a whole number.`);
|
|
77
|
+
if (options.width < 1 || options.height < 1) throw new Error("--width and --height need at least 1.");
|
|
78
|
+
if (options.port > 65535) throw new Error("--port needs a port number, at most 65535.");
|
|
79
|
+
return options;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Applies the argument at `index` to `options`, returning the index of the last argument it used. */
|
|
83
|
+
function readArgument(options: Options, argv: string[], index: number): number {
|
|
84
|
+
const arg = argv[index]!;
|
|
85
|
+
if (!arg.startsWith("--")) {
|
|
86
|
+
options.args.push(arg);
|
|
87
|
+
return index;
|
|
88
|
+
}
|
|
89
|
+
const name = arg.slice(2);
|
|
90
|
+
if (name === "no-seed") options.seed = false;
|
|
91
|
+
else if (isFlag(name)) options[name] = true;
|
|
92
|
+
else if (isNumber(name) || isString(name)) {
|
|
93
|
+
setValue(options, name, arg, argv[index + 1]);
|
|
94
|
+
return index + 1;
|
|
95
|
+
} else throw new Error(`Unknown option ${arg}.`);
|
|
96
|
+
return index;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Stores the value that follows a `--name` option, as a number where the option takes one. */
|
|
100
|
+
function setValue(options: Options, name: NumberOption | StringOption, arg: string, value: string | undefined): void {
|
|
101
|
+
if (value === undefined) throw new Error(`${arg} needs a value.`);
|
|
102
|
+
if (isNumber(name)) {
|
|
103
|
+
const number = Number(value);
|
|
104
|
+
if (!Number.isFinite(number) || number < 0) throw new Error(`${arg} needs a non-negative number.`);
|
|
105
|
+
options[name] = number;
|
|
106
|
+
} else options[name] = value;
|
|
107
|
+
}
|