rvlib-shipkit 2.12.0 → 2.14.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 (378) hide show
  1. package/CHANGELOG.md +75 -21
  2. package/README.md +1 -1
  3. package/package.json +4 -2
  4. package/src/agent-time/store.ts +2 -2
  5. package/src/assets/run-assets.ts +2 -2
  6. package/src/assets/server/studio-server.ts +27 -23
  7. package/src/check.ts +4 -4
  8. package/src/checks/SK001-package-json-shape.check.ts +8 -4
  9. package/src/checks/SK002-contracts-fulfillness.check.ts +2 -2
  10. package/src/checks/SK003-claude-md-shape.check.ts +20 -13
  11. package/src/checks/SK004-gitignore-policy.check.ts +45 -6
  12. package/src/checks/SK005-rvlib-versions.check.ts +2 -2
  13. package/src/checks/SK006-npm-publish-safety.check.ts +3 -3
  14. package/src/checks/SK007-github-visibility.check.ts +2 -2
  15. package/src/checks/SK008-reviewer-agent.check.ts +3 -3
  16. package/src/checks/SK010-undeclared-unit.check.ts +2 -2
  17. package/src/checks/SK011-sibling-unit-ranges.check.ts +2 -2
  18. package/src/checks/SK012-config-barrel-import.check.ts +2 -2
  19. package/src/checks/SK013-one-way-in-policy.check.ts +2 -2
  20. package/src/checks/SK015-nested-repo.check.ts +3 -3
  21. package/src/checks/SK016-legacy-check-shapes.check.ts +2 -2
  22. package/src/checks/SK017-vscode-hub-task.check.ts +2 -2
  23. package/src/checks/SK018-test-files-run.check.ts +2 -2
  24. package/src/checks/SK019-tests-run-in-units.check.ts +2 -2
  25. package/src/checks/SK020-self-spawning-check.check.ts +2 -2
  26. package/src/checks/SK022-machine-runs-the-pin.check.ts +2 -2
  27. package/src/checks/SK024-identity-colors.check.ts +1 -1
  28. package/src/checks/SK025-release-drift.check.ts +2 -2
  29. package/src/checks/SK026-asks-autoclose.check.ts +2 -2
  30. package/src/checks/SK027-agent-wiki-links.check.ts +8 -2
  31. package/src/checks/SK028-readme.check.ts +2 -2
  32. package/src/checks/SK029-explicit-check-files.check.ts +3 -3
  33. package/src/checks/SK030-cache-audit.check.ts +7 -5
  34. package/src/checks/SK031-trace-audit.check.ts +7 -7
  35. package/src/checks/SK032-ignored-inputs.check.ts +3 -3
  36. package/src/checks/SK033-global-contribution.check.ts +11 -4
  37. package/src/checks/SK034-commit-gates-armed.check.ts +2 -2
  38. package/src/checks/SK035-public-clean.check.ts +46 -0
  39. package/src/checks/SK036-draft-media-size.check.ts +28 -0
  40. package/src/checks/SK037-keyword-additions.check.ts +43 -0
  41. package/src/cli/cmd_Backup.ts +152 -0
  42. package/src/cli/cmd_Ci.ts +8 -11
  43. package/src/cli/cmd_Commands.ts +4 -4
  44. package/src/cli/cmd_ConfigKeys.ts +2 -2
  45. package/src/cli/cmd_Drill.ts +145 -0
  46. package/src/cli/cmd_Home.ts +50 -3
  47. package/src/cli/cmd_Init.ts +1 -1
  48. package/src/cli/cmd_Media.ts +10 -8
  49. package/src/cli/cmd_Mv.ts +14 -7
  50. package/src/cli/cmd_Review.ts +6 -4
  51. package/src/cli/cmd_Shot.ts +5 -2
  52. package/src/cli/cmd_Smoke.ts +5 -2
  53. package/src/cli/cmd_Social.ts +226 -0
  54. package/src/cli/cmd_Sound.ts +1 -1
  55. package/src/cli/cmd_Start.ts +1 -1
  56. package/src/cli/cmd_Time.ts +1 -1
  57. package/src/cli/cmd_TraceAudit.ts +6 -6
  58. package/src/cli/cmd_Trailer.ts +7 -4
  59. package/src/cli/cmd_Veille.ts +173 -0
  60. package/src/cli/cmd_When.ts +2 -2
  61. package/src/cli/family-pages.ts +19 -16
  62. package/src/cli/registry.ts +13 -2
  63. package/src/cli.ts +5 -2
  64. package/src/collections/actions.ts +1 -49
  65. package/src/collections/checks.ts +2 -1
  66. package/src/collections/collection-types.ts +12 -3
  67. package/src/collections/providers.ts +4 -4
  68. package/src/collections/review.ts +3 -2
  69. package/src/collections/tests.ts +19 -8
  70. package/src/comfy/comfy-panel.ts +2 -2
  71. package/src/contracts/apply-contracts.ts +1 -3
  72. package/src/contracts/contract-manifests.ts +2 -3
  73. package/src/contracts/contract-types.ts +0 -1
  74. package/src/contracts/contracts-engine.ts +0 -3
  75. package/src/contracts/manifests/discord.contract.ts +1 -1
  76. package/src/contracts/manifests/identity.contract.ts +1 -1
  77. package/src/contracts/manifests/itch.contract.ts +1 -1
  78. package/src/contracts/manifests/steam.contract.ts +1 -1
  79. package/src/core/agent-dir-at.ts +12 -0
  80. package/src/core/agent-dir.ts +16 -0
  81. package/src/core/app-icon.ts +9 -3
  82. package/src/core/budget.ts +1 -1
  83. package/src/core/bun-builtins.ts +2 -2
  84. package/src/core/canonical-scripts.ts +2 -2
  85. package/src/core/discover-checks.ts +38 -6
  86. package/src/core/fix-scope.ts +4 -2
  87. package/src/core/floor-resolve.ts +68 -48
  88. package/src/core/floor.ts +9 -0
  89. package/src/core/git-root.ts +24 -0
  90. package/src/core/global-contribution.ts +4 -1
  91. package/src/core/ignored-block.ts +1 -1
  92. package/src/core/ignored-inputs.ts +3 -2
  93. package/src/core/last-good.ts +3 -1
  94. package/src/core/layout.ts +8 -0
  95. package/src/core/log-stamp.ts +36 -0
  96. package/src/core/loop-watch.ts +93 -0
  97. package/src/core/machine-link.ts +134 -0
  98. package/src/core/memory-watch.ts +41 -0
  99. package/src/core/motherhome.ts +2 -2
  100. package/src/core/one-way-in-policy.ts +34 -26
  101. package/src/core/run-ci.ts +9 -11
  102. package/src/core/run-fixers.ts +9 -9
  103. package/src/core/runs-matrix.ts +1 -1
  104. package/src/core/slots.ts +30 -0
  105. package/src/core/trace-audit.ts +50 -9
  106. package/src/core/tree-rev.ts +60 -0
  107. package/src/core/unit-files.ts +42 -0
  108. package/src/drill/render.ts +140 -0
  109. package/src/drill/run.ts +269 -0
  110. package/src/fleet/scan-fleet.ts +6 -5
  111. package/src/home/daemon-jobs.ts +201 -0
  112. package/src/home/global-context.ts +44 -8
  113. package/src/home/gui-app/ShipkitGui.swift +91 -2
  114. package/src/home/home-routes.ts +22 -15
  115. package/src/home/hubs.ts +10 -3
  116. package/src/home/inbox-shape.ts +54 -5
  117. package/src/home/inbox.ts +17 -2
  118. package/src/home/lib-watch.ts +10 -3
  119. package/src/home/machine-stores.ts +15 -29
  120. package/src/home/pm-config.ts +4 -1
  121. package/src/home/pm-inputs.ts +2 -0
  122. package/src/home/resources.ts +7 -2
  123. package/src/home/run-daemon.ts +15 -18
  124. package/src/home/run-pm.ts +3 -1
  125. package/src/home/serve-daemon.ts +4 -3
  126. package/src/home/serve-web.ts +104 -1
  127. package/src/hooks/commit-message.ts +29 -20
  128. package/src/hooks/hook-gates.ts +1 -1
  129. package/src/hooks/leak-guard.ts +69 -9
  130. package/src/hooks/run-hooks.ts +18 -22
  131. package/src/identities/identities.ts +334 -0
  132. package/src/identities/machine-route.ts +126 -0
  133. package/src/identities/machine.ts +62 -0
  134. package/src/init-repo.ts +3 -3
  135. package/src/ledger/check-stats.ts +10 -9
  136. package/src/ledger/gate-checks.ts +32 -1
  137. package/src/ledger/record-kept.ts +112 -0
  138. package/src/ledger/repo-view.ts +10 -0
  139. package/src/ledger/run-log.ts +17 -12
  140. package/src/ledger/run-timeline.ts +8 -4
  141. package/src/ledger/store.ts +7 -0
  142. package/src/ledger/suite-log.ts +17 -13
  143. package/src/media-kinds.ts +3 -2
  144. package/src/media-store/backup/daemon.ts +73 -0
  145. package/src/media-store/backup/keys.ts +25 -0
  146. package/src/media-store/backup/manifest.ts +193 -0
  147. package/src/media-store/backup/restore.ts +192 -0
  148. package/src/media-store/backup/run.ts +278 -0
  149. package/src/media-store/backup/secret.ts +86 -0
  150. package/src/media-store/backup/snapshot.ts +64 -0
  151. package/src/media-store/backup/sources.ts +199 -0
  152. package/src/media-store/content.ts +1 -1
  153. package/src/media-store/daemon.ts +56 -70
  154. package/src/media-store/db.ts +1 -1
  155. package/src/media-store/fact.ts +1 -1
  156. package/src/media-store/hand.ts +1 -1
  157. package/src/media-store/kind.ts +1 -1
  158. package/src/media-store/purge.ts +1 -1
  159. package/src/media-store/put.ts +5 -3
  160. package/src/media-store/remote.ts +1 -1
  161. package/src/media-store/space.ts +24 -5
  162. package/src/mv/mv-md.ts +63 -22
  163. package/src/pages/forward.ts +35 -0
  164. package/src/pages/frame-client.ts +118 -0
  165. package/src/pages/routes.ts +29 -0
  166. package/src/pages/unit.ts +92 -0
  167. package/src/plan/planner.ts +12 -0
  168. package/src/plan/repo-source.ts +19 -5
  169. package/src/reflect/transcript.ts +35 -10
  170. package/src/release/public-clean.ts +319 -0
  171. package/src/release/published-here.ts +22 -0
  172. package/src/release/run-bump.ts +3 -2
  173. package/src/release/run-release.ts +7 -4
  174. package/src/repo-config.ts +71 -13
  175. package/src/review/anim.ts +1 -1
  176. package/src/review/auto.ts +1 -1
  177. package/src/review/cells.ts +15 -1
  178. package/src/review/format.ts +2 -2
  179. package/src/review/http.ts +16 -2
  180. package/src/review/marks.ts +1 -1
  181. package/src/review/media-kind.ts +1 -1
  182. package/src/review/media-read.ts +1 -1
  183. package/src/review/model.ts +27 -6
  184. package/src/review/notes.ts +125 -0
  185. package/src/review/previews.ts +1 -1
  186. package/src/review/project.ts +7 -39
  187. package/src/review/role.ts +1 -1
  188. package/src/review/routes.ts +18 -14
  189. package/src/review/store.ts +42 -2
  190. package/src/review/threads.ts +1 -1
  191. package/src/review/trailer-desk.ts +3 -3
  192. package/src/review/trailer-media.ts +8 -5
  193. package/src/review/trailer-model.ts +1 -1
  194. package/src/review/trailer-routes.ts +1 -1
  195. package/src/review/trailer-shots.ts +22 -5
  196. package/src/review/unit.ts +2 -2
  197. package/src/scaffold/files/agent-handoff.md +3 -0
  198. package/src/scaffold/files/agent-index.md +4 -12
  199. package/src/scaffold/files/tsconfig.json +1 -1
  200. package/src/scaffold/project-scaffold.ts +6 -5
  201. package/src/serve/embed.ts +2 -2
  202. package/src/serve/hub-app/check-words.ts +1 -1
  203. package/src/serve/hub-app/col-card.tsx +3 -17
  204. package/src/serve/hub-app/col-tables-view.tsx +2 -1
  205. package/src/serve/hub-app/cols-svc.ts +0 -13
  206. package/src/serve/hub-app/dock-st.ts +4 -2
  207. package/src/serve/hub-app/dock-view.tsx +2 -0
  208. package/src/serve/hub-app/frames-st.ts +35 -0
  209. package/src/serve/hub-app/hash-route.ts +64 -1
  210. package/src/serve/hub-app/home-st.ts +32 -8
  211. package/src/serve/hub-app/home-strip.css +9 -1
  212. package/src/serve/hub-app/home-strip.tsx +7 -6
  213. package/src/serve/hub-app/home.html +5 -0
  214. package/src/serve/hub-app/hub-app.tsx +51 -7
  215. package/src/serve/hub-app/hub.css +29 -11
  216. package/src/serve/hub-app/icons.tsx +16 -1
  217. package/src/serve/hub-app/identities-st.ts +210 -0
  218. package/src/serve/hub-app/identities-view.tsx +353 -0
  219. package/src/serve/hub-app/identities.css +48 -0
  220. package/src/serve/hub-app/identity-address.ts +52 -0
  221. package/src/serve/hub-app/inbox-st.ts +60 -7
  222. package/src/serve/hub-app/inbox-view.tsx +49 -7
  223. package/src/serve/hub-app/inbox.css +12 -1
  224. package/src/serve/hub-app/index.html +3 -0
  225. package/src/serve/hub-app/kept-cols.tsx +30 -0
  226. package/src/serve/hub-app/keys.ts +10 -2
  227. package/src/serve/hub-app/list-walk.ts +89 -0
  228. package/src/serve/hub-app/machine-st.ts +12 -0
  229. package/src/serve/hub-app/media-svc.ts +1 -1
  230. package/src/serve/hub-app/media-view.tsx +2 -1
  231. package/src/serve/hub-app/pages-frames.tsx +134 -0
  232. package/src/serve/hub-app/pages-svc.ts +111 -0
  233. package/src/serve/hub-app/palette-st.ts +18 -3
  234. package/src/serve/hub-app/palette-view.tsx +9 -2
  235. package/src/serve/hub-app/planned-view.tsx +2 -1
  236. package/src/serve/hub-app/project-list.css +18 -14
  237. package/src/serve/hub-app/project-list.tsx +88 -49
  238. package/src/serve/hub-app/projects-svc.ts +33 -3
  239. package/src/serve/hub-app/repo-sections.ts +19 -2
  240. package/src/serve/hub-app/repo-st.ts +76 -20
  241. package/src/serve/hub-app/review/review-board.tsx +1 -1
  242. package/src/serve/hub-app/review/review-cells.tsx +6 -5
  243. package/src/serve/hub-app/review/review-kit.ts +30 -7
  244. package/src/serve/hub-app/review/review-page.tsx +6 -5
  245. package/src/serve/hub-app/review/review-st.ts +34 -15
  246. package/src/serve/hub-app/review/review-thread.tsx +63 -14
  247. package/src/serve/hub-app/review/review-views.tsx +133 -51
  248. package/src/serve/hub-app/review/thread-st.ts +80 -37
  249. package/src/serve/hub-app/review/trailer-page.tsx +7 -5
  250. package/src/serve/hub-app/review/trailer-st.ts +1 -1
  251. package/src/serve/hub-app/review.css +26 -9
  252. package/src/serve/hub-app/site/site-part.tsx +173 -0
  253. package/src/serve/hub-app/site/site-st.ts +157 -0
  254. package/src/serve/hub-app/site.css +35 -0
  255. package/src/serve/hub-app/social/calendar.tsx +182 -0
  256. package/src/serve/hub-app/social/comms-page.tsx +330 -0
  257. package/src/serve/hub-app/social/kit.tsx +244 -0
  258. package/src/serve/hub-app/social/post-card.tsx +456 -0
  259. package/src/serve/hub-app/social/problems.tsx +60 -0
  260. package/src/serve/hub-app/social/social-model.ts +154 -0
  261. package/src/serve/hub-app/social/social-page.tsx +681 -0
  262. package/src/serve/hub-app/social/social-st.ts +1014 -0
  263. package/src/serve/hub-app/social.css +289 -0
  264. package/src/serve/hub-app/stores/stores-page.tsx +312 -0
  265. package/src/serve/hub-app/stores/stores-st.ts +286 -0
  266. package/src/serve/hub-app/stores.css +54 -0
  267. package/src/serve/hub-app/timeline-geometry.ts +1 -1
  268. package/src/serve/hub-app/timeline-view.tsx +3 -2
  269. package/src/serve/hub-app/tree-build.ts +6 -0
  270. package/src/serve/hub-app/tree-row.tsx +27 -4
  271. package/src/serve/hub-app/tree-svc.ts +18 -49
  272. package/src/serve/hub-app/veille/veille-page.tsx +515 -0
  273. package/src/serve/hub-app/veille/veille-st.ts +443 -0
  274. package/src/serve/hub-app/veille.css +84 -0
  275. package/src/serve/hub-runtime.ts +20 -11
  276. package/src/serve/project-gutter-route.ts +44 -12
  277. package/src/serve/run-lanes.ts +7 -4
  278. package/src/serve/same-origin.ts +1 -1
  279. package/src/serve/serve-hub.ts +20 -12
  280. package/src/serve/tracked-watch.ts +24 -3
  281. package/src/serve/warm-cell.ts +5 -1
  282. package/src/shipkit-files.ts +15 -4
  283. package/src/shipkit.ts +0 -1
  284. package/src/shot/box.ts +160 -0
  285. package/src/shot/browser-slot.ts +74 -0
  286. package/src/shot/client.ts +42 -7
  287. package/src/shot/clip-encoder.ts +108 -24
  288. package/src/shot/film-box.ts +292 -0
  289. package/src/shot/shooter.ts +71 -17
  290. package/src/shot/shot-ask.ts +10 -2
  291. package/src/shot/stepped-clip.ts +5 -4
  292. package/src/site/desk.ts +242 -0
  293. package/src/site/routes.ts +66 -0
  294. package/src/site/unit.ts +62 -0
  295. package/src/social/brands.ts +22 -0
  296. package/src/social/card-drafts.ts +24 -0
  297. package/src/social/compose.ts +97 -0
  298. package/src/social/desk-index.ts +123 -0
  299. package/src/social/desk-wire.ts +64 -0
  300. package/src/social/drafts.ts +183 -0
  301. package/src/social/house.ts +24 -0
  302. package/src/social/load.ts +332 -0
  303. package/src/social/md.ts +70 -0
  304. package/src/social/media-facts.ts +53 -0
  305. package/src/social/media-kind.ts +189 -0
  306. package/src/social/media-limit.ts +42 -0
  307. package/src/social/media-of.ts +30 -0
  308. package/src/social/migrate.ts +123 -0
  309. package/src/social/open.ts +17 -0
  310. package/src/social/post-url.ts +158 -0
  311. package/src/social/presence.ts +332 -0
  312. package/src/social/public-read.ts +53 -0
  313. package/src/social/publish/bluesky.ts +168 -0
  314. package/src/social/publish/discord.ts +76 -0
  315. package/src/social/publish/index.ts +24 -0
  316. package/src/social/publish/secret.ts +13 -0
  317. package/src/social/push.ts +37 -0
  318. package/src/social/richtext.ts +37 -0
  319. package/src/social/routes.ts +186 -0
  320. package/src/social/stats.ts +134 -0
  321. package/src/social/text.ts +267 -0
  322. package/src/social/tracker-route.ts +39 -0
  323. package/src/social/tracker.ts +255 -0
  324. package/src/social/unit.ts +53 -0
  325. package/src/social/writes.ts +130 -0
  326. package/src/start-repo.ts +14 -9
  327. package/src/stores/collection.ts +27 -0
  328. package/src/stores/desk.ts +336 -0
  329. package/src/stores/model.ts +187 -0
  330. package/src/stores/routes.ts +126 -0
  331. package/src/stores/unit.ts +57 -0
  332. package/src/suite/calibrate.ts +127 -0
  333. package/src/suite/core-counters.ts +91 -0
  334. package/src/suite/judge-suites.ts +95 -35
  335. package/src/suite/suite-cli.ts +44 -10
  336. package/src/suite/suite-cpu-preload.ts +34 -9
  337. package/src/trace/tracer.ts +12 -5
  338. package/src/trailer/adapter.ts +5 -1
  339. package/src/trailer/build.ts +45 -12
  340. package/src/trailer/ffmpeg.ts +11 -0
  341. package/src/trailer/footage.ts +30 -13
  342. package/src/trailer/grammar.ts +18 -2
  343. package/src/trailer/graph.ts +28 -6
  344. package/src/trailer/holes.ts +1 -1
  345. package/src/trailer/passage.ts +18 -6
  346. package/src/trailer/plan.ts +74 -3
  347. package/src/trailer/prune.ts +1 -1
  348. package/src/trailer/states.ts +1 -1
  349. package/src/trailer/stitch.ts +67 -26
  350. package/src/trailer/url.ts +1 -1
  351. package/src/trailer/versions.ts +24 -0
  352. package/src/trailer/words.ts +1 -1
  353. package/src/ts/gate-typecheck.ts +32 -0
  354. package/src/ts/typecheck-cli.ts +9 -11
  355. package/src/tui/run-tui.ts +1 -1
  356. package/src/tui/tui-app.tsx +0 -1
  357. package/src/tui/tui-store.ts +1 -1
  358. package/src/veille/asks.ts +155 -0
  359. package/src/veille/auto.ts +31 -0
  360. package/src/veille/batch.ts +27 -0
  361. package/src/veille/chrome.ts +127 -0
  362. package/src/veille/collection.ts +28 -0
  363. package/src/veille/desk.ts +242 -0
  364. package/src/veille/identity.ts +80 -0
  365. package/src/veille/import.ts +68 -0
  366. package/src/veille/log.ts +183 -0
  367. package/src/veille/platforms.ts +118 -0
  368. package/src/veille/reads.ts +66 -0
  369. package/src/veille/replied.ts +110 -0
  370. package/src/veille/routes.ts +185 -0
  371. package/src/veille/service.ts +81 -0
  372. package/src/veille/watch.ts +116 -0
  373. package/src/veille/worth.ts +46 -0
  374. package/src/wiki/scan-md.ts +18 -0
  375. package/src/collections/posts.ts +0 -142
  376. package/src/contracts/manifests/social.contract.ts +0 -20
  377. package/src/scaffold/files/agent-coding.md +0 -35
  378. package/src/ts/typecheck-cache.ts +0 -11
@@ -0,0 +1,74 @@
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_BOX_BROWSERS, 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: { host: string; max: number } | null }
18
+
19
+ /** the box this machine films on for the repo, or null: a Mac whose repo names one, unless SK_FILM_HERE=1 */
20
+ export function filmBox(c: Pick<BrowserCap, 'box'> | null, env: Record<string, string | undefined> = process.env, platform = process.platform): string | null {
21
+ return c?.box != null && platform === 'darwin' && env[HERE_ENV] !== '1' ? c.box.host : null
22
+ }
23
+
24
+ /** how many browsers of the repo run at once where this run films: its box's cap there, else browsers.max */
25
+ export const filmingCap = (c: BrowserCap): number => (filmBox(c) != null ? c.box!.max : c.cap)
26
+
27
+ /** the nearest dir at or above `from` holding a repo.config.ts, or null */
28
+ function configRoot(from: string): string | null {
29
+ for (let d = resolve(from); ; d = dirname(d)) {
30
+ if (existsSync(join(d, 'repo.config.ts'))) return d
31
+ if (dirname(d) === d) return null
32
+ }
33
+ }
34
+
35
+ /** the browser cap of the repo at `root` (default: the repo the cwd is in), or null outside any repo; a value that is
36
+ * not a whole number of browsers throws */
37
+ export async function browserCap(root?: string): Promise<BrowserCap | null> {
38
+ const at = root ?? configRoot(process.cwd())
39
+ if (at == null || !existsSync(join(at, 'repo.config.ts'))) return null
40
+ const { loadRepoConfig } = await import('../repo-config.ts')
41
+ const c = await loadRepoConfig(at)
42
+ const bad = browsersProblem(c.browsers)
43
+ if (bad != null) throw new Error(`${join(at, 'repo.config.ts')}: ${bad}`)
44
+ const box = c.browsers?.box
45
+ return { repo: c.name, cap: c.browsers?.max ?? DEFAULT_BROWSERS, root: at, box: box == null ? null : { host: box.host, max: box.max ?? DEFAULT_BOX_BROWSERS } }
46
+ }
47
+
48
+ /** why `who` may not start a browser of this repo on this machine, or null: a repo filmed by its box never starts one
49
+ * on a Mac, unless the slot is the box route's own (its browser on the box) */
50
+ export function browserRefusal(c: Pick<BrowserCap, 'repo' | 'box'>, who: string, onBox: boolean, platform = process.platform, env: Record<string, string | undefined> = process.env): string | null {
51
+ if (c.box == null || onBox || platform !== 'darwin' || env[HERE_ENV] === '1') return null
52
+ return `${who}: ${c.repo} films on ${c.box.host} (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)`
53
+ }
54
+
55
+ /** wait for one of the repo's browser slots and hold it until the returned release (or this process ends), saying
56
+ * once whom it waits on; outside any repo there is no cap and nothing is held. `onBox`: the browser runs on the
57
+ * repo's box, this Mac only drives it */
58
+ export async function browserSlot(who: string, o: { root?: string; say?: (l: string) => void; pollMs?: number; onBox?: boolean } = {}): Promise<() => void> {
59
+ const c = await browserCap(o.root)
60
+ if (c == null) return () => undefined
61
+ const no = browserRefusal(c, who, o.onBox === true)
62
+ if (no != null) throw new Error(no)
63
+ const say = o.say ?? ((l: string) => console.error(l))
64
+ // the box's browsers are a pool apart, sized by browsers.box.max
65
+ const box = o.onBox === true && c.box != null ? c.box : null
66
+ const [pool, cap, key] = box ? [browserPool(`${c.repo}@${box.host}`, box.max), box.max, 'browsers.box.max'] : [browserPool(c.repo, c.cap), c.cap, 'browsers.max']
67
+ const got = await takeSlot(pool, { repo: c.repo, check: who }, {
68
+ pollMs: o.pollMs ?? 250,
69
+ onWait: (held) =>
70
+ say(`${who}: waiting for a browser of ${c.repo}${box ? ` on ${box.host}` : ''}, all ${cap} held (repo.config.ts ${key}): ${held.map((h) => `pid ${h.pid} (${h.check})`).join(', ') || 'a holder starting'}`),
71
+ })
72
+ if (got == null) throw new Error(`${who}: the browser slot wait of ${c.repo} stopped with no slot`)
73
+ return got.release
74
+ }
@@ -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,52 @@ 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, filmBox } = await import('./browser-slot.ts')
55
+ const cap = await browserCap(i.root)
56
+ if (cap == null || filmBox(cap) == null) return null
57
+ const { Shooter } = await import('./shooter.ts')
58
+ const { dirname } = await import('path')
59
+ const s = new Shooter([cap.root, dirname(import.meta.dir)], { slot: { root: cap.root, who, say: log === quiet ? (l) => console.error(l) : log } })
60
+ try {
61
+ return { ...(await run(s)), via: 'box' }
62
+ } finally {
63
+ await s.close()
64
+ }
65
+ }
66
+
67
+ /** the ask run while it holds one of its repo's browser slots: the warm browser shooting for a repo counts against
68
+ * that repo's cap; a wait is said through `log`, or on stderr when the caller logs nothing */
69
+ async function held<T>(who: string, i: ShotInput, log: (l: string) => void, run: () => Promise<T>): Promise<T> {
70
+ const { browserSlot } = await import('./browser-slot.ts')
71
+ const release = await browserSlot(who, { ...(i.root ? { root: i.root } : {}), ...(log === quiet ? {} : { say: log }) })
72
+ try {
73
+ return await run()
74
+ } finally {
75
+ release()
76
+ }
77
+ }
78
+
44
79
  /** null when nothing listens (start it), else the service's answer; a refusal throws its reason */
45
80
  async function post(route: string, a: ShotAsk): Promise<ShotDone | null> {
46
81
  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
 
@@ -54,17 +72,20 @@ export async function installClip(a: PageClipAsk): Promise<string | null> {
54
72
  const height = even(canvas.height)
55
73
  const blocks = Math.ceil(width / 16) * Math.ceil(height / 16)
56
74
  const level = blocks <= 8192 ? '28' : blocks <= 36864 ? '33' : '34'
57
- const config: VideoEncoderConfig = {
58
- codec: `avc1.6400${level}`,
59
- width,
60
- height,
61
- framerate: a.fps,
62
- latencyMode: 'quality',
63
- bitrateMode: 'quantizer',
64
- hardwareAcceleration: 'prefer-hardware',
65
- avc: { format: 'annexb' },
66
- }
67
- if (!(await VideoEncoder.isConfigSupported(config)).supported) return `the page's H.264 encoder takes no ${width}x${height} at a fixed quantizer`
75
+ const base: VideoEncoderConfig = { codec: `avc1.6400${level}`, width, height, framerate: a.fps, latencyMode: 'quality', avc: { format: 'annexb' } }
76
+ // a fixed quantizer where the encoder takes one; Windows' takes none, so there a variable bitrate of half a bit a
77
+ // pixel and frame (31 Mb/s at 1080p30)
78
+ let config: VideoEncoderConfig | null = null
79
+ for (const c of [
80
+ { ...base, bitrateMode: 'quantizer', hardwareAcceleration: 'prefer-hardware' },
81
+ { ...base, bitrateMode: 'variable', bitrate: Math.round(width * height * a.fps * 0.5), hardwareAcceleration: 'no-preference' },
82
+ ] as VideoEncoderConfig[])
83
+ if ((await VideoEncoder.isConfigSupported(c)).supported) {
84
+ config = c
85
+ break
86
+ }
87
+ if (config == null) return `the page's H.264 encoder takes no ${width}x${height}, at a fixed quantizer or a variable bitrate`
88
+ const per = config.bitrateMode === 'quantizer' ? { avc: { quantizer: a.quantizer } } : {}
68
89
  const box = canvas.getBoundingClientRect()
69
90
  const canvasOfViewport = `${Math.round(box.width)}x${Math.round(box.height)} css px of ${innerWidth}x${innerHeight}`
70
91
  const st: ClipState = { chunks: [], next: 0, failed: null, done: Promise.resolve({ frames: 0, repeated: 0, width, height, canvasOfViewport }) }
@@ -80,6 +101,69 @@ export async function installClip(a: PageClipAsk): Promise<string | null> {
80
101
  const total = Math.round(a.seconds * a.fps)
81
102
  const step = 1000 / a.fps
82
103
  const rect = { x: 0, y: 0, width, height }
104
+ if (a.step != null) {
105
+ const hook = (window as unknown as Record<string, unknown>)[a.step]
106
+ if (typeof hook !== 'function') {
107
+ enc.close()
108
+ return `the page has no window.${a.step}(t): a stepped page draws the time it is given there`
109
+ }
110
+ const webgpu = (canvas as unknown as { __skWebgpu?: boolean }).__skWebgpu === true
111
+ const frame = (): Promise<void> => new Promise((ok) => requestAnimationFrame(() => ok()))
112
+ const mark = (): string | null => {
113
+ const m = document.querySelector('meta[name="shot-ready"]')
114
+ return m == null ? null : (m.getAttribute('content') ?? '').trim().toLowerCase()
115
+ }
116
+ const on = w as unknown as { __skOnDraw?: (c: HTMLCanvasElement) => void }
117
+ const drawn: { frame: VideoFrame | null } = { frame: null }
118
+ on.__skOnDraw = (c) => {
119
+ if (c !== canvas) return
120
+ drawn.frame?.close()
121
+ drawn.frame = new VideoFrame(canvas, { timestamp: 0 })
122
+ }
123
+ const us = 1e6 / a.fps
124
+ st.done = (async (): Promise<PageClipDone> => {
125
+ let last: VideoFrame | null = null
126
+ let repeated = 0
127
+ const t0 = performance.now()
128
+ try {
129
+ for (let n = 0; n < total; n++) {
130
+ if (st.failed) throw new Error(st.failed)
131
+ drawn.frame?.close()
132
+ drawn.frame = null
133
+ await (hook as (t: number) => unknown)(+(n / a.fps).toFixed(6))
134
+ await frame()
135
+ await frame()
136
+ for (const since = performance.now(); mark() != null && mark() !== 'ready'; await frame())
137
+ 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`)
138
+ // a WebGPU drawing is the one taken at its submit; none since the hook: the canvas shows the last one
139
+ if (webgpu && drawn.frame == null) {
140
+ 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`)
141
+ repeated++
142
+ } else {
143
+ last?.close()
144
+ last = (webgpu ? drawn.frame : null) ?? new VideoFrame(canvas, { timestamp: 0 })
145
+ if (last === drawn.frame) drawn.frame = null
146
+ }
147
+ const f = new VideoFrame(last, { timestamp: Math.round(n * us), duration: Math.round(us), visibleRect: rect })
148
+ enc.encode(f, { keyFrame: n % a.keyEvery === 0, ...per } as VideoEncoderEncodeOptions)
149
+ f.close()
150
+ while (enc.encodeQueueSize > 4) await frame()
151
+ }
152
+ const msPerFrame = (performance.now() - t0) / total
153
+ await enc.flush()
154
+ if (st.failed) throw new Error(st.failed)
155
+ return { frames: total, repeated, width, height, canvasOfViewport, msPerFrame }
156
+ } finally {
157
+ delete on.__skOnDraw
158
+ last?.close()
159
+ drawn.frame?.close()
160
+ if (enc.state !== 'closed') enc.close()
161
+ }
162
+ })()
163
+ st.done.catch(() => undefined)
164
+ w.__skClip = st
165
+ return null
166
+ }
83
167
  // a WebGPU canvas is read only on a frame it drew (CLIP_INIT counts them), else its last drawing is filmed again
84
168
  const gpu = w as unknown as { __skDraws?: number }
85
169
  st.done = new Promise<PageClipDone>((ok, fail) => {
@@ -103,7 +187,7 @@ export async function installClip(a: PageClipAsk): Promise<string | null> {
103
187
  let made = 0
104
188
  while (n < total && n * step <= t - t0) {
105
189
  const frame = new VideoFrame(last!, { timestamp: Math.round(n * step * 1000), duration: Math.round(step * 1000) })
106
- enc.encode(frame, { keyFrame: n % a.keyEvery === 0, avc: { quantizer: a.quantizer } } as VideoEncoderEncodeOptions)
190
+ enc.encode(frame, { keyFrame: n % a.keyEvery === 0, ...per } as VideoEncoderEncodeOptions)
107
191
  frame.close()
108
192
  if (made++ > 0 || !fresh) repeated++
109
193
  n++
@@ -0,0 +1,292 @@
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> closes a page whose film died, ends the browser once nothing used it for IDLE_MS (started
9
+ // by up, outside the ssh session)
10
+ // the constraint a reader breaks first: Windows OpenSSH ends every process of its session when it closes, so the
11
+ // browser and the watcher are created through WMI, outside it
12
+ import { createHash } from 'node:crypto'
13
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
14
+ import { homedir, uptime } from 'node:os'
15
+ import { dirname, join } from 'node:path'
16
+
17
+ export const CDP_PORT = 9333
18
+ const PROBE_PORT = 9334
19
+ /** the browser ends once no film touched it for this long and no page holds a url */
20
+ const IDLE_MS = 10 * 60_000
21
+ /** and past this long with no film, whatever its pages */
22
+ const STALE_MS = 60 * 60_000
23
+
24
+ const DIR = join(homedir(), 'dev', 'shipkit-film')
25
+ const USED = join(DIR, 'used')
26
+ const PID = join(DIR, 'browser.pid')
27
+ const say = (s: string) => console.error(`box: ${s}`)
28
+
29
+ /** this script's version: a browser another version started is replaced */
30
+ const VERSION = createHash('sha1').update(readFileSync(import.meta.path)).digest('hex').slice(0, 12)
31
+
32
+ /** playwright's own switches for a launched chromium (chromiumSwitches, headless), so a page films here as it would
33
+ * under a launch: --disable-ipc-flooding-protection above all, without which chromium drops a page's history updates
34
+ * past 200 in 10 s and a take's clock (its hash's stop=) froze at frame 201 */
35
+ const BROWSER_ARGS = [
36
+ '--use-angle=d3d11',
37
+ '--enable-gpu',
38
+ '--ignore-gpu-blocklist',
39
+ '--enable-unsafe-webgpu',
40
+ '--disable-ipc-flooding-protection',
41
+ '--force-color-profile=srgb',
42
+ '--disable-field-trial-config',
43
+ '--disable-background-networking',
44
+ '--disable-background-timer-throttling',
45
+ '--disable-backgrounding-occluded-windows',
46
+ '--disable-renderer-backgrounding',
47
+ '--disable-back-forward-cache',
48
+ '--disable-breakpad',
49
+ '--disable-client-side-phishing-detection',
50
+ '--disable-component-extensions-with-background-pages',
51
+ '--disable-component-update',
52
+ '--disable-default-apps',
53
+ '--disable-extensions',
54
+ '--disable-hang-monitor',
55
+ '--disable-popup-blocking',
56
+ '--disable-prompt-on-repost',
57
+ '--disable-sync',
58
+ '--disable-features=PaintHolding,Translate,OptimizationHints,MediaRouter,DialMediaRouteProvider,GlobalMediaControls,HttpsUpgrades,LensOverlay,ThirdPartyStoragePartitioning,AutoDeElevate,CalculateNativeWinOcclusion',
59
+ '--enable-features=CDPScreenshotNewSurface',
60
+ '--allow-pre-commit-input',
61
+ '--metrics-recording-only',
62
+ '--password-store=basic',
63
+ '--no-service-autorun',
64
+ '--no-first-run',
65
+ '--no-default-browser-check',
66
+ '--autoplay-policy=no-user-gesture-required',
67
+ '--hide-scrollbars',
68
+ '--mute-audio',
69
+ '--blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4',
70
+ '--lang=en-US',
71
+ ]
72
+
73
+ async function answers(port: number): Promise<boolean> {
74
+ try {
75
+ return (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) })).ok
76
+ } catch {
77
+ return false
78
+ }
79
+ }
80
+
81
+ /** playwright `version`'s full chromium and headless shell, installed into the user's ms-playwright when missing, the
82
+ * shell given the full one's DirectX shader compiler */
83
+ function chromium(version: string): { full: string; shell: string } {
84
+ const root = join(process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'), 'ms-playwright')
85
+ const find = (prefix: string, exe: string) =>
86
+ (existsSync(root) ? readdirSync(root) : [])
87
+ .filter((d) => d.startsWith(prefix) && /^\d+$/.test(d.slice(prefix.length)))
88
+ .sort((a, b) => Number(b.slice(prefix.length)) - Number(a.slice(prefix.length)))
89
+ .map((d) => join(root, d, exe))
90
+ .find((p) => existsSync(p))
91
+ const both = () => ({ full: find('chromium-', 'chrome-win64/chrome.exe'), shell: find('chromium_headless_shell-', 'chrome-headless-shell-win64/chrome-headless-shell.exe') })
92
+ let got = both()
93
+ if (!got.full || !got.shell) {
94
+ say(`installing playwright ${version}'s chromium and headless shell into ${root}`)
95
+ const p = Bun.spawnSync(['bunx', `playwright@${version}`, 'install', 'chromium', 'chromium-headless-shell'], { cwd: DIR, stdout: 'inherit', stderr: 'inherit' })
96
+ got = both()
97
+ if (p.exitCode !== 0 || !got.full || !got.shell) throw new Error(`installing chromium (playwright ${version}) failed, exit ${p.exitCode}`)
98
+ }
99
+ for (const dll of ['dxil.dll', 'dxcompiler.dll']) {
100
+ const to = join(dirname(got.shell), dll)
101
+ if (!existsSync(to)) copyFileSync(join(dirname(got.full), dll), to)
102
+ }
103
+ return { full: got.full, shell: got.shell }
104
+ }
105
+
106
+ /** a process outside the ssh session (WMI), its pid */
107
+ function detached(line: string): number {
108
+ 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`
109
+ const p = Bun.spawnSync(['powershell', '-NoProfile', '-NonInteractive', '-Command', ps], { stdout: 'pipe', stderr: 'pipe' })
110
+ const pid = Number(p.stdout.toString().trim())
111
+ if (p.exitCode !== 0 || !(pid > 0)) throw new Error(`starting ${line.slice(0, 80)} failed (${p.exitCode}): ${p.stderr.toString().trim()}`)
112
+ return pid
113
+ }
114
+
115
+ const kill = (pid: number) => Bun.spawnSync(['taskkill', '/T', '/F', '/PID', String(pid)], { stdout: 'ignore', stderr: 'ignore' })
116
+
117
+ const alive = (pid: number) => {
118
+ try {
119
+ process.kill(pid, 0)
120
+ return true
121
+ } catch {
122
+ return false
123
+ }
124
+ }
125
+
126
+ const quote = (s: string) => `"${s}"`
127
+
128
+ /** the LUID of the box's discrete GPU as chromium names it (`high,low`): chromium on Windows draws on the adapter the
129
+ * display uses (an integrated one on wm), whatever the page's powerPreference. Read once per boot from chrome://gpu */
130
+ async function discreteLuid(exe: string): Promise<string | null> {
131
+ const cache = join(DIR, 'luid.txt')
132
+ const boot = String(Math.round((Date.now() / 1000 - uptime()) / 60))
133
+ const [at, luid] = existsSync(cache) ? readFileSync(cache, 'utf8').trim().split(' ') : []
134
+ if (at === boot && luid) return luid === 'none' ? null : luid
135
+ const profile = join(DIR, 'probe-profile')
136
+ const pid = detached([exe, '--headless=new', `--remote-debugging-port=${PROBE_PORT}`, `--user-data-dir=${profile}`, '--no-first-run', 'about:blank'].map(quote).join(' '))
137
+ try {
138
+ for (let i = 0; i < 100 && !(await answers(PROBE_PORT)); i++) await Bun.sleep(100)
139
+ const target = (await (await fetch(`http://127.0.0.1:${PROBE_PORT}/json/new?chrome://gpu`, { method: 'PUT' })).json()) as { webSocketDebuggerUrl: string }
140
+ const text = await new Promise<string>((done, fail) => {
141
+ const ws = new WebSocket(target.webSocketDebuggerUrl)
142
+ let n = 0
143
+ const ask = () => ws.send(JSON.stringify({ id: ++n, method: 'Runtime.evaluate', params: { expression: "document.querySelector('info-view')?.shadowRoot?.textContent ?? ''", returnByValue: true } }))
144
+ ws.onopen = ask
145
+ ws.onmessage = (e) => {
146
+ const v = (JSON.parse(String(e.data)) as { result?: { result?: { value?: string } } }).result?.result?.value ?? ''
147
+ if (/GPU0/.test(v)) {
148
+ ws.close()
149
+ done(v)
150
+ } else if (n > 50) fail(new Error('chrome://gpu named no GPU in 5 s'))
151
+ else setTimeout(ask, 100)
152
+ }
153
+ ws.onerror = () => fail(new Error('chrome://gpu: its devtools socket failed'))
154
+ })
155
+ const found = /GPU\d+\s*:\s*VENDOR= 0x(?:10de|1002)[^\n]*?LUID=\{(\d+),(\d+)\}/i.exec(text)
156
+ const got = found ? `${found[1]},${found[2]}` : null
157
+ writeFileSync(cache, `${boot} ${got ?? 'none'}`)
158
+ return got
159
+ } finally {
160
+ // its profile stays for the next boot's probe: chromium holds its files a while after the kill
161
+ kill(pid)
162
+ }
163
+ }
164
+
165
+ /** the browser up now, as browser.pid holds it: its pid, the script version that started it, its devtools port */
166
+ function current(): { pid: number; version: string; port: number } | null {
167
+ if (!existsSync(PID)) return null
168
+ const [pid, version, port] = readFileSync(PID, 'utf8').trim().split(' ')
169
+ return Number(pid) > 0 ? { pid: Number(pid), version: version ?? '', port: Number(port) || CDP_PORT } : null
170
+ }
171
+
172
+ async function up(version: string): Promise<void> {
173
+ const t = performance.now()
174
+ mkdirSync(DIR, { recursive: true })
175
+ writeFileSync(USED, String(Date.now()))
176
+ const warm = async () => {
177
+ const c = current()
178
+ return c != null && c.version === VERSION && (await answers(c.port)) ? c : null
179
+ }
180
+ const w = await warm()
181
+ if (w) {
182
+ console.log(`up warm ${Math.round(performance.now() - t)} port ${w.port}`)
183
+ return
184
+ }
185
+ // several films asking at once start one browser: the first starts it, the others wait and find it warm
186
+ const lock = join(DIR, 'up.lock')
187
+ for (;;) {
188
+ try {
189
+ mkdirSync(lock)
190
+ break
191
+ } catch {
192
+ if (Date.now() - (statSync(lock, { throwIfNoEntry: false })?.mtimeMs ?? Date.now()) > 60_000) rmSync(lock, { recursive: true, force: true })
193
+ await Bun.sleep(200)
194
+ }
195
+ }
196
+ try {
197
+ const again = await warm()
198
+ if (again) console.log(`up warm ${Math.round(performance.now() - t)} port ${again.port}`)
199
+ else await start(version, t)
200
+ } finally {
201
+ rmSync(lock, { recursive: true, force: true })
202
+ }
203
+ }
204
+
205
+ /** a new browser on the port the old one does not hold, with its own profile (chromium locks one per process): the
206
+ * old one, if a film still runs in it, drains (its watcher ends it once no film drives a page), never killed mid take */
207
+ async function start(version: string, t: number): Promise<void> {
208
+ const old = current()
209
+ const oldUp = old != null && alive(old.pid) && (await answers(old.port))
210
+ const port = oldUp && old.port === CDP_PORT ? CDP_PORT + 3 : CDP_PORT
211
+ if (old != null && !oldUp) kill(old.pid)
212
+ if (oldUp) {
213
+ if ((await filming(old.port).catch(() => 0)) === 0) kill(old.pid)
214
+ else detached([process.execPath, import.meta.path, 'watch', String(old.pid), String(old.port), 'drain'].map(quote).join(' '))
215
+ }
216
+ const exe = chromium(version)
217
+ const luid = await discreteLuid(exe.full)
218
+ if (luid == null) say('no discrete GPU named in chrome://gpu: the browser draws on the default adapter')
219
+ const args = [`--remote-debugging-port=${port}`, `--user-data-dir=${join(DIR, `profile-${port}`)}`, ...BROWSER_ARGS, ...(luid ? [`--use-adapter-luid=${luid}`] : []), 'about:blank']
220
+ const pid = detached([exe.shell, ...args].map(quote).join(' '))
221
+ writeFileSync(PID, `${pid} ${VERSION} ${port}`)
222
+ for (let i = 0; i < 150 && !(await answers(port)); i++) await Bun.sleep(100)
223
+ if (!(await answers(port))) throw new Error(`the browser (pid ${pid}) did not answer on 127.0.0.1:${port} in 15 s`)
224
+ detached([process.execPath, import.meta.path, 'watch', String(pid), String(port)].map(quote).join(' '))
225
+ console.log(`up started ${Math.round(performance.now() - t)} port ${port} pid ${pid}${luid ? ` luid ${luid}` : ''}${oldUp ? `, the old one on ${old.port} draining` : ''}`)
226
+ }
227
+
228
+ /** one devtools call on the browser's own socket */
229
+ async function browserCall<T>(port: number, method: string, params: Record<string, unknown> = {}): Promise<T> {
230
+ const { webSocketDebuggerUrl } = (await (await fetch(`http://127.0.0.1:${port}/json/version`)).json()) as { webSocketDebuggerUrl: string }
231
+ return await new Promise<T>((done, fail) => {
232
+ const ws = new WebSocket(webSocketDebuggerUrl)
233
+ const t = setTimeout(() => (ws.close(), fail(new Error(`${method}: no answer in 5 s`))), 5000)
234
+ ws.onopen = () => ws.send(JSON.stringify({ id: 1, method, params }))
235
+ ws.onmessage = (e) => {
236
+ clearTimeout(t)
237
+ ws.close()
238
+ done((JSON.parse(String(e.data)) as { result: T }).result)
239
+ }
240
+ ws.onerror = () => fail(new Error(`${method}: the browser's socket failed`))
241
+ })
242
+ }
243
+
244
+ type Target = { targetId: string; type: string; url: string; attached: boolean }
245
+
246
+ /** the pages a film drives now */
247
+ async function filming(port: number): Promise<number> {
248
+ const { targetInfos } = await browserCall<{ targetInfos: Target[] }>(port, 'Target.getTargets')
249
+ return targetInfos.filter((p) => p.type === 'page' && p.url !== 'about:blank' && p.attached).length
250
+ }
251
+
252
+ /** every SWEEP_MS: a page no client drives two sweeps in a row is closed (its film's process died and left it drawing
253
+ * on the GPU); every IDLE_CHECK_MS the idle rule. `drain`: a replaced browser, ended once no film drives a page */
254
+ const SWEEP_MS = 5000
255
+ const IDLE_CHECK_MS = 30_000
256
+
257
+ async function watch(pid: number, port: number, drain: boolean): Promise<void> {
258
+ let orphans = new Set<string>()
259
+ for (let n = 1; ; n++) {
260
+ await Bun.sleep(SWEEP_MS)
261
+ if (!alive(pid)) return
262
+ let busy = false
263
+ let driven = 1
264
+ try {
265
+ const { targetInfos } = await browserCall<{ targetInfos: Target[] }>(port, 'Target.getTargets')
266
+ const pages = targetInfos.filter((t) => t.type === 'page' && t.url !== 'about:blank')
267
+ busy = pages.length > 0
268
+ driven = pages.filter((t) => t.attached).length
269
+ const now = new Set(pages.filter((t) => !t.attached).map((t) => t.targetId))
270
+ for (const id of now) if (orphans.has(id)) await browserCall(port, 'Target.closeTarget', { targetId: id })
271
+ orphans = now
272
+ } catch {}
273
+ if (drain && driven === 0) return void kill(pid)
274
+ if ((n * SWEEP_MS) % IDLE_CHECK_MS !== 0) continue
275
+ const idle = Date.now() - (statSync(USED, { throwIfNoEntry: false })?.mtimeMs ?? 0)
276
+ if (idle > STALE_MS || (idle > IDLE_MS && !busy)) {
277
+ kill(pid)
278
+ if (current()?.pid === pid) rmSync(PID, { force: true })
279
+ return
280
+ }
281
+ }
282
+ }
283
+
284
+ if (import.meta.main) {
285
+ const [cmd, arg, port, mode] = process.argv.slice(2)
286
+ if (cmd === 'up' && arg) await up(arg)
287
+ else if (cmd === 'watch' && Number(arg) > 0) await watch(Number(arg), Number(port) || CDP_PORT, mode === 'drain')
288
+ else {
289
+ console.error('usage: film-box.ts up <playwright version> | watch <browser pid> [port] [drain]')
290
+ process.exit(2)
291
+ }
292
+ }