rvlib-shipkit 2.11.0 → 2.13.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 (298) hide show
  1. package/CHANGELOG.md +56 -12
  2. package/README.md +1 -1
  3. package/package.json +4 -2
  4. package/src/agent-time/store.ts +2 -2
  5. package/src/check.ts +1 -1
  6. package/src/checks/SK001-package-json-shape.check.ts +4 -0
  7. package/src/checks/SK003-claude-md-shape.check.ts +1 -1
  8. package/src/checks/SK004-gitignore-policy.check.ts +27 -2
  9. package/src/checks/SK005-rvlib-versions.check.ts +1 -1
  10. package/src/checks/SK008-reviewer-agent.check.ts +2 -2
  11. package/src/checks/SK012-config-barrel-import.check.ts +1 -1
  12. package/src/checks/SK015-nested-repo.check.ts +1 -1
  13. package/src/checks/SK035-public-clean.check.ts +46 -0
  14. package/src/checks/SK036-draft-media-size.check.ts +28 -0
  15. package/src/cli/cmd_Backup.ts +152 -0
  16. package/src/cli/cmd_Ci.ts +8 -11
  17. package/src/cli/cmd_Drill.ts +145 -0
  18. package/src/cli/cmd_Home.ts +50 -3
  19. package/src/cli/cmd_Media.ts +96 -5
  20. package/src/cli/cmd_Review.ts +8 -2
  21. package/src/cli/cmd_Shot.ts +5 -2
  22. package/src/cli/cmd_Smoke.ts +4 -1
  23. package/src/cli/cmd_Social.ts +226 -0
  24. package/src/cli/cmd_Start.ts +1 -1
  25. package/src/cli/cmd_Time.ts +1 -1
  26. package/src/cli/cmd_Trailer.ts +9 -2
  27. package/src/cli/cmd_Veille.ts +173 -0
  28. package/src/cli/family-pages.ts +3 -0
  29. package/src/cli/registry.ts +13 -2
  30. package/src/cli.ts +5 -2
  31. package/src/collections/actions.ts +1 -49
  32. package/src/collections/checks.ts +2 -1
  33. package/src/collections/collection-types.ts +11 -2
  34. package/src/collections/providers.ts +4 -4
  35. package/src/collections/review.ts +2 -1
  36. package/src/collections/tests.ts +19 -8
  37. package/src/contracts/apply-contracts.ts +1 -3
  38. package/src/contracts/contract-manifests.ts +2 -3
  39. package/src/contracts/contract-types.ts +0 -1
  40. package/src/contracts/contracts-engine.ts +0 -3
  41. package/src/core/app-icon.ts +9 -3
  42. package/src/core/bun-builtins.ts +2 -2
  43. package/src/core/discover-checks.ts +37 -5
  44. package/src/core/fix-scope.ts +4 -2
  45. package/src/core/floor-resolve.ts +68 -48
  46. package/src/core/floor.ts +9 -0
  47. package/src/core/git-root.ts +24 -0
  48. package/src/core/last-good.ts +3 -1
  49. package/src/core/layout.ts +8 -0
  50. package/src/core/log-stamp.ts +36 -0
  51. package/src/core/loop-watch.ts +93 -0
  52. package/src/core/machine-link.ts +134 -0
  53. package/src/core/memory-watch.ts +41 -0
  54. package/src/core/one-way-in-policy.ts +27 -19
  55. package/src/core/run-ci.ts +6 -8
  56. package/src/core/run-fixers.ts +9 -9
  57. package/src/core/slots.ts +21 -0
  58. package/src/core/tree-rev.ts +60 -0
  59. package/src/core/unit-files.ts +42 -0
  60. package/src/drill/render.ts +140 -0
  61. package/src/drill/run.ts +269 -0
  62. package/src/fleet/scan-fleet.ts +6 -5
  63. package/src/home/daemon-jobs.ts +201 -0
  64. package/src/home/global-context.ts +34 -1
  65. package/src/home/home-routes.ts +22 -15
  66. package/src/home/hubs.ts +10 -3
  67. package/src/home/inbox-shape.ts +61 -6
  68. package/src/home/inbox.ts +75 -4
  69. package/src/home/lib-watch.ts +10 -3
  70. package/src/home/machine-stores.ts +15 -29
  71. package/src/home/run-daemon.ts +15 -18
  72. package/src/home/run-pm.ts +2 -0
  73. package/src/home/serve-daemon.ts +4 -3
  74. package/src/home/serve-web.ts +110 -1
  75. package/src/hooks/commit-message.ts +28 -19
  76. package/src/hooks/leak-guard.ts +10 -3
  77. package/src/hooks/run-hooks.ts +2 -6
  78. package/src/identities/identities.ts +334 -0
  79. package/src/identities/machine-route.ts +126 -0
  80. package/src/identities/machine.ts +62 -0
  81. package/src/init-repo.ts +1 -1
  82. package/src/ledger/check-stats.ts +10 -9
  83. package/src/ledger/gate-checks.ts +32 -1
  84. package/src/ledger/record-kept.ts +112 -0
  85. package/src/ledger/repo-view.ts +10 -0
  86. package/src/ledger/run-log.ts +17 -12
  87. package/src/ledger/run-timeline.ts +8 -4
  88. package/src/ledger/store.ts +7 -0
  89. package/src/ledger/suite-log.ts +17 -13
  90. package/src/media-kinds.ts +9 -1
  91. package/src/media-store/backup/daemon.ts +73 -0
  92. package/src/media-store/backup/keys.ts +25 -0
  93. package/src/media-store/backup/manifest.ts +193 -0
  94. package/src/media-store/backup/restore.ts +192 -0
  95. package/src/media-store/backup/run.ts +278 -0
  96. package/src/media-store/backup/secret.ts +86 -0
  97. package/src/media-store/backup/snapshot.ts +64 -0
  98. package/src/media-store/backup/sources.ts +199 -0
  99. package/src/media-store/content.ts +11 -1
  100. package/src/media-store/daemon.ts +56 -70
  101. package/src/media-store/hand.ts +58 -0
  102. package/src/media-store/put.ts +122 -0
  103. package/src/media-store/space.ts +73 -11
  104. package/src/pages/forward.ts +35 -0
  105. package/src/pages/frame-client.ts +118 -0
  106. package/src/pages/routes.ts +29 -0
  107. package/src/pages/unit.ts +92 -0
  108. package/src/plan/planner.ts +12 -0
  109. package/src/plan/repo-source.ts +19 -5
  110. package/src/reflect/transcript.ts +35 -10
  111. package/src/release/public-clean.ts +301 -0
  112. package/src/release/published-here.ts +22 -0
  113. package/src/release/run-bump.ts +2 -1
  114. package/src/release/run-release.ts +4 -1
  115. package/src/repo-config.ts +53 -2
  116. package/src/review/http.ts +16 -2
  117. package/src/review/media-kind.ts +3 -3
  118. package/src/review/media-read.ts +3 -3
  119. package/src/review/model.ts +24 -5
  120. package/src/review/notes.ts +77 -0
  121. package/src/review/project.ts +6 -38
  122. package/src/review/routes.ts +8 -13
  123. package/src/review/store.ts +46 -4
  124. package/src/review/trailer-media.ts +24 -3
  125. package/src/review/trailer-shots.ts +106 -0
  126. package/src/review/unit.ts +1 -1
  127. package/src/scaffold/files/agent-handoff.md +3 -0
  128. package/src/scaffold/files/agent-index.md +4 -12
  129. package/src/scaffold/project-scaffold.ts +5 -4
  130. package/src/serve/embed.ts +1 -1
  131. package/src/serve/hub-app/col-card.tsx +3 -17
  132. package/src/serve/hub-app/col-tables-view.tsx +2 -1
  133. package/src/serve/hub-app/cols-svc.ts +12 -14
  134. package/src/serve/hub-app/dock-st.ts +4 -2
  135. package/src/serve/hub-app/dock-view.tsx +2 -0
  136. package/src/serve/hub-app/frames-st.ts +35 -0
  137. package/src/serve/hub-app/hash-route.ts +64 -1
  138. package/src/serve/hub-app/home-st.ts +31 -7
  139. package/src/serve/hub-app/home-strip.css +9 -1
  140. package/src/serve/hub-app/home-strip.tsx +7 -6
  141. package/src/serve/hub-app/home.html +5 -0
  142. package/src/serve/hub-app/hub-app.tsx +49 -5
  143. package/src/serve/hub-app/hub.css +29 -11
  144. package/src/serve/hub-app/icons.tsx +16 -1
  145. package/src/serve/hub-app/identities-st.ts +210 -0
  146. package/src/serve/hub-app/identities-view.tsx +352 -0
  147. package/src/serve/hub-app/identities.css +48 -0
  148. package/src/serve/hub-app/identity-address.ts +52 -0
  149. package/src/serve/hub-app/inbox-st.ts +59 -6
  150. package/src/serve/hub-app/inbox-view.tsx +48 -6
  151. package/src/serve/hub-app/inbox.css +12 -1
  152. package/src/serve/hub-app/index.html +3 -0
  153. package/src/serve/hub-app/keys.ts +10 -2
  154. package/src/serve/hub-app/list-walk.ts +89 -0
  155. package/src/serve/hub-app/machine-st.ts +12 -0
  156. package/src/serve/hub-app/media-view.tsx +2 -1
  157. package/src/serve/hub-app/pages-frames.tsx +134 -0
  158. package/src/serve/hub-app/pages-svc.ts +111 -0
  159. package/src/serve/hub-app/palette-st.ts +18 -3
  160. package/src/serve/hub-app/palette-view.tsx +9 -2
  161. package/src/serve/hub-app/planned-view.tsx +2 -1
  162. package/src/serve/hub-app/project-list.css +18 -14
  163. package/src/serve/hub-app/project-list.tsx +88 -49
  164. package/src/serve/hub-app/projects-svc.ts +33 -3
  165. package/src/serve/hub-app/repo-sections.ts +19 -2
  166. package/src/serve/hub-app/repo-st.ts +75 -19
  167. package/src/serve/hub-app/review/review-cells.tsx +3 -3
  168. package/src/serve/hub-app/review/review-kit.ts +30 -7
  169. package/src/serve/hub-app/review/review-page.tsx +1 -1
  170. package/src/serve/hub-app/review/review-st.ts +33 -11
  171. package/src/serve/hub-app/review/review-thread.tsx +11 -9
  172. package/src/serve/hub-app/review/review-views.tsx +84 -19
  173. package/src/serve/hub-app/review/thread-st.ts +1 -10
  174. package/src/serve/hub-app/review/trailer-page.tsx +2 -1
  175. package/src/serve/hub-app/review.css +17 -8
  176. package/src/serve/hub-app/site/site-part.tsx +173 -0
  177. package/src/serve/hub-app/site/site-st.ts +157 -0
  178. package/src/serve/hub-app/site.css +35 -0
  179. package/src/serve/hub-app/social/calendar.tsx +182 -0
  180. package/src/serve/hub-app/social/comms-page.tsx +306 -0
  181. package/src/serve/hub-app/social/kit.tsx +244 -0
  182. package/src/serve/hub-app/social/post-card.tsx +456 -0
  183. package/src/serve/hub-app/social/problems.tsx +60 -0
  184. package/src/serve/hub-app/social/social-model.ts +154 -0
  185. package/src/serve/hub-app/social/social-page.tsx +674 -0
  186. package/src/serve/hub-app/social/social-st.ts +986 -0
  187. package/src/serve/hub-app/social.css +289 -0
  188. package/src/serve/hub-app/stores/stores-page.tsx +311 -0
  189. package/src/serve/hub-app/stores/stores-st.ts +286 -0
  190. package/src/serve/hub-app/stores.css +54 -0
  191. package/src/serve/hub-app/test-view.tsx +9 -2
  192. package/src/serve/hub-app/tests-svc.ts +16 -1
  193. package/src/serve/hub-app/timeline-geometry.ts +1 -1
  194. package/src/serve/hub-app/timeline-view.tsx +3 -2
  195. package/src/serve/hub-app/tree-build.ts +6 -0
  196. package/src/serve/hub-app/tree-row.tsx +27 -4
  197. package/src/serve/hub-app/tree-svc.ts +18 -49
  198. package/src/serve/hub-app/veille/veille-page.tsx +514 -0
  199. package/src/serve/hub-app/veille/veille-st.ts +443 -0
  200. package/src/serve/hub-app/veille.css +84 -0
  201. package/src/serve/hub-runtime.ts +14 -9
  202. package/src/serve/project-gutter-route.ts +44 -12
  203. package/src/serve/resources-wire.ts +48 -0
  204. package/src/serve/run-lanes.ts +7 -4
  205. package/src/serve/same-origin.ts +1 -1
  206. package/src/serve/serve-hub.ts +27 -18
  207. package/src/serve/tracked-watch.ts +24 -3
  208. package/src/serve/warm-cell.ts +5 -1
  209. package/src/shipkit-files.ts +15 -4
  210. package/src/shipkit.ts +0 -1
  211. package/src/shot/box.ts +162 -0
  212. package/src/shot/browser-slot.ts +62 -0
  213. package/src/shot/client.ts +43 -7
  214. package/src/shot/clip-encoder.ts +93 -12
  215. package/src/shot/film-box.ts +188 -0
  216. package/src/shot/shooter.ts +50 -15
  217. package/src/shot/shot-ask.ts +10 -2
  218. package/src/shot/stepped-clip.ts +5 -4
  219. package/src/site/desk.ts +242 -0
  220. package/src/site/routes.ts +66 -0
  221. package/src/site/unit.ts +62 -0
  222. package/src/social/brands.ts +22 -0
  223. package/src/social/compose.ts +97 -0
  224. package/src/social/desk-index.ts +123 -0
  225. package/src/social/desk-wire.ts +64 -0
  226. package/src/social/drafts.ts +183 -0
  227. package/src/social/house.ts +24 -0
  228. package/src/social/load.ts +319 -0
  229. package/src/social/md.ts +70 -0
  230. package/src/social/media-facts.ts +53 -0
  231. package/src/social/media-kind.ts +189 -0
  232. package/src/social/media-limit.ts +42 -0
  233. package/src/social/media-of.ts +30 -0
  234. package/src/social/migrate.ts +123 -0
  235. package/src/social/open.ts +17 -0
  236. package/src/social/post-url.ts +158 -0
  237. package/src/social/presence.ts +332 -0
  238. package/src/social/public-read.ts +53 -0
  239. package/src/social/publish/bluesky.ts +168 -0
  240. package/src/social/publish/discord.ts +76 -0
  241. package/src/social/publish/index.ts +24 -0
  242. package/src/social/publish/secret.ts +13 -0
  243. package/src/social/push.ts +31 -0
  244. package/src/social/richtext.ts +37 -0
  245. package/src/social/routes.ts +180 -0
  246. package/src/social/stats.ts +134 -0
  247. package/src/social/text.ts +267 -0
  248. package/src/social/tracker-route.ts +39 -0
  249. package/src/social/tracker.ts +255 -0
  250. package/src/social/unit.ts +53 -0
  251. package/src/social/writes.ts +130 -0
  252. package/src/start-repo.ts +14 -9
  253. package/src/stores/collection.ts +27 -0
  254. package/src/stores/desk.ts +336 -0
  255. package/src/stores/model.ts +187 -0
  256. package/src/stores/routes.ts +126 -0
  257. package/src/stores/unit.ts +57 -0
  258. package/src/suite/calibrate.ts +127 -0
  259. package/src/suite/core-counters.ts +91 -0
  260. package/src/suite/judge-suites.ts +94 -34
  261. package/src/suite/suite-cli.ts +44 -10
  262. package/src/suite/suite-cpu-preload.ts +34 -9
  263. package/src/trailer/adapter.ts +4 -0
  264. package/src/trailer/build.ts +42 -11
  265. package/src/trailer/ffmpeg.ts +11 -0
  266. package/src/trailer/footage.ts +30 -13
  267. package/src/trailer/grammar.ts +18 -2
  268. package/src/trailer/graph.ts +28 -6
  269. package/src/trailer/passage.ts +21 -6
  270. package/src/trailer/plan.ts +74 -3
  271. package/src/trailer/shelf.ts +16 -0
  272. package/src/trailer/stitch.ts +67 -26
  273. package/src/trailer/url.ts +1 -1
  274. package/src/trailer/versions.ts +24 -0
  275. package/src/ts/gate-typecheck.ts +32 -0
  276. package/src/ts/typecheck-cli.ts +9 -11
  277. package/src/tui/tui-app.tsx +0 -1
  278. package/src/veille/asks.ts +155 -0
  279. package/src/veille/auto.ts +31 -0
  280. package/src/veille/batch.ts +27 -0
  281. package/src/veille/chrome.ts +127 -0
  282. package/src/veille/collection.ts +28 -0
  283. package/src/veille/desk.ts +242 -0
  284. package/src/veille/identity.ts +80 -0
  285. package/src/veille/import.ts +68 -0
  286. package/src/veille/log.ts +183 -0
  287. package/src/veille/platforms.ts +118 -0
  288. package/src/veille/reads.ts +66 -0
  289. package/src/veille/replied.ts +110 -0
  290. package/src/veille/routes.ts +185 -0
  291. package/src/veille/service.ts +81 -0
  292. package/src/veille/watch.ts +116 -0
  293. package/src/veille/worth.ts +46 -0
  294. package/src/wiki/scan-md.ts +18 -0
  295. package/src/collections/posts.ts +0 -142
  296. package/src/contracts/manifests/social.contract.ts +0 -20
  297. package/src/scaffold/files/agent-coding.md +0 -35
  298. package/src/ts/typecheck-cache.ts +0 -11
@@ -0,0 +1,162 @@
1
+ // THE BOX ROUTE: a repo whose repo.config.ts `browsers.box` names an ssh host films there when it runs on a Mac. Every
2
+ // browser start of the repo (a take, a Shooter: sk shot, look sheets, thumbs, the trailer's films) asks `openBrowser`,
3
+ // which on such a Mac connects to the box's warm chromium (film-box.ts) instead of launching one: its devtools reached
4
+ // through an ssh forward, each localhost page it opens reached back on this Mac through a reverse forward (the urls
5
+ // unchanged), its frames drawn and encoded on the box's GPU, only the result crossing back. Anywhere else, or with
6
+ // SK_FILM_HERE=1 for one run, it launches here as before, under the browser cap either way.
7
+ //
8
+ // The one constraint a reader breaks first: a box that does not answer is one loud line and nothing filmed, never a
9
+ // browser launched on the Mac instead (the Mac is the machine the route protects).
10
+ import { createHash } from 'crypto'
11
+ import { readFileSync } from 'fs'
12
+ import { browserCap, type BrowserCap, browserSlot, HERE_ENV } from './browser-slot.ts'
13
+ import { CDP_PORT } from './film-box.ts'
14
+
15
+ /** the box this machine films on for the repo, or null: a Mac whose repo names one, unless SK_FILM_HERE=1 */
16
+ export function filmBox(c: Pick<BrowserCap, 'box'> | null, env: Record<string, string | undefined> = process.env, platform = process.platform): string | null {
17
+ return c?.box != null && platform === 'darwin' && env[HERE_ENV] !== '1' ? c.box : null
18
+ }
19
+
20
+ /** the slice of playwright the route drives: a browser to connect to, its default context, a page's viewport */
21
+ type PwPage = { setViewportSize(v: { width: number; height: number }): Promise<void>; addInitScript(s: { content: string }): Promise<void>; close(): Promise<void> }
22
+ type PwContext = { newPage(): Promise<PwPage>; newCDPSession(p: PwPage): Promise<{ send(m: string, p?: Record<string, unknown>): Promise<unknown> }> }
23
+ export type PwBrowser = { contexts(): PwContext[]; close(): Promise<void>; isConnected(): boolean; on(e: 'disconnected', cb: () => void): void }
24
+ export type Pw = { chromium: { launch(o: { headless: boolean; args: string[] }): Promise<unknown>; connectOverCDP(url: string): Promise<PwBrowser> } }
25
+
26
+ /** a browser opened for a repo: `browser` takes newContext as a launched one does; `reach` before a page goes to a
27
+ * url (the box needs this Mac's localhost port forwarded); `close` ends it and frees its slot */
28
+ export type Opened<B> = { browser: B; where: string; reach(url: string): Promise<void>; close(): Promise<void> }
29
+
30
+ const SSH = (box: string) => ['ssh', '-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes', box]
31
+ /** where the box's devtools answer on this Mac */
32
+ const localCdp = (box: string): number => 40000 + (parseInt(createHash('sha1').update(box).digest('hex').slice(0, 4), 16) % 9000)
33
+ const FILM_DIR = 'dev/shipkit-film'
34
+ const BOX_FILE = new URL('./film-box.ts', import.meta.url).pathname
35
+ const BOX_SCRIPT = readFileSync(BOX_FILE)
36
+ const BOX_HASH = createHash('sha1').update(BOX_SCRIPT).digest('hex').slice(0, 12)
37
+ const MISSING = 86
38
+
39
+ const down = (box: string, why: string): Error =>
40
+ new Error(`${box} is down, nothing filmed (${why.trim().split('\n').at(-1) ?? why}). To film on this Mac for one run: ${HERE_ENV}=1 <the same command>`)
41
+
42
+ async function run(cmd: string[], stdin?: Uint8Array): Promise<{ code: number; out: string; err: string }> {
43
+ const p = Bun.spawn(cmd, { stdin: stdin ?? 'ignore', stdout: 'pipe', stderr: 'pipe' })
44
+ const [out, err] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()])
45
+ return { code: await p.exited, out, err }
46
+ }
47
+
48
+ /** the box's warm browser answering, its script uploaded first when the box lacks this version of it */
49
+ async function boxUp(box: string, version: string, say: (l: string) => void): Promise<string> {
50
+ const script = `${FILM_DIR}/film-box-${BOX_HASH}.ts`
51
+ const go = () => run([...SSH(box), `if exist ${script.replaceAll('/', '\\')} (bun ${script} up ${version}) else (exit ${MISSING})`])
52
+ let r = await go()
53
+ if (r.code === MISSING) {
54
+ await run([...SSH(box), `mkdir ${FILM_DIR.replaceAll('/', '\\')} 2>nul`])
55
+ const up = await run(['scp', '-q', '-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes', BOX_FILE, `${box}:${script}`])
56
+ if (up.code === 255 && /connect|resolve|timed out|refused/i.test(up.err)) throw down(box, up.err)
57
+ if (up.code !== 0) throw new Error(`${box}: uploading ${script} failed (exit ${up.code}): ${up.err.trim()}`)
58
+ r = await go()
59
+ }
60
+ if (r.code === 255) throw down(box, r.err)
61
+ if (r.code !== 0) throw new Error(`${box}: its film browser did not come up (exit ${r.code}): ${r.err.trim()}`)
62
+ for (const l of r.err.split('\n').filter(Boolean)) say(l)
63
+ return r.out.trim()
64
+ }
65
+
66
+ /** an ssh forward added to the box's master connection (instant, kept with it), else a tunnel process of our own */
67
+ async function forward(box: string, spec: string[], own: { p: ReturnType<typeof Bun.spawn> | null }): Promise<void> {
68
+ const r = await run(['ssh', '-O', 'forward', ...spec, box])
69
+ if (r.code === 0) return
70
+ own.p?.kill()
71
+ own.p = Bun.spawn([...SSH(box), '-N', '-o', 'ExitOnForwardFailure=yes', ...spec], { stdin: 'ignore', stdout: 'ignore', stderr: 'pipe' })
72
+ await Bun.sleep(1500)
73
+ if (own.p.exitCode != null) throw down(box, await new Response(own.p.stderr as ReadableStream).text())
74
+ }
75
+
76
+ const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]'])
77
+
78
+ /** the box's default context as a launched browser's newContext: each context a set of pages there, the viewport set
79
+ * per page; one context because only it keeps the profile's HTTP cache */
80
+ function asLaunched(b: PwBrowser, all: PwPage[]) {
81
+ return {
82
+ isConnected: () => b.isConnected(),
83
+ on: (e: 'disconnected', cb: () => void) => b.on(e, cb),
84
+ close: async () => {
85
+ await Promise.all(all.splice(0).map((p) => p.close().catch(() => undefined)))
86
+ await b.close()
87
+ },
88
+ async newContext(o: { viewport: { width: number; height: number }; deviceScaleFactor: number }) {
89
+ const ctx = b.contexts()[0]
90
+ if (ctx == null) throw new Error('the box browser has no default context')
91
+ const pages: PwPage[] = []
92
+ const scripts: string[] = []
93
+ return {
94
+ async newPage() {
95
+ const p = await ctx.newPage()
96
+ pages.push(p)
97
+ all.push(p)
98
+ await p.setViewportSize(o.viewport)
99
+ if (o.deviceScaleFactor !== 1)
100
+ await (await ctx.newCDPSession(p)).send('Emulation.setDeviceMetricsOverride', { ...o.viewport, deviceScaleFactor: o.deviceScaleFactor, mobile: false })
101
+ for (const content of scripts) await p.addInitScript({ content })
102
+ return p
103
+ },
104
+ newCDPSession: (p: PwPage) => ctx.newCDPSession(p),
105
+ async addInitScript(s: { content: string }) {
106
+ scripts.push(s.content)
107
+ for (const p of pages) await p.addInitScript(s)
108
+ },
109
+ async close() {
110
+ await Promise.all(pages.splice(0).map((p) => p.close().catch(() => undefined)))
111
+ },
112
+ }
113
+ },
114
+ }
115
+ }
116
+
117
+ /** a browser for `who` of the repo at `root`: on its box from a Mac (filmBox), else launched here; one of the repo's
118
+ * browser slots held until close */
119
+ export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; args: string[]; say?: (l: string) => void }): Promise<Opened<B>> {
120
+ const say = o.say ?? ((l: string) => console.error(l))
121
+ const cap = await browserCap(o.root)
122
+ const box = filmBox(cap)
123
+ const release = await browserSlot(o.who, { ...(o.root ? { root: o.root } : {}), say, onBox: box != null })
124
+ try {
125
+ if (box == null) {
126
+ const b = (await pw.chromium.launch({ headless: true, args: o.args })) as B & { close(): Promise<void> }
127
+ return { browser: b, where: 'here', reach: async () => undefined, close: () => b.close().catch(() => undefined).finally(release) }
128
+ }
129
+ const t = performance.now()
130
+ const version = (JSON.parse(readFileSync(Bun.resolveSync('playwright-core/package.json', import.meta.dir), 'utf8')) as { version: string }).version
131
+ const state = await boxUp(box, version, say)
132
+ const own: { p: ReturnType<typeof Bun.spawn> | null } = { p: null }
133
+ const cdp = localCdp(box)
134
+ await forward(box, ['-L', `${cdp}:127.0.0.1:${CDP_PORT}`], own)
135
+ const b = await pw.chromium.connectOverCDP(`http://127.0.0.1:${cdp}`)
136
+ say(`${o.who}: filming on ${box} (${state.split(' ').slice(0, 2).join(' ')}, ${Math.round(performance.now() - t)} ms to its browser)`)
137
+ const reached = new Set<number>()
138
+ const pages: PwPage[] = []
139
+ const browser = asLaunched(b, pages)
140
+ return {
141
+ browser: browser as B,
142
+ where: box,
143
+ async reach(url: string) {
144
+ const u = new URL(url)
145
+ if (!LOCAL.has(u.hostname)) return
146
+ const port = Number(u.port || (u.protocol === 'https:' ? 443 : 80))
147
+ if (reached.has(port)) return
148
+ await forward(box, ['-R', `${port}:127.0.0.1:${port}`], own)
149
+ reached.add(port)
150
+ },
151
+ async close() {
152
+ // its pages close, the connection drops, the box's browser stays warm
153
+ await browser.close().catch(() => undefined)
154
+ own.p?.kill()
155
+ release()
156
+ },
157
+ }
158
+ } catch (e) {
159
+ release()
160
+ throw e
161
+ }
162
+ }
@@ -0,0 +1,62 @@
1
+ // THE BROWSER CAP: every headless browser that shoots or records on a repo's behalf (an sk shot ask, a Shooter given
2
+ // a slot, sk smoke, the trailer's films, a repo script's own browser) holds one slot of that repo's pool
3
+ // (core/slots.ts browserPool) for its whole life; repo.config.ts `browsers.max` sizes the pool. A slot left by a dead
4
+ // process is free at once (the lease's liveness rule). A repo whose `browsers.box` names a host never starts one on a
5
+ // Mac: browserSlot refuses there, but for the box route's own slot (`onBox`, box.ts) and SK_FILM_HERE=1.
6
+ //
7
+ // The one constraint a reader breaks first: the slot belongs to the process that starts the browser. A parent that
8
+ // holds one and waits on a child that takes one deadlocks at cap 1, so a parent only counts its children (the
9
+ // trailer's lanes are the cap) and never holds a slot for them.
10
+ import { existsSync } from 'fs'
11
+ import { dirname, join, resolve } from 'path'
12
+ import { browserPool, browsersProblem, DEFAULT_BROWSERS, takeSlot } from '../core/slots.ts'
13
+
14
+ /** one run films on this machine even though its repo names a box: the owner's switch when the box is off */
15
+ export const HERE_ENV = 'SK_FILM_HERE'
16
+
17
+ export type BrowserCap = { repo: string; cap: number; root: string; box: string | null }
18
+
19
+ /** the nearest dir at or above `from` holding a repo.config.ts, or null */
20
+ function configRoot(from: string): string | null {
21
+ for (let d = resolve(from); ; d = dirname(d)) {
22
+ if (existsSync(join(d, 'repo.config.ts'))) return d
23
+ if (dirname(d) === d) return null
24
+ }
25
+ }
26
+
27
+ /** the browser cap of the repo at `root` (default: the repo the cwd is in), or null outside any repo; a value that is
28
+ * not a whole number of browsers throws */
29
+ export async function browserCap(root?: string): Promise<BrowserCap | null> {
30
+ const at = root ?? configRoot(process.cwd())
31
+ if (at == null || !existsSync(join(at, 'repo.config.ts'))) return null
32
+ const { loadRepoConfig } = await import('../repo-config.ts')
33
+ const c = await loadRepoConfig(at)
34
+ const bad = browsersProblem(c.browsers)
35
+ if (bad != null) throw new Error(`${join(at, 'repo.config.ts')}: ${bad}`)
36
+ return { repo: c.name, cap: c.browsers?.max ?? DEFAULT_BROWSERS, root: at, box: c.browsers?.box ?? null }
37
+ }
38
+
39
+ /** why `who` may not start a browser of this repo on this machine, or null: a repo filmed by its box never starts one
40
+ * on a Mac, unless the slot is the box route's own (its browser on the box) */
41
+ export function browserRefusal(c: Pick<BrowserCap, 'repo' | 'box'>, who: string, onBox: boolean, platform = process.platform, env: Record<string, string | undefined> = process.env): string | null {
42
+ if (c.box == null || onBox || platform !== 'darwin' || env[HERE_ENV] === '1') return null
43
+ return `${who}: ${c.repo} films on ${c.box} (repo.config.ts browsers.box), so no browser of it starts on this Mac: a browser goes through shot/box.ts openBrowser (${HERE_ENV}=1 films here for one run, the owner's call)`
44
+ }
45
+
46
+ /** wait for one of the repo's browser slots and hold it until the returned release (or this process ends), saying
47
+ * once whom it waits on; outside any repo there is no cap and nothing is held. `onBox`: the browser runs on the
48
+ * repo's box, this Mac only drives it */
49
+ export async function browserSlot(who: string, o: { root?: string; say?: (l: string) => void; pollMs?: number; onBox?: boolean } = {}): Promise<() => void> {
50
+ const c = await browserCap(o.root)
51
+ if (c == null) return () => undefined
52
+ const no = browserRefusal(c, who, o.onBox === true)
53
+ if (no != null) throw new Error(no)
54
+ const say = o.say ?? ((l: string) => console.error(l))
55
+ const got = await takeSlot(browserPool(c.repo, c.cap), { repo: c.repo, check: who }, {
56
+ pollMs: o.pollMs ?? 250,
57
+ onWait: (held) =>
58
+ say(`${who}: waiting for a browser of ${c.repo}, all ${c.cap} held (repo.config.ts browsers.max): ${held.map((h) => `pid ${h.pid} (${h.check})`).join(', ') || 'a holder starting'}`),
59
+ })
60
+ if (got == null) throw new Error(`${who}: the browser slot wait of ${c.repo} stopped with no slot`)
61
+ return got.release
62
+ }
@@ -1,6 +1,7 @@
1
1
  // the one way code asks for a shot or a clip: `shotUrl` and `clipUrl` post to
2
2
  // the warm shot service (serve-shot.ts), start it through pm when it is down,
3
- // and shoot in process only when the machine has no pm (CI, SHIPKIT_NO_HOME).
3
+ // and shoot in process only when the machine has no pm (CI, SHIPKIT_NO_HOME). A repo filmed by its box films there
4
+ // from a Mac (box.ts), on a Shooter of this process.
4
5
  // `sk shot` and the trailer's `url` film both call these.
5
6
  import { DEFAULT_FPS, DEFAULT_VIEWPORT, DEFAULT_WAIT_MS, type ClipAsk, type ShotAsk, shotUrlBase, type Viewport } from './shot-ask.ts'
6
7
  import type { ShotDone } from './shooter.ts'
@@ -8,9 +9,11 @@ import type { ShotDone } from './shooter.ts'
8
9
  /** the global process id pm knows the service by (shot.shipkit.ts) */
9
10
  export const SHOT_PROCESS = 'shot'
10
11
 
11
- export type ShotInput = { url: string; out: string; viewport?: Viewport; dpr?: number; reload?: boolean; waitMs?: number; step?: string; at?: number }
12
+ /** `root`: the repo the shot is for, whose browser cap it holds a slot of while it runs (browser-slot.ts); default the
13
+ * repo the cwd is in */
14
+ export type ShotInput = { url: string; out: string; viewport?: Viewport; dpr?: number; reload?: boolean; waitMs?: number; step?: string; at?: number; root?: string }
12
15
  export type ClipInput = ShotInput & { seconds: number; fps?: number; dom?: boolean }
13
- export type ShotResult = ShotDone & { via: 'warm' | 'started' | 'local' }
16
+ export type ShotResult = ShotDone & { via: 'warm' | 'started' | 'local' | 'box' }
14
17
 
15
18
  const shotAsk = (i: ShotInput): ShotAsk => ({
16
19
  url: i.url,
@@ -27,20 +30,53 @@ function stepped(i: { step?: string }, r: ShotResult): void {
27
30
  }
28
31
 
29
32
  /** a png of `url` at `out` (absolute), through the warm browser; with `step`, the page drawn at `at` first */
30
- export async function shotUrl(i: ShotInput, log: (l: string) => void = () => {}): Promise<ShotResult> {
31
- const r = await ask('/shot', { ...shotAsk(i), ...(i.step ? { step: i.step, at: i.at ?? 0 } : {}) }, log)
33
+ export async function shotUrl(i: ShotInput, log: (l: string) => void = quiet): Promise<ShotResult> {
34
+ const a: ShotAsk = { ...shotAsk(i), ...(i.step ? { step: i.step, at: i.at ?? 0 } : {}) }
35
+ const r = (await onBox(`shot ${i.url}`, i, log, (s) => s.shot(a))) ?? (await held(`shot ${i.url}`, i, log, () => ask('/shot', a, log)))
32
36
  stepped(i, r)
33
37
  return r
34
38
  }
35
39
 
36
40
  /** an mp4 of `seconds` of `url` at `out` (absolute): a page that is a canvas through its WebCodecs, any other page (or
37
41
  * `dom`) as chromium paints it */
38
- export async function clipUrl(i: ClipInput, log: (l: string) => void = () => {}): Promise<ShotResult> {
39
- const r = await ask('/clip', { ...shotAsk(i), seconds: i.seconds, fps: i.fps ?? DEFAULT_FPS, dom: i.dom ?? false, ...(i.step ? { step: i.step } : {}) } satisfies ClipAsk, log)
42
+ export async function clipUrl(i: ClipInput, log: (l: string) => void = quiet): Promise<ShotResult> {
43
+ const a: ClipAsk = { ...shotAsk(i), seconds: i.seconds, fps: i.fps ?? DEFAULT_FPS, dom: i.dom ?? false, ...(i.step ? { step: i.step } : {}) }
44
+ const r = (await onBox(`clip ${i.url}`, i, log, (s) => s.clip(a))) ?? (await held(`clip ${i.url}`, i, log, () => ask('/clip', a, log)))
40
45
  stepped(i, r)
41
46
  return r
42
47
  }
43
48
 
49
+ const quiet = (): void => {}
50
+
51
+ /** a repo whose browsers live on its box films there from a Mac (box.ts): on a Shooter of this process, connected to
52
+ * the box's warm browser, never on this machine's shot service; null when the repo films here */
53
+ async function onBox(who: string, i: ShotInput, log: (l: string) => void, run: (s: import('./shooter.ts').Shooter) => Promise<ShotDone>): Promise<ShotResult | null> {
54
+ const { browserCap } = await import('./browser-slot.ts')
55
+ const { filmBox } = await import('./box.ts')
56
+ const cap = await browserCap(i.root)
57
+ if (cap == null || filmBox(cap) == null) return null
58
+ const { Shooter } = await import('./shooter.ts')
59
+ const { dirname } = await import('path')
60
+ const s = new Shooter([cap.root, dirname(import.meta.dir)], { slot: { root: cap.root, who, say: log === quiet ? (l) => console.error(l) : log } })
61
+ try {
62
+ return { ...(await run(s)), via: 'box' }
63
+ } finally {
64
+ await s.close()
65
+ }
66
+ }
67
+
68
+ /** the ask run while it holds one of its repo's browser slots: the warm browser shooting for a repo counts against
69
+ * that repo's cap; a wait is said through `log`, or on stderr when the caller logs nothing */
70
+ async function held<T>(who: string, i: ShotInput, log: (l: string) => void, run: () => Promise<T>): Promise<T> {
71
+ const { browserSlot } = await import('./browser-slot.ts')
72
+ const release = await browserSlot(who, { ...(i.root ? { root: i.root } : {}), ...(log === quiet ? {} : { say: log }) })
73
+ try {
74
+ return await run()
75
+ } finally {
76
+ release()
77
+ }
78
+ }
79
+
44
80
  /** null when nothing listens (start it), else the service's answer; a refusal throws its reason */
45
81
  async function post(route: string, a: ShotAsk): Promise<ShotDone | null> {
46
82
  let r: Response
@@ -1,37 +1,55 @@
1
1
  // a clip filmed by the page itself: each frame of its largest canvas goes to
2
- // the page's WebCodecs encoder (H.264, the media engine) on the page's own
3
- // animation frames, in real time, and the stream comes back in takes of at
4
- // most TAKE bytes, never whole (one answer of a long clip's base64 can close
5
- // the browser). ffmpeg then muxes it into an mp4 with no second encode.
2
+ // the page's WebCodecs encoder (H.264, the media engine), and the stream comes
3
+ // back in takes of at most TAKE bytes, never whole (one answer of a long
4
+ // clip's base64 can close the browser). ffmpeg then muxes it into an mp4 with
5
+ // no second encode. Real time films the page's own animation frames; a step
6
+ // hook films frame n once `window[step](n / fps)` drew it, stamped n / fps
7
+ // whatever the page's speed.
6
8
  //
7
9
  // the constraint a reader breaks first: `installClip`, `takeClip` and
8
10
  // `CLIP_INIT` run IN the page, so they import nothing and read only their
9
11
  // argument and the document. A WebGL canvas keeps no drawing buffer after it
10
12
  // presents, so the clip's page is opened with CLIP_INIT, which asks every
11
- // WebGL context for `preserveDrawingBuffer`; a WebGPU canvas read on a frame
12
- // it did not draw gives an older drawing, so it is read only after a draw.
13
+ // WebGL context for `preserveDrawingBuffer`; a WebGPU canvas read after the
14
+ // task of its draw gives an older drawing, so a stepped clip takes it at the
15
+ // queue's submit (CLIP_INIT calls `__skOnDraw`), and the real time clip reads
16
+ // it only on a frame it drew.
13
17
 
14
- /** what the page films: seconds of its largest canvas at fps, H.264 at a fixed quantizer */
15
- export type PageClipAsk = { seconds: number; fps: number; quantizer: number; keyEvery: number }
18
+ /** what the page films: seconds of its largest canvas at fps, H.264 at a fixed quantizer; with `step`, frame by frame
19
+ * through `window[step](t)` */
20
+ export type PageClipAsk = { seconds: number; fps: number; quantizer: number; keyEvery: number; step?: string }
16
21
 
17
- /** what the page says once the film ran */
18
- export type PageClipDone = { frames: number; repeated: number; width: number; height: number; canvasOfViewport: string }
22
+ /** what the page says once the film ran; `msPerFrame` the stepped clip's wall time a frame */
23
+ export type PageClipDone = { frames: number; repeated: number; width: number; height: number; canvasOfViewport: string; msPerFrame?: number }
19
24
 
20
25
  /** IN THE PAGE, as an init script: every WebGL context keeps its drawing buffer, so a frame reads back after it presents;
21
- * a WebGPU canvas counts its drawings (window.__skDraws): read on a frame it did not draw, it gives an older drawing */
26
+ * a WebGPU canvas is marked (`__skWebgpu`) and counts its drawings (window.__skDraws): read on a frame it did not
27
+ * draw, it gives an older drawing. Each queue submit after a canvas's getCurrentTexture, in that same task, calls
28
+ * window.__skOnDraw(canvas): the one moment its drawing reads back */
22
29
  export const CLIP_INIT = `(() => {
23
30
  const get = HTMLCanvasElement.prototype.getContext
24
31
  HTMLCanvasElement.prototype.getContext = function (type, attrs) {
25
32
  if (type === 'webgl' || type === 'webgl2' || type === 'experimental-webgl') attrs = Object.assign({}, attrs, { preserveDrawingBuffer: true })
26
- if (type === 'webgpu') window.__skDraws ??= 0
33
+ if (type === 'webgpu') { window.__skDraws ??= 0; this.__skWebgpu = true }
27
34
  return get.call(this, type, attrs)
28
35
  }
29
36
  if (typeof GPUCanvasContext !== 'undefined') {
37
+ let drawing = new Set()
38
+ const later = new MessageChannel()
39
+ later.port1.onmessage = () => (drawing = new Set())
30
40
  const current = GPUCanvasContext.prototype.getCurrentTexture
31
41
  GPUCanvasContext.prototype.getCurrentTexture = function () {
32
42
  window.__skDraws = (window.__skDraws ?? 0) + 1
43
+ if (drawing.size === 0) later.port2.postMessage(0)
44
+ drawing.add(this.canvas)
33
45
  return current.call(this)
34
46
  }
47
+ const submit = GPUQueue.prototype.submit
48
+ GPUQueue.prototype.submit = function (buffers) {
49
+ const r = submit.call(this, buffers)
50
+ if (window.__skOnDraw) for (const c of drawing) window.__skOnDraw(c)
51
+ return r
52
+ }
35
53
  }
36
54
  })()`
37
55
 
@@ -80,6 +98,69 @@ export async function installClip(a: PageClipAsk): Promise<string | null> {
80
98
  const total = Math.round(a.seconds * a.fps)
81
99
  const step = 1000 / a.fps
82
100
  const rect = { x: 0, y: 0, width, height }
101
+ if (a.step != null) {
102
+ const hook = (window as unknown as Record<string, unknown>)[a.step]
103
+ if (typeof hook !== 'function') {
104
+ enc.close()
105
+ return `the page has no window.${a.step}(t): a stepped page draws the time it is given there`
106
+ }
107
+ const webgpu = (canvas as unknown as { __skWebgpu?: boolean }).__skWebgpu === true
108
+ const frame = (): Promise<void> => new Promise((ok) => requestAnimationFrame(() => ok()))
109
+ const mark = (): string | null => {
110
+ const m = document.querySelector('meta[name="shot-ready"]')
111
+ return m == null ? null : (m.getAttribute('content') ?? '').trim().toLowerCase()
112
+ }
113
+ const on = w as unknown as { __skOnDraw?: (c: HTMLCanvasElement) => void }
114
+ const drawn: { frame: VideoFrame | null } = { frame: null }
115
+ on.__skOnDraw = (c) => {
116
+ if (c !== canvas) return
117
+ drawn.frame?.close()
118
+ drawn.frame = new VideoFrame(canvas, { timestamp: 0 })
119
+ }
120
+ const us = 1e6 / a.fps
121
+ st.done = (async (): Promise<PageClipDone> => {
122
+ let last: VideoFrame | null = null
123
+ let repeated = 0
124
+ const t0 = performance.now()
125
+ try {
126
+ for (let n = 0; n < total; n++) {
127
+ if (st.failed) throw new Error(st.failed)
128
+ drawn.frame?.close()
129
+ drawn.frame = null
130
+ await (hook as (t: number) => unknown)(+(n / a.fps).toFixed(6))
131
+ await frame()
132
+ await frame()
133
+ for (const since = performance.now(); mark() != null && mark() !== 'ready'; await frame())
134
+ if (performance.now() - since > 30_000) throw new Error(`frame ${n}: the page has <meta name="shot-ready"> and never set content="ready" in 30 s`)
135
+ // a WebGPU drawing is the one taken at its submit; none since the hook: the canvas shows the last one
136
+ if (webgpu && drawn.frame == null) {
137
+ if (last == null) throw new Error(`frame 0: the page's WebGPU canvas drew nothing after window.${a.step}(0), and it reads back only in the task of its draw: the hook draws the time it is given`)
138
+ repeated++
139
+ } else {
140
+ last?.close()
141
+ last = (webgpu ? drawn.frame : null) ?? new VideoFrame(canvas, { timestamp: 0 })
142
+ if (last === drawn.frame) drawn.frame = null
143
+ }
144
+ const f = new VideoFrame(last, { timestamp: Math.round(n * us), duration: Math.round(us), visibleRect: rect })
145
+ enc.encode(f, { keyFrame: n % a.keyEvery === 0, avc: { quantizer: a.quantizer } } as VideoEncoderEncodeOptions)
146
+ f.close()
147
+ while (enc.encodeQueueSize > 4) await frame()
148
+ }
149
+ const msPerFrame = (performance.now() - t0) / total
150
+ await enc.flush()
151
+ if (st.failed) throw new Error(st.failed)
152
+ return { frames: total, repeated, width, height, canvasOfViewport, msPerFrame }
153
+ } finally {
154
+ delete on.__skOnDraw
155
+ last?.close()
156
+ drawn.frame?.close()
157
+ if (enc.state !== 'closed') enc.close()
158
+ }
159
+ })()
160
+ st.done.catch(() => undefined)
161
+ w.__skClip = st
162
+ return null
163
+ }
83
164
  // a WebGPU canvas is read only on a frame it drew (CLIP_INIT counts them), else its last drawing is filmed again
84
165
  const gpu = w as unknown as { __skDraws?: number }
85
166
  st.done = new Promise<PageClipDone>((ok, fail) => {
@@ -0,0 +1,188 @@
1
+ // the box half of the box route (box.ts): run by bun on the box that films for a repo (repo.config.ts browsers.box),
2
+ // uploaded there by its content hash, node builtins only. One warm chromium on the box's discrete GPU, its devtools on
3
+ // 127.0.0.1:CDP_PORT (the Mac reaches it through ssh), its profile kept, so its HTTP cache outlives each film. It is
4
+ // chromium's headless shell: the full chromium's headless mode composites a WebGPU canvas black in the box's session 0
5
+ // (no display). The shell ships without the DirectX shader compiler Dawn's D3D12 loads, so it gets the full
6
+ // chromium's copy; the full chromium also reads the discrete GPU's LUID off chrome://gpu, which the shell lacks.
7
+ // up <playwright version> the browser answering (started when down: installed when missing, its GPU's LUID found)
8
+ // watch <pid> ends the browser once nothing used it for IDLE_MS (started by up, outside the ssh session)
9
+ // the constraint a reader breaks first: Windows OpenSSH ends every process of its session when it closes, so the
10
+ // browser and the watcher are created through WMI, outside it
11
+ import { createHash } from 'node:crypto'
12
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
13
+ import { homedir, uptime } from 'node:os'
14
+ import { dirname, join } from 'node:path'
15
+
16
+ export const CDP_PORT = 9333
17
+ const PROBE_PORT = 9334
18
+ /** the browser ends once no film touched it for this long and no page holds a url */
19
+ const IDLE_MS = 10 * 60_000
20
+ /** and past this long with no film, whatever its pages */
21
+ const STALE_MS = 60 * 60_000
22
+
23
+ const DIR = join(homedir(), 'dev', 'shipkit-film')
24
+ const USED = join(DIR, 'used')
25
+ const PID = join(DIR, 'browser.pid')
26
+ const say = (s: string) => console.error(`box: ${s}`)
27
+
28
+ /** this script's version: a browser another version started is replaced */
29
+ const VERSION = createHash('sha1').update(readFileSync(import.meta.path)).digest('hex').slice(0, 12)
30
+
31
+ const BROWSER_ARGS = [
32
+ '--use-angle=d3d11',
33
+ '--enable-gpu',
34
+ '--ignore-gpu-blocklist',
35
+ '--enable-unsafe-webgpu',
36
+ '--autoplay-policy=no-user-gesture-required',
37
+ '--mute-audio',
38
+ '--no-first-run',
39
+ '--no-default-browser-check',
40
+ '--lang=en-US',
41
+ // a headless page is never backgrounded: its frames and timers run at full rate
42
+ '--disable-background-timer-throttling',
43
+ '--disable-backgrounding-occluded-windows',
44
+ '--disable-renderer-backgrounding',
45
+ '--disable-features=CalculateNativeWinOcclusion',
46
+ ]
47
+
48
+ async function answers(port: number): Promise<boolean> {
49
+ try {
50
+ return (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) })).ok
51
+ } catch {
52
+ return false
53
+ }
54
+ }
55
+
56
+ /** playwright `version`'s full chromium and headless shell, installed into the user's ms-playwright when missing, the
57
+ * shell given the full one's DirectX shader compiler */
58
+ function chromium(version: string): { full: string; shell: string } {
59
+ const root = join(process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'), 'ms-playwright')
60
+ const find = (prefix: string, exe: string) =>
61
+ (existsSync(root) ? readdirSync(root) : [])
62
+ .filter((d) => d.startsWith(prefix) && /^\d+$/.test(d.slice(prefix.length)))
63
+ .sort((a, b) => Number(b.slice(prefix.length)) - Number(a.slice(prefix.length)))
64
+ .map((d) => join(root, d, exe))
65
+ .find((p) => existsSync(p))
66
+ const both = () => ({ full: find('chromium-', 'chrome-win64/chrome.exe'), shell: find('chromium_headless_shell-', 'chrome-headless-shell-win64/chrome-headless-shell.exe') })
67
+ let got = both()
68
+ if (!got.full || !got.shell) {
69
+ say(`installing playwright ${version}'s chromium and headless shell into ${root}`)
70
+ const p = Bun.spawnSync(['bunx', `playwright@${version}`, 'install', 'chromium', 'chromium-headless-shell'], { cwd: DIR, stdout: 'inherit', stderr: 'inherit' })
71
+ got = both()
72
+ if (p.exitCode !== 0 || !got.full || !got.shell) throw new Error(`installing chromium (playwright ${version}) failed, exit ${p.exitCode}`)
73
+ }
74
+ for (const dll of ['dxil.dll', 'dxcompiler.dll']) {
75
+ const to = join(dirname(got.shell), dll)
76
+ if (!existsSync(to)) copyFileSync(join(dirname(got.full), dll), to)
77
+ }
78
+ return { full: got.full, shell: got.shell }
79
+ }
80
+
81
+ /** a process outside the ssh session (WMI), its pid */
82
+ function detached(line: string): number {
83
+ const ps = `$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = '${line.replaceAll("'", "''")}'; CurrentDirectory = '${DIR}' }; if ($r.ReturnValue -ne 0) { exit $r.ReturnValue }; $r.ProcessId`
84
+ const p = Bun.spawnSync(['powershell', '-NoProfile', '-NonInteractive', '-Command', ps], { stdout: 'pipe', stderr: 'pipe' })
85
+ const pid = Number(p.stdout.toString().trim())
86
+ if (p.exitCode !== 0 || !(pid > 0)) throw new Error(`starting ${line.slice(0, 80)} failed (${p.exitCode}): ${p.stderr.toString().trim()}`)
87
+ return pid
88
+ }
89
+
90
+ const kill = (pid: number) => Bun.spawnSync(['taskkill', '/T', '/F', '/PID', String(pid)], { stdout: 'ignore', stderr: 'ignore' })
91
+
92
+ const alive = (pid: number) => {
93
+ try {
94
+ process.kill(pid, 0)
95
+ return true
96
+ } catch {
97
+ return false
98
+ }
99
+ }
100
+
101
+ const quote = (s: string) => `"${s}"`
102
+
103
+ /** the LUID of the box's discrete GPU as chromium names it (`high,low`): chromium on Windows draws on the adapter the
104
+ * display uses (an integrated one on wm), whatever the page's powerPreference. Read once per boot from chrome://gpu */
105
+ async function discreteLuid(exe: string): Promise<string | null> {
106
+ const cache = join(DIR, 'luid.txt')
107
+ const boot = String(Math.round((Date.now() / 1000 - uptime()) / 60))
108
+ const [at, luid] = existsSync(cache) ? readFileSync(cache, 'utf8').trim().split(' ') : []
109
+ if (at === boot && luid) return luid === 'none' ? null : luid
110
+ const profile = join(DIR, 'probe-profile')
111
+ const pid = detached([exe, '--headless=new', `--remote-debugging-port=${PROBE_PORT}`, `--user-data-dir=${profile}`, '--no-first-run', 'about:blank'].map(quote).join(' '))
112
+ try {
113
+ for (let i = 0; i < 100 && !(await answers(PROBE_PORT)); i++) await Bun.sleep(100)
114
+ const target = (await (await fetch(`http://127.0.0.1:${PROBE_PORT}/json/new?chrome://gpu`, { method: 'PUT' })).json()) as { webSocketDebuggerUrl: string }
115
+ const text = await new Promise<string>((done, fail) => {
116
+ const ws = new WebSocket(target.webSocketDebuggerUrl)
117
+ let n = 0
118
+ const ask = () => ws.send(JSON.stringify({ id: ++n, method: 'Runtime.evaluate', params: { expression: "document.querySelector('info-view')?.shadowRoot?.textContent ?? ''", returnByValue: true } }))
119
+ ws.onopen = ask
120
+ ws.onmessage = (e) => {
121
+ const v = (JSON.parse(String(e.data)) as { result?: { result?: { value?: string } } }).result?.result?.value ?? ''
122
+ if (/GPU0/.test(v)) {
123
+ ws.close()
124
+ done(v)
125
+ } else if (n > 50) fail(new Error('chrome://gpu named no GPU in 5 s'))
126
+ else setTimeout(ask, 100)
127
+ }
128
+ ws.onerror = () => fail(new Error('chrome://gpu: its devtools socket failed'))
129
+ })
130
+ const found = /GPU\d+\s*:\s*VENDOR= 0x(?:10de|1002)[^\n]*?LUID=\{(\d+),(\d+)\}/i.exec(text)
131
+ const got = found ? `${found[1]},${found[2]}` : null
132
+ writeFileSync(cache, `${boot} ${got ?? 'none'}`)
133
+ return got
134
+ } finally {
135
+ // its profile stays for the next boot's probe: chromium holds its files a while after the kill
136
+ kill(pid)
137
+ }
138
+ }
139
+
140
+ async function up(version: string): Promise<void> {
141
+ const t = performance.now()
142
+ mkdirSync(DIR, { recursive: true })
143
+ writeFileSync(USED, String(Date.now()))
144
+ const [was, by] = existsSync(PID) ? readFileSync(PID, 'utf8').trim().split(' ') : []
145
+ if (by === VERSION && (await answers(CDP_PORT))) {
146
+ console.log(`up warm ${Math.round(performance.now() - t)}`)
147
+ return
148
+ }
149
+ if (Number(was) > 0) kill(Number(was))
150
+ const exe = chromium(version)
151
+ const luid = await discreteLuid(exe.full)
152
+ if (luid == null) say('no discrete GPU named in chrome://gpu: the browser draws on the default adapter')
153
+ const args = [`--remote-debugging-port=${CDP_PORT}`, `--user-data-dir=${join(DIR, 'profile')}`, ...BROWSER_ARGS, ...(luid ? [`--use-adapter-luid=${luid}`] : []), 'about:blank']
154
+ const pid = detached([exe.shell, ...args].map(quote).join(' '))
155
+ writeFileSync(PID, `${pid} ${VERSION}`)
156
+ for (let i = 0; i < 150 && !(await answers(CDP_PORT)); i++) await Bun.sleep(100)
157
+ if (!(await answers(CDP_PORT))) throw new Error(`the browser (pid ${pid}) did not answer on 127.0.0.1:${CDP_PORT} in 15 s`)
158
+ detached([process.execPath, import.meta.path, 'watch', String(pid)].map(quote).join(' '))
159
+ console.log(`up started ${Math.round(performance.now() - t)} pid ${pid}${luid ? ` luid ${luid}` : ''}`)
160
+ }
161
+
162
+ async function watch(pid: number): Promise<void> {
163
+ for (;;) {
164
+ await Bun.sleep(30_000)
165
+ if (!alive(pid)) return
166
+ const idle = Date.now() - (statSync(USED, { throwIfNoEntry: false })?.mtimeMs ?? 0)
167
+ let busy = false
168
+ try {
169
+ const pages = (await (await fetch(`http://127.0.0.1:${CDP_PORT}/json/list`)).json()) as { type: string; url: string }[]
170
+ busy = pages.some((p) => p.type === 'page' && p.url !== 'about:blank')
171
+ } catch {}
172
+ if (idle > STALE_MS || (idle > IDLE_MS && !busy)) {
173
+ kill(pid)
174
+ rmSync(PID, { force: true })
175
+ return
176
+ }
177
+ }
178
+ }
179
+
180
+ if (import.meta.main) {
181
+ const [cmd, arg] = process.argv.slice(2)
182
+ if (cmd === 'up' && arg) await up(arg)
183
+ else if (cmd === 'watch' && Number(arg) > 0) await watch(Number(arg))
184
+ else {
185
+ console.error('usage: film-box.ts up <playwright version> | watch <browser pid>')
186
+ process.exit(2)
187
+ }
188
+ }