@sixb/agent 0.0.0-stage → 0.1.0

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.
Files changed (219) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +31 -2
  3. package/dist/abort.d.ts +6 -0
  4. package/dist/abort.d.ts.map +1 -0
  5. package/dist/agent-prompt.d.ts +120 -0
  6. package/dist/agent-prompt.d.ts.map +1 -0
  7. package/dist/agent-runtime/errors.d.ts +13 -0
  8. package/dist/agent-runtime/errors.d.ts.map +1 -0
  9. package/dist/agent-runtime/preflight.d.ts +18 -0
  10. package/dist/agent-runtime/preflight.d.ts.map +1 -0
  11. package/dist/agent-runtime/profile.d.ts +14 -0
  12. package/dist/agent-runtime/profile.d.ts.map +1 -0
  13. package/dist/artifacts/layout-check/layout-check.d.ts +87 -0
  14. package/dist/artifacts/layout-check/layout-check.d.ts.map +1 -0
  15. package/dist/artifacts/materialize.d.ts +115 -0
  16. package/dist/artifacts/materialize.d.ts.map +1 -0
  17. package/dist/artifacts/publish-tool.d.ts +86 -0
  18. package/dist/artifacts/publish-tool.d.ts.map +1 -0
  19. package/dist/ask-parent-tool.d.ts +36 -0
  20. package/dist/ask-parent-tool.d.ts.map +1 -0
  21. package/dist/attachments.d.ts +68 -0
  22. package/dist/attachments.d.ts.map +1 -0
  23. package/dist/child-files.d.ts +96 -0
  24. package/dist/child-files.d.ts.map +1 -0
  25. package/dist/child-questions.d.ts +24 -0
  26. package/dist/child-questions.d.ts.map +1 -0
  27. package/dist/computer-runner.d.ts +65 -0
  28. package/dist/computer-runner.d.ts.map +1 -0
  29. package/dist/context-budget.d.ts +28 -0
  30. package/dist/context-budget.d.ts.map +1 -0
  31. package/dist/context-compaction.d.ts +48 -0
  32. package/dist/context-compaction.d.ts.map +1 -0
  33. package/dist/conversation-memory.d.ts +21 -0
  34. package/dist/conversation-memory.d.ts.map +1 -0
  35. package/dist/errors.d.ts +46 -0
  36. package/dist/errors.d.ts.map +1 -0
  37. package/dist/execution-plan.d.ts +34 -0
  38. package/dist/execution-plan.d.ts.map +1 -0
  39. package/dist/failure.d.ts +14 -0
  40. package/dist/failure.d.ts.map +1 -0
  41. package/dist/family-mailbox.d.ts +60 -0
  42. package/dist/family-mailbox.d.ts.map +1 -0
  43. package/dist/file-ref.d.ts +6 -0
  44. package/dist/file-ref.d.ts.map +1 -0
  45. package/dist/image-attachments.d.ts +34 -0
  46. package/dist/image-attachments.d.ts.map +1 -0
  47. package/dist/index.d.ts +35 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +12168 -0
  50. package/dist/index.js.map +65 -0
  51. package/dist/message-authors.d.ts +34 -0
  52. package/dist/message-authors.d.ts.map +1 -0
  53. package/dist/message-times.d.ts +8 -0
  54. package/dist/message-times.d.ts.map +1 -0
  55. package/dist/model-adapters.d.ts +55 -0
  56. package/dist/model-adapters.d.ts.map +1 -0
  57. package/dist/model-lines.d.ts +16 -0
  58. package/dist/model-lines.d.ts.map +1 -0
  59. package/dist/requester.d.ts +15 -0
  60. package/dist/requester.d.ts.map +1 -0
  61. package/dist/run-agent-turn.d.ts +63 -0
  62. package/dist/run-agent-turn.d.ts.map +1 -0
  63. package/dist/run-child.d.ts +77 -0
  64. package/dist/run-child.d.ts.map +1 -0
  65. package/dist/run-conversation-turn.d.ts +42 -0
  66. package/dist/run-conversation-turn.d.ts.map +1 -0
  67. package/dist/run-credential.d.ts +22 -0
  68. package/dist/run-credential.d.ts.map +1 -0
  69. package/dist/run-environment.d.ts +115 -0
  70. package/dist/run-environment.d.ts.map +1 -0
  71. package/dist/run-fate.d.ts +15 -0
  72. package/dist/run-fate.d.ts.map +1 -0
  73. package/dist/run-sandbox.d.ts +60 -0
  74. package/dist/run-sandbox.d.ts.map +1 -0
  75. package/dist/run-subagent.d.ts +51 -0
  76. package/dist/run-subagent.d.ts.map +1 -0
  77. package/dist/run-workflow-agent-node.d.ts +41 -0
  78. package/dist/run-workflow-agent-node.d.ts.map +1 -0
  79. package/dist/sandbox-api-context.d.ts +34 -0
  80. package/dist/sandbox-api-context.d.ts.map +1 -0
  81. package/dist/sandbox-file-registry.d.ts +9 -0
  82. package/dist/sandbox-file-registry.d.ts.map +1 -0
  83. package/dist/sandbox-files.d.ts +71 -0
  84. package/dist/sandbox-files.d.ts.map +1 -0
  85. package/dist/sandbox-handle.d.ts +15 -0
  86. package/dist/sandbox-handle.d.ts.map +1 -0
  87. package/dist/sandbox-readiness.d.ts +8 -0
  88. package/dist/sandbox-readiness.d.ts.map +1 -0
  89. package/dist/skills/built-in.d.ts +15 -0
  90. package/dist/skills/built-in.d.ts.map +1 -0
  91. package/dist/subagent-continuation.d.ts +27 -0
  92. package/dist/subagent-continuation.d.ts.map +1 -0
  93. package/dist/subagent-inbox.d.ts +53 -0
  94. package/dist/subagent-inbox.d.ts.map +1 -0
  95. package/dist/subagent-tools.d.ts +282 -0
  96. package/dist/subagent-tools.d.ts.map +1 -0
  97. package/dist/thread-context.d.ts +12 -0
  98. package/dist/thread-context.d.ts.map +1 -0
  99. package/dist/tools/attachments.d.ts +11 -0
  100. package/dist/tools/attachments.d.ts.map +1 -0
  101. package/dist/tools/bash.d.ts +60 -0
  102. package/dist/tools/bash.d.ts.map +1 -0
  103. package/dist/tools/model-spec.d.ts +4 -0
  104. package/dist/tools/model-spec.d.ts.map +1 -0
  105. package/dist/tools/read.d.ts +43 -0
  106. package/dist/tools/read.d.ts.map +1 -0
  107. package/dist/tools/result-media.d.ts +22 -0
  108. package/dist/tools/result-media.d.ts.map +1 -0
  109. package/dist/tools/result-output.d.ts +18 -0
  110. package/dist/tools/result-output.d.ts.map +1 -0
  111. package/dist/tools/tool-files.d.ts +59 -0
  112. package/dist/tools/tool-files.d.ts.map +1 -0
  113. package/dist/tools/view-file.d.ts +40 -0
  114. package/dist/tools/view-file.d.ts.map +1 -0
  115. package/dist/tsconfig.json +5 -0
  116. package/dist/turn-runtime.d.ts +19 -0
  117. package/dist/turn-runtime.d.ts.map +1 -0
  118. package/dist/types.d.ts +76 -0
  119. package/dist/types.d.ts.map +1 -0
  120. package/dist/workflow-input-attachments.d.ts +18 -0
  121. package/dist/workflow-input-attachments.d.ts.map +1 -0
  122. package/package.json +59 -4
  123. package/src/abort.ts +40 -0
  124. package/src/agent-prompt.ts +758 -0
  125. package/src/agent-runtime/errors.ts +44 -0
  126. package/src/agent-runtime/preflight.ts +314 -0
  127. package/src/agent-runtime/profile.ts +23 -0
  128. package/src/artifacts/layout-check/check.cjs +478 -0
  129. package/src/artifacts/layout-check/layout-check.ts +460 -0
  130. package/src/artifacts/materialize.ts +380 -0
  131. package/src/artifacts/publish-tool.ts +700 -0
  132. package/src/ask-parent-tool.ts +100 -0
  133. package/src/attachments.ts +850 -0
  134. package/src/child-files.ts +540 -0
  135. package/src/child-questions.ts +42 -0
  136. package/src/computer-runner.ts +284 -0
  137. package/src/context-budget.ts +161 -0
  138. package/src/context-compaction.ts +529 -0
  139. package/src/conversation-memory.ts +45 -0
  140. package/src/errors.ts +85 -0
  141. package/src/execution-plan.ts +50 -0
  142. package/src/failure.ts +71 -0
  143. package/src/family-mailbox.ts +189 -0
  144. package/src/file-ref.ts +18 -0
  145. package/src/image-attachments.ts +322 -0
  146. package/src/index.ts +54 -0
  147. package/src/message-authors.ts +77 -0
  148. package/src/message-times.ts +21 -0
  149. package/src/model-adapters.ts +227 -0
  150. package/src/model-lines.ts +28 -0
  151. package/src/requester.ts +21 -0
  152. package/src/run-agent-turn.ts +347 -0
  153. package/src/run-child.ts +319 -0
  154. package/src/run-conversation-turn.ts +257 -0
  155. package/src/run-credential.ts +55 -0
  156. package/src/run-environment.ts +769 -0
  157. package/src/run-fate.ts +51 -0
  158. package/src/run-sandbox.ts +63 -0
  159. package/src/run-subagent.ts +347 -0
  160. package/src/run-workflow-agent-node.ts +270 -0
  161. package/src/sandbox-api-context.ts +234 -0
  162. package/src/sandbox-file-registry.ts +26 -0
  163. package/src/sandbox-files.ts +326 -0
  164. package/src/sandbox-handle.ts +19 -0
  165. package/src/sandbox-readiness.ts +22 -0
  166. package/src/skills/built-in.ts +183 -0
  167. package/src/skills/sixb-artifacts/SKILL.md +95 -0
  168. package/src/skills/sixb-artifacts/canvas.md +104 -0
  169. package/src/skills/sixb-artifacts/document.md +63 -0
  170. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/first-job.html +42 -0
  171. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/region.html +29 -0
  172. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/shared.css +35 -0
  173. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/welcome.html +31 -0
  174. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/canvas.json +107 -0
  175. package/src/skills/sixb-artifacts/examples/canvas/retro/canvas.json +158 -0
  176. package/src/skills/sixb-artifacts/examples/document/incident-report/document.md +35 -0
  177. package/src/skills/sixb-artifacts/examples/document/operations-review/document.md +41 -0
  178. package/src/skills/sixb-artifacts/examples/document/operations-review/figures/restorations.svg +1 -0
  179. package/src/skills/sixb-artifacts/examples/page/collections-desk/index.html +169 -0
  180. package/src/skills/sixb-artifacts/examples/page/collections-desk/queries/overdue.json +13 -0
  181. package/src/skills/sixb-artifacts/examples/page/dispatch-board/data/dispatch.json +234 -0
  182. package/src/skills/sixb-artifacts/examples/page/dispatch-board/index.html +245 -0
  183. package/src/skills/sixb-artifacts/examples/page/fleet-planner/data/plan.json +53 -0
  184. package/src/skills/sixb-artifacts/examples/page/fleet-planner/index.html +462 -0
  185. package/src/skills/sixb-artifacts/examples/page/service-explorer/data/service.json +276 -0
  186. package/src/skills/sixb-artifacts/examples/page/service-explorer/index.html +549 -0
  187. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/queries/overdue.json +13 -0
  188. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/workbook.json +30 -0
  189. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Inventory.csv +13 -0
  190. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Spend.csv +6 -0
  191. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/workbook.json +47 -0
  192. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Quarters.csv +5 -0
  193. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Regions.csv +5 -0
  194. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/workbook.json +78 -0
  195. package/src/skills/sixb-artifacts/examples/slides/launch-plan/index.html +63 -0
  196. package/src/skills/sixb-artifacts/examples/slides/q3-review/index.html +133 -0
  197. package/src/skills/sixb-artifacts/file.md +17 -0
  198. package/src/skills/sixb-artifacts/page.md +215 -0
  199. package/src/skills/sixb-artifacts/queries.md +66 -0
  200. package/src/skills/sixb-artifacts/references.md +68 -0
  201. package/src/skills/sixb-artifacts/sheet.md +223 -0
  202. package/src/skills/sixb-artifacts/slides.md +137 -0
  203. package/src/skills/sixb-memory/SKILL.md +68 -0
  204. package/src/skills/text-assets.d.ts +25 -0
  205. package/src/subagent-continuation.ts +51 -0
  206. package/src/subagent-inbox.ts +101 -0
  207. package/src/subagent-tools.ts +1609 -0
  208. package/src/thread-context.ts +25 -0
  209. package/src/tools/attachments.ts +28 -0
  210. package/src/tools/bash.ts +217 -0
  211. package/src/tools/model-spec.ts +22 -0
  212. package/src/tools/read.ts +262 -0
  213. package/src/tools/result-media.ts +147 -0
  214. package/src/tools/result-output.ts +44 -0
  215. package/src/tools/tool-files.ts +204 -0
  216. package/src/tools/view-file.ts +155 -0
  217. package/src/turn-runtime.ts +33 -0
  218. package/src/types.ts +79 -0
  219. package/src/workflow-input-attachments.ts +140 -0
@@ -0,0 +1,478 @@
1
+ // The Agent's layout check, run in the sandbox by publish_artifact: it serves a deck, a page, or a
2
+ // canvas's boards as the API serves its frame, with the kit and the runtime, and opens them in the
3
+ // sandbox's headless Chromium. A deck shows at 1280×720 with each slide filling the page, and every
4
+ // slide is measured in each of its themes with the layout probe and screenshot in the first. A page
5
+ // loads at 1280px and at a phone's 390px, is measured whole in each theme, its top 4000px, and
6
+ // screenshot at each width. A canvas's boards load each at its own size, measured as a page is and
7
+ // screenshot as boards/<id>.png. It writes one line of JSON:
8
+ // { layout, slides, problems, errors, screenshots, stopped? } or { skipped }.
9
+ //
10
+ // node check.cjs <directory> <output directory> <library directory> <deadline in ms> <layout>
11
+ //
12
+ // The library holds what the worker installs beside this script: deck.css, page.css, runtime.js,
13
+ // probe.js. The output directory holds entries.json, each page the check opens by its path, with
14
+ // the kit and runtime in it; boards.json, a canvas's boards and their sizes; files.json,
15
+ // the paths the version publishes: only those are served, since the reader gets only those; and
16
+ // themes.json, the themes the reader sees it in: Sixb's light and dark, or the mode its
17
+ // theme.json pins, with its tokens; and queries.json, the version's queries by name with the
18
+ // status each is served with, its answer in queries/<name>.json: the page reads them at
19
+ // __sixb/queries/<name>.json, as the runtime does with no app around it.
20
+ //
21
+ // A deck or a page can stop answering, with a script that never yields or a font that never
22
+ // loads, and a browser outlives a node that is killed. So every wait on the page is bounded, and
23
+ // when one runs out, or the deadline passes, the check reports what it found so far and exits:
24
+ // Playwright kills the browser it launched when node exits.
25
+ "use strict"
26
+
27
+ const http = require("node:http")
28
+ const fs = require("node:fs")
29
+ const path = require("node:path")
30
+
31
+ const [deck, out, lib, deadline, layout = "deck"] = process.argv.slice(2)
32
+ const DEADLINE_MS = Number(deadline) || 100_000
33
+ /** The most one step waits on the page: its fonts, a slide's measure, a screenshot. */
34
+ const STEP_MS = 10_000
35
+ const PROTOCOL = "sixb-frame/1"
36
+ /** The frame's own files, served from the library as the API serves them beside a version's. */
37
+ const FRAME_FILES = new Set(["/__sixb/deck.css", "/__sixb/page.css", "/__sixb/runtime.js"])
38
+ /** Where the runtime reads a query when it is opened on its own. */
39
+ const QUERY_PATH = /^\/__sixb\/queries\/([a-z0-9][a-z0-9-]{0,63})\.json$/
40
+ /** The widths a page is checked at: a laptop's, and a phone's. */
41
+ const VIEWS = [
42
+ { name: "desktop", width: 1280, height: 800 },
43
+ { name: "phone", width: 390, height: 844 },
44
+ ]
45
+ /** How much of a page the check measures and shows, from its top. */
46
+ const PAGE_HEIGHT = 4000
47
+ const TYPES = {
48
+ ".html": "text/html; charset=utf-8",
49
+ ".css": "text/css; charset=utf-8",
50
+ ".js": "text/javascript; charset=utf-8",
51
+ ".mjs": "text/javascript; charset=utf-8",
52
+ ".json": "application/json",
53
+ ".svg": "image/svg+xml",
54
+ ".png": "image/png",
55
+ ".jpg": "image/jpeg",
56
+ ".jpeg": "image/jpeg",
57
+ ".gif": "image/gif",
58
+ ".webp": "image/webp",
59
+ ".avif": "image/avif",
60
+ ".woff": "font/woff",
61
+ ".woff2": "font/woff2",
62
+ ".ttf": "font/ttf",
63
+ ".otf": "font/otf",
64
+ }
65
+
66
+ /** What the check has found so far, which a check that stops early reports. */
67
+ const found = { layout, slides: 0, problems: [], errors: [], screenshots: [] }
68
+ const findings = () => ({ ...found, errors: [...new Set(found.errors)].slice(0, 10) })
69
+
70
+ let reported = false
71
+ /** Writes the report, then exits once it is written. */
72
+ function report(result, code = 0) {
73
+ if (reported) return process.exit(code)
74
+ reported = true
75
+ process.stdout.write(`${JSON.stringify(result)}\n`, () => process.exit(code))
76
+ }
77
+
78
+ class Stalled extends Error {}
79
+
80
+ /** `promise`, or a {@link Stalled} naming `what` once it has taken `ms`. */
81
+ function within(what, promise, ms = STEP_MS) {
82
+ let timer
83
+ return Promise.race([
84
+ promise,
85
+ new Promise((_, reject) => {
86
+ timer = setTimeout(
87
+ () => reject(new Stalled(`${what} did not respond within ${ms / 1000} seconds`)),
88
+ ms
89
+ )
90
+ }),
91
+ ]).finally(() => clearTimeout(timer))
92
+ }
93
+
94
+ function loadPlaywright() {
95
+ for (const candidate of [process.env.SIXB_PLAYWRIGHT, "/opt/sixb/js/node_modules/playwright"]) {
96
+ if (!candidate) continue
97
+ try {
98
+ return require(candidate)
99
+ } catch {
100
+ // The next candidate, then none.
101
+ }
102
+ }
103
+ return null
104
+ }
105
+
106
+ function serve() {
107
+ // Each page the check opens, with the kit and the runtime in it, by its path in the version.
108
+ const entries = JSON.parse(fs.readFileSync(path.join(out, "entries.json"), "utf8"))
109
+ const published = new Set(JSON.parse(fs.readFileSync(path.join(out, "files.json"), "utf8")))
110
+ const queries = fs.existsSync(path.join(out, "queries.json"))
111
+ ? JSON.parse(fs.readFileSync(path.join(out, "queries.json"), "utf8"))
112
+ : {}
113
+ const root = path.resolve(deck)
114
+ const server = http.createServer((request, response) => {
115
+ const pathname = decodeURIComponent(new URL(request.url, "http://deck").pathname)
116
+ let body = null
117
+ let file = null
118
+ let status = 200
119
+ if (pathname === "/favicon.ico") {
120
+ response.writeHead(204).end()
121
+ return
122
+ }
123
+ const entry = entries[pathname === "/" ? "index.html" : pathname.slice(1)]
124
+ const query = QUERY_PATH.exec(pathname)?.[1]
125
+ if (entry) file = path.join(out, entry)
126
+ else if (FRAME_FILES.has(pathname)) file = path.join(lib, pathname.slice("/__sixb/".length))
127
+ else if (query && Object.hasOwn(queries, query)) {
128
+ file = path.join(out, "queries", `${query}.json`)
129
+ status = queries[query]
130
+ } else if (published.has(pathname.slice(1))) file = path.join(root, pathname.slice(1))
131
+ try {
132
+ if (file) body = fs.readFileSync(file)
133
+ } catch {
134
+ body = null
135
+ }
136
+ if (body === null) {
137
+ response.writeHead(404).end()
138
+ return
139
+ }
140
+ const type = TYPES[path.extname(file).toLowerCase()]
141
+ response.writeHead(status, type ? { "content-type": type } : {}).end(body)
142
+ })
143
+ return new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(server)))
144
+ }
145
+
146
+ async function main() {
147
+ const playwright = loadPlaywright()
148
+ if (!playwright) return { skipped: "no_browser" }
149
+ const probe = fs.readFileSync(path.join(lib, "probe.js"), "utf8")
150
+ const themes = JSON.parse(fs.readFileSync(path.join(out, "themes.json"), "utf8"))
151
+ const server = await serve()
152
+ let browser
153
+ try {
154
+ browser = await playwright.chromium.launch({
155
+ headless: true,
156
+ ...(process.env.SIXB_CHROMIUM ? { executablePath: process.env.SIXB_CHROMIUM } : {}),
157
+ })
158
+ } catch (error) {
159
+ server.close()
160
+ return { skipped: "no_browser", detail: String(error?.message ?? error).slice(0, 300) }
161
+ }
162
+ const noun = { canvas: "the canvas", page: "the page" }[layout] ?? "the deck"
163
+ let step = noun
164
+ let stalled = false
165
+ try {
166
+ // Reduced motion, so what animates in is measured and shown where it lands.
167
+ const page = await browser.newPage({
168
+ viewport: { width: 1280, height: 720 },
169
+ deviceScaleFactor: 1,
170
+ reducedMotion: "reduce",
171
+ })
172
+ const { errors, problems, screenshots } = found
173
+ page.on("pageerror", (error) => errors.push(error.message))
174
+ // A file that fails names itself; Chromium's console line for it does not.
175
+ const local = (url) => url.replace(/^http:\/\/127\.0\.0\.1:\d+\//, "")
176
+ page.on("console", (message) => {
177
+ if (message.type() === "error" && !message.text().startsWith("Failed to load resource")) {
178
+ errors.push(message.text())
179
+ }
180
+ })
181
+ page.on("requestfailed", (request) => errors.push(`${local(request.url())} did not load`))
182
+ page.on("response", (response) => {
183
+ if (response.status() >= 400) {
184
+ errors.push(`${local(response.url())} did not load (${response.status()})`)
185
+ }
186
+ })
187
+ const { port } = server.address()
188
+ // A font or a library from a CDN may be out of reach; the entry is measured as it loaded.
189
+ const load = async (url) => {
190
+ await page
191
+ .goto(url, { waitUntil: "load", timeout: 15_000 })
192
+ .catch((error) => errors.push(`${noun} did not finish loading: ${error.message}`))
193
+ // Each theme is measured as it settles, not on its way there.
194
+ await within(
195
+ step,
196
+ page.addStyleTag({
197
+ content: "*, *::before, *::after { transition-duration: 0s !important; transition-delay: 0s !important; }",
198
+ })
199
+ ).catch(() => {})
200
+ await within(`${noun}'s fonts`, page.evaluate(() => document.fonts?.ready)).catch(() => {})
201
+ }
202
+ const settle = () =>
203
+ within(
204
+ step,
205
+ page.evaluate(() => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))))
206
+ )
207
+ const send = (method, params) =>
208
+ within(
209
+ step,
210
+ page.evaluate(
211
+ ({ protocol, method, params }) =>
212
+ window.postMessage({ protocol, id: 0, method, params }, "*"),
213
+ { protocol: PROTOCOL, method, params }
214
+ )
215
+ )
216
+ if (layout === "canvas") {
217
+ // Each board at its own size, as the canvas shows it, in each theme.
218
+ const boards = JSON.parse(fs.readFileSync(path.join(out, "boards.json"), "utf8"))
219
+ fs.mkdirSync(path.join(out, "boards"), { recursive: true })
220
+ for (const board of boards) {
221
+ step = `board '${board.id}'`
222
+ await page.setViewportSize({ width: board.w, height: Math.min(board.h, PAGE_HEIGHT) })
223
+ await load(`http://127.0.0.1:${port}/${board.file.split("/").map(encodeURIComponent).join("/")}`)
224
+ for (const [index, name] of Object.keys(themes).entries()) {
225
+ step = `board '${board.id}' in ${name} mode`
226
+ await send("theme", themes[name])
227
+ await settle()
228
+ for (const problem of await within(step, page.evaluate(`(${probe})("page")`))) {
229
+ problems.push({ ...problem, board: board.id, theme: name })
230
+ }
231
+ if (index === 0) {
232
+ const file = path.join(out, "boards", `${board.id}.png`)
233
+ await page.screenshot({ path: file, timeout: STEP_MS })
234
+ screenshots.push(file)
235
+ }
236
+ }
237
+ }
238
+ return findings()
239
+ }
240
+ if (layout === "page") {
241
+ for (const view of VIEWS) {
242
+ step = `the page at ${view.width}px`
243
+ await page.setViewportSize({ width: view.width, height: view.height })
244
+ await load(`http://127.0.0.1:${port}/index.html`)
245
+ for (const [index, name] of Object.keys(themes).entries()) {
246
+ step = `the page at ${view.width}px in ${name} mode`
247
+ await send("theme", themes[name])
248
+ await settle()
249
+ // The page in one view, up to its cut: the probe judges only what the viewport shows.
250
+ const height = await within(
251
+ step,
252
+ page.evaluate(() => document.documentElement.scrollHeight)
253
+ )
254
+ await page.setViewportSize({
255
+ width: view.width,
256
+ height: Math.max(view.height, Math.min(PAGE_HEIGHT, height)),
257
+ })
258
+ await settle()
259
+ for (const problem of await within(step, page.evaluate(`(${probe})("page")`))) {
260
+ problems.push({ ...problem, view: view.name, theme: name })
261
+ }
262
+ if (index === 0) {
263
+ const file = path.join(out, `${view.name}.png`)
264
+ await page.screenshot({ path: file, timeout: STEP_MS })
265
+ screenshots.push(file)
266
+ }
267
+ await page.setViewportSize({ width: view.width, height: view.height })
268
+ }
269
+ }
270
+ return findings()
271
+ }
272
+ await load(`http://127.0.0.1:${port}/index.html#sixb-fill`)
273
+ found.slides = await within(
274
+ step,
275
+ page.evaluate(() => document.querySelectorAll("section.slide").length)
276
+ )
277
+ for (const [index, name] of Object.keys(themes).entries()) {
278
+ step = `the deck in ${name} mode`
279
+ await send("theme", themes[name])
280
+ for (let slide = 1; slide <= found.slides; slide++) {
281
+ step = `slide ${slide} in ${name} mode`
282
+ await send("goto", { slide })
283
+ await page.waitForFunction(
284
+ (slide) => document.querySelectorAll("section.slide")[slide - 1]?.hasAttribute("data-current"),
285
+ slide,
286
+ { timeout: 5_000 }
287
+ )
288
+ await settle()
289
+ for (const problem of await within(step, page.evaluate(`(${probe})(${slide})`))) {
290
+ problems.push({ ...problem, slide, theme: name })
291
+ }
292
+ for (const problem of await photoContrast(page, slide, step)) {
293
+ problems.push({ ...problem, slide, theme: name })
294
+ }
295
+ if (index === 0) {
296
+ const file = path.join(out, `slide-${String(slide).padStart(2, "0")}.png`)
297
+ await page.screenshot({ path: file, timeout: STEP_MS })
298
+ screenshots.push(file)
299
+ }
300
+ }
301
+ }
302
+ return findings()
303
+ } catch (error) {
304
+ // Playwright's own timeouts, for a slide that never shows or a screenshot never taken, are
305
+ // stalls too.
306
+ if (!(error instanceof Stalled) && error?.name !== "TimeoutError") throw error
307
+ stalled = true
308
+ return {
309
+ ...findings(),
310
+ stopped: error instanceof Stalled ? error.message : `${step} did not respond in time`,
311
+ }
312
+ } finally {
313
+ // A page that stalled may not let its browser close; exiting kills it.
314
+ if (!stalled) await within("the browser", browser.close(), 5_000).catch(() => {})
315
+ server.close()
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Text over a photo, which the probe cannot judge from styles: each text whose center sits over
321
+ * an image is hidden, the slide is shot without it, and the pixels under its box are read. The
322
+ * text fails when the darker or lighter tenth of them, whichever is worse, is under WCAG AA
323
+ * against its color.
324
+ */
325
+ async function photoContrast(page, slide, step) {
326
+ try {
327
+ return await readPhotoContrast(page, slide, step)
328
+ } catch (error) {
329
+ // A stall stops the check as the probe's would; any other failure only skips this slide.
330
+ if (error instanceof Stalled || error?.name === "TimeoutError") throw error
331
+ return []
332
+ }
333
+ }
334
+
335
+ async function readPhotoContrast(page, slide, step) {
336
+ const candidates = await within(
337
+ step,
338
+ page.evaluate((slide) => {
339
+ const root = document.querySelectorAll("section.slide")[slide - 1]
340
+ if (!root) return []
341
+ const found = []
342
+ for (const element of root.querySelectorAll("*")) {
343
+ const own = Array.from(element.childNodes).some(
344
+ (node) => node.nodeType === Node.TEXT_NODE && (node.textContent ?? "").trim() !== ""
345
+ )
346
+ if (!own || element.closest("svg")) continue
347
+ const rect = element.getBoundingClientRect()
348
+ if (rect.width < 1 || rect.height < 1) continue
349
+ const style = getComputedStyle(element)
350
+ if (style.visibility === "hidden" || Number(style.opacity) === 0) continue
351
+ const stack = document.elementsFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2)
352
+ const under = stack.slice(Math.max(0, stack.indexOf(element)))
353
+ let photo = false
354
+ for (const node of under) {
355
+ if (/^(img|picture|video|canvas)$/i.test(node.tagName)) { photo = true; break }
356
+ if (node === element) continue
357
+ // A solid box between the text and the photo, such as a panel, is the probe's to judge.
358
+ const color = getComputedStyle(node).backgroundColor
359
+ const alpha = color.startsWith("rgba") ? Number(color.split(",")[3]?.replace(")", "")) : color === "transparent" ? 0 : 1
360
+ if (alpha >= 0.99 && !node.contains(root.querySelector("img, picture, video, canvas"))) break
361
+ }
362
+ if (!photo) continue
363
+ const size = Number.parseFloat(style.fontSize)
364
+ const bold = Number.parseInt(style.fontWeight, 10) >= 700
365
+ element.setAttribute("data-sixb-photo-text", String(found.length))
366
+ found.push({
367
+ index: found.length,
368
+ rect: { x: rect.left, y: rect.top, width: rect.width, height: rect.height },
369
+ color: style.color,
370
+ large: size >= 24 || (bold && size >= 18.66),
371
+ text: (element.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 60),
372
+ selector: [element.tagName.toLowerCase(), ...Array.from(element.classList).slice(0, 2)].join("."),
373
+ })
374
+ }
375
+ return found
376
+ }, slide)
377
+ )
378
+ if (!Array.isArray(candidates) || candidates.length === 0) return []
379
+ const hide = await page.addStyleTag({
380
+ content: "[data-sixb-photo-text] { color: transparent !important; -webkit-text-fill-color: transparent !important; text-shadow: none !important; }",
381
+ })
382
+ let shot
383
+ try {
384
+ shot = await within(step, page.screenshot({ type: "png", timeout: STEP_MS }))
385
+ } finally {
386
+ await hide.evaluate((node) => node.remove()).catch(() => {})
387
+ await page.evaluate(() => {
388
+ for (const node of document.querySelectorAll("[data-sixb-photo-text]")) node.removeAttribute("data-sixb-photo-text")
389
+ }).catch(() => {})
390
+ }
391
+ return within(
392
+ step,
393
+ page.evaluate(
394
+ async ({ data, candidates, slide }) => {
395
+ const image = new Image()
396
+ image.src = `data:image/png;base64,${data}`
397
+ await image.decode()
398
+ const canvas = document.createElement("canvas")
399
+ canvas.width = image.naturalWidth
400
+ canvas.height = image.naturalHeight
401
+ const context = canvas.getContext("2d", { willReadFrequently: true })
402
+ context.drawImage(image, 0, 0)
403
+ const parse = (color) => {
404
+ context.clearRect(0, 0, 1, 1)
405
+ context.fillStyle = color
406
+ context.fillRect(0, 0, 1, 1)
407
+ return Array.from(context.getImageData(0, 0, 1, 1).data)
408
+ }
409
+ const channel = (value) => {
410
+ const c = value / 255
411
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
412
+ }
413
+ const luminance = ([r, g, b]) => 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b)
414
+ const ratio = (a, b) => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)
415
+ const hex = (rgb) => `#${rgb.slice(0, 3).map((v) => Math.round(v).toString(16).padStart(2, "0")).join("")}`
416
+ const box = document.querySelectorAll("section.slide")[slide - 1].getBoundingClientRect()
417
+ const problems = []
418
+ for (const candidate of candidates) {
419
+ const { x, y, width, height } = candidate.rect
420
+ const left = Math.max(0, Math.floor(x))
421
+ const top = Math.max(0, Math.floor(y))
422
+ const right = Math.min(canvas.width, Math.ceil(x + width))
423
+ const bottom = Math.min(canvas.height, Math.ceil(y + height))
424
+ if (right <= left || bottom <= top) continue
425
+ const pixels = context.getImageData(left, top, right - left, bottom - top).data
426
+ const step = Math.max(1, Math.floor(Math.sqrt(((right - left) * (bottom - top)) / 4000)))
427
+ const samples = []
428
+ for (let row = 0; row < bottom - top; row += step) {
429
+ for (let column = 0; column < right - left; column += step) {
430
+ const at = (row * (right - left) + column) * 4
431
+ samples.push([pixels[at], pixels[at + 1], pixels[at + 2]])
432
+ }
433
+ }
434
+ if (samples.length === 0) continue
435
+ const [r, g, b, a] = parse(candidate.color)
436
+ const text = luminance([r, g, b])
437
+ // The tenth of the area that reads worst stands for the text's background.
438
+ const scored = samples
439
+ .map((sample) => ({ sample, contrast: ratio(text, luminance(sample)) }))
440
+ .sort((p, q) => p.contrast - q.contrast)
441
+ const worst = scored[Math.floor(scored.length * 0.1)]
442
+ const needed = candidate.large ? 3 : 4.5
443
+ if (a / 255 >= 0.5 && worst.contrast < needed) {
444
+ problems.push({
445
+ code: "contrast",
446
+ rect: {
447
+ x: Math.round(x - box.left),
448
+ y: Math.round(y - box.top),
449
+ width: Math.round(width),
450
+ height: Math.round(height),
451
+ },
452
+ text: candidate.text,
453
+ selector: candidate.selector,
454
+ ratio: Math.round(worst.contrast * 100) / 100,
455
+ colors: [hex([r, g, b]), `${hex(worst.sample)} in the photo`],
456
+ })
457
+ }
458
+ }
459
+ return problems
460
+ },
461
+ { data: shot.toString("base64"), candidates, slide }
462
+ )
463
+ )
464
+ }
465
+
466
+ setTimeout(
467
+ () =>
468
+ report({
469
+ ...findings(),
470
+ stopped: `the check took longer than ${Math.round(DEADLINE_MS / 1000)} seconds`,
471
+ }),
472
+ DEADLINE_MS
473
+ ).unref()
474
+
475
+ main().then(
476
+ (result) => report(result),
477
+ (error) => report({ failed: String(error?.stack ?? error).slice(0, 1000) }, 1)
478
+ )