@booki-aui/readiness 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1169 @@
1
+ import {
2
+ PERSON_ACTION,
3
+ SECRET_LABEL,
4
+ findSecrets
5
+ } from "./chunk-5SCOA3ZP.js";
6
+
7
+ // src/rules.ts
8
+ var RULES = {
9
+ "bridge-missing": {
10
+ id: "bridge-missing",
11
+ title: "No agent bridge on the page",
12
+ contract: "\xA72 Bridge, \xA74.1",
13
+ severity: "critical",
14
+ why: "Without a bridge (snapshot, act, subscribe) an agent has to read the accessibility tree, guess which element is which and click or type into it. That is where the cost, the time and the wrong postings come from.",
15
+ fix: "Expose the screen's controls through an agent bridge: each control with a name, its state as values and its named actions. With ui-sdk, create the agent once and register its tools for browser agents (WebMCP).",
16
+ booki: "createBookiAgent() + registerTools() from @booki-aui/react",
17
+ points: 25,
18
+ cap: 25
19
+ },
20
+ "bridge-unnamed-control": {
21
+ id: "bridge-unnamed-control",
22
+ title: "Bridge control without a name",
23
+ contract: "\xA73.1",
24
+ severity: "serious",
25
+ why: "An agent addresses a bridge control by its label. One without a label can only be reached by its ref, which changes between page loads, so the agent has to snapshot and guess.",
26
+ fix: "Give the control an aria-label or a visible label the bridge reads.",
27
+ booki: "Every Booki control takes aria-label and reports it as its label",
28
+ points: 4,
29
+ cap: 12
30
+ },
31
+ "bridge-person-action": {
32
+ id: "bridge-person-action",
33
+ title: "A person's decision is offered to the agent",
34
+ contract: "\xA75.1",
35
+ severity: "critical",
36
+ why: "Approving, rejecting, releasing, finalizing, submitting and signing off are a person's decisions. Offered as an agent action, an agent can take them, and the audit trail records an approval nobody gave.",
37
+ fix: "Remove the action from the agent's list. Keep the decision as a person's button whose handler requires a real input event, and refuse it on the server for agent callers.",
38
+ booki: "ApprovalChain, AttestationStatus, PaymentBatch, CloseChecklist (person-only buttons); @booki-aui/core/server guards (PERSON_ONLY)",
39
+ points: 15,
40
+ cap: 30
41
+ },
42
+ "field-unnamed": {
43
+ id: "field-unnamed",
44
+ title: "Field without an accessible name",
45
+ contract: "\xA73.1, \xA74.1",
46
+ severity: "serious",
47
+ why: "The agent sees only a role (textbox, listbox, combobox) with no name, so it can find the field only by where it sits among others. One row off and the amount lands in the wrong field or the wrong account.",
48
+ fix: 'Name every field: a <label for>, aria-labelledby pointing at the visible column header, or aria-label. In tables, include the row ("Line 2 amount").',
49
+ points: 5,
50
+ cap: 30
51
+ },
52
+ "field-broken-name": {
53
+ id: "field-broken-name",
54
+ title: "Field named by a rendering bug",
55
+ contract: "\xA73.1",
56
+ severity: "serious",
57
+ why: `The accessible name is a programming artefact such as "[object Object]" or "undefined". The agent reads it as the field's name and cannot tell what the field is.`,
58
+ fix: "Render the label text, not the object. Check that aria-label receives a string.",
59
+ points: 5,
60
+ cap: 15
61
+ },
62
+ "field-ambiguous": {
63
+ id: "field-ambiguous",
64
+ title: "Fields that share one name",
65
+ contract: "\xA73.1, \xA74.1",
66
+ severity: "moderate",
67
+ why: "Several fields of the same role carry the same name, so the name does not say which one to use. The agent has to count positions, and the count changes as rows are added.",
68
+ fix: 'Make each name unique on the page: add the row or section ("Debit account, line 2").',
69
+ booki: "VoucherComposer: one control, lines changed by index through named actions",
70
+ points: 2,
71
+ cap: 8
72
+ },
73
+ "field-not-on-bridge": {
74
+ id: "field-not-on-bridge",
75
+ title: "Field missing from the bridge",
76
+ contract: "\xA73.1, \xA74.1",
77
+ severity: "serious",
78
+ why: "The page has a bridge, and a person can use this field, but the bridge's snapshot has no entry for it. An agent working through the bridge does not know the field exists; to set it, it has to fall back to the accessibility tree and click, and a page that otherwise looks ready hides the gap.",
79
+ fix: "Put the field on the bridge: build it from a bridge-registered control (with ui-sdk, its Select, RadioGroup, Checkbox or Input; with Booki, the matching control) instead of a plain element, so it appears in snapshot() with its label and actions. A field that should stay with the person goes inside data-agent-hidden.",
80
+ booki: "AccountPicker, TaxCodeSelect, CurrencySelect, AccountingPeriodSelect, AmountField; ui-sdk Select, RadioGroup, Checkbox",
81
+ points: 5,
82
+ cap: 30
83
+ },
84
+ "focusable-without-role": {
85
+ id: "focusable-without-role",
86
+ title: "Focusable element that is not a control",
87
+ contract: "\xA73.1, \xA74.1",
88
+ severity: "serious",
89
+ why: "A person can tab to it or click it, and something happens (an editor opens, a value changes), but the accessibility tree calls it a cell or plain text. An agent does not see a field there: it has to click by position and hope an editor appears.",
90
+ fix: 'Use a real control (an input in the cell, a button) or give the element the role it plays (gridcell in a role=grid, button) with a name. Grid editors: role="grid" with named gridcells, or an input per cell labelled by its column header and row.',
91
+ booki: "VoucherComposer, InvoiceEditor, DataTable",
92
+ points: 3,
93
+ cap: 12
94
+ },
95
+ "button-unnamed": {
96
+ id: "button-unnamed",
97
+ title: "Button without a name",
98
+ contract: "\xA73.1, \xA74.1",
99
+ severity: "serious",
100
+ why: 'The agent sees "button" and nothing else. It has to press it to learn what it does.',
101
+ fix: "Give the button visible text or an aria-label that says what it does.",
102
+ points: 3,
103
+ cap: 12
104
+ },
105
+ "button-icon-name": {
106
+ id: "button-icon-name",
107
+ title: "Button named by an icon font",
108
+ contract: "\xA73.1, \xA74.1",
109
+ severity: "moderate",
110
+ why: `An icon font draws the icon from a ligature, so the button's accessible name is the ligature ("close", "content_copy"). The agent reads a developer's word in English on a screen in the person's language, and "close" may delete a line.`,
111
+ fix: 'Hide the icon from assistive technology (aria-hidden="true" on the glyph) and name the button by what it does (aria-label="Delete line 2").',
112
+ points: 2,
113
+ cap: 10
114
+ },
115
+ "chart-pixels-only": {
116
+ id: "chart-pixels-only",
117
+ title: "Figures only in pixels",
118
+ contract: "\xA73.3",
119
+ severity: "serious",
120
+ why: "The chart is a canvas or an SVG with no name and no figures in the DOM. An agent can read it only from a screenshot or by hovering for tooltips, month by month, and guesses the month from where the pointer is.",
121
+ fix: "Put the figures in the DOM: an accessible name that states them, a table next to the chart (it may be visually hidden), or chart parts as buttons named by their value. On a bridge, expose the series as state.",
122
+ booki: "TrendChart, BarChart, AgingChart, CashflowWaterfall, KpiStat",
123
+ points: 10,
124
+ cap: 30
125
+ },
126
+ "irreversible-ungated": {
127
+ id: "irreversible-ungated",
128
+ title: "Irreversible button without a gate",
129
+ contract: "\xA75.2",
130
+ severity: "critical",
131
+ why: "The button posts, pays, sends or approves, and nothing marks it. An agent presses it like any other button: no policy is asked, no person is asked, and the step cannot be undone.",
132
+ fix: `Mark it with data-agent-confirm="<what it does>" and decide in the bridge's allow() whether the company lets an agent take the step; otherwise send it to a person. For approvals, keep it a person's button and off the agent's actions.`,
133
+ booki: "ui-sdk Button with data-agent-confirm + createBookiAgent({ allow })",
134
+ points: 10,
135
+ cap: 20
136
+ },
137
+ "secret-visible": {
138
+ id: "secret-visible",
139
+ title: "Secret readable by the agent",
140
+ contract: "\xA73.5",
141
+ severity: "serious",
142
+ why: "Bank account numbers, IBANs, payment references (KID) and card data are in the text the agent reads. They end up in the model's context, its logs and its provider's logs.",
143
+ fix: "Show the value to the person but keep it out of what the agent reads: mark the element data-agent-secret so the bridge redacts it, and keep it out of the control's state. An agent may set a secret; it must not read one back.",
144
+ booki: "BankAccountInput, IbanInput, PaymentReferenceInput (redacted in the snapshot)",
145
+ points: 8,
146
+ cap: 16
147
+ },
148
+ "snapshot-size": {
149
+ id: "snapshot-size",
150
+ title: "Large accessibility snapshot",
151
+ contract: "\xA71",
152
+ severity: "minor",
153
+ why: "A browser agent reads the whole accessibility snapshot after most steps. Every token in it is paid for again on every step of a task.",
154
+ fix: "Cut what the agent does not need: hide decoration (aria-hidden), collapse long lists behind a search, and give the agent a bridge whose snapshot holds only controls and their state.",
155
+ points: 5,
156
+ cap: 10
157
+ }
158
+ };
159
+ var SNAPSHOT_TOKENS = { warn: 6e3, high: 15e3 };
160
+
161
+ // src/score.ts
162
+ function score(findings) {
163
+ const counts = /* @__PURE__ */ new Map();
164
+ for (const finding of findings) {
165
+ const weight = finding.rule === "snapshot-size" ? finding.count ?? 1 : 1;
166
+ counts.set(finding.rule, (counts.get(finding.rule) ?? 0) + weight);
167
+ }
168
+ const deductions = [...counts.entries()].map(([rule, n]) => ({ rule, findings: n, points: Math.min(RULES[rule].cap, RULES[rule].points * n) })).sort((a, b) => b.points - a.points);
169
+ const total = Math.max(0, 100 - deductions.reduce((sum, d) => sum + d.points, 0));
170
+ return { score: total, grade: total >= 85 ? "ready" : total >= 60 ? "partly ready" : "not ready", deductions };
171
+ }
172
+
173
+ // src/snapshot.ts
174
+ var LINE = /^(\s*)- (.*)$/;
175
+ function unquoteYaml(text) {
176
+ const t = text.trim();
177
+ if (t.startsWith("'") && t.endsWith("'")) return t.slice(1, -1).replace(/''/g, "'");
178
+ if (t.startsWith('"') && t.endsWith('"')) {
179
+ try {
180
+ return JSON.parse(t);
181
+ } catch {
182
+ return t.slice(1, -1);
183
+ }
184
+ }
185
+ return t;
186
+ }
187
+ function splitKeyValue(text) {
188
+ let quote = null;
189
+ for (let i = 0; i < text.length; i++) {
190
+ const ch = text[i];
191
+ if (quote) {
192
+ if (ch === "\\" && quote === '"') i++;
193
+ else if (ch === quote) quote = null;
194
+ } else if (ch === '"' || ch === "'") quote = ch;
195
+ else if (ch === ":" && (i === text.length - 1 || text[i + 1] === " ")) {
196
+ return [text.slice(0, i), text.slice(i + 1).trim()];
197
+ }
198
+ }
199
+ return [text, ""];
200
+ }
201
+ function parseSnapshot(snapshot) {
202
+ const nodes = [];
203
+ snapshot.split("\n").forEach((raw, line) => {
204
+ const match = LINE.exec(raw);
205
+ if (!match) return;
206
+ const [keyRaw, valueRaw] = splitKeyValue(match[2]);
207
+ const key = unquoteYaml(keyRaw);
208
+ const head = /^([a-z][a-z-]*)(?: "((?:[^"\\]|\\.)*)")?((?: \[[^\]]*\])*)\s*$/.exec(key);
209
+ if (!head) return;
210
+ const role = head[1];
211
+ if (role === "text" || role === "/url") return;
212
+ let name = "";
213
+ if (head[2] !== void 0) {
214
+ try {
215
+ name = JSON.parse(`"${head[2]}"`);
216
+ } catch {
217
+ name = head[2];
218
+ }
219
+ }
220
+ const flags = [...(head[3] ?? "").matchAll(/\[([^\]]*)\]/g)].map((m) => m[1]);
221
+ const refFlag = flags.find((flag) => flag.startsWith("ref="));
222
+ nodes.push({
223
+ role,
224
+ name,
225
+ ref: refFlag ? refFlag.slice(4) : null,
226
+ line,
227
+ flags: flags.filter((flag) => !flag.startsWith("ref=")),
228
+ value: unquoteYaml(valueRaw)
229
+ });
230
+ });
231
+ return nodes;
232
+ }
233
+ function estimateTokens(text) {
234
+ return Math.ceil(text.length / 4);
235
+ }
236
+
237
+ // src/audit.ts
238
+ import { existsSync } from "fs";
239
+ import path from "path";
240
+ import { pathToFileURL } from "url";
241
+ import { chromium } from "playwright-core";
242
+
243
+ // src/page.ts
244
+ function inPage(fn) {
245
+ const source = `(...args) => { const __name = (target) => target; return (${fn.toString()})(...args); }`;
246
+ return new Function(`return ${source}`)();
247
+ }
248
+ var INIT_SCRIPT = `(() => {
249
+ const tools = [];
250
+ Object.defineProperty(globalThis, "__readinessTools", { value: tools, configurable: true });
251
+ const add = (tool) => {
252
+ if (!tool || typeof tool !== "object") return;
253
+ const i = tools.findIndex((t) => t.name === tool.name);
254
+ if (i >= 0) tools.splice(i, 1, tool); else tools.push(tool);
255
+ };
256
+ const context = {
257
+ registerTool(tool, options) {
258
+ const signal = options && options.signal;
259
+ if (signal && signal.aborted) return Promise.resolve();
260
+ add(tool);
261
+ if (signal && typeof signal.addEventListener === "function") {
262
+ signal.addEventListener("abort", () => { const i = tools.indexOf(tool); if (i >= 0) tools.splice(i, 1); }, { once: true });
263
+ }
264
+ return Promise.resolve();
265
+ },
266
+ unregisterTool(name) { const i = tools.findIndex((t) => t.name === name); if (i >= 0) tools.splice(i, 1); return Promise.resolve(); },
267
+ provideContext(value) { tools.length = 0; for (const tool of (value && value.tools) || []) add(tool); return Promise.resolve(); },
268
+ clearContext() { tools.length = 0; return Promise.resolve(); },
269
+ };
270
+ try { if (!document.modelContext) Object.defineProperty(document, "modelContext", { value: context, configurable: true }); } catch {}
271
+ try { if (!navigator.modelContext) Object.defineProperty(navigator, "modelContext", { value: context, configurable: true }); } catch {}
272
+ })();`;
273
+ function describeElement(element2) {
274
+ const cssEscape = (value) => typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(value) : value.replace(/[^\w-]/g, "\\$&");
275
+ const selectorOf = (el) => {
276
+ const parts = [];
277
+ let node = el;
278
+ while (node && node.nodeType === 1 && parts.length < 6) {
279
+ if (node.id && !/^(ui-sdk-|:r|_r)/.test(node.id) && document.querySelectorAll(`#${cssEscape(node.id)}`).length === 1) {
280
+ parts.unshift(`#${cssEscape(node.id)}`);
281
+ break;
282
+ }
283
+ let part = node.tagName.toLowerCase();
284
+ const slot = node.getAttribute("data-slot");
285
+ const role = node.getAttribute("role");
286
+ if (slot) part += `[data-slot="${slot}"]`;
287
+ else if (role) part += `[role="${role}"]`;
288
+ const parent = node.parentElement;
289
+ if (parent) {
290
+ const same = [...parent.children].filter((child) => child.tagName === node.tagName);
291
+ if (same.length > 1) part += `:nth-of-type(${same.indexOf(node) + 1})`;
292
+ }
293
+ parts.unshift(part);
294
+ if (node.tagName === "BODY") break;
295
+ node = parent;
296
+ }
297
+ return parts.join(" > ");
298
+ };
299
+ const clean = (text) => (text ?? "").replace(/\s+/g, " ").trim();
300
+ const contextOf = (el) => {
301
+ const cell = el.closest("td, [role=cell], [role=gridcell]");
302
+ if (cell) {
303
+ const row = cell.parentElement;
304
+ const table = cell.closest("table, [role=table], [role=grid]");
305
+ const index = row ? [...row.children].indexOf(cell) : -1;
306
+ const header = table?.querySelectorAll("thead th, [role=columnheader]")[index];
307
+ if (header && clean(header.textContent)) return clean(header.textContent).slice(0, 60);
308
+ }
309
+ const box = el.getBoundingClientRect();
310
+ const midY = box.top + box.height / 2;
311
+ const midX = box.left + box.width / 2;
312
+ const interactive = "a, button, input, select, textarea, [role], [contenteditable]";
313
+ let left = null;
314
+ let above = null;
315
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
316
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
317
+ const text = clean(node.textContent);
318
+ const parent = node.parentElement;
319
+ if (!text || text.length > 80 || !parent || el.contains(parent)) continue;
320
+ if (parent.closest(interactive) && !parent.closest("label, th, [role=columnheader]")) continue;
321
+ if (parent.closest("[aria-hidden=true]")) continue;
322
+ const range = document.createRange();
323
+ range.selectNodeContents(node);
324
+ const r = range.getBoundingClientRect();
325
+ if (!r.width || !r.height) continue;
326
+ if (r.right <= box.left + 4 && r.top <= midY && r.bottom >= midY) {
327
+ const distance = box.left - r.right;
328
+ if (distance < 240 && (!left || distance < left.distance)) left = { text, distance };
329
+ } else if (r.bottom <= box.top + 2 && r.left <= midX + 8 && r.right >= box.left - 8) {
330
+ const distance = box.top - r.bottom;
331
+ if (distance < 320 && (!above || distance < above.distance)) above = { text, distance };
332
+ }
333
+ }
334
+ return (left ?? above)?.text ?? "";
335
+ };
336
+ const iconPattern = /material|icon|symbol|awesome|glyph/i;
337
+ const usesIconFont = (el) => {
338
+ const candidates = [el, ...el.querySelectorAll("*")].slice(0, 6);
339
+ return candidates.some((candidate) => {
340
+ const family = getComputedStyle(candidate).fontFamily;
341
+ const classes = typeof candidate.className === "string" ? candidate.className : "";
342
+ return iconPattern.test(family) || /(^|\s)(material-(icons|symbols)[\w-]*|icon[\w-]*|[\w-]+-icon|fa|fa-[\w-]+|glyphicon[\w-]*)(\s|$)/i.test(
343
+ classes
344
+ );
345
+ });
346
+ };
347
+ const html = (el) => {
348
+ const copy = el.cloneNode(true);
349
+ const text = copy.outerHTML.replace(/\s+/g, " ");
350
+ return text.length > 220 ? `${text.slice(0, 217)}\u2026` : text;
351
+ };
352
+ const hiddenFromPeople = (el) => {
353
+ if (el.getAttribute("type")?.toLowerCase() === "hidden" && el.tagName === "INPUT") return true;
354
+ if (el.closest("[aria-hidden=true], [inert]")) return true;
355
+ if (el instanceof HTMLElement && el.hidden) return true;
356
+ for (let node = el; node; node = node.parentElement) {
357
+ const style = getComputedStyle(node);
358
+ if (style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse") return true;
359
+ }
360
+ if (el.tabIndex < 0) {
361
+ const style = getComputedStyle(el);
362
+ const box = el.getBoundingClientRect();
363
+ const clipped = /rect\(0(px)?,? 0(px)?,? 0(px)?,? 0(px)?\)/.test(style.clip) || style.clipPath === "inset(50%)";
364
+ if (Number(style.opacity) === 0 || box.width <= 1 || box.height <= 1 || clipped) return true;
365
+ }
366
+ return false;
367
+ };
368
+ const confirmHost = element2.closest("[data-agent-confirm]");
369
+ return {
370
+ tag: element2.tagName.toLowerCase(),
371
+ selector: selectorOf(element2),
372
+ html: html(element2),
373
+ context: contextOf(element2),
374
+ type: element2.getAttribute("type"),
375
+ confirm: confirmHost ? confirmHost.getAttribute("data-agent-confirm") || "(marked)" : null,
376
+ secret: element2.closest("[data-agent-secret]") !== null,
377
+ iconFont: usesIconFont(element2),
378
+ disabled: element2.disabled === true || element2.getAttribute("aria-disabled") === "true",
379
+ hidden: hiddenFromPeople(element2)
380
+ };
381
+ }
382
+ function findCharts() {
383
+ const clean = (text) => (text ?? "").replace(/\s+/g, " ").trim();
384
+ const countFigures = (text) => (text.match(/\d[\d\s.,]*\d|\d/g) ?? []).length;
385
+ const textOfIds = (ids) => clean(
386
+ (ids ?? "").split(/\s+/).map((id) => id ? document.getElementById(id)?.textContent ?? "" : "").join(" ")
387
+ );
388
+ const hidden = (el) => {
389
+ for (let node = el; node; node = node.parentElement) {
390
+ if (node.getAttribute("aria-hidden") === "true") return true;
391
+ const style = getComputedStyle(node);
392
+ if (style.display === "none" || style.visibility === "hidden") return true;
393
+ }
394
+ return false;
395
+ };
396
+ const out = [];
397
+ const all = [...document.querySelectorAll("canvas, svg")];
398
+ all.forEach((el, index) => {
399
+ if (el.tagName.toLowerCase() === "svg" && el.parentElement?.closest("svg")) return;
400
+ if (el.closest("button, a, [role=button], [role=link], [role=menuitem], [role=tab]")) return;
401
+ if (hidden(el)) return;
402
+ const box = el.getBoundingClientRect();
403
+ const kind = el.tagName.toLowerCase() === "canvas" ? "canvas" : "svg";
404
+ if (kind === "canvas" ? box.width < 32 || box.height < 16 : Math.max(box.width, box.height) < 48 || Math.min(box.width, box.height) < 12)
405
+ return;
406
+ if (kind === "svg") {
407
+ const marks = el.querySelectorAll("rect, path, circle, line, polyline, polygon, ellipse").length;
408
+ if (marks < 3) return;
409
+ }
410
+ const role = el.getAttribute("role");
411
+ if (role === "presentation" || role === "none") return;
412
+ const title = kind === "svg" ? clean(el.querySelector(":scope > title")?.textContent) : "";
413
+ const name = clean(el.getAttribute("aria-label")) || textOfIds(el.getAttribute("aria-labelledby")) || title;
414
+ const description = textOfIds(el.getAttribute("aria-describedby")) + " " + clean(el.getAttribute("aria-description")) + " " + (kind === "svg" ? clean(el.querySelector(":scope > desc")?.textContent) : clean(el.textContent));
415
+ const host = el.parentElement?.closest(
416
+ "figure, [role=figure], [role=img], [role=group], [role=region], section, article"
417
+ );
418
+ const table = host?.querySelector("table, [role=table], [role=grid]");
419
+ const tableText = table ? clean(table.textContent) : "";
420
+ const figures = countFigures(`${name} ${description}`) + (table && !el.contains(table) ? countFigures(tableText) : 0);
421
+ out.push({ index, kind, width: Math.round(box.width), height: Math.round(box.height), name, figures, role });
422
+ });
423
+ return out;
424
+ }
425
+ async function readBridge() {
426
+ const g = globalThis;
427
+ const tools = [...new Set((g.__readinessTools ?? []).map((tool) => String(tool.name)))];
428
+ const toList = (value) => {
429
+ if (Array.isArray(value)) return value;
430
+ if (value && typeof value === "object") {
431
+ const v = value;
432
+ if (Array.isArray(v.components)) return v.components;
433
+ const text = v.content?.find((part) => part.type === "text")?.text;
434
+ if (text) {
435
+ try {
436
+ return toList(JSON.parse(text));
437
+ } catch {
438
+ return [];
439
+ }
440
+ }
441
+ }
442
+ return [];
443
+ };
444
+ try {
445
+ if (typeof g.agent?.snapshot === "function") {
446
+ const components = toList(await g.agent.snapshot());
447
+ return { source: "window.agent", components, tools, error: null };
448
+ }
449
+ const snapshotTool = (g.__readinessTools ?? []).find((tool) => tool.name === "snapshot");
450
+ if (snapshotTool?.execute) {
451
+ const components = toList(await snapshotTool.execute({}));
452
+ return { source: "webmcp", components, tools, error: null };
453
+ }
454
+ return { source: tools.length ? "webmcp" : null, components: [], tools, error: null };
455
+ } catch (error) {
456
+ return { source: null, components: [], tools, error: String(error) };
457
+ }
458
+ }
459
+ function bridgeCoverage(element2, entries) {
460
+ const clean = (text) => (text ?? "").replace(/\s+/g, " ").trim();
461
+ const norm = (text) => clean(text).toLowerCase();
462
+ const textOfIds = (ids) => (ids ?? "").split(/\s+/).map((id) => id ? document.getElementById(id)?.textContent ?? "" : "").join(" ");
463
+ const nameOf = (el) => {
464
+ const labelledby = clean(textOfIds(el.getAttribute("aria-labelledby")));
465
+ if (labelledby) return labelledby;
466
+ const label = clean(el.getAttribute("aria-label"));
467
+ if (label) return label;
468
+ if (el.tagName === "FIELDSET") return clean(el.querySelector(":scope > legend")?.textContent);
469
+ const labels = el.labels;
470
+ if (labels?.length) return clean([...labels].map((l) => l.textContent).join(" "));
471
+ return "";
472
+ };
473
+ const quote = (value) => `"${value.replace(/["\\]/g, "\\$&")}"`;
474
+ const counts = /* @__PURE__ */ new Map();
475
+ const labelsOf = /* @__PURE__ */ new Map();
476
+ for (const entry of entries) {
477
+ if (!entry.component) continue;
478
+ counts.set(entry.component, (counts.get(entry.component) ?? 0) + 1);
479
+ const labels = labelsOf.get(entry.component) ?? /* @__PURE__ */ new Set();
480
+ if (norm(entry.label)) labels.add(norm(entry.label));
481
+ labelsOf.set(entry.component, labels);
482
+ }
483
+ const roots = [];
484
+ for (const [kind, labels] of labelsOf) {
485
+ const parts = [...document.querySelectorAll(`[data-slot=${quote(kind)}], [data-slot^=${quote(`${kind}-`)}]`)];
486
+ const found = parts.filter(
487
+ (el) => !el.closest("[data-agent-hidden]") && !parts.some((other) => other !== el && other.contains(el))
488
+ );
489
+ if (found.length <= (counts.get(kind) ?? 0)) roots.push(...found);
490
+ else roots.push(...found.filter((el) => labels.has(norm(nameOf(el)))));
491
+ }
492
+ const inside = (el) => roots.some((root) => root.contains(el));
493
+ const allLabels = new Set(entries.map((entry) => norm(entry.label)).filter(Boolean));
494
+ let group = null;
495
+ const isRadio = element2.getAttribute("role") === "radio" || element2.tagName === "INPUT" && element2.type === "radio";
496
+ if (isRadio) {
497
+ const host = element2.closest("[role=radiogroup], fieldset, [role=group]");
498
+ const name = host ? nameOf(host) : "";
499
+ if (host && name) group = { name, covered: allLabels.has(norm(name)) || inside(host) };
500
+ }
501
+ return { inRoot: inside(element2), agentHidden: element2.closest("[data-agent-hidden]") !== null, group };
502
+ }
503
+ function findFocusableNonControls() {
504
+ const native = "a[href], button, input, select, textarea, summary, details, iframe, audio, video, [contenteditable=''], [contenteditable=true]";
505
+ const neutral = /* @__PURE__ */ new Set([
506
+ "",
507
+ "generic",
508
+ "none",
509
+ "presentation",
510
+ "cell",
511
+ "row",
512
+ "text",
513
+ "paragraph",
514
+ "listitem",
515
+ "group"
516
+ ]);
517
+ const out = [];
518
+ [...document.querySelectorAll("[tabindex]")].forEach((el, index) => {
519
+ if (el.tabIndex < 0) return;
520
+ if (el.matches(native) || el.tagName.toLowerCase() === "svg" || el.tagName.toLowerCase() === "canvas") return;
521
+ const role = (el.getAttribute("role") ?? "").trim().toLowerCase();
522
+ if (!neutral.has(role)) return;
523
+ for (let node = el; node; node = node.parentElement) {
524
+ if (node.getAttribute("aria-hidden") === "true") return;
525
+ }
526
+ const style = getComputedStyle(el);
527
+ if (style.display === "none" || style.visibility === "hidden") return;
528
+ if (/(auto|scroll)/.test(style.overflow + style.overflowY + style.overflowX) && el.scrollHeight > el.clientHeight + 1)
529
+ return;
530
+ if (el.matches("[role=dialog], dialog, main, [aria-modal]")) return;
531
+ out.push({
532
+ index,
533
+ tag: el.tagName.toLowerCase(),
534
+ text: (el.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 60)
535
+ });
536
+ });
537
+ return out;
538
+ }
539
+ function onlyInSecrets(value) {
540
+ const digits = (text) => text.replace(/[^0-9A-Za-z]/g, "");
541
+ const wanted = digits(value);
542
+ let found = 0;
543
+ let marked = 0;
544
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
545
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
546
+ if (!digits(node.textContent ?? "").includes(wanted)) continue;
547
+ found++;
548
+ if (node.parentElement?.closest("[data-agent-secret]")) marked++;
549
+ }
550
+ for (const input of document.querySelectorAll("input, textarea")) {
551
+ if (!digits(input.value).includes(wanted)) continue;
552
+ found++;
553
+ if (input.closest("[data-agent-secret]")) marked++;
554
+ }
555
+ return found > 0 && found === marked;
556
+ }
557
+
558
+ // src/audit.ts
559
+ var VERSION = "0.1.0";
560
+ var FIELD_ROLES = /* @__PURE__ */ new Set([
561
+ "textbox",
562
+ "searchbox",
563
+ "combobox",
564
+ "listbox",
565
+ "spinbutton",
566
+ "checkbox",
567
+ "radio",
568
+ "switch",
569
+ "slider"
570
+ ]);
571
+ var ACTION_ROLES = /* @__PURE__ */ new Set(["button", "link", "menuitem"]);
572
+ var ICON_WORDS = new Set(
573
+ "add add_circle arrow_back arrow_drop_down arrow_forward attach_file calendar_month calendar_today cancel check check_circle chevron_left chevron_right clear close content_copy content_paste date_range delete delete_outline done download edit edit_note error expand_less expand_more file_download file_upload filter_alt filter_list help help_outline home info keyboard_arrow_down keyboard_arrow_up launch link menu more_horiz more_vert notifications open_in_new print refresh remove save search send settings sort star sync tune undo upload visibility visibility_off warning".split(" ")
574
+ );
575
+ function looksLikeIconName(name, iconFont) {
576
+ const n = name.trim();
577
+ if (!n || n.length > 40) return false;
578
+ if (/^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/.test(n)) return true;
579
+ if (ICON_WORDS.has(n)) return true;
580
+ return iconFont && /^[a-z][a-z0-9_]*$/.test(n);
581
+ }
582
+ var IRREVERSIBLE = /(^|[^\p{L}])(bokfør|opprett|godkjenn|attester|betal|send|signer|fullfør|frigi|overfør|utbetal|lukk periode|post|pay|approve|submit|finali[sz]e|release|sign[ -]?off|transfer)(e|er)?(?=$|[^\p{L}])/iu;
583
+ var DESCRIBE = inPage(describeElement);
584
+ var READ_BRIDGE = inPage(readBridge);
585
+ var FIND_FOCUSABLE = inPage(findFocusableNonControls);
586
+ var FIND_CHARTS = inPage(findCharts);
587
+ var ONLY_IN_SECRETS = inPage(onlyInSecrets);
588
+ var BRIDGE_COVERAGE = inPage(bridgeCoverage);
589
+ var BROKEN_NAME = /\[object \w+\]|\bundefined\b|\bnull\b|\bNaN\b/;
590
+ function toTarget(input) {
591
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(input)) return input;
592
+ const resolved = path.resolve(input);
593
+ if (existsSync(resolved)) return pathToFileURL(resolved).href;
594
+ return `https://${input}`;
595
+ }
596
+ async function open(target, options) {
597
+ const viewport = options.viewport ?? { width: 1280, height: 900 };
598
+ const launch = {
599
+ headless: !options.headed,
600
+ ...options.executablePath ? { executablePath: options.executablePath } : options.channel === "chromium" ? {} : { channel: options.channel ?? "chrome" }
601
+ };
602
+ let browser = null;
603
+ let context;
604
+ if (options.profile) {
605
+ context = await chromium.launchPersistentContext(path.resolve(options.profile), { ...launch, viewport });
606
+ } else {
607
+ browser = await chromium.launch(launch);
608
+ context = await browser.newContext({
609
+ viewport,
610
+ ...options.storageState ? { storageState: path.resolve(options.storageState) } : {}
611
+ });
612
+ }
613
+ await context.addInitScript(INIT_SCRIPT);
614
+ const page = context.pages()[0] ?? await context.newPage();
615
+ const timeout = options.timeout ?? 3e4;
616
+ page.setDefaultTimeout(timeout);
617
+ page.setDefaultNavigationTimeout(timeout);
618
+ await page.goto(target, { waitUntil: "load", timeout });
619
+ await page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => void 0);
620
+ if (options.waitFor) await page.waitForSelector(options.waitFor);
621
+ await page.waitForTimeout(options.wait ?? 500);
622
+ return {
623
+ page,
624
+ close: async () => {
625
+ await context.close();
626
+ await browser?.close();
627
+ }
628
+ };
629
+ }
630
+ async function describe(page, node) {
631
+ if (!node.ref) return null;
632
+ try {
633
+ return await page.locator(`aria-ref=${node.ref}`).evaluate(DESCRIBE, void 0, { timeout: 2e3 });
634
+ } catch {
635
+ return null;
636
+ }
637
+ }
638
+ function element(node, info) {
639
+ return {
640
+ role: node.role,
641
+ name: node.name,
642
+ ref: node.ref,
643
+ selector: info?.selector,
644
+ html: info?.html,
645
+ context: info?.context || void 0
646
+ };
647
+ }
648
+ function bookiControlFor(role, info) {
649
+ const near = `${info?.context ?? ""} ${info?.html ?? ""}`.toLowerCase();
650
+ if (info?.type === "date" || /dato|date|forfall|due/.test(near)) return "FinancialDateField";
651
+ if (/kid|payment ref|betalingsref/.test(near)) return "PaymentReferenceInput";
652
+ if (/iban/.test(near)) return "IbanInput";
653
+ if (/kontonummer|bank ?account|routing/.test(near)) return "BankAccountInput";
654
+ if (/mva|vat|tax|avgift/.test(near)) return "TaxCodeSelect";
655
+ if (/valuta|currency/.test(near)) return "CurrencySelect";
656
+ if (/beløp|amount|sum|total|pris|price|debet|kredit|debit|credit/.test(near) && (role === "textbox" || role === "spinbutton"))
657
+ return "AmountField";
658
+ if (/faktura(nummer|nr)|invoice (no|number)/.test(near)) return "InvoiceNumberInput";
659
+ if (/periode|period|termin/.test(near)) return "AccountingPeriodSelect";
660
+ if (/org\.?nr|organisasjonsnummer|ein\b/.test(near)) return "OrganizationNumberInput";
661
+ if (role === "listbox" || role === "combobox")
662
+ return "AccountPicker (accounts, customers, suppliers) or TaxCodeSelect";
663
+ return void 0;
664
+ }
665
+ function samePage(a, b) {
666
+ try {
667
+ const x = new URL(a);
668
+ const y = new URL(b);
669
+ const trim = (p) => p.replace(/\/+$/, "") || "/";
670
+ return x.origin === y.origin && trim(x.pathname) === trim(y.pathname);
671
+ } catch {
672
+ return a === b;
673
+ }
674
+ }
675
+ async function audit(input, options = {}) {
676
+ const target = toTarget(input);
677
+ const { page, close } = await open(target, options);
678
+ try {
679
+ const landed = page.url();
680
+ if (!samePage(landed, target)) return { ...await check(page, landed), redirectedFrom: target };
681
+ return await check(page, target);
682
+ } finally {
683
+ await close();
684
+ }
685
+ }
686
+ var NOT_MEASURED = "Nothing measured: the bridge has no controls and the page has no fields or charts, so the checks had nothing to compare. The tool never clicks: a form that appears after a row is selected or a button is pressed is not on the page yet. Open the form first (a Playwright step), then call check(page) from @booki-aui/readiness.";
687
+ async function check(page, url = page.url()) {
688
+ const snapshot = await page.ariaSnapshot({ mode: "ai" });
689
+ const nodes = parseSnapshot(snapshot);
690
+ const findings = [];
691
+ const raw = await page.evaluate(READ_BRIDGE);
692
+ const controls = raw.components.map((c) => ({
693
+ label: typeof c.label === "string" ? c.label : "",
694
+ component: String(c.component ?? "?"),
695
+ actions: Array.isArray(c.actions) ? c.actions.map(String) : [],
696
+ ...typeof c.confirm === "string" ? { confirm: c.confirm } : {}
697
+ }));
698
+ const bridge = {
699
+ source: raw.source,
700
+ components: controls.length,
701
+ named: controls.filter((c) => c.label.trim()).length,
702
+ actions: controls.reduce((sum, c) => sum + c.actions.length, 0),
703
+ controls,
704
+ webmcpTools: raw.tools,
705
+ error: raw.error
706
+ };
707
+ const generic = /* @__PURE__ */ new Set(["snapshot", "act", "query"]);
708
+ const ownTools = raw.tools.filter((tool) => !generic.has(tool));
709
+ const hasBridge = bridge.actions > 0 || ownTools.length > 0;
710
+ if (!hasBridge) {
711
+ findings.push({
712
+ rule: "bridge-missing",
713
+ message: bridge.source === null ? "No window.agent and no WebMCP tools: an agent can only read the accessibility tree and click." : `A bridge answers (${bridge.source}) but offers no controls with actions on this page.`
714
+ });
715
+ }
716
+ for (const control of controls) {
717
+ if (!control.label.trim()) {
718
+ findings.push({
719
+ rule: "bridge-unnamed-control",
720
+ message: `A ${control.component} on the bridge has no label.`,
721
+ element: { role: control.component, name: "" }
722
+ });
723
+ }
724
+ for (const action of control.actions.filter((a) => PERSON_ACTION.test(a))) {
725
+ findings.push({
726
+ rule: "bridge-person-action",
727
+ message: `"${control.label || control.component}" offers the agent "${action}".`,
728
+ element: { role: control.component, name: control.label }
729
+ });
730
+ }
731
+ }
732
+ const fields = nodes.filter((n) => FIELD_ROLES.has(n.role) && !n.flags.includes("aria-hidden"));
733
+ const named = /* @__PURE__ */ new Map();
734
+ for (const node of fields) {
735
+ const name = node.name.trim();
736
+ if (!name) {
737
+ const info = await describe(page, node);
738
+ if (info?.hidden) continue;
739
+ findings.push({
740
+ rule: "field-unnamed",
741
+ message: `A ${node.role} with no name${info?.context ? `, near "${info.context}"` : ""}.`,
742
+ element: element(node, info),
743
+ booki: bookiControlFor(node.role, info)
744
+ });
745
+ continue;
746
+ }
747
+ if (BROKEN_NAME.test(name)) {
748
+ const info = await describe(page, node);
749
+ if (info?.hidden) continue;
750
+ findings.push({
751
+ rule: "field-broken-name",
752
+ message: `A ${node.role} named "${name}".`,
753
+ element: element(node, info),
754
+ booki: bookiControlFor(node.role, info)
755
+ });
756
+ continue;
757
+ }
758
+ if (node.role === "radio") continue;
759
+ const key = `${node.role}\0${name}`;
760
+ named.set(key, [...named.get(key) ?? [], node]);
761
+ }
762
+ for (const candidates of named.values()) {
763
+ if (candidates.length < 2) continue;
764
+ const group = [];
765
+ for (const node of candidates) {
766
+ const info = await describe(page, node);
767
+ if (!info?.hidden) group.push({ node, info });
768
+ }
769
+ if (group.length < 2) continue;
770
+ const first = group[0];
771
+ findings.push({
772
+ rule: "field-ambiguous",
773
+ message: `${group.length} fields are each a ${first.node.role} named "${first.node.name}".`,
774
+ element: element(first.node, first.info),
775
+ count: group.length
776
+ });
777
+ }
778
+ const entries = raw.components.filter((c) => !c.offPage && c.component !== "more").map((c) => ({ component: String(c.component ?? ""), label: typeof c.label === "string" ? c.label : "" }));
779
+ const truncated = raw.components.some((c) => c.component === "more");
780
+ if (hasBridge && entries.length && !truncated) {
781
+ const norm = (text) => text.replace(/\s+/g, " ").trim().toLowerCase();
782
+ const labels = new Set(entries.map((e) => norm(e.label)).filter(Boolean));
783
+ const seenGroups = /* @__PURE__ */ new Set();
784
+ for (const node of fields) {
785
+ const name = node.name.trim();
786
+ if (!name || BROKEN_NAME.test(name) || node.flags.includes("disabled") || !node.ref) continue;
787
+ if (labels.has(norm(name))) continue;
788
+ const coverage = await page.locator(`aria-ref=${node.ref}`).evaluate(BRIDGE_COVERAGE, entries, { timeout: 2e3 }).catch(() => null);
789
+ if (!coverage || coverage.inRoot || coverage.agentHidden || coverage.group?.covered) continue;
790
+ const group = coverage.group;
791
+ if (group) {
792
+ if (seenGroups.has(norm(group.name))) continue;
793
+ seenGroups.add(norm(group.name));
794
+ }
795
+ const info = await describe(page, node);
796
+ if (info?.hidden) continue;
797
+ const role = group ? "radiogroup" : node.role;
798
+ const shown = group ? group.name : name;
799
+ findings.push({
800
+ rule: "field-not-on-bridge",
801
+ message: `A ${role} named "${shown}" is on the page but not on the bridge: no snapshot entry has that label or contains it.`,
802
+ element: { ...element(node, info), role, name: shown },
803
+ booki: bookiControlFor(node.role, info)
804
+ });
805
+ }
806
+ }
807
+ const focusables = await page.evaluate(FIND_FOCUSABLE);
808
+ const focusLocator = page.locator("[tabindex]");
809
+ for (const item of focusables) {
810
+ const info = await focusLocator.nth(item.index).evaluate(DESCRIBE, void 0, { timeout: 2e3 }).catch(() => null);
811
+ findings.push({
812
+ rule: "focusable-without-role",
813
+ message: `A focusable <${item.tag}> with no control role${item.text ? ` ("${item.text}")` : ""}${info?.context ? `, under "${info.context}"` : ""}.`,
814
+ element: {
815
+ role: item.tag,
816
+ name: item.text,
817
+ selector: info?.selector,
818
+ html: info?.html,
819
+ context: info?.context || void 0
820
+ },
821
+ booki: bookiControlFor("textbox", info)
822
+ });
823
+ }
824
+ const actionNodes = nodes.filter((n) => ACTION_ROLES.has(n.role));
825
+ const bridgeButtons = new Map(controls.filter((c) => c.component === "button").map((c) => [c.label.trim(), c]));
826
+ for (const node of actionNodes) {
827
+ const name = node.name.trim();
828
+ if (node.role === "button" && !name) {
829
+ const info = await describe(page, node);
830
+ findings.push({ rule: "button-unnamed", message: "A button with no name.", element: element(node, info) });
831
+ continue;
832
+ }
833
+ if (node.role !== "link") {
834
+ const plain = looksLikeIconName(name, false);
835
+ const info = plain || /^[a-z][a-z0-9_]*$/.test(name) ? await describe(page, node) : null;
836
+ if (looksLikeIconName(name, info?.iconFont ?? false)) {
837
+ findings.push({
838
+ rule: "button-icon-name",
839
+ message: `A ${node.role} named "${name}", the icon's ligature.`,
840
+ element: element(node, info)
841
+ });
842
+ continue;
843
+ }
844
+ }
845
+ if (IRREVERSIBLE.test(name)) {
846
+ const info = await describe(page, node);
847
+ const onBridge = bridgeButtons.get(name);
848
+ const gated = Boolean(info?.confirm) || Boolean(onBridge?.confirm);
849
+ if (!gated) {
850
+ findings.push({
851
+ rule: "irreversible-ungated",
852
+ message: `"${name}" ${node.role === "link" ? "(a link) " : ""}takes an irreversible step with no data-agent-confirm and no person gate.`,
853
+ element: element(node, info)
854
+ });
855
+ }
856
+ }
857
+ }
858
+ const charts = await page.evaluate(FIND_CHARTS);
859
+ const chartLocator = page.locator("canvas, svg");
860
+ for (const chart of charts) {
861
+ if (chart.figures >= 2) continue;
862
+ const info = await chartLocator.nth(chart.index).evaluate(DESCRIBE, void 0, { timeout: 2e3 }).catch(() => null);
863
+ const what = chart.kind === "canvas" ? "A canvas" : `An SVG${chart.role ? ` (role ${chart.role})` : ""}`;
864
+ findings.push({
865
+ rule: "chart-pixels-only",
866
+ message: `${what} ${chart.width}\xD7${chart.height} ${chart.name ? `named "${chart.name}" but` : "with no name and"} no figures in the DOM.`,
867
+ element: {
868
+ role: chart.role ?? chart.kind,
869
+ name: chart.name,
870
+ selector: info?.selector,
871
+ html: info?.html,
872
+ context: info?.context || void 0
873
+ }
874
+ });
875
+ }
876
+ const lines = snapshot.split("\n");
877
+ const readable = snapshot.replace(/\[ref=e\d+\]/g, (m) => " ".repeat(m.length));
878
+ const secrets = findSecrets(readable);
879
+ for (const hit of secrets) {
880
+ const lineIndex = snapshot.slice(0, hit.index).split("\n").length - 1;
881
+ const node = nodes.find((n) => n.line === lineIndex) ?? nodes.filter((n) => n.line < lineIndex).at(-1);
882
+ const info = node ? await describe(page, node) : null;
883
+ if (hasBridge && (info?.secret || await page.evaluate(ONLY_IN_SECRETS, hit.value))) continue;
884
+ findings.push({
885
+ rule: "secret-visible",
886
+ message: `${SECRET_LABEL[hit.kind]} ${hit.masked} is in the accessibility snapshot.`,
887
+ element: {
888
+ ...node ? element(node, info) : {},
889
+ context: lines[lineIndex]?.trim().replace(hit.value, hit.masked)
890
+ }
891
+ });
892
+ }
893
+ const bridgeText = JSON.stringify(raw.components);
894
+ const bridgeSecrets = findSecrets(bridgeText);
895
+ secrets.push(...bridgeSecrets);
896
+ for (const hit of bridgeSecrets) {
897
+ const owner = raw.components.find((c) => JSON.stringify(c).includes(hit.value));
898
+ findings.push({
899
+ rule: "secret-visible",
900
+ message: `${SECRET_LABEL[hit.kind]} ${hit.masked} is in the bridge snapshot${owner?.label ? ` of "${owner.label}"` : ""}.`,
901
+ element: { role: owner?.component, name: owner?.label }
902
+ });
903
+ }
904
+ const tokens = estimateTokens(snapshot);
905
+ if (tokens > SNAPSHOT_TOKENS.warn) {
906
+ findings.push({
907
+ rule: "snapshot-size",
908
+ message: `The accessibility snapshot is about ${tokens.toLocaleString("en-US")} tokens; an agent reads it again after most steps.`,
909
+ count: tokens > SNAPSHOT_TOKENS.high ? 2 : 1
910
+ });
911
+ }
912
+ const redact = (text) => {
913
+ if (!text) return text;
914
+ let out = text;
915
+ for (const hit of secrets) {
916
+ for (const form of /* @__PURE__ */ new Set([hit.value, hit.value.replace(/[^0-9A-Za-z]/g, "")])) {
917
+ if (form.length >= 4) out = out.split(form).join(hit.masked);
918
+ }
919
+ }
920
+ return out;
921
+ };
922
+ for (const finding of findings) {
923
+ finding.message = redact(finding.message);
924
+ if (finding.element) {
925
+ for (const key of ["name", "html", "context", "selector"])
926
+ finding.element[key] = redact(finding.element[key]);
927
+ }
928
+ }
929
+ for (const control of controls) control.label = redact(control.label);
930
+ const title = await page.title();
931
+ const result = score(findings);
932
+ const measured = bridge.components > 0 || fields.length > 0 || charts.length > 0;
933
+ return {
934
+ tool: { name: "@booki-aui/readiness", version: VERSION },
935
+ url,
936
+ title,
937
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
938
+ ...result,
939
+ measured,
940
+ ...measured ? {} : { grade: "not measured", notMeasured: NOT_MEASURED },
941
+ findings: sortFindings(findings),
942
+ metrics: {
943
+ snapshotChars: snapshot.length,
944
+ snapshotTokens: tokens,
945
+ fields: fields.length,
946
+ buttons: actionNodes.filter((n) => n.role === "button").length,
947
+ charts: charts.length
948
+ },
949
+ bridge,
950
+ snapshot: redact(snapshot)
951
+ };
952
+ }
953
+ var ORDER = { critical: 0, serious: 1, moderate: 2, minor: 3 };
954
+ function sortFindings(findings) {
955
+ return [...findings].sort((a, b) => ORDER[RULES[a.rule].severity] - ORDER[RULES[b.rule].severity]);
956
+ }
957
+
958
+ // src/report.ts
959
+ var esc = (value) => String(value ?? "").replace(
960
+ /[&<>"']/g,
961
+ (ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[ch]
962
+ );
963
+ function toJson(report, { snapshot = false } = {}) {
964
+ const { snapshot: text, ...rest } = report;
965
+ return JSON.stringify(
966
+ snapshot ? report : { ...rest, snapshotIncluded: false, snapshotPreview: text.slice(0, 2e3) },
967
+ null,
968
+ 2
969
+ );
970
+ }
971
+ var tty = process.stdout.isTTY && !process.env.NO_COLOR;
972
+ var paint = (code) => (text) => tty ? `\x1B[${code}m${text}\x1B[0m` : text;
973
+ var bold = paint("1");
974
+ var dim = paint("2");
975
+ var red = paint("31");
976
+ var yellow = paint("33");
977
+ var green = paint("32");
978
+ function toConsole(report) {
979
+ const colour = !report.measured ? yellow : report.score >= 85 ? green : report.score >= 60 ? yellow : red;
980
+ const out = [];
981
+ out.push(`${bold("Agent readiness")} ${report.url}`);
982
+ if (report.redirectedFrom) out.push(yellow(redirectNote(report)));
983
+ const headline = report.measured ? `${report.score}/100` : "no score";
984
+ out.push(
985
+ `${colour(bold(headline))} ${colour(report.grade)} ${dim(`\xB7 ${report.findings.length} findings \xB7 snapshot \u2248 ${report.metrics.snapshotTokens.toLocaleString("en-US")} tokens \xB7 bridge: ${bridgeLine(report)}`)}`
986
+ );
987
+ out.push("");
988
+ if (!report.measured) {
989
+ out.push(yellow(report.notMeasured ?? ""));
990
+ out.push("");
991
+ }
992
+ const byRule = groupByRule(report.findings);
993
+ for (const d of report.deductions) {
994
+ const rule = RULES[d.rule];
995
+ const list = byRule.get(d.rule) ?? [];
996
+ out.push(
997
+ `${sevMark(rule.severity)} ${bold(rule.title)} ${dim(`(${rule.contract}) \u2212${d.points}`)} \xD7${list.length}`
998
+ );
999
+ for (const f of list.slice(0, 6))
1000
+ out.push(` ${f.message}${f.element?.selector ? dim(` ${f.element.selector}`) : ""}`);
1001
+ if (list.length > 6) out.push(dim(` \u2026 and ${list.length - 6} more`));
1002
+ out.push(` ${dim("Fix:")} ${rule.fix}`);
1003
+ if (rule.booki) out.push(` ${dim("Booki:")} ${rule.booki}`);
1004
+ out.push("");
1005
+ }
1006
+ if (!report.findings.length && report.measured) out.push(green("Nothing found that stops an agent on this page."));
1007
+ return out.join("\n");
1008
+ }
1009
+ function bridgeLine(report) {
1010
+ const b = report.bridge;
1011
+ if (!b.components && !b.webmcpTools.length) return "none";
1012
+ return `${b.components} controls, ${b.actions} named actions${b.webmcpTools.length ? `, WebMCP: ${b.webmcpTools.join(", ")}` : ""}`;
1013
+ }
1014
+ function sevMark(severity) {
1015
+ return severity === "critical" ? red("\u2716") : severity === "serious" ? red("\u25CF") : severity === "moderate" ? yellow("\u25CF") : dim("\u25CF");
1016
+ }
1017
+ function groupByRule(findings) {
1018
+ const map = /* @__PURE__ */ new Map();
1019
+ for (const f of findings) map.set(f.rule, [...map.get(f.rule) ?? [], f]);
1020
+ return map;
1021
+ }
1022
+ function redirectNote(report) {
1023
+ return `Measured ${report.url}, not ${report.redirectedFrom}: the page sent the browser on, often to sign in. For a screen behind a sign-in, pass --storage-state <file> of a signed-in session (or --profile <dir>).`;
1024
+ }
1025
+ function toHtml(report) {
1026
+ const byRule = groupByRule(report.findings);
1027
+ const tone = !report.measured ? "warn" : report.score >= 85 ? "good" : report.score >= 60 ? "warn" : "bad";
1028
+ const sections = report.deductions.map((d) => {
1029
+ const rule = RULES[d.rule];
1030
+ const items = (byRule.get(d.rule) ?? []).map((f) => {
1031
+ const e = f.element;
1032
+ const booki = f.booki ?? rule.booki;
1033
+ return `<li class="finding">
1034
+ <p class="msg">${esc(f.message)}</p>
1035
+ ${e ? `<dl class="el">
1036
+ ${e.role ? `<dt>Role</dt><dd><code>${esc(e.role)}</code>${e.name ? ` \u201C${esc(e.name)}\u201D` : " <em>no name</em>"}${e.ref ? ` <span class="muted">ref ${esc(e.ref)}</span>` : ""}</dd>` : ""}
1037
+ ${e.context ? `<dt>Near</dt><dd>${esc(e.context)}</dd>` : ""}
1038
+ ${e.selector ? `<dt>Selector</dt><dd><code>${esc(e.selector)}</code></dd>` : ""}
1039
+ ${e.html ? `<dt>HTML</dt><dd><code class="html">${esc(e.html)}</code></dd>` : ""}
1040
+ ${f.booki && f.booki !== rule.booki ? `<dt>Booki</dt><dd>${esc(booki)}</dd>` : ""}
1041
+ </dl>` : ""}
1042
+ </li>`;
1043
+ }).join("\n");
1044
+ return `<section class="rule sev-${rule.severity}" id="${rule.id}">
1045
+ <header>
1046
+ <h2>${esc(rule.title)}</h2>
1047
+ <p class="meta"><span class="sev">${rule.severity}</span> \xB7 Agent Contract ${esc(rule.contract)} \xB7 ${d.findings} found \xB7 <strong>\u2212${d.points}</strong> <span class="muted">(${rule.points} each, at most ${rule.cap})</span></p>
1048
+ </header>
1049
+ <div class="explain">
1050
+ <p><strong>Why it matters to an agent.</strong> ${esc(rule.why)}</p>
1051
+ <p><strong>Fix.</strong> ${esc(rule.fix)}</p>
1052
+ ${rule.booki ? `<p><strong>Booki.</strong> ${esc(rule.booki)}</p>` : ""}
1053
+ </div>
1054
+ <ol class="findings">${items}</ol>
1055
+ </section>`;
1056
+ }).join("\n");
1057
+ const b = report.bridge;
1058
+ const bridgeRows = b.controls.map(
1059
+ (c) => `<tr><td>${esc(c.label) || "<em>no label</em>"}</td><td><code>${esc(c.component)}</code></td><td>${c.actions.map((a) => `<code>${esc(a)}</code>`).join(" ")}${c.confirm ? ` <span class="muted">confirm: ${esc(c.confirm)}</span>` : ""}</td></tr>`
1060
+ ).join("");
1061
+ return `<!doctype html>
1062
+ <html lang="en">
1063
+ <head>
1064
+ <meta charset="utf-8">
1065
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1066
+ <title>Agent readiness: ${esc(report.title || report.url)}</title>
1067
+ <style>
1068
+ :root { --paper:#f7f5ef; --card:#fffdf8; --ink:#1d1c19; --muted:#6b675e; --line:#dcd7cb; --bad:#a3321f; --warn:#8a6100; --good:#2f6b2a; --code:#efebe1; }
1069
+ @media (prefers-color-scheme: dark) { :root { --paper:#151513; --card:#1d1c19; --ink:#ece8de; --muted:#a39e92; --line:#3a3832; --bad:#e2775f; --warn:#d9a940; --good:#8cc27f; --code:#26251f; } }
1070
+ * { box-sizing: border-box; }
1071
+ body { margin:0; background:var(--paper); color:var(--ink); font:15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
1072
+ main { max-width: 960px; margin: 0 auto; padding: 32px 16px 64px; }
1073
+ h1 { font-size: 22px; margin: 0 0 4px; }
1074
+ h2 { font-size: 17px; margin: 0; }
1075
+ a { color: inherit; text-decoration-color: var(--muted); text-underline-offset: 2px; }
1076
+ code { font: 13px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; background: var(--code); padding: 1px 4px; border-radius: 3px; overflow-wrap: anywhere; }
1077
+ .muted { color: var(--muted); }
1078
+ .url { color: var(--muted); overflow-wrap: anywhere; margin: 0 0 24px; }
1079
+ .summary { display:grid; grid-template-columns: auto 1fr; gap: 24px; align-items: center; background: var(--card); border:1px solid var(--line); border-radius: 8px; padding: 20px; margin-bottom: 24px; }
1080
+ .score { font-size: 56px; font-weight: 700; font-variant-numeric: tabular-nums; line-height: 1; }
1081
+ .score small { font-size: 18px; color: var(--muted); font-weight: 400; }
1082
+ .tone-good { color: var(--good); } .tone-warn { color: var(--warn); } .tone-bad { color: var(--bad); }
1083
+ .facts { display:grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 8px 16px; margin: 0; }
1084
+ .facts div { display:grid; } .facts dt { color: var(--muted); font-size: 13px; } .facts dd { margin:0; font-variant-numeric: tabular-nums; }
1085
+ table { border-collapse: collapse; width: 100%; font-size: 14px; }
1086
+ th, td { text-align: left; border-bottom: 1px solid var(--line); padding: 6px 8px; vertical-align: top; }
1087
+ td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
1088
+ .block { background: var(--card); border:1px solid var(--line); border-radius: 8px; padding: 16px 20px; margin-bottom: 24px; overflow-x: auto; }
1089
+ .rule { background: var(--card); border:1px solid var(--line); border-left: 4px solid var(--muted); border-radius: 8px; padding: 16px 20px; margin-bottom: 16px; }
1090
+ .sev-critical, .sev-serious { border-left-color: var(--bad); } .sev-moderate { border-left-color: var(--warn); }
1091
+ .meta { margin: 4px 0 0; color: var(--muted); font-size: 13px; }
1092
+ .sev { text-transform: uppercase; letter-spacing: .04em; font-weight: 600; }
1093
+ .explain p { margin: 8px 0; }
1094
+ .findings { padding-left: 20px; margin: 12px 0 0; }
1095
+ .finding { margin-bottom: 12px; }
1096
+ .msg { margin: 0 0 4px; }
1097
+ .el { display:grid; grid-template-columns: 72px 1fr; gap: 2px 8px; margin: 0; font-size: 13px; }
1098
+ .el dt { color: var(--muted); } .el dd { margin: 0; min-width: 0; }
1099
+ .html { display:inline-block; max-width: 100%; }
1100
+ details pre { white-space: pre-wrap; font: 12px/1.4 ui-monospace, Menlo, monospace; max-height: 480px; overflow: auto; background: var(--code); padding: 12px; border-radius: 6px; }
1101
+ @media (max-width: 560px) { .summary { grid-template-columns: 1fr; } .el { grid-template-columns: 1fr; } }
1102
+ </style>
1103
+ </head>
1104
+ <body>
1105
+ <main>
1106
+ <h1>Agent readiness</h1>
1107
+ <p class="url">${esc(report.title)} \xB7 <a href="${esc(report.url)}">${esc(report.url)}</a> \xB7 ${esc(report.checkedAt.slice(0, 16).replace("T", " "))} UTC</p>
1108
+ ${report.redirectedFrom ? `<p class="redirect"><strong>${esc(redirectNote(report))}</strong></p>` : ""}
1109
+ ${report.measured ? "" : `<p class="redirect"><strong>${esc(report.notMeasured ?? "")}</strong></p>`}
1110
+
1111
+ <div class="summary">
1112
+ <div class="score tone-${tone}">${report.measured ? `${report.score}<small>/100</small>` : `<small>no score</small>`}<div style="font-size:15px;font-weight:600;margin-top:6px">${esc(report.grade)}</div></div>
1113
+ <dl class="facts">
1114
+ <div><dt>Findings</dt><dd>${report.findings.length}</dd></div>
1115
+ <div><dt>Snapshot</dt><dd>\u2248 ${report.metrics.snapshotTokens.toLocaleString("en-US")} tokens</dd></div>
1116
+ <div><dt>Fields</dt><dd>${report.metrics.fields}</dd></div>
1117
+ <div><dt>Buttons</dt><dd>${report.metrics.buttons}</dd></div>
1118
+ <div><dt>Charts</dt><dd>${report.metrics.charts}</dd></div>
1119
+ <div><dt>Bridge</dt><dd>${b.components ? `${b.components} controls \xB7 ${b.actions} actions` : "none"}</dd></div>
1120
+ </dl>
1121
+ </div>
1122
+
1123
+ <div class="block">
1124
+ <h2>Score</h2>
1125
+ ${report.measured ? "" : `<p class="muted"><strong>Not measured.</strong> There is no score: the bridge had no controls and the page has no fields or charts.</p>`}
1126
+ <p class="muted">100, minus each rule's points per finding, capped per rule. 85 and up: ready. 60 to 84: partly ready. Below 60: not ready.</p>
1127
+ <table><thead><tr><th>Rule</th><th>Contract</th><th class="num">Found</th><th class="num">Points</th></tr></thead><tbody>
1128
+ ${report.deductions.map((d) => `<tr><td><a href="#${d.rule}">${esc(RULES[d.rule].title)}</a></td><td>${esc(RULES[d.rule].contract)}</td><td class="num">${d.findings}</td><td class="num">\u2212${d.points}</td></tr>`).join("")}
1129
+ ${report.deductions.length ? "" : `<tr><td colspan="4">${report.measured ? "Nothing found." : "Nothing found, and nothing measured."}</td></tr>`}
1130
+ </tbody></table>
1131
+ </div>
1132
+
1133
+ ${sections}
1134
+
1135
+ <div class="block">
1136
+ <h2>Agent bridge</h2>
1137
+ <p class="muted">${b.source ? `Read through ${esc(b.source)}.` : "No window.agent and no WebMCP tools on this page."}${b.webmcpTools.length ? ` WebMCP tools: ${b.webmcpTools.map((t) => `<code>${esc(t)}</code>`).join(" ")}.` : ""}${b.error ? ` Error: ${esc(b.error)}` : ""}</p>
1138
+ ${b.controls.length ? `<table><thead><tr><th>Label</th><th>Control</th><th>Actions</th></tr></thead><tbody>${bridgeRows}</tbody></table>` : ""}
1139
+ </div>
1140
+
1141
+ <div class="block">
1142
+ <h2>What a browser agent reads</h2>
1143
+ <p class="muted">The page's accessibility snapshot, as browser tools give it to a model: ${report.metrics.snapshotChars.toLocaleString("en-US")} characters, about ${report.metrics.snapshotTokens.toLocaleString("en-US")} tokens (characters \xF7 4).</p>
1144
+ <details><summary>Show the snapshot</summary><pre>${esc(report.snapshot)}</pre></details>
1145
+ </div>
1146
+
1147
+ <p class="muted">@booki-aui/readiness ${esc(report.tool.version)} \xB7 checks reference the Agent Contract (spec/agent-contract.md).</p>
1148
+ </main>
1149
+ </body>
1150
+ </html>
1151
+ `;
1152
+ }
1153
+
1154
+ export {
1155
+ RULES,
1156
+ SNAPSHOT_TOKENS,
1157
+ score,
1158
+ parseSnapshot,
1159
+ estimateTokens,
1160
+ VERSION,
1161
+ looksLikeIconName,
1162
+ IRREVERSIBLE,
1163
+ bookiControlFor,
1164
+ audit,
1165
+ check,
1166
+ toJson,
1167
+ toConsole,
1168
+ toHtml
1169
+ };