@a2f0/agent-tool 0.1.71 → 0.1.73

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 CHANGED
@@ -5,9 +5,10 @@ where Claude Code, Codex, OpenCode, or Hermes make the changes. It provides shar
5
5
  GitHub, review, validation, and release workflows: independent agent reviews of
6
6
  a committed branch, guarded pushes and squash merges of the exact reviewed
7
7
  commit, package versioning, brand image rendering, screenshot staging with a
8
- framework-free gallery, a live SEO probe for websites, and compact output for
9
- noisy commands. Repository policy stays in `agent-tool.json`; the portable skills
10
- coordinate independently reviewed changes.
8
+ framework-free gallery, safe disk cleanup, page-load measurement, a live SEO
9
+ probe for websites, and compact output for noisy commands. Repository policy
10
+ stays in `agent-tool.json`; the portable skills coordinate independently
11
+ reviewed changes.
11
12
 
12
13
  ## Quick start
13
14
 
@@ -83,8 +84,8 @@ validation suite, and release procedures.
83
84
  aggregate gates, release verification, durable validation receipts, and
84
85
  toolchain/protection diagnostics.
85
86
  - [CLI reference](docs/reference.md): existing review, version, skill installation,
86
- command capture, the SEO probe, import-graph checks, configuration, and
87
- distribution contracts.
87
+ command capture, disk cleanup, page performance, the SEO probe, import-graph
88
+ checks, configuration, and distribution contracts.
88
89
  - [Development](docs/development.md): setup, source layout, validation, and release
89
90
  procedures for this package.
90
91
  - [Images](docs/images.md): declarative brand sources and generated outputs.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a2f0/agent-tool",
3
- "version": "0.1.71",
3
+ "version": "0.1.73",
4
4
  "packageManager": "bun@1.4.4",
5
5
  "type": "module",
6
6
  "description": "Portable cross-agent review, PR workflows, and shared skills",
@@ -43,6 +43,7 @@
43
43
  "@happy-dom/global-registrator": "21.0.4",
44
44
  "@types/bun": "1.4.4",
45
45
  "happy-dom": "21.0.4",
46
+ "playwright": "1.64.1",
46
47
  "typescript": "7.0.2"
47
48
  },
48
49
  "dependencies": {
@@ -0,0 +1,107 @@
1
+ ---
2
+ name: performance-pass
3
+ description: Make a page or embedded viewer load faster without changing what it shows, in measured rounds that each ship through ship-pr, then carry the release to every consumer. Use when the user asks to speed up loading, startup, or first render, or to dogfood a performance round; not for changing visual quality, content, or features.
4
+ ---
5
+
6
+ # Performance Pass
7
+
8
+ A pass is a few rounds. Each round measures, changes one thing, proves the
9
+ output is unchanged, measures again, and ships. Numbers decide what lands;
10
+ impressions do not. What the page shows is fixed: a faster load that changes a
11
+ pixel, a mesh, or a behaviour is a regression, not a win.
12
+
13
+ ## The measuring command
14
+
15
+ `agent-tool perf` runs the measurements; run the repository's pinned
16
+ agent-tool (`bun run agent-tool perf` or `node_modules/.bin/agent-tool perf`).
17
+ It drives Chrome through the measured repository's own `playwright`, found
18
+ from the working directory or `--from <directory>` inside the checkout it
19
+ runs in, and never fetches one.
20
+ From a matrix workspace, measure a checkout with
21
+ `agent-tool perf <command> --from checkouts/<name>`. If the pinned agent-tool
22
+ predates the command, run `bunx --bun @a2f0/agent-tool@latest perf`.
23
+
24
+ | Command | Does |
25
+ | --- | --- |
26
+ | `serve <dir> [--port N] [--http1]` | Serves a production build over HTTP/2 with gzip (compressed before the first request) and ETag revalidation, as a CDN does, never following links out of the directory. Start it with `agent-tool proc start --label serve -- node_modules/.bin/agent-tool perf serve <dir>` and stop it with `agent-tool proc stop`. |
27
+ | `measure <url> --ready <js>` | Cold, cache-disabled loads timed from the start of navigation (it waits only for the commit, never the `load` event); prints the median time until the `--ready` expression is true, requests, bytes, when the finished requests ended, and how many were still pending. `--waterfall` lists requests; `--profile` adds the first run's CPU self and inclusive times; `--json` prints the report as JSON. |
28
+ | `shot <url> --ready <js> --out <png>` | Screenshot of the ready state with a seeded `Math.random`, for fidelity diffs. `--eval <js>` runs an interaction first (switch a mode on); `--hide <css>` hides random decoration, reaching into open shadow roots. |
29
+ | `diff <a.png> <b.png>` | Counts differing pixels, and the busiest 50-pixel cells, without a browser; exits 1 on any. |
30
+ | `graph <dir> <entry...> [--out <file>]` | Relative static and dynamic import closure of ES modules, as JSON. |
31
+
32
+ Defaults: 5 runs, 40 ms latency, 20 Mbps, no CPU slowdown, 1600x900. Always
33
+ also measure a slow profile, `--latency 150 --mbps 5 --cpu 4`, since a
34
+ phone's CPU, not the network, is often what remains.
35
+
36
+ ## Procedure
37
+
38
+ 1. Scope. Name the pages, the ready signal (what "usable" means: first frame
39
+ drawn, `aria-busy` cleared, a hydration flag), and every consumer that
40
+ embeds the package. Read each repository's guidance first; it decides
41
+ validation, versioning, and shipping.
42
+ 2. Baseline. Build the production output from the base commit into a scratch
43
+ copy (`git archive <base> | tar -x -C <dir>`, link `node_modules`), serve
44
+ it, and measure both profiles with `--waterfall --profile`. Check the live
45
+ deployment's headers with `curl -sSI -H 'Accept-Encoding: br, gzip'`
46
+ (compression, `cache-control`, HTTP version): local serving only stands in
47
+ for them.
48
+ 3. Read the time. Split ready time into network (request chain depth, bytes,
49
+ queueing) and main thread (the CPU profile's inclusive table). A waterfall
50
+ whose requests start in steps is a dependency chain; a long tail after
51
+ `network done` is CPU.
52
+ 4. Choose one change, safest first:
53
+ - Transport: preload hints for a known module graph, fewer chained
54
+ requests, compression, cache headers. Output cannot change.
55
+ - Deferral: build what the first frame does not show (hidden modes, unused
56
+ layers) on first use instead of at startup. The first frame must be
57
+ identical, and the deferred feature must still work when first used.
58
+ - Same-output speedups: faster algorithms, fewer allocations, typed arrays,
59
+ reused buffers. Prove byte-identical output (geometry arrays, generated
60
+ files), not just "looks the same".
61
+ - Never, unless the user asks: lower resolution, level of detail,
62
+ sampling, lossy re-encoding, removing content, or changing a bundler or
63
+ vendored engine against repository guidance.
64
+ 5. Prove fidelity. Run the repository's own pixel, geometry, and browser
65
+ suites, and `shot` + `diff` the ready state of base and change at the same
66
+ viewport. First diff two base shots against each other: if the page is
67
+ not deterministic even when seeded, say which regions vary and compare
68
+ with that in mind, never by loosening the repository's own thresholds.
69
+ 6. Measure again with the same commands and runs. Keep the change only when
70
+ both medians improve beyond the base's own min-max spread; report both
71
+ profiles' before and after medians and network-done times.
72
+ 7. Ship with `ship-pr` in that repository, the measurements in the PR body.
73
+ Then, for each consumer, bump to the published version with its own
74
+ `ship-pr`, and measure the consumer's page the same way when it can be
75
+ served locally.
76
+ 8. Learn. Repository-specific findings (what dominated, what was tried and
77
+ rejected and why) go in that repository's agent guidance or skill.
78
+ Cross-repository lessons go in agent-tool's
79
+ `skills/performance-pass/references/lessons.md`, by PR there. Next round
80
+ starts from step 3 with the new profile.
81
+
82
+ ## Pitfalls
83
+
84
+ - Serve over HTTP/2. Browsers open six HTTP/1.1 connections per host, so a
85
+ plain local server queues a module graph that a CDN serves at once, and
86
+ makes preload changes look worthless.
87
+ - Compress once per file, not per request: a server compressing on every
88
+ request adds its own CPU time to the waterfall.
89
+ - Preload links that hosts' pages receive must go in the document head (not
90
+ a shadow root) and should be removed once loading settles; skip assets a
91
+ host replaces, such as a shared engine.
92
+ - Medians of one or two runs are noise; run at least five, seven for a
93
+ close call. Check `uptime` first: other sessions' test suites inflate the
94
+ CPU-throttled profile most. Under load, interleave base and change runs,
95
+ and back a CPU change with `--profile`, comparing the changed function's
96
+ inclusive time against what remains, rather than wall medians alone.
97
+ - Deferring work is only output-neutral if nothing the deferred work reads
98
+ changes before it runs. Find every writer of its inputs and make it run
99
+ before the first one, then test a deferred instance against an eager one
100
+ step by step.
101
+
102
+ ## Ownership
103
+
104
+ agent-tool (`a2f0/agent-tool`) owns this skill at `skills/performance-pass/`
105
+ and the command at `src/perf/`, with its tests beside it; `agent-tool skills
106
+ install --apply` installs it in each adopting repository. Change it there,
107
+ never in an installed copy.
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "Performance Pass"
3
+ short_description: "Speed up loading in measured rounds without changing output"
4
+ default_prompt: "Use $performance-pass to make this page load faster without changing what it shows: measure, change one thing, prove fidelity, measure again, and ship."
@@ -0,0 +1,30 @@
1
+ # Performance lessons
2
+
3
+ Cross-repository findings from performance passes, newest first. Each names
4
+ the repository and PR it came from; recheck before relying on one.
5
+
6
+ ## Layers that change nothing until used can wait for first use
7
+
8
+ skyline built its colour-trial layer, which reads every vertex of every
9
+ building, before the first frame, though its shaders install only when colour,
10
+ a previewed time or a celebration is used. Making it on first use (and before
11
+ a celebration rewrites the greys it reads) took its 160 to 270 ms off the
12
+ first frame, pixel-identical in seven before/after interaction shots.
13
+
14
+ ## Unbundled ES module graphs pay one round trip per import level
15
+
16
+ skyline (a2f0/skyline) ships tsc output without a bundler, so the viewer's
17
+ first frame waited on a chain seven requests deep. Listing the graph at build
18
+ time and preloading it with `modulepreload` from the mounting code moved
19
+ network-done from 1471 to 833 ms and the ready median from 2369 to 1763 ms at
20
+ 40 ms / 20 Mbps (5204 to 4514 ms on the slow profile), pixel-identical with
21
+ the random stars hidden. Generate the list from the built files so it cannot
22
+ drift, leave out modules the host may replace, and expect a host-bundle size
23
+ budget to need room for the preloading code.
24
+
25
+ ## Seeded randomness still drifts when load order changes
26
+
27
+ Three.js draws object UUIDs from `Math.random`, so a seeded page that builds
28
+ its scene earlier or later relative to random decoration (skyline's stars)
29
+ shows that decoration elsewhere. Hide the decoration with `shot --hide` and
30
+ diff the rest; two base shots must still diff to zero first.
@@ -66,9 +66,12 @@ lists the page's internal links that do not answer 200 directly; and
66
66
  `--sitemap` checks every sitemap URL's status, canonical, and robots, and
67
67
  reports duplicate titles and descriptions. The mode flag comes first, the
68
68
  host is a hostname with an optional port, and each path starts with `/`. The
69
- probe matches with regular expressions, so confirm anything surprising in the
70
- raw response before acting on it. Set `SEO_PROBE_USER_AGENT` to a browser user
71
- agent to see what a zone injects only for browsers.
69
+ probe matches text patterns rather than parsing HTML, so confirm anything
70
+ surprising in the raw response before acting on it. A `000` status means no
71
+ response, including a URL it refused to request: one that is not HTTP or
72
+ HTTPS, or one on a private or local address that a page or redirect, not the
73
+ command line, named. Set `SEO_PROBE_USER_AGENT` to a browser user agent to see
74
+ what a zone injects only for browsers.
72
75
 
73
76
  Check whether the default branch already has merged work that has not been
74
77
  deployed, because a deploy ships it too. Deployment listings often do not
@@ -0,0 +1,96 @@
1
+ ---
2
+ name: space-cleanup
3
+ description: Free disk space safely in a repository, across a matrix workspace and its checkouts, or in this machine's developer caches, by removing only regenerable, git-ignored output after a dry run. Use when the disk is low, `bun run health` asks for space, a command fails with ENOSPC, or the user asks to clean up space; not for deleting clones, branches, or anyone's work.
4
+ ---
5
+
6
+ # Space Cleanup
7
+
8
+ Free space by removing what a command can rebuild, never what a person made.
9
+ Measure first, remove the cheapest tier that frees enough, and report what
10
+ was freed from the volume's real free space, not from the estimate.
11
+
12
+ ## Run it
13
+
14
+ `agent-tool space` does the work; run the repository's pinned agent-tool
15
+ (`bun run agent-tool space` or `node_modules/.bin/agent-tool space`). It is a
16
+ dry run until `--apply`.
17
+
18
+ - In a repository: `agent-tool space [path...] [flags]`. With no paths it
19
+ covers only the repository holding the working directory; each path names
20
+ the repository holding it.
21
+ - From a matrix workspace (`matrix.json` beside `checkouts/`):
22
+ `agent-tool space [checkout...] [flags]`. With no names it covers the
23
+ workspace and every checkout in `checkouts/`; names are checkout names or
24
+ `owner/name`.
25
+ - If the pinned agent-tool predates the command, run
26
+ `bunx --bun @a2f0/agent-tool@latest space`.
27
+
28
+ Caches are always included; each other flag adds its own tier independently:
29
+
30
+ | Flag | Removes | Cost to restore |
31
+ | --- | --- | --- |
32
+ | (default) | Caches: `.turbo`, `.parcel-cache`, `.eslintcache`, `.stylelintcache`, `coverage`, `.nyc_output`, test reports (`test-results`, `playwright-report`, `blob-report`), Python caches (`__pycache__`, `.pytest_cache`, `.mypy_cache`, `.ruff_cache`), `node_modules/.cache` and `.vite`, `.next/cache`, `.wrangler/tmp` | Next run is slower |
33
+ | `--builds` | Build output: `dist`, `build`, `out`, `.next`, `.nuxt`, `.output`, `.svelte-kit`, `.expo`, `.gradle`, `.build`, `DerivedData`, Rust `target`, `*.tsbuildinfo` | The repository's build |
34
+ | `--deps` | `node_modules`, `.venv`, CocoaPods `Pods`, `vendor/bundle` | The repository's documented install |
35
+ | `--machine` | Xcode DerivedData (not its `SourcePackages` clones), `brew cleanup`, Bun and npm caches, `pnpm store prune` | Re-downloads and rebuilds |
36
+
37
+ `--json` gives agents the same report, and the command exits 1 when a
38
+ repository could not be scanned or a removal failed, 2 when it cannot run at
39
+ all (an unknown option, or processes that cannot be listed).
40
+ `--include-busy` cleans repositories other processes are working in; use it
41
+ only after confirming those processes are your own or finished. It never
42
+ applies to `--machine` items, which always wait for running installs and Xcode
43
+ builds.
44
+
45
+ ## Procedure
46
+
47
+ 1. Check the volume: `df -h .` (on macOS, `df -h /System/Volumes/Data`). Note
48
+ how much the task needs; matrix sweeps want 50 GiB free.
49
+ 2. Run the dry run with `--builds --deps --machine` to see every tier's size,
50
+ then choose the cheapest set of tiers that frees enough. Default caches
51
+ alone are always fine to apply.
52
+ 3. Apply with only the chosen flags plus `--apply`. Read the `Free: before ->
53
+ after` line; APFS clones and hard links mean freed space can be far less
54
+ than the listed sizes, and Time Machine local snapshots can hold it until
55
+ macOS thins them.
56
+ 4. After `--deps`, reinstall dependencies in each cleaned repository that will
57
+ be used next, with its documented setup, so hooks and `status` keep
58
+ working. Deleting `node_modules` also deletes the pinned agent-tool, so
59
+ where setup runs `bun run agent-tool bun install`, first bootstrap with the
60
+ repository's pinned Bun: `bun install --frozen-lockfile`.
61
+ After `--builds`, nothing is needed: the next build regenerates output.
62
+ 5. Report the before and after free space, the tiers applied, repositories
63
+ skipped as busy, and the `review` items from `--machine` with their sizes,
64
+ so the user can decide about them.
65
+
66
+ ## Safety rules
67
+
68
+ The command enforces these; keep them when cleaning by hand:
69
+
70
+ - Remove a repository path only when git reports it ignored, nothing under it
71
+ is tracked (rechecked just before removal), its name is on the tier's list,
72
+ nothing under it is a repository, `.env` file, `.secrets`, or SQLite
73
+ database, and neither it nor any parent inside the repository is a symlink. Untracked files that are not ignored
74
+ belong to someone: never remove them.
75
+ - Never run `git clean` (`-X` included), `rm -rf` on a whole ignored tree, or
76
+ delete `.env*`, `.secrets`, `.wrangler/state`, local databases, or anything
77
+ under `../matrix-secrets`.
78
+ - Skip a repository another process is working in (a dev server, a test run,
79
+ another agent session). Idle shells and the session running the command do
80
+ not count. When processes cannot be listed, the command stops instead of
81
+ guessing.
82
+ - Never delete clones, worktrees, branches, stashes, Docker data, Gradle
83
+ caches, simulator devices (unavailable ones included: they keep app data),
84
+ or iOS DeviceSupport on your own: the `--machine`
85
+ report lists the large ones as `review` for the user to decide.
86
+ - Package caches wait while an install runs, and DerivedData waits for Xcode.
87
+ - In a matrix workspace, cleaning ignored output does not change any
88
+ checkout's git state, so it is not a sweep and needs no ledger; a checkout's
89
+ `status` need not be `ready`.
90
+
91
+ ## Ownership
92
+
93
+ agent-tool (`a2f0/agent-tool`) owns this skill at `skills/space-cleanup/` and
94
+ the command at `src/space/`, with its tests beside it; `agent-tool skills
95
+ install --apply` installs it in each adopting repository. Change it there,
96
+ never in an installed copy.
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "Space Cleanup"
3
+ short_description: "Free disk space by removing regenerable output safely"
4
+ default_prompt: "Use $space-cleanup to free disk space here: dry run first, then remove only the tiers needed."
package/src/cli.ts CHANGED
@@ -8,6 +8,8 @@ import { checkGraph } from "./graph/check";
8
8
  import { stateMachinesCommand } from "./stateMachines/command";
9
9
  import { seoCommand } from "./seo/probe";
10
10
  import { buildScreenshots, describeScreenshots } from "./screenshots/build";
11
+ import { spaceCommand } from "./space/command";
12
+ import { perfCommand } from "./perf/command";
11
13
  import { review } from "./harnesses";
12
14
  import { carryReviewCommand } from "./review/carry";
13
15
  import { runAgentToolAction } from "./runAgentToolAction";
@@ -92,6 +94,10 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
92
94
  graph check Import cycles and layer violations per agent-tool.json
93
95
  state-machines [path...] [--limit N] [--min-score N] [--json] Rank files that look like implicit state machines
94
96
  seo probe [--page|--headers|--links|--sitemap] <host> [path...] Live search and preview metadata of a site
97
+ space [checkout-or-path...] [--builds] [--deps] [--machine] [--include-busy] [--apply] [--json]
98
+ Regenerable, git-ignored output and developer caches; dry run until --apply
99
+ perf serve <dir> | measure <url> | shot <url> --out <png> | diff <a.png> <b.png> | graph <dir> <entry...>
100
+ Page load timing, seeded screenshots, and pixel diffs; perf --help lists options
95
101
  init Create agent-tool.json without overwriting
96
102
  config show
97
103
  doctor JSON versions and supported review flags
@@ -191,6 +197,8 @@ export function main(argv = process.argv.slice(2)): number | Promise<number> {
191
197
  }
192
198
  if (command === "state-machines") return stateMachinesCommand(args, process.cwd(), undefined, invoked);
193
199
  if (command === "seo") return seoCommand(args);
200
+ if (command === "space") return spaceCommand(args);
201
+ if (command === "perf") return perfCommand(args);
194
202
  if (command === "skills") {
195
203
  const action = args.shift();
196
204
  if (action === "list") { usage(args.length === 0, "Usage: agent-tool skills list"); output(Object.keys(BUNDLED_SKILLS)); return 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
+ }