@air-jam/sdk 0.9.3 → 1.0.0-beta.2

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 (594) hide show
  1. package/README.md +168 -205
  2. package/dist/actions-D4eh6Xaa.d.cts +72 -0
  3. package/dist/actions-D4eh6Xaa.d.ts +72 -0
  4. package/dist/{agent-contract-CD2QnbBJ.d.cts → agent-contract-BMvCMvhE.d.ts} +3 -19
  5. package/dist/{agent-contract-CD2QnbBJ.d.ts → agent-contract-DtYf3ici.d.cts} +3 -19
  6. package/dist/agent-tooling.cjs +135 -46
  7. package/dist/agent-tooling.cjs.map +1 -1
  8. package/dist/agent-tooling.d.cts +96 -5
  9. package/dist/agent-tooling.d.ts +96 -5
  10. package/dist/agent-tooling.js +15 -14
  11. package/dist/agent-tooling.js.map +1 -1
  12. package/dist/{use-air-jam-host-COLy8t4s.d.ts → air-jam-context-B1fQvyYY.d.ts} +121 -114
  13. package/dist/{use-air-jam-host-DM-ybB3C.d.cts → air-jam-context-BKg_ujpd.d.cts} +121 -114
  14. package/dist/arcade/bridge/controller.cjs +873 -603
  15. package/dist/arcade/bridge/controller.cjs.map +1 -1
  16. package/dist/arcade/bridge/controller.d.cts +28 -76
  17. package/dist/arcade/bridge/controller.d.ts +28 -76
  18. package/dist/arcade/bridge/controller.js +27 -28
  19. package/dist/arcade/bridge/controller.js.map +1 -1
  20. package/dist/arcade/bridge/host.cjs +1017 -252
  21. package/dist/arcade/bridge/host.cjs.map +1 -1
  22. package/dist/arcade/bridge/host.d.cts +6 -72
  23. package/dist/arcade/bridge/host.d.ts +6 -72
  24. package/dist/arcade/bridge/host.js +19 -22
  25. package/dist/arcade/bridge/host.js.map +1 -1
  26. package/dist/arcade/bridge/iframe.cjs +3 -31
  27. package/dist/arcade/bridge/iframe.cjs.map +1 -1
  28. package/dist/arcade/bridge/iframe.d.cts +4 -46
  29. package/dist/arcade/bridge/iframe.d.ts +4 -46
  30. package/dist/arcade/bridge/iframe.js +6 -18
  31. package/dist/arcade/bridge/iframe.js.map +1 -1
  32. package/dist/arcade/host.cjs +0 -502
  33. package/dist/arcade/host.cjs.map +1 -1
  34. package/dist/arcade/host.d.cts +1 -19
  35. package/dist/arcade/host.d.ts +1 -19
  36. package/dist/arcade/host.js +0 -14
  37. package/dist/arcade/host.js.map +1 -1
  38. package/dist/arcade/runtime.cjs +10373 -4688
  39. package/dist/arcade/runtime.cjs.map +1 -1
  40. package/dist/arcade/runtime.d.cts +45 -13
  41. package/dist/arcade/runtime.d.ts +45 -13
  42. package/dist/arcade/runtime.js +37 -24
  43. package/dist/arcade/runtime.js.map +1 -1
  44. package/dist/arcade/surface.cjs +3 -35
  45. package/dist/arcade/surface.cjs.map +1 -1
  46. package/dist/arcade/surface.d.cts +14 -2
  47. package/dist/arcade/surface.d.ts +14 -2
  48. package/dist/arcade/surface.js +7 -13
  49. package/dist/arcade/surface.js.map +1 -1
  50. package/dist/arcade/url.cjs +45 -283
  51. package/dist/arcade/url.cjs.map +1 -1
  52. package/dist/arcade/url.d.cts +3 -56
  53. package/dist/arcade/url.d.ts +3 -56
  54. package/dist/arcade/url.js +33 -16
  55. package/dist/arcade/url.js.map +1 -1
  56. package/dist/chunk-24NZZOIO.js +700 -0
  57. package/dist/chunk-24NZZOIO.js.map +1 -0
  58. package/dist/chunk-27QLKLZL.js +469 -0
  59. package/dist/chunk-27QLKLZL.js.map +1 -0
  60. package/dist/{chunk-UWJOIVON.js → chunk-2H2FGF3H.js} +3 -6
  61. package/dist/chunk-2H2FGF3H.js.map +1 -0
  62. package/dist/chunk-3LDQCQL2.js +307 -0
  63. package/dist/chunk-3LDQCQL2.js.map +1 -0
  64. package/dist/chunk-3M7656SU.js +389 -0
  65. package/dist/chunk-3M7656SU.js.map +1 -0
  66. package/dist/{chunk-K4OZ54UD.js → chunk-5CRZFIN6.js} +2 -55
  67. package/dist/chunk-5CRZFIN6.js.map +1 -0
  68. package/dist/chunk-5L3O3G5K.js +802 -0
  69. package/dist/chunk-5L3O3G5K.js.map +1 -0
  70. package/dist/{chunk-O6X7FJ6N.js → chunk-6PLOJMJD.js} +619 -643
  71. package/dist/chunk-6PLOJMJD.js.map +1 -0
  72. package/dist/{chunk-EVZJA6RN.js → chunk-6ZJUA63D.js} +183 -2
  73. package/dist/chunk-6ZJUA63D.js.map +1 -0
  74. package/dist/chunk-A6EOGRRG.js +49 -0
  75. package/dist/chunk-A6EOGRRG.js.map +1 -0
  76. package/dist/chunk-AXG6FA2H.js +366 -0
  77. package/dist/chunk-AXG6FA2H.js.map +1 -0
  78. package/dist/chunk-BEM77SVQ.js +57 -0
  79. package/dist/chunk-BEM77SVQ.js.map +1 -0
  80. package/dist/chunk-BQHGPXXN.js +1995 -0
  81. package/dist/chunk-BQHGPXXN.js.map +1 -0
  82. package/dist/chunk-C5722GTG.js +176 -0
  83. package/dist/chunk-C5722GTG.js.map +1 -0
  84. package/dist/{chunk-CV3PBXPT.js → chunk-C5GS2GMK.js} +99 -105
  85. package/dist/chunk-C5GS2GMK.js.map +1 -0
  86. package/dist/chunk-CDL7LYZH.js +19 -0
  87. package/dist/chunk-CDL7LYZH.js.map +1 -0
  88. package/dist/{chunk-PSUYTD2L.js → chunk-DA3TE4OP.js} +1 -1
  89. package/dist/chunk-DA3TE4OP.js.map +1 -0
  90. package/dist/chunk-DBF7NJ3S.js +72 -0
  91. package/dist/chunk-DBF7NJ3S.js.map +1 -0
  92. package/dist/chunk-DRBPVG47.js +89 -0
  93. package/dist/chunk-DRBPVG47.js.map +1 -0
  94. package/dist/chunk-FCG42U7D.js +131 -0
  95. package/dist/chunk-FCG42U7D.js.map +1 -0
  96. package/dist/chunk-FJ4J2BEC.js +26 -0
  97. package/dist/chunk-FJ4J2BEC.js.map +1 -0
  98. package/dist/chunk-H4DEVMTO.js +221 -0
  99. package/dist/chunk-H4DEVMTO.js.map +1 -0
  100. package/dist/chunk-ISQZ7F3N.js +83 -0
  101. package/dist/chunk-ISQZ7F3N.js.map +1 -0
  102. package/dist/{chunk-IG6GZZSS.js → chunk-JCGTL77W.js} +1 -1
  103. package/dist/chunk-JCGTL77W.js.map +1 -0
  104. package/dist/chunk-JJVCBUYM.js +98 -0
  105. package/dist/chunk-JJVCBUYM.js.map +1 -0
  106. package/dist/chunk-K6BJJJJM.js +138 -0
  107. package/dist/chunk-K6BJJJJM.js.map +1 -0
  108. package/dist/{chunk-MIMPMB7O.js → chunk-KGY4PV2A.js} +24 -3
  109. package/dist/chunk-KGY4PV2A.js.map +1 -0
  110. package/dist/chunk-KKRLHT2M.js +2477 -0
  111. package/dist/chunk-KKRLHT2M.js.map +1 -0
  112. package/dist/chunk-KSYN4I5Y.js +50 -0
  113. package/dist/chunk-KSYN4I5Y.js.map +1 -0
  114. package/dist/chunk-KUGROY5S.js +265 -0
  115. package/dist/chunk-KUGROY5S.js.map +1 -0
  116. package/dist/chunk-LX6CTPDW.js +16 -0
  117. package/dist/chunk-LX6CTPDW.js.map +1 -0
  118. package/dist/{chunk-BE6Z4SIT.js → chunk-M5553I2G.js} +2 -11
  119. package/dist/chunk-M5553I2G.js.map +1 -0
  120. package/dist/{chunk-X24K52DG.js → chunk-MD25536W.js} +1 -1
  121. package/dist/chunk-MD25536W.js.map +1 -0
  122. package/dist/{chunk-3USU7GY2.js → chunk-MJAWAHLT.js} +1 -1
  123. package/dist/chunk-MJAWAHLT.js.map +1 -0
  124. package/dist/chunk-NBA7UIWG.js +921 -0
  125. package/dist/chunk-NBA7UIWG.js.map +1 -0
  126. package/dist/chunk-OAXCFPZ7.js +14 -0
  127. package/dist/chunk-OAXCFPZ7.js.map +1 -0
  128. package/dist/{chunk-D4VDEVTZ.js → chunk-QHBRHYMV.js} +18 -17
  129. package/dist/chunk-QHBRHYMV.js.map +1 -0
  130. package/dist/chunk-QTNYGAZ7.js +45 -0
  131. package/dist/chunk-QTNYGAZ7.js.map +1 -0
  132. package/dist/chunk-UC24OG4X.js +129 -0
  133. package/dist/chunk-UC24OG4X.js.map +1 -0
  134. package/dist/chunk-VN2PX2I3.js +188 -0
  135. package/dist/chunk-VN2PX2I3.js.map +1 -0
  136. package/dist/chunk-WAFGYJZN.js +1513 -0
  137. package/dist/chunk-WAFGYJZN.js.map +1 -0
  138. package/dist/chunk-WGHNGQUS.js +78 -0
  139. package/dist/chunk-WGHNGQUS.js.map +1 -0
  140. package/dist/{chunk-X35LLCWV.js → chunk-X5HZBQ6K.js} +6 -8
  141. package/dist/chunk-X5HZBQ6K.js.map +1 -0
  142. package/dist/chunk-XLY44PXZ.js +46 -0
  143. package/dist/chunk-XLY44PXZ.js.map +1 -0
  144. package/dist/chunk-YXHAWWVU.js +7 -0
  145. package/dist/chunk-YXHAWWVU.js.map +1 -0
  146. package/dist/connection-store-CqW-E7ma.d.cts +41 -0
  147. package/dist/connection-store-ffHWMrMe.d.ts +41 -0
  148. package/dist/control-Bv8dWjyp.d.ts +1400 -0
  149. package/dist/control-CNzybWMd.d.cts +1400 -0
  150. package/dist/controller-ClW0R8mZ.d.cts +26 -0
  151. package/dist/controller-DRKCa7uQ.d.ts +26 -0
  152. package/dist/controller-agent-vOiuK7T6.d.cts +130 -0
  153. package/dist/controller-agent-vOiuK7T6.d.ts +130 -0
  154. package/dist/controller-bridge.cjs +992 -0
  155. package/dist/controller-bridge.cjs.map +1 -0
  156. package/dist/controller-bridge.d.cts +52 -0
  157. package/dist/controller-bridge.d.ts +52 -0
  158. package/dist/controller-bridge.js +23 -0
  159. package/dist/controller-bridge.js.map +1 -0
  160. package/dist/controller-capture-2GKKGHJ2.js +8 -0
  161. package/dist/controller-capture-2GKKGHJ2.js.map +1 -0
  162. package/dist/controller-press-EWWIMVXP.js +231 -0
  163. package/dist/controller-press-EWWIMVXP.js.map +1 -0
  164. package/dist/core-BAO0pHrJ.d.cts +15 -0
  165. package/dist/core-BAO0pHrJ.d.ts +15 -0
  166. package/dist/core.cjs +5956 -0
  167. package/dist/core.cjs.map +1 -0
  168. package/dist/core.d.cts +250 -0
  169. package/dist/core.d.ts +250 -0
  170. package/dist/core.js +910 -0
  171. package/dist/core.js.map +1 -0
  172. package/dist/dev-events-BffobOfb.d.ts +31 -0
  173. package/dist/dev-events-Ct7QEgKb.d.cts +31 -0
  174. package/dist/dev-log-events-B1_B3guZ.d.cts +47 -0
  175. package/dist/dev-log-events-B1_B3guZ.d.ts +47 -0
  176. package/dist/frames-D-xKuODS.d.cts +686 -0
  177. package/dist/frames-D-xKuODS.d.ts +686 -0
  178. package/dist/game-5n-dh5np.d.cts +77 -0
  179. package/dist/game-RYb97BN8.d.ts +77 -0
  180. package/dist/host-runtime-BRtUidEJ.d.cts +399 -0
  181. package/dist/host-runtime-RrO4pCXI.d.ts +399 -0
  182. package/dist/index.cjs +11571 -7554
  183. package/dist/index.cjs.map +1 -1
  184. package/dist/index.d.cts +100 -358
  185. package/dist/index.d.ts +100 -358
  186. package/dist/index.js +414 -1903
  187. package/dist/index.js.map +1 -1
  188. package/dist/input-D7FNeehb.d.cts +92 -0
  189. package/dist/input-D7FNeehb.d.ts +92 -0
  190. package/dist/input-bindings-686sTen7.d.ts +129 -0
  191. package/dist/input-bindings-BRac-P0e.d.cts +129 -0
  192. package/dist/leased-control-BEg4JuXA.d.cts +158 -0
  193. package/dist/leased-control-BEg4JuXA.d.ts +158 -0
  194. package/dist/metadata.cjs +3 -9
  195. package/dist/metadata.cjs.map +1 -1
  196. package/dist/metadata.d.cts +6 -16
  197. package/dist/metadata.d.ts +6 -16
  198. package/dist/metadata.js +8 -76
  199. package/dist/metadata.js.map +1 -1
  200. package/dist/phone-room-session-Byomkt92.d.cts +439 -0
  201. package/dist/phone-room-session-D9C8cSxS.d.ts +439 -0
  202. package/dist/platform-machine.cjs +133 -3
  203. package/dist/platform-machine.cjs.map +1 -1
  204. package/dist/platform-machine.d.cts +525 -27
  205. package/dist/platform-machine.d.ts +525 -27
  206. package/dist/platform-machine.js +119 -4
  207. package/dist/platform-machine.js.map +1 -1
  208. package/dist/{platform-settings-DUWs4JTy.d.cts → platform-settings-Yb0fQ1dl.d.cts} +1 -3
  209. package/dist/{platform-settings-DUWs4JTy.d.ts → platform-settings-Yb0fQ1dl.d.ts} +1 -3
  210. package/dist/prefabs.cjs +134 -3
  211. package/dist/prefabs.cjs.map +1 -1
  212. package/dist/prefabs.d.cts +23 -47
  213. package/dist/prefabs.d.ts +23 -47
  214. package/dist/prefabs.js +23 -4
  215. package/dist/prefabs.js.map +1 -1
  216. package/dist/preview.cjs +2199 -767
  217. package/dist/preview.cjs.map +1 -1
  218. package/dist/preview.d.cts +193 -38
  219. package/dist/preview.d.ts +193 -38
  220. package/dist/preview.js +478 -254
  221. package/dist/preview.js.map +1 -1
  222. package/dist/protocol.cjs +585 -391
  223. package/dist/protocol.cjs.map +1 -1
  224. package/dist/protocol.d.cts +13 -117
  225. package/dist/protocol.d.ts +13 -117
  226. package/dist/protocol.js +43 -80
  227. package/dist/protocol.js.map +1 -1
  228. package/dist/release.cjs.map +1 -1
  229. package/dist/release.d.cts +2 -2
  230. package/dist/release.d.ts +2 -2
  231. package/dist/release.js +1 -1
  232. package/dist/release.js.map +1 -1
  233. package/dist/replay-input-log-D0NpnA3P.d.ts +31 -0
  234. package/dist/replay-input-log-bg0g-PCz.d.cts +31 -0
  235. package/dist/room-protocol.cjs +794 -0
  236. package/dist/room-protocol.cjs.map +1 -0
  237. package/dist/room-protocol.d.cts +63 -0
  238. package/dist/room-protocol.d.ts +63 -0
  239. package/dist/room-protocol.js +143 -0
  240. package/dist/room-protocol.js.map +1 -0
  241. package/dist/room-session.cjs +2336 -0
  242. package/dist/room-session.cjs.map +1 -0
  243. package/dist/room-session.d.cts +77 -0
  244. package/dist/room-session.d.ts +77 -0
  245. package/dist/room-session.js +103 -0
  246. package/dist/room-session.js.map +1 -0
  247. package/dist/runtime/prefab-inspection-bridge.cjs +207 -0
  248. package/dist/runtime/prefab-inspection-bridge.cjs.map +1 -0
  249. package/dist/runtime/prefab-inspection-bridge.d.cts +156 -0
  250. package/dist/runtime/prefab-inspection-bridge.d.ts +156 -0
  251. package/dist/runtime/prefab-inspection-bridge.js +22 -0
  252. package/dist/runtime/prefab-inspection-bridge.js.map +1 -0
  253. package/dist/runtime-control.cjs +2133 -8
  254. package/dist/runtime-control.cjs.map +1 -1
  255. package/dist/runtime-control.d.cts +980 -12
  256. package/dist/runtime-control.d.ts +980 -12
  257. package/dist/runtime-control.js +264 -4
  258. package/dist/runtime-control.js.map +1 -1
  259. package/dist/runtime-inspection.cjs +1222 -558
  260. package/dist/runtime-inspection.cjs.map +1 -1
  261. package/dist/runtime-inspection.d.cts +530 -22
  262. package/dist/runtime-inspection.d.ts +530 -22
  263. package/dist/runtime-inspection.js +21 -22
  264. package/dist/runtime-inspection.js.map +1 -1
  265. package/dist/runtime-reporting-K_ZXpubu.d.cts +43 -0
  266. package/dist/runtime-reporting-K_ZXpubu.d.ts +43 -0
  267. package/dist/runtime-topology.cjs +2 -5
  268. package/dist/runtime-topology.cjs.map +1 -1
  269. package/dist/runtime-topology.d.cts +1 -1
  270. package/dist/runtime-topology.d.ts +1 -1
  271. package/dist/runtime-topology.js +1 -1
  272. package/dist/runtime-topology.js.map +1 -1
  273. package/dist/scoped-connector-DEOZvCCG.d.cts +66 -0
  274. package/dist/scoped-connector-nTHACYTl.d.ts +66 -0
  275. package/dist/sdk-channels-S6j6AH8v.d.cts +103 -0
  276. package/dist/sdk-channels-S6j6AH8v.d.ts +103 -0
  277. package/dist/simulation-DL9j-ghn.d.ts +782 -0
  278. package/dist/simulation-HmgsvF5H.d.cts +782 -0
  279. package/dist/{standard-match-phase-BzSgBYFg.d.ts → standard-match-phase-D4N-AU0d.d.cts} +3 -13
  280. package/dist/{standard-match-phase-CvJUW8Oe.d.cts → standard-match-phase-abt8ZjCh.d.ts} +3 -13
  281. package/dist/transport-CWF29jU6.d.cts +173 -0
  282. package/dist/transport-CWF29jU6.d.ts +173 -0
  283. package/dist/types-p28maMEo.d.cts +102 -0
  284. package/dist/types-p28maMEo.d.ts +102 -0
  285. package/dist/ui.cjs +2167 -892
  286. package/dist/ui.cjs.map +1 -1
  287. package/dist/ui.d.cts +75 -17
  288. package/dist/ui.d.ts +75 -17
  289. package/dist/ui.js +554 -393
  290. package/dist/ui.js.map +1 -1
  291. package/package.json +38 -21
  292. package/src/agent/agent-action.ts +0 -39
  293. package/src/agent/agent-contract-conformance.ts +8 -1
  294. package/src/agent/agent-contract.ts +2 -4
  295. package/src/agent/agent-evaluator.ts +95 -0
  296. package/src/agent/capture-canvas.ts +79 -0
  297. package/src/agent/host-canvas-capture.ts +189 -0
  298. package/src/agent-tooling.ts +5 -20
  299. package/src/arcade/bridge/controller.ts +8 -11
  300. package/src/arcade/bridge/host.ts +6 -11
  301. package/src/arcade/bridge/iframe.ts +1 -50
  302. package/src/arcade/host.ts +0 -1
  303. package/src/arcade/surface.ts +5 -1
  304. package/src/arcade/url.ts +2 -9
  305. package/src/audio/audio-manager.ts +23 -47
  306. package/src/audio/hooks.tsx +59 -72
  307. package/src/components/controller-player-name-field.tsx +2 -2
  308. package/src/components/controller-primary-action.tsx +1 -1
  309. package/src/components/controls.tsx +398 -0
  310. package/src/components/gamepad-layout.tsx +69 -0
  311. package/src/components/join-url-controls.tsx +5 -1
  312. package/src/components/lifecycle-action-group.tsx +1 -1
  313. package/src/components/player-avatar.tsx +50 -3
  314. package/src/components/room-qr-code.tsx +36 -77
  315. package/src/components/stage-capture-surface.tsx +91 -0
  316. package/src/components/surface-viewport.tsx +16 -3
  317. package/src/components/ui/button.tsx +1 -1
  318. package/src/constants.ts +0 -15
  319. package/src/context/air-jam-context.tsx +56 -187
  320. package/src/context/session-providers.tsx +13 -10
  321. package/src/controller-bridge.ts +7 -0
  322. package/src/core/assets.ts +48 -0
  323. package/src/core/config.ts +70 -0
  324. package/src/core/connection-store.ts +77 -0
  325. package/src/core/controller-input.ts +147 -0
  326. package/src/core/controller-runtime.ts +427 -0
  327. package/src/core/dev-events.ts +18 -0
  328. package/src/core/environment.ts +132 -0
  329. package/src/core/game-description.ts +44 -0
  330. package/src/core/game.ts +130 -0
  331. package/src/core/host-input.ts +207 -0
  332. package/src/core/host-runtime.ts +988 -0
  333. package/src/core/hosted-rooms.ts +65 -0
  334. package/src/core/input-bindings.ts +180 -0
  335. package/src/core/input-log.ts +144 -0
  336. package/src/core/input.ts +228 -0
  337. package/src/core/local-input.ts +319 -0
  338. package/src/core/replay-input-log.ts +298 -0
  339. package/src/core/replicated-store.ts +1178 -0
  340. package/src/core/room-action-ack.ts +43 -0
  341. package/src/core/settings.ts +202 -0
  342. package/src/core/simulation.ts +307 -0
  343. package/src/core/theme.ts +33 -0
  344. package/src/core.ts +167 -0
  345. package/src/dev/browser-log-sink.ts +35 -12
  346. package/src/diagnostics.ts +5 -6
  347. package/src/hooks/internal/use-controller-runtime-api.ts +58 -925
  348. package/src/hooks/internal/use-host-runtime-api.ts +98 -1270
  349. package/src/hooks/internal/use-runtime-inspection-contract.ts +14 -2
  350. package/src/hooks/use-air-jam-controller.ts +32 -53
  351. package/src/hooks/use-air-jam-host.ts +59 -100
  352. package/src/hooks/use-air-jam-settings.ts +27 -0
  353. package/src/hooks/use-controller-toasts.ts +16 -19
  354. package/src/hooks/use-host-agent-capture.ts +31 -0
  355. package/src/hooks/use-lifecycle-action-group-model.ts +1 -1
  356. package/src/hooks/use-send-signal.ts +23 -156
  357. package/src/hooks/use-simulation.ts +83 -0
  358. package/src/index.ts +24 -85
  359. package/src/lifecycle/index.ts +0 -4
  360. package/src/lifecycle/standard-match-phase.ts +1 -22
  361. package/src/metadata/manifest.ts +8 -19
  362. package/src/metadata.ts +1 -1
  363. package/src/platform-machine.ts +127 -3
  364. package/src/prefabs/types.ts +91 -20
  365. package/src/prefabs/view.ts +82 -0
  366. package/src/prefabs.ts +19 -0
  367. package/src/preview/host-workspace.tsx +4 -9
  368. package/src/preview/identity.ts +31 -23
  369. package/src/preview/layout.ts +5 -1
  370. package/src/preview/manager.ts +205 -78
  371. package/src/preview/messages.ts +47 -0
  372. package/src/preview/ownership.ts +6 -1
  373. package/src/preview/url.ts +46 -23
  374. package/src/preview/window.tsx +26 -69
  375. package/src/preview/workspace-local-seats.ts +166 -0
  376. package/src/preview/workspace.tsx +89 -37
  377. package/src/preview.ts +27 -15
  378. package/src/protocol/actions.ts +58 -0
  379. package/src/protocol/arcade-platform-actions.ts +2 -16
  380. package/src/protocol/controller.ts +14 -174
  381. package/src/protocol/core.ts +8 -15
  382. package/src/protocol/dev-log-events.ts +5 -81
  383. package/src/protocol/leased-control.ts +177 -0
  384. package/src/protocol/room/addressing.ts +35 -0
  385. package/src/protocol/room/close-codes.ts +33 -0
  386. package/src/protocol/room/frames.ts +343 -0
  387. package/src/protocol/room/input-codec.ts +182 -0
  388. package/src/protocol/room/limits.ts +58 -0
  389. package/src/protocol/room/patch.ts +135 -0
  390. package/src/protocol/room/sdk-channels.ts +81 -0
  391. package/src/protocol/room/seat-id.ts +31 -0
  392. package/src/protocol/room/transport.ts +63 -0
  393. package/src/protocol/room/weight.ts +58 -0
  394. package/src/protocol/runtime-reporting.ts +56 -10
  395. package/src/protocol.ts +2 -7
  396. package/src/qrcode.d.ts +3 -13
  397. package/src/room-protocol.ts +10 -0
  398. package/src/room-session/browser-wake-events.ts +14 -0
  399. package/src/room-session/channel-state.ts +293 -0
  400. package/src/room-session/clock.ts +24 -0
  401. package/src/room-session/host-room-session.ts +379 -0
  402. package/src/room-session/input-lane.ts +125 -0
  403. package/src/room-session/listeners.ts +22 -0
  404. package/src/room-session/loopback-link.ts +58 -0
  405. package/src/room-session/phone-room-session.ts +368 -0
  406. package/src/room-session/port-link.ts +116 -0
  407. package/src/room-session/room-key.ts +9 -0
  408. package/src/room-session/roster.ts +23 -0
  409. package/src/room-session/scoped-connector.ts +577 -0
  410. package/src/room-session/session-link.ts +306 -0
  411. package/src/room-session/web-socket-link.ts +57 -0
  412. package/src/room-session.ts +12 -0
  413. package/src/runtime/air-jam-config.ts +49 -37
  414. package/src/runtime/air-jam-error-boundary.tsx +9 -3
  415. package/src/runtime/arcade-runtime-url.ts +8 -9
  416. package/src/runtime/browser-controller-environment.ts +116 -0
  417. package/src/runtime/browser-host-environment.ts +137 -0
  418. package/src/runtime/browser-replay.ts +211 -0
  419. package/src/runtime/browser-room.ts +41 -0
  420. package/src/runtime/connected-runtime-error-boundary.tsx +35 -8
  421. package/src/runtime/contracts/agent-control.ts +195 -0
  422. package/src/runtime/contracts/clip.ts +169 -0
  423. package/src/runtime/contracts/control.ts +653 -16
  424. package/src/runtime/contracts/controller-agent.ts +130 -0
  425. package/src/runtime/contracts/input-log.ts +38 -0
  426. package/src/runtime/contracts/inspection.ts +25 -22
  427. package/src/runtime/contracts/observation.ts +186 -0
  428. package/src/runtime/contracts/runtime-identity.ts +43 -0
  429. package/src/runtime/contracts/timeline.ts +59 -0
  430. package/src/runtime/controller-agent-bridge.ts +152 -0
  431. package/src/runtime/controller-bridge-context.ts +29 -0
  432. package/src/runtime/controller-capture.ts +50 -0
  433. package/src/runtime/controller-identity.ts +53 -142
  434. package/src/runtime/controller-presentation.ts +47 -17
  435. package/src/runtime/controller-press.ts +271 -0
  436. package/src/runtime/create-air-jam-app.tsx +103 -74
  437. package/src/runtime/dev-runtime-events.ts +6 -18
  438. package/src/runtime/embedded-parent.ts +22 -0
  439. package/src/runtime/embedded-runtime-adapters.ts +10 -9
  440. package/src/runtime/host-agent-bridge.ts +127 -0
  441. package/src/runtime/host-capture-boundary.tsx +92 -0
  442. package/src/runtime/host-capture-context.ts +7 -0
  443. package/src/runtime/host-clip-reader.ts +93 -0
  444. package/src/runtime/host-clip-recorder.ts +342 -0
  445. package/src/runtime/host-input-log-reader.ts +120 -0
  446. package/src/runtime/host-observation.ts +207 -0
  447. package/src/runtime/host-pace.ts +36 -0
  448. package/src/runtime/host-runtime-fault.ts +51 -0
  449. package/src/runtime/host-timeline.ts +152 -0
  450. package/src/runtime/local-players.tsx +96 -0
  451. package/src/runtime/local-seats.ts +612 -0
  452. package/src/runtime/participant-control.ts +162 -0
  453. package/src/runtime/prefab-inspection-bridge.ts +174 -0
  454. package/src/runtime/prefab-inspection-clock.ts +12 -0
  455. package/src/runtime/prefab-inspection-context.ts +20 -0
  456. package/src/runtime/prefab-inspection-runtime.tsx +328 -0
  457. package/src/runtime/preview-inspection-bridge.ts +130 -0
  458. package/src/runtime/replay-runtime.tsx +101 -0
  459. package/src/runtime/room-bridge.ts +110 -0
  460. package/src/runtime/runtime-owner-contexts.tsx +9 -0
  461. package/src/runtime/runtime-session-params.ts +20 -23
  462. package/src/runtime/session-runtimes.tsx +231 -64
  463. package/src/runtime/stage-capture.ts +25 -0
  464. package/src/runtime-control.ts +41 -0
  465. package/src/runtime-inspection.ts +14 -7
  466. package/src/runtime-topology.ts +7 -8
  467. package/src/settings/platform-settings-runtime.tsx +47 -2
  468. package/src/settings/platform-settings.ts +0 -65
  469. package/src/store/use-air-jam-store.ts +73 -0
  470. package/src/ui.ts +3 -3
  471. package/src/utils/is-rpc-serializable.ts +11 -19
  472. package/src/utils/url-builder.ts +0 -7
  473. package/dist/air-jam-context-BlLPvCup.d.cts +0 -175
  474. package/dist/air-jam-context-DTsxF-tP.d.ts +0 -175
  475. package/dist/arcade/bridge.cjs +0 -1087
  476. package/dist/arcade/bridge.cjs.map +0 -1
  477. package/dist/arcade/bridge.d.cts +0 -11
  478. package/dist/arcade/bridge.d.ts +0 -11
  479. package/dist/arcade/bridge.js +0 -78
  480. package/dist/arcade/bridge.js.map +0 -1
  481. package/dist/arcade-runtime-url-BW-MUAOY.d.cts +0 -28
  482. package/dist/arcade-runtime-url-l8qj01Pg.d.ts +0 -28
  483. package/dist/arcade.cjs +0 -1767
  484. package/dist/arcade.cjs.map +0 -1
  485. package/dist/arcade.d.cts +0 -18
  486. package/dist/arcade.d.ts +0 -18
  487. package/dist/arcade.js +0 -129
  488. package/dist/arcade.js.map +0 -1
  489. package/dist/chunk-2SZ2YYGJ.js +0 -280
  490. package/dist/chunk-2SZ2YYGJ.js.map +0 -1
  491. package/dist/chunk-32RSSFSF.js +0 -214
  492. package/dist/chunk-32RSSFSF.js.map +0 -1
  493. package/dist/chunk-3USU7GY2.js.map +0 -1
  494. package/dist/chunk-3YMUAKPU.js +0 -10
  495. package/dist/chunk-3YMUAKPU.js.map +0 -1
  496. package/dist/chunk-56DM2KEW.js +0 -14
  497. package/dist/chunk-56DM2KEW.js.map +0 -1
  498. package/dist/chunk-BE6Z4SIT.js.map +0 -1
  499. package/dist/chunk-CM53YLT5.js +0 -59
  500. package/dist/chunk-CM53YLT5.js.map +0 -1
  501. package/dist/chunk-CV3PBXPT.js.map +0 -1
  502. package/dist/chunk-D4VDEVTZ.js.map +0 -1
  503. package/dist/chunk-EVZJA6RN.js.map +0 -1
  504. package/dist/chunk-FUA6EMSJ.js +0 -90
  505. package/dist/chunk-FUA6EMSJ.js.map +0 -1
  506. package/dist/chunk-GMLU7RI5.js +0 -70
  507. package/dist/chunk-GMLU7RI5.js.map +0 -1
  508. package/dist/chunk-IG6GZZSS.js.map +0 -1
  509. package/dist/chunk-IKKDONQL.js +0 -1
  510. package/dist/chunk-IKKDONQL.js.map +0 -1
  511. package/dist/chunk-ITMQSBTH.js +0 -26
  512. package/dist/chunk-ITMQSBTH.js.map +0 -1
  513. package/dist/chunk-J5MCII33.js +0 -620
  514. package/dist/chunk-J5MCII33.js.map +0 -1
  515. package/dist/chunk-JTF47B56.js +0 -1
  516. package/dist/chunk-JTF47B56.js.map +0 -1
  517. package/dist/chunk-K4OZ54UD.js.map +0 -1
  518. package/dist/chunk-LIHEEAVE.js +0 -191
  519. package/dist/chunk-LIHEEAVE.js.map +0 -1
  520. package/dist/chunk-LIXPF4P6.js +0 -22
  521. package/dist/chunk-LIXPF4P6.js.map +0 -1
  522. package/dist/chunk-MIMPMB7O.js.map +0 -1
  523. package/dist/chunk-MPDMJIX5.js +0 -1
  524. package/dist/chunk-MPDMJIX5.js.map +0 -1
  525. package/dist/chunk-O6X7FJ6N.js.map +0 -1
  526. package/dist/chunk-PSUYTD2L.js.map +0 -1
  527. package/dist/chunk-QO4KFUEI.js +0 -32
  528. package/dist/chunk-QO4KFUEI.js.map +0 -1
  529. package/dist/chunk-QTLYZADF.js +0 -125
  530. package/dist/chunk-QTLYZADF.js.map +0 -1
  531. package/dist/chunk-TGRTEWYV.js +0 -195
  532. package/dist/chunk-TGRTEWYV.js.map +0 -1
  533. package/dist/chunk-TTQDHKXL.js +0 -3017
  534. package/dist/chunk-TTQDHKXL.js.map +0 -1
  535. package/dist/chunk-UCPY7UJC.js +0 -8
  536. package/dist/chunk-UCPY7UJC.js.map +0 -1
  537. package/dist/chunk-UPV6YWT5.js +0 -43
  538. package/dist/chunk-UPV6YWT5.js.map +0 -1
  539. package/dist/chunk-UWJOIVON.js.map +0 -1
  540. package/dist/chunk-W2VK36RO.js +0 -11
  541. package/dist/chunk-W2VK36RO.js.map +0 -1
  542. package/dist/chunk-X24K52DG.js.map +0 -1
  543. package/dist/chunk-X35LLCWV.js.map +0 -1
  544. package/dist/chunk-YXHH3MQT.js +0 -230
  545. package/dist/chunk-YXHH3MQT.js.map +0 -1
  546. package/dist/controller-PZEM_1cH.d.ts +0 -176
  547. package/dist/controller-vj82tKm4.d.cts +0 -176
  548. package/dist/dev-log-events-BCJKmygo.d.cts +0 -120
  549. package/dist/dev-log-events-BCJKmygo.d.ts +0 -120
  550. package/dist/handshake-CC_LrK5g.d.cts +0 -31
  551. package/dist/handshake-CC_LrK5g.d.ts +0 -31
  552. package/dist/host-B9pRy0Aa.d.cts +0 -122
  553. package/dist/host-DylGsX7p.d.ts +0 -122
  554. package/dist/notices-C4bao3oi.d.ts +0 -38
  555. package/dist/notices-DNdOjwtj.d.cts +0 -38
  556. package/dist/realtime-client-Cu8yVJFw.d.cts +0 -15
  557. package/dist/realtime-client-Cu8yVJFw.d.ts +0 -15
  558. package/dist/runtime-reporting-pe-eryVz.d.cts +0 -27
  559. package/dist/runtime-reporting-pe-eryVz.d.ts +0 -27
  560. package/dist/signals-ZHftIKuc.d.cts +0 -33
  561. package/dist/signals-ZHftIKuc.d.ts +0 -33
  562. package/dist/sync-xtPfWhif.d.cts +0 -81
  563. package/dist/sync-xtPfWhif.d.ts +0 -81
  564. package/src/arcade/bridge.ts +0 -3
  565. package/src/arcade.ts +0 -4
  566. package/src/context/socket-manager.ts +0 -72
  567. package/src/events.ts +0 -119
  568. package/src/hooks/use-connection-status.ts +0 -8
  569. package/src/hooks/use-controller-tick.ts +0 -65
  570. package/src/hooks/use-get-input.ts +0 -100
  571. package/src/hooks/use-host-arcade-restore.ts +0 -35
  572. package/src/hooks/use-host-tick.ts +0 -171
  573. package/src/hooks/use-input-writer.ts +0 -83
  574. package/src/hooks/use-players.ts +0 -12
  575. package/src/internal/input-manager.ts +0 -356
  576. package/src/protocol/errors.ts +0 -21
  577. package/src/protocol/host-grant.ts +0 -103
  578. package/src/protocol/host.ts +0 -150
  579. package/src/protocol/notices.ts +0 -43
  580. package/src/protocol/signals.ts +0 -38
  581. package/src/protocol/socket-events.ts +0 -152
  582. package/src/protocol/sync.ts +0 -105
  583. package/src/runtime/admission-retry.ts +0 -62
  584. package/src/runtime/bridge-envelope-args.ts +0 -21
  585. package/src/runtime/controller-bridge.ts +0 -439
  586. package/src/runtime/controller-realtime-client.ts +0 -552
  587. package/src/runtime/host-bridge.ts +0 -380
  588. package/src/runtime/host-realtime-client.ts +0 -550
  589. package/src/runtime/realtime-client.ts +0 -20
  590. package/src/runtime/validate-arcade-bridge-attach.ts +0 -14
  591. package/src/state/connection-store.ts +0 -159
  592. package/src/store/create-air-jam-store.ts +0 -1193
  593. package/src/store/index.ts +0 -1
  594. package/src/utils/ids.ts +0 -58
@@ -0,0 +1,1995 @@
1
+ import {
2
+ describeHostRuntimeFault,
3
+ hostRuntimeFault
4
+ } from "./chunk-XLY44PXZ.js";
5
+ import {
6
+ emitAirJamDiagnostic
7
+ } from "./chunk-DBF7NJ3S.js";
8
+ import {
9
+ AIRJAM_DEV_LOG_EVENTS,
10
+ playerProfilePatchSchema
11
+ } from "./chunk-KUGROY5S.js";
12
+ import {
13
+ getReconnectingPlayerIds
14
+ } from "./chunk-AXG6FA2H.js";
15
+ import {
16
+ CLIP_FRAME_INTERVAL_MS,
17
+ CLIP_FRAME_MAX_BYTES,
18
+ CLIP_FRAME_MAX_EDGE,
19
+ CLIP_FRAME_QUALITY,
20
+ CLIP_MAX_BYTES,
21
+ CLIP_MAX_DURATION_MS,
22
+ CLIP_MAX_RECORDINGS,
23
+ CLIP_MIN_FRAME_INTERVAL_MS,
24
+ CLIP_PAGE_BASE64_CHARS,
25
+ CLIP_RECORDING_LIFETIME_MS,
26
+ CLIP_STOPPED_RELEASE_MS,
27
+ HostSettings,
28
+ InputRecorder,
29
+ applyHostRuntimeLeasedControl,
30
+ clearHostRuntimeParticipant,
31
+ clipFrameSchema,
32
+ clipImageBytes,
33
+ registerHostAgentContract,
34
+ registerHostObservationSurface,
35
+ registerHostRuntimeParticipantReceiver,
36
+ trackHostSimulation
37
+ } from "./chunk-WAFGYJZN.js";
38
+ import {
39
+ controllerLeasedControlSchema,
40
+ leasedControlRequestSchema,
41
+ participantInputSchemaDescriptionSchema
42
+ } from "./chunk-H4DEVMTO.js";
43
+ import {
44
+ AIRJAM_CONTROL_CHANNEL,
45
+ AIRJAM_LEASED_CONTROL_REQUEST,
46
+ parseAirJamSignal,
47
+ presentationDocumentSchema,
48
+ presentationRequestSchema,
49
+ roomCodeSchema
50
+ } from "./chunk-24NZZOIO.js";
51
+
52
+ // src/core/input.ts
53
+ import { z } from "zod";
54
+ var button = (mode) => ({ kind: "button", mode });
55
+ var axis = () => ({ kind: "axis" });
56
+ var stick = (options = {}) => ({ kind: "stick", keepDirection: options.keepDirection ?? false });
57
+ var defineAirJamInput = (controls) => Object.freeze(
58
+ Object.fromEntries(
59
+ Object.entries(controls).map(([name, spec]) => [
60
+ name,
61
+ Object.freeze({ ...spec, name })
62
+ ])
63
+ )
64
+ );
65
+ var unit = z.number().min(-1).max(1);
66
+ var vectorSchema = z.object({ x: unit, y: unit }).strict();
67
+ var buttonStateSchema = z.object({ down: z.boolean(), presses: z.number().int().nonnegative() }).strict();
68
+ var describeControl = (control) => {
69
+ if (control.kind === "button")
70
+ return control.mode === "held" ? "Button: true while held down." : "Button: set true to press; set false and true again to press again.";
71
+ if (control.kind === "axis") return "Axis from -1 to 1.";
72
+ return "Stick with x and y from -1 to 1; y is down, like screen space.";
73
+ };
74
+ var createInputStateSchema = (input) => z.object(
75
+ Object.fromEntries(
76
+ Object.values(input).map((control) => [
77
+ control.name,
78
+ (control.kind === "button" ? buttonStateSchema : control.kind === "axis" ? unit : vectorSchema).optional()
79
+ ])
80
+ )
81
+ ).strict();
82
+ var createAgentInputSchema = (input) => z.object(
83
+ Object.fromEntries(
84
+ Object.values(input).map((control) => [
85
+ control.name,
86
+ (control.kind === "button" ? z.boolean() : control.kind === "axis" ? unit : vectorSchema).describe(describeControl(control)).optional()
87
+ ])
88
+ )
89
+ ).strict();
90
+ var neutralState = (control) => control.kind === "button" ? { down: false, presses: 0 } : control.kind === "axis" ? 0 : { x: 0, y: 0 };
91
+ var completeInputState = (input, state) => Object.fromEntries(
92
+ Object.values(input).map((control) => [
93
+ control.name,
94
+ state[control.name] ?? neutralState(control)
95
+ ])
96
+ );
97
+ var agentValuesToInputState = (previous, values) => Object.fromEntries(
98
+ Object.entries(values).map(([name, value]) => {
99
+ if (typeof value !== "boolean") return [name, value];
100
+ const before = previous?.[name];
101
+ const presses = before?.presses ?? 0;
102
+ return [
103
+ name,
104
+ {
105
+ down: value,
106
+ presses: value && !before?.down ? presses + 1 : presses
107
+ }
108
+ ];
109
+ })
110
+ );
111
+ var neutralInputValues = (input) => Object.fromEntries(
112
+ Object.values(input).map((control) => [
113
+ control.name,
114
+ control.kind === "button" ? false : control.kind === "axis" ? 0 : { x: 0, y: 0 }
115
+ ])
116
+ );
117
+ var airJamInputDescriptionSchema = z.record(
118
+ z.string(),
119
+ z.discriminatedUnion("kind", [
120
+ z.object({
121
+ kind: z.literal("button"),
122
+ name: z.string(),
123
+ mode: z.enum(["held", "pressed"])
124
+ }).strict(),
125
+ z.object({ kind: z.literal("axis"), name: z.string() }).strict(),
126
+ z.object({
127
+ kind: z.literal("stick"),
128
+ name: z.string(),
129
+ keepDirection: z.boolean()
130
+ }).strict()
131
+ ])
132
+ );
133
+
134
+ // src/core/controller-input.ts
135
+ var roundUnit = (value) => Math.round(Math.max(-1, Math.min(1, value)) * 100) / 100 || 0;
136
+ var ControllerInput = class {
137
+ constructor(input, transport) {
138
+ this.input = input;
139
+ this.transport = transport;
140
+ this.state = completeInputState(input, {});
141
+ }
142
+ state;
143
+ axisHolds = /* @__PURE__ */ new Map();
144
+ buttonHolds = /* @__PURE__ */ new Map();
145
+ listeners = /* @__PURE__ */ new Set();
146
+ pending = false;
147
+ /** Whether a button is down. */
148
+ isDown(name) {
149
+ return this.state[name].down;
150
+ }
151
+ value(name) {
152
+ return this.state[name];
153
+ }
154
+ /** Puts a button down until the returned release is called; each call is one press. */
155
+ press(name) {
156
+ this.assertKind(name, "button");
157
+ const holds = (this.buttonHolds.get(name) ?? 0) + 1;
158
+ this.buttonHolds.set(name, holds);
159
+ const { presses } = this.state[name];
160
+ this.update(name, { down: true, presses: presses + 1 });
161
+ let released = false;
162
+ return () => {
163
+ if (released) return;
164
+ released = true;
165
+ const remaining = (this.buttonHolds.get(name) ?? 1) - 1;
166
+ this.buttonHolds.set(name, remaining);
167
+ if (remaining > 0) return;
168
+ const current = this.state[name];
169
+ this.update(name, { down: false, presses: current.presses });
170
+ };
171
+ }
172
+ /**
173
+ * Holds an axis at `value` until the returned release is called. With
174
+ * several holds, the latest one wins, so pressing down while up is held
175
+ * moves down and releasing it moves up again.
176
+ */
177
+ hold(name, value) {
178
+ this.assertKind(name, "axis");
179
+ const hold = { value: roundUnit(value) };
180
+ const holds = [...this.axisHolds.get(name) ?? [], hold];
181
+ this.axisHolds.set(name, holds);
182
+ this.update(name, hold.value);
183
+ return () => {
184
+ const remaining = (this.axisHolds.get(name) ?? []).filter(
185
+ (candidate) => candidate !== hold
186
+ );
187
+ this.axisHolds.set(name, remaining);
188
+ this.update(name, remaining.at(-1)?.value ?? 0);
189
+ };
190
+ }
191
+ /** Sets an axis or a stick. */
192
+ set(name, value) {
193
+ if (typeof value === "number") {
194
+ this.assertKind(name, "axis");
195
+ this.update(name, roundUnit(value));
196
+ return;
197
+ }
198
+ this.assertKind(name, "stick");
199
+ this.update(name, { x: roundUnit(value.x), y: roundUnit(value.y) });
200
+ }
201
+ /** Releases every control, such as when the page loses focus. */
202
+ releaseAll() {
203
+ this.axisHolds.clear();
204
+ this.buttonHolds.clear();
205
+ const released = Object.fromEntries(
206
+ Object.entries(this.state).map(([name, value]) => [
207
+ name,
208
+ typeof value === "object" && "down" in value ? { down: false, presses: value.presses } : typeof value === "number" ? 0 : { x: 0, y: 0 }
209
+ ])
210
+ );
211
+ if (JSON.stringify(released) === JSON.stringify(this.state)) return;
212
+ this.state = released;
213
+ this.changed();
214
+ }
215
+ /** Sends the current state now, such as after joining the room. */
216
+ flush() {
217
+ this.pending = false;
218
+ this.transport.send(this.state);
219
+ }
220
+ subscribe(listener) {
221
+ this.listeners.add(listener);
222
+ return () => this.listeners.delete(listener);
223
+ }
224
+ update(name, value) {
225
+ if (JSON.stringify(this.state[name]) === JSON.stringify(value)) return;
226
+ this.state = { ...this.state, [name]: value };
227
+ this.changed();
228
+ }
229
+ changed() {
230
+ for (const listener of this.listeners) listener();
231
+ if (this.pending) return;
232
+ this.pending = true;
233
+ this.transport.requestFrame(() => {
234
+ if (this.pending) this.flush();
235
+ });
236
+ }
237
+ assertKind(name, kind) {
238
+ if (this.input[name]?.kind !== kind)
239
+ throw new Error(`"${name}" is not a declared ${kind} control.`);
240
+ }
241
+ };
242
+
243
+ // src/core/room-action-ack.ts
244
+ var awaitRoomConfirmation = ({
245
+ follow,
246
+ confirmed,
247
+ lost,
248
+ unconfirmed
249
+ }) => new Promise((resolve) => {
250
+ let settled = false;
251
+ let stop = null;
252
+ const check = () => {
253
+ if (settled) return;
254
+ const ok = confirmed();
255
+ if (!ok && !lost()) return;
256
+ settled = true;
257
+ stop?.();
258
+ resolve(ok ? { ok: true } : { ok: false, message: unconfirmed });
259
+ };
260
+ stop = follow(check);
261
+ if (settled) stop();
262
+ });
263
+
264
+ // src/core/controller-runtime.ts
265
+ var resolveControllerJoinSource = ({
266
+ embeddedRoomId,
267
+ optionRoomId,
268
+ urlRoomId
269
+ }) => {
270
+ if (embeddedRoomId) return "embedded";
271
+ if (optionRoomId) return "options";
272
+ if (urlRoomId) return "url";
273
+ return "unknown";
274
+ };
275
+ var HAPTIC_PATTERNS = {
276
+ light: 10,
277
+ medium: 30,
278
+ heavy: [50, 20, 50],
279
+ success: [10, 30, 10],
280
+ failure: [50, 50, 50, 50]
281
+ };
282
+ var KEEPS_BINDING = /* @__PURE__ */ new Set(["owner", "restarting", "replaced"]);
283
+ var ControllerRuntime = class {
284
+ store;
285
+ /** The room this controller joins, or null when none was given. */
286
+ roomId;
287
+ /** This player's controls; null when the game declares none. */
288
+ input;
289
+ environment;
290
+ stores;
291
+ declaredInput;
292
+ joinSource;
293
+ nickname = "";
294
+ avatarId = "";
295
+ currentSession = null;
296
+ running = false;
297
+ constructor(dependencies, identity = {}) {
298
+ const environment = dependencies.environment;
299
+ this.store = dependencies.store;
300
+ this.environment = environment;
301
+ this.stores = dependencies.stores;
302
+ this.declaredInput = dependencies.input;
303
+ const embedded = environment.embedded;
304
+ this.joinSource = resolveControllerJoinSource({
305
+ embeddedRoomId: embedded?.roomId,
306
+ optionRoomId: identity.roomId ?? null,
307
+ urlRoomId: environment.requestedRoomId
308
+ });
309
+ const code = embedded?.roomId ?? identity.roomId ?? environment.requestedRoomId;
310
+ const parsed = code ? roomCodeSchema.safeParse(code.toUpperCase()) : null;
311
+ this.roomId = parsed?.success ? parsed.data : null;
312
+ this.input = dependencies.input ? new ControllerInput(dependencies.input, {
313
+ send: (state) => this.currentSession?.sendInput(state),
314
+ requestFrame: (callback) => environment.requestFrame(callback)
315
+ }) : null;
316
+ }
317
+ /** Whether an embedding shell holds this phone's seat. */
318
+ get isEmbedded() {
319
+ return this.environment.embedded !== null;
320
+ }
321
+ /** The seat's session while the runtime runs. */
322
+ get session() {
323
+ return this.currentSession;
324
+ }
325
+ /** Joins the seat and keeps it until the returned stop is called. */
326
+ start() {
327
+ if (this.running) throw new Error("Controller runtime is already running.");
328
+ this.running = true;
329
+ const roomId = this.roomId;
330
+ const state = this.store.getState();
331
+ state.setMode(this.environment.runMode);
332
+ state.setRole("controller");
333
+ state.setRoomId(roomId);
334
+ state.setError(void 0);
335
+ this.updateDevLogContext();
336
+ if (!roomId) {
337
+ state.setStatus("idle");
338
+ return () => {
339
+ this.running = false;
340
+ };
341
+ }
342
+ state.setStatus("connecting");
343
+ const binding = this.environment.readBinding(roomId);
344
+ const key = binding?.key ?? this.environment.createKey();
345
+ if (!binding) this.environment.writeBinding(roomId, { key });
346
+ const profile = this.joinProfile();
347
+ this.emitRuntimeEvent({
348
+ event: AIRJAM_DEV_LOG_EVENTS.runtime.roomStatus,
349
+ message: binding?.instance ? "Controller resuming its seat" : "Controller joining",
350
+ roomId,
351
+ data: { joinSource: this.joinSource, resume: Boolean(binding?.instance) }
352
+ });
353
+ const session = this.environment.joinRoom({
354
+ key,
355
+ code: roomId,
356
+ kind: this.environment.seatKind,
357
+ ...binding?.instance ? { instance: binding.instance } : {},
358
+ ...profile ? { profile } : {},
359
+ ...this.declaredInput ? { input: this.declaredInput } : {}
360
+ });
361
+ this.currentSession = session;
362
+ const presentation = this.environment.presentationChannel;
363
+ const applyPresentation = (document) => {
364
+ const parsed = presentationDocumentSchema.safeParse(document);
365
+ if (!parsed.success) return;
366
+ const current = this.store.getState();
367
+ if (current.runtimeState !== parsed.data.runtimeState)
368
+ this.emitRuntimeEvent({
369
+ event: AIRJAM_DEV_LOG_EVENTS.runtime.phaseTransition,
370
+ message: "Controller runtime phase transition",
371
+ roomId,
372
+ data: {
373
+ from: current.runtimeState,
374
+ to: parsed.data.runtimeState
375
+ }
376
+ });
377
+ current.setRuntimeState(parsed.data.runtimeState);
378
+ current.setControllerOrientation(parsed.data.orientation);
379
+ };
380
+ const releases = [
381
+ session.on("status", (status) => this.followStatus(roomId, key, status)),
382
+ session.on("seats", (seats) => this.store.getState().setPlayers(seats)),
383
+ session.on("state", ({ channel, document }) => {
384
+ if (channel === presentation) applyPresentation(document);
385
+ }),
386
+ session.on("signal", (signal) => {
387
+ const parsed = parseAirJamSignal(signal);
388
+ if (parsed?.kind === "haptic") this.vibrate(parsed.payload);
389
+ })
390
+ ];
391
+ const storeRoom = this.storeRoom(session);
392
+ const detachStores = this.stores.map(
393
+ (store) => store.attach({
394
+ room: storeRoom,
395
+ connection: this.store,
396
+ defaultStoreDomain: this.environment.defaultStoreDomain,
397
+ controlTarget: null,
398
+ now: () => performance.now()
399
+ })
400
+ );
401
+ return () => {
402
+ for (const release of releases) release();
403
+ for (const detach of detachStores) detach();
404
+ session.close();
405
+ this.currentSession = null;
406
+ this.environment.setDevLogContext({
407
+ role: void 0,
408
+ roomId: void 0,
409
+ controllerId: void 0
410
+ });
411
+ this.running = false;
412
+ };
413
+ }
414
+ setNickname = (value) => {
415
+ this.nickname = value;
416
+ };
417
+ setAvatarId = (value) => {
418
+ this.avatarId = value;
419
+ };
420
+ /**
421
+ * Gives the seat up for good; settles once the room confirms it, or at
422
+ * once when the room had already let this phone go, as after a refusal.
423
+ */
424
+ leave = () => {
425
+ const roomId = this.roomId;
426
+ const session = this.currentSession;
427
+ if (!session || !roomId)
428
+ return Promise.resolve({ ok: false, message: "Not in a room." });
429
+ this.environment.clearBinding(roomId);
430
+ const confirmation = session.status.phase === "closed" ? Promise.resolve({
431
+ ok: false,
432
+ message: "The room had already let this phone go."
433
+ }) : awaitRoomConfirmation({
434
+ follow: (changed) => session.on("status", changed),
435
+ confirmed: () => session.status.phase === "closed" && session.status.reason === "left",
436
+ lost: () => session.status.phase === "closed",
437
+ unconfirmed: "The room did not confirm the seat was given up."
438
+ });
439
+ session.leave();
440
+ const state = this.store.getState();
441
+ state.setControllerId(null);
442
+ state.setStatus("disconnected");
443
+ state.resetRuntimeState();
444
+ return confirmation;
445
+ };
446
+ /**
447
+ * Changes this player's name or avatar; settles with the seat as the room
448
+ * stored it, from the room's next word on this seat (the room may show a
449
+ * name of its own over the one asked for), or as unconfirmed when the link
450
+ * drops first.
451
+ */
452
+ updatePlayerProfile = (patch) => {
453
+ const parsed = playerProfilePatchSchema.safeParse(patch);
454
+ const session = this.currentSession;
455
+ if (!parsed.success)
456
+ return Promise.resolve({ ok: false, message: parsed.error.message });
457
+ if (parsed.data.label === void 0 && parsed.data.avatarId === void 0)
458
+ return Promise.resolve({ ok: false, message: "Nothing to change." });
459
+ if (!session || session.status.phase !== "open")
460
+ return Promise.resolve({
461
+ ok: false,
462
+ message: "Not connected to a room."
463
+ });
464
+ const ownSeat = () => session.seats.find((seat) => seat.id === session.seat);
465
+ const before = ownSeat();
466
+ return new Promise((resolve) => {
467
+ const releases = [
468
+ session.on("seats", () => {
469
+ const after = ownSeat();
470
+ if (!after || after === before) return;
471
+ settle({
472
+ ok: true,
473
+ profile: {
474
+ label: after.label,
475
+ ...after.avatarId === void 0 ? {} : { avatarId: after.avatarId }
476
+ }
477
+ });
478
+ }),
479
+ session.on("status", (status) => {
480
+ if (status.phase !== "open")
481
+ settle({
482
+ ok: false,
483
+ message: "The room did not confirm the change."
484
+ });
485
+ })
486
+ ];
487
+ const settle = (ack) => {
488
+ for (const release of releases) release();
489
+ resolve(ack);
490
+ };
491
+ session.setProfile(parsed.data);
492
+ });
493
+ };
494
+ /** Asks the host to pause or resume play. */
495
+ sendSystemCommand = (command) => {
496
+ void this.currentSession?.request(
497
+ this.environment.presentationChannel,
498
+ command
499
+ );
500
+ };
501
+ /** The view replicated stores have of this phone's room. */
502
+ storeRoom(session) {
503
+ return {
504
+ role: "controller",
505
+ document: (channel) => session.channel(channel),
506
+ onDocument: (channel, listener) => session.on("state", (state) => {
507
+ if (state.channel === channel) listener(state.document);
508
+ }),
509
+ request: (channel, name, payload) => session.request(channel, name, payload)
510
+ };
511
+ }
512
+ joinProfile() {
513
+ const embedded = this.environment.embedded?.playerProfile;
514
+ const label = embedded?.label || this.nickname;
515
+ const avatarId = embedded?.avatarId || this.avatarId;
516
+ const localSeatLabel = this.environment.localSeatLabel;
517
+ if (!label && !avatarId && !localSeatLabel) return null;
518
+ return {
519
+ ...label ? { label: label.slice(0, 24) } : {},
520
+ ...avatarId ? { avatarId } : {},
521
+ ...localSeatLabel ? { localSeatLabel } : {}
522
+ };
523
+ }
524
+ followStatus(roomId, key, status) {
525
+ const state = this.store.getState();
526
+ const session = this.currentSession;
527
+ this.emitRuntimeEvent({
528
+ event: AIRJAM_DEV_LOG_EVENTS.runtime.roomStatus,
529
+ message: `Controller room ${status.phase}`,
530
+ roomId,
531
+ data: { ...status }
532
+ });
533
+ switch (status.phase) {
534
+ case "connecting":
535
+ case "waiting":
536
+ state.setStatus("connecting");
537
+ return;
538
+ case "reconnecting":
539
+ state.setStatus("reconnecting");
540
+ return;
541
+ case "open": {
542
+ const instance = session?.instance;
543
+ const seat = session?.seat ?? null;
544
+ if (instance) this.environment.writeBinding(roomId, { key, instance });
545
+ state.setControllerId(seat);
546
+ state.setError(void 0);
547
+ state.setStatus("connected");
548
+ this.updateDevLogContext();
549
+ return;
550
+ }
551
+ case "closed":
552
+ if (!KEEPS_BINDING.has(status.reason))
553
+ this.environment.clearBinding(roomId);
554
+ state.setStatus("disconnected");
555
+ state.resetRuntimeState();
556
+ if (status.reason !== "owner" && status.reason !== "left")
557
+ state.setError(`The room closed the connection: ${status.reason}.`);
558
+ return;
559
+ }
560
+ }
561
+ vibrate(payload) {
562
+ if (payload.pattern === "custom") {
563
+ const sequence = payload.sequence;
564
+ if (Array.isArray(sequence) || typeof sequence === "number")
565
+ this.environment.vibrate(sequence);
566
+ return;
567
+ }
568
+ const pattern = HAPTIC_PATTERNS[payload.pattern];
569
+ this.environment.vibrate(
570
+ typeof pattern === "number" ? pattern : [...pattern]
571
+ );
572
+ }
573
+ updateDevLogContext() {
574
+ this.environment.setDevLogContext({
575
+ role: "controller",
576
+ traceId: void 0,
577
+ roomId: this.roomId ?? void 0,
578
+ controllerId: this.store.getState().controllerId ?? void 0
579
+ });
580
+ }
581
+ emitRuntimeEvent({
582
+ level = "info",
583
+ ...detail
584
+ }) {
585
+ this.environment.emitDevEvent({
586
+ ...detail,
587
+ level,
588
+ role: "controller",
589
+ controllerId: this.store.getState().controllerId ?? void 0
590
+ });
591
+ }
592
+ };
593
+
594
+ // src/core/simulation.ts
595
+ var defineAirJamSimulation = (simulation) => simulation;
596
+ var createSeededRandom = (seed) => {
597
+ let state = seed >>> 0;
598
+ return () => {
599
+ state = state + 1831565813 >>> 0;
600
+ let value = state;
601
+ value = Math.imul(value ^ value >>> 15, value | 1);
602
+ value ^= value + Math.imul(value ^ value >>> 7, value | 61);
603
+ return ((value ^ value >>> 14) >>> 0) / 4294967296;
604
+ };
605
+ };
606
+ var MAX_FRAME_DELTA_MS = 250;
607
+ var MAX_STEPS_PER_FRAME = 5;
608
+ var SimulationClock = class {
609
+ constructor(simulation, room, seed) {
610
+ this.simulation = simulation;
611
+ this.room = room;
612
+ this.seed = seed >>> 0;
613
+ this.random = createSeededRandom(this.seed);
614
+ this.sim = simulation.create({
615
+ random: this.random,
616
+ settings: this.settings
617
+ });
618
+ }
619
+ seed;
620
+ sim;
621
+ pace = { frames: 0, wallMs: 0, simulatedMs: 0 };
622
+ tick = 0;
623
+ drawingDeferred = 0;
624
+ inStep = false;
625
+ accumulatorMs = 0;
626
+ lastFrameAt = null;
627
+ random;
628
+ eventListeners = /* @__PURE__ */ new Set();
629
+ frameListeners = /* @__PURE__ */ new Set();
630
+ get settings() {
631
+ return this.room.settings?.() ?? {};
632
+ }
633
+ get ticks() {
634
+ return this.tick;
635
+ }
636
+ /** Whether a step is running, so what it causes is told apart from what reaches it. */
637
+ get stepping() {
638
+ return this.inStep;
639
+ }
640
+ /** Milliseconds of game time per step. */
641
+ get stepMs() {
642
+ return this.simulation.stepMs;
643
+ }
644
+ /** Game time in milliseconds: the steps taken so far. */
645
+ get timeMs() {
646
+ return this.tick * this.simulation.stepMs;
647
+ }
648
+ /**
649
+ * Runs as many whole steps as `ms` of game time holds, without a cap. Time
650
+ * that passes while the room is paused is not game time.
651
+ */
652
+ advance(ms) {
653
+ this.accumulatorMs += ms;
654
+ this.runSteps(Number.POSITIVE_INFINITY);
655
+ this.notifyFrame();
656
+ }
657
+ /**
658
+ * Advances by real elapsed time, dropping steps a slow device cannot run.
659
+ * Frames keep drawing while the room is paused, and resuming does not count
660
+ * the paused gap.
661
+ */
662
+ frame(now) {
663
+ if (!this.playing) {
664
+ this.lastFrameAt = null;
665
+ this.accumulatorMs = 0;
666
+ this.notifyFrame();
667
+ return;
668
+ }
669
+ const elapsedMs = this.lastFrameAt === null ? 0 : Math.max(0, now - this.lastFrameAt);
670
+ this.lastFrameAt = now;
671
+ const stepMs = this.simulation.stepMs;
672
+ this.accumulatorMs += Math.min(
673
+ elapsedMs,
674
+ Math.max(stepMs, MAX_FRAME_DELTA_MS)
675
+ );
676
+ const steps = this.runSteps(MAX_STEPS_PER_FRAME);
677
+ if (steps === MAX_STEPS_PER_FRAME) this.accumulatorMs = 0;
678
+ this.pace.frames += 1;
679
+ this.pace.wallMs += elapsedMs;
680
+ this.pace.simulatedMs += steps * stepMs;
681
+ this.notifyFrame();
682
+ }
683
+ /** Forgets the last frame time, so a resumed loop does not count the gap. */
684
+ rest() {
685
+ this.lastFrameAt = null;
686
+ }
687
+ onEvent(listener) {
688
+ this.eventListeners.add(listener);
689
+ return () => this.eventListeners.delete(listener);
690
+ }
691
+ onFrame(listener) {
692
+ this.frameListeners.add(listener);
693
+ return () => this.frameListeners.delete(listener);
694
+ }
695
+ get playing() {
696
+ return this.room.runtimeState() === "playing";
697
+ }
698
+ runSteps(maxSteps) {
699
+ let steps = 0;
700
+ while (this.playing && this.accumulatorMs >= this.simulation.stepMs && steps < maxSteps) {
701
+ this.accumulatorMs -= this.simulation.stepMs;
702
+ this.step();
703
+ steps += 1;
704
+ }
705
+ if (!this.playing) this.accumulatorMs = 0;
706
+ return steps;
707
+ }
708
+ step() {
709
+ this.room.beginStep(this.tick + 1);
710
+ this.tick += 1;
711
+ const stepMs = this.simulation.stepMs;
712
+ this.inStep = true;
713
+ try {
714
+ this.simulation.step(this.sim, {
715
+ tick: this.tick,
716
+ settings: this.settings,
717
+ stepMs,
718
+ dtSeconds: stepMs / 1e3,
719
+ random: this.random,
720
+ input: this.room.input,
721
+ players: this.room.players(),
722
+ reconnectingPlayerIds: this.room.reconnectingPlayerIds(),
723
+ emit: (event) => {
724
+ for (const listener of this.eventListeners) listener(event);
725
+ }
726
+ });
727
+ } finally {
728
+ this.inStep = false;
729
+ }
730
+ }
731
+ /** Batch replay steps without drawing intermediate states. */
732
+ batch(advance) {
733
+ this.drawingDeferred += 1;
734
+ try {
735
+ advance();
736
+ } finally {
737
+ this.drawingDeferred -= 1;
738
+ this.notifyFrame();
739
+ }
740
+ }
741
+ /** The current drawing position; reading it never advances the game. */
742
+ readFrame() {
743
+ return {
744
+ sim: this.sim,
745
+ tick: this.tick,
746
+ alpha: Math.min(1, this.accumulatorMs / this.simulation.stepMs)
747
+ };
748
+ }
749
+ notifyFrame() {
750
+ if (this.drawingDeferred || this.frameListeners.size === 0) return;
751
+ const frame = this.readFrame();
752
+ for (const listener of this.frameListeners) listener(frame);
753
+ }
754
+ };
755
+
756
+ // src/runtime/host-clip-recorder.ts
757
+ var idleSince = (recording) => recording.stopped === null ? null : Math.max(recording.stopped, recording.lastRead);
758
+ var HostClipRecorder = class {
759
+ constructor(source) {
760
+ this.source = source;
761
+ }
762
+ recordings = /* @__PURE__ */ new Map();
763
+ stopTimer = null;
764
+ scheduledIntervalMs = 0;
765
+ capturing = false;
766
+ generation = 0;
767
+ start(clipId, identity, frameIntervalMs = CLIP_FRAME_INTERVAL_MS, delivery = "pages") {
768
+ if (!Number.isInteger(frameIntervalMs) || frameIntervalMs <= 0)
769
+ throw new Error("Clip frame interval must be a positive integer.");
770
+ frameIntervalMs = Math.max(CLIP_MIN_FRAME_INTERVAL_MS, frameIntervalMs);
771
+ if (!this.source.capture())
772
+ throw new Error("clip_unsupported: The game has no capture surface.");
773
+ this.sweep();
774
+ const previous = this.recordings.get(clipId);
775
+ if (previous) return { clipId, startedAt: previous.startedAt };
776
+ if (this.recordings.size >= CLIP_MAX_RECORDINGS) {
777
+ let oldest;
778
+ for (const recording2 of this.recordings.values()) {
779
+ const since = idleSince(recording2);
780
+ if (since !== null && recording2.delivered && (!oldest || since < idleSince(oldest)))
781
+ oldest = recording2;
782
+ }
783
+ if (!oldest)
784
+ throw new Error(
785
+ "clip_busy: Four clips are already recording or being delivered in this runtime."
786
+ );
787
+ oldest.video?.dispose();
788
+ this.recordings.delete(oldest.clipId);
789
+ }
790
+ const now = this.source.now();
791
+ const recording = {
792
+ identity,
793
+ clipId,
794
+ startedAt: new Date(this.source.wallNow?.() ?? Date.now()).toISOString(),
795
+ start: now,
796
+ frameIntervalMs,
797
+ nextCaptureAt: now + frameIntervalMs,
798
+ stopped: null,
799
+ delivered: false,
800
+ lastRead: now,
801
+ frames: [],
802
+ bytes: 0,
803
+ nextIndex: 0,
804
+ droppedFrames: 0,
805
+ skippedFrames: 0,
806
+ attempts: 0,
807
+ errors: 0
808
+ };
809
+ if (delivery === "video") {
810
+ const startVideo = this.source.capture()?.startVideo;
811
+ if (!startVideo)
812
+ throw new Error("clip_unsupported: Native recording is unavailable.");
813
+ recording.video = startVideo(frameIntervalMs);
814
+ }
815
+ this.recordings.set(clipId, recording);
816
+ this.schedule();
817
+ return { clipId, startedAt: recording.startedAt };
818
+ }
819
+ schedule() {
820
+ const intervalMs = Math.min(
821
+ ...[...this.recordings.values()].filter((recording) => recording.stopped === null && !recording.video).map((recording) => recording.frameIntervalMs)
822
+ );
823
+ if (intervalMs === this.scheduledIntervalMs) return;
824
+ this.stopTimer?.();
825
+ this.stopTimer = null;
826
+ this.scheduledIntervalMs = intervalMs;
827
+ if (!Number.isFinite(intervalMs)) return;
828
+ const schedule = this.source.schedule ?? ((tick, ms) => {
829
+ const timer = setInterval(tick, ms);
830
+ return () => clearInterval(timer);
831
+ });
832
+ this.stopTimer = schedule(() => {
833
+ void this.sample();
834
+ }, intervalMs);
835
+ }
836
+ trim(recording, now) {
837
+ while (recording.frames.length && (recording.frames[0].atMs < now - recording.start - CLIP_MAX_DURATION_MS || recording.frames.length > Math.ceil(CLIP_MAX_DURATION_MS / recording.frameIntervalMs) || recording.bytes > CLIP_MAX_BYTES)) {
838
+ recording.bytes -= clipImageBytes(recording.frames.shift().data);
839
+ recording.droppedFrames++;
840
+ }
841
+ }
842
+ freeze(recording, stopped) {
843
+ if (recording.stopped !== null) return;
844
+ recording.stopped = stopped;
845
+ this.trim(recording, stopped);
846
+ }
847
+ sweep() {
848
+ const now = this.source.now();
849
+ for (const [id, recording] of this.recordings) {
850
+ if (recording.stopped === null && now - recording.start >= CLIP_RECORDING_LIFETIME_MS) {
851
+ this.freeze(recording, recording.start + CLIP_RECORDING_LIFETIME_MS);
852
+ void recording.video?.stop().catch((error) => this.source.onCaptureError?.(error));
853
+ }
854
+ const since = idleSince(recording);
855
+ if (since !== null && now - since >= CLIP_STOPPED_RELEASE_MS) {
856
+ recording.video?.dispose();
857
+ this.recordings.delete(id);
858
+ }
859
+ }
860
+ this.schedule();
861
+ }
862
+ async sample() {
863
+ this.sweep();
864
+ if (this.capturing) return;
865
+ const now = this.source.now();
866
+ const active = [...this.recordings.values()].filter(
867
+ (recording) => recording.stopped === null && !recording.video && (recording.frameIntervalMs === this.scheduledIntervalMs || now >= recording.nextCaptureAt)
868
+ );
869
+ if (!active.length) return;
870
+ const generation = this.generation;
871
+ for (const recording of active) {
872
+ recording.nextCaptureAt += (Math.floor(
873
+ (now - recording.nextCaptureAt) / recording.frameIntervalMs
874
+ ) + 1) * recording.frameIntervalMs;
875
+ this.trim(recording, now);
876
+ }
877
+ const capture = this.source.capture();
878
+ this.capturing = true;
879
+ let image = null;
880
+ let failed = false;
881
+ try {
882
+ image = await capture?.({
883
+ maxEdge: CLIP_FRAME_MAX_EDGE,
884
+ quality: CLIP_FRAME_QUALITY
885
+ }) ?? null;
886
+ } catch (error) {
887
+ failed = true;
888
+ if (active.some((recording) => recording.errors === 0))
889
+ this.source.onCaptureError?.(error);
890
+ } finally {
891
+ if (generation === this.generation) this.capturing = false;
892
+ }
893
+ if (generation !== this.generation) return;
894
+ for (const recording of active) {
895
+ if (this.recordings.get(recording.clipId) !== recording || recording.stopped !== null)
896
+ continue;
897
+ recording.attempts++;
898
+ if (failed) recording.errors++;
899
+ const atMs = now - recording.start;
900
+ const parsed = image && clipFrameSchema.safeParse({
901
+ index: recording.nextIndex,
902
+ atMs,
903
+ width: image.width,
904
+ height: image.height,
905
+ mimeType: image.mimeType,
906
+ data: image.data
907
+ });
908
+ if (!parsed || !parsed.success || clipImageBytes(parsed.data.data) > CLIP_FRAME_MAX_BYTES || atMs <= (recording.frames.at(-1)?.atMs ?? -1)) {
909
+ recording.skippedFrames++;
910
+ continue;
911
+ }
912
+ recording.frames.push(parsed.data);
913
+ recording.nextIndex++;
914
+ recording.bytes += clipImageBytes(parsed.data.data);
915
+ this.trim(recording, this.source.now());
916
+ }
917
+ }
918
+ async stop(clipId) {
919
+ const recording = this.recordings.get(clipId);
920
+ if (!recording) throw new Error("clip_not_found: Recording was released.");
921
+ this.freeze(recording, this.source.now());
922
+ await recording.video?.stop();
923
+ this.schedule();
924
+ }
925
+ read(clipId, stop, fromFrame, fromChunk = 0) {
926
+ this.sweep();
927
+ const recording = this.recordings.get(clipId);
928
+ if (!recording)
929
+ throw new Error(
930
+ "clip_not_found: Recording was released or its runtime was replaced."
931
+ );
932
+ const now = this.source.now();
933
+ recording.lastRead = now;
934
+ if (recording.stopped === null) {
935
+ if (stop) this.freeze(recording, now);
936
+ else this.trim(recording, now);
937
+ }
938
+ const frames = [];
939
+ let chars = 0;
940
+ let nextFrame = null;
941
+ for (const frame of recording.frames) {
942
+ if (frame.index < fromFrame) continue;
943
+ if (chars + frame.data.length > CLIP_PAGE_BASE64_CHARS) {
944
+ nextFrame = frame.index;
945
+ break;
946
+ }
947
+ frames.push(frame);
948
+ chars += frame.data.length;
949
+ }
950
+ const video = recording.video?.page(fromChunk);
951
+ if (recording.stopped !== null && nextFrame === null && (!video || video.nextChunk === null))
952
+ recording.delivered = true;
953
+ const nativeCapture = recording.video?.stats();
954
+ const frameCount = nativeCapture ? null : recording.frames.length;
955
+ return {
956
+ clipId,
957
+ identity: recording.identity,
958
+ startedAt: recording.startedAt,
959
+ state: recording.stopped === null ? "recording" : "stopped",
960
+ frameIntervalMs: recording.frameIntervalMs,
961
+ durationMs: Math.min(
962
+ CLIP_RECORDING_LIFETIME_MS,
963
+ (recording.stopped ?? now) - recording.start
964
+ ),
965
+ frameCount,
966
+ ...video ? { video, nativeCapture } : {},
967
+ droppedFrames: nativeCapture ? null : recording.droppedFrames,
968
+ skippedFrames: nativeCapture ? null : recording.skippedFrames,
969
+ notCaptured: nativeCapture?.drawsMade ?? frameCount ? null : recording.attempts > 0 && recording.errors === recording.attempts ? "capture-failed" : "surface-unavailable",
970
+ frames,
971
+ nextFrame
972
+ };
973
+ }
974
+ dispose() {
975
+ this.generation++;
976
+ this.capturing = false;
977
+ for (const recording of this.recordings.values())
978
+ recording.video?.dispose();
979
+ this.recordings.clear();
980
+ this.stopTimer?.();
981
+ this.stopTimer = null;
982
+ this.scheduledIntervalMs = 0;
983
+ }
984
+ };
985
+
986
+ // src/runtime/host-timeline.ts
987
+ var WINDOW_MS = 5e3;
988
+ var RETENTION_MS = 30 * 6e4;
989
+ var HostTimeline = class {
990
+ startedAt;
991
+ // Only successfully appended recorder entries have a time; the input log bounds this map.
992
+ entryTimes = /* @__PURE__ */ new Map();
993
+ moments = [];
994
+ windows = [];
995
+ momentSequence = 0;
996
+ sampledAt;
997
+ sampled = { frames: 0, wallMs: 0, simulatedMs: 0 };
998
+ constructor(at) {
999
+ this.startedAt = at;
1000
+ this.sampledAt = at;
1001
+ }
1002
+ /** Start the loaded simulation without losing room events received during loading. */
1003
+ start(at) {
1004
+ this.startedAt = at;
1005
+ this.sampledAt = at;
1006
+ }
1007
+ record(entry, at) {
1008
+ this.entryTimes.set(entry, at);
1009
+ }
1010
+ moment(text, tick, at) {
1011
+ if (!text?.trim()) return;
1012
+ this.moments.push({
1013
+ id: `moment:${++this.momentSequence}`,
1014
+ kind: "moment",
1015
+ tick,
1016
+ at,
1017
+ text: text.trim().slice(0, 240)
1018
+ });
1019
+ if (this.moments.length > 200) this.moments.shift();
1020
+ }
1021
+ frame(at, pace) {
1022
+ if (at - this.sampledAt < WINDOW_MS) return;
1023
+ const wallMs = pace.wallMs - this.sampled.wallMs;
1024
+ if (wallMs > 0)
1025
+ this.windows.push({
1026
+ at,
1027
+ fps: (pace.frames - this.sampled.frames) * 1e3 / wallMs,
1028
+ speed: (pace.simulatedMs - this.sampled.simulatedMs) / wallMs
1029
+ });
1030
+ this.sampled = { ...pace };
1031
+ this.sampledAt = at;
1032
+ while (this.windows.length && (this.windows[0].at < at - RETENTION_MS || this.windows.length > 360))
1033
+ this.windows.shift();
1034
+ }
1035
+ read(log, at) {
1036
+ const entries = [];
1037
+ const seats = /* @__PURE__ */ new Map();
1038
+ let state = "playing";
1039
+ let settings = { ...log.settings };
1040
+ for (const [index, entry] of log.entries.entries()) {
1041
+ const { tick, event, payload } = entry;
1042
+ const recordedAt = this.entryTimes.get(index);
1043
+ if (recordedAt === void 0) continue;
1044
+ const base = { id: `input:${index}`, tick, at: recordedAt };
1045
+ if (event === "seat") {
1046
+ const seat = payload.seat;
1047
+ const known = seats.get(seat.id);
1048
+ seats.set(seat.id, { name: seat.label, connected: seat.connected });
1049
+ if (!known)
1050
+ entries.push({
1051
+ ...base,
1052
+ kind: "join",
1053
+ controllerId: seat.id,
1054
+ name: seat.label
1055
+ });
1056
+ else if (known.connected && !seat.connected)
1057
+ entries.push({
1058
+ ...base,
1059
+ kind: "drop",
1060
+ controllerId: seat.id,
1061
+ name: seat.label
1062
+ });
1063
+ if (known && known.name !== seat.label)
1064
+ entries.push({
1065
+ ...base,
1066
+ kind: "name",
1067
+ controllerId: seat.id,
1068
+ name: seat.label,
1069
+ previousName: known.name
1070
+ });
1071
+ } else if (event === "left") {
1072
+ const controllerId = payload.seat;
1073
+ entries.push({
1074
+ ...base,
1075
+ kind: "leave",
1076
+ controllerId,
1077
+ name: seats.get(controllerId)?.name
1078
+ });
1079
+ seats.delete(controllerId);
1080
+ } else if (event === "runtime") {
1081
+ const runtimeState = payload.runtimeState;
1082
+ if ((runtimeState === "paused" || runtimeState === "playing") && state !== runtimeState)
1083
+ entries.push({ ...base, kind: "state", state: runtimeState });
1084
+ state = runtimeState;
1085
+ } else if (event === "settings") {
1086
+ const values = payload.patch;
1087
+ const changed = Object.fromEntries(
1088
+ Object.entries(values).filter(
1089
+ ([key, value]) => settings[key] !== value
1090
+ )
1091
+ );
1092
+ if (Object.keys(changed).length)
1093
+ entries.push({
1094
+ ...base,
1095
+ kind: "settings",
1096
+ values: changed,
1097
+ previousValues: Object.fromEntries(
1098
+ Object.keys(changed).filter((key) => key in settings).map((key) => [key, settings[key]])
1099
+ )
1100
+ });
1101
+ settings = { ...settings, ...values };
1102
+ }
1103
+ }
1104
+ return {
1105
+ startedAt: this.startedAt,
1106
+ stepMs: log.stepMs,
1107
+ entries: [...entries, ...this.moments].sort(
1108
+ (a, b) => a.at - b.at || a.tick - b.tick
1109
+ ),
1110
+ pace: this.windows.filter((window) => window.at >= at - RETENTION_MS)
1111
+ };
1112
+ }
1113
+ };
1114
+
1115
+ // src/core/host-input.ts
1116
+ import { z as z2 } from "zod";
1117
+ var HostInput = class {
1118
+ constructor(declaration, now) {
1119
+ this.declaration = declaration;
1120
+ this.now = now;
1121
+ this.stateSchema = createInputStateSchema(declaration);
1122
+ this.agentSchema = createAgentInputSchema(declaration);
1123
+ this.neutral = neutralInputValues(declaration);
1124
+ }
1125
+ seats = /* @__PURE__ */ new Map();
1126
+ leases = /* @__PURE__ */ new Map();
1127
+ stateSchema;
1128
+ agentSchema;
1129
+ neutral;
1130
+ inputDescription;
1131
+ /** A phone's controls; ignored while an agent lease owns the seat. */
1132
+ receive(controllerId, state) {
1133
+ if (this.leases.has(controllerId)) return;
1134
+ const parsed = this.stateSchema.safeParse(state);
1135
+ if (!parsed.success) {
1136
+ emitAirJamDiagnostic({
1137
+ code: "AJ_INPUT_INVALID",
1138
+ severity: "warn",
1139
+ message: `Input from controller ${controllerId} does not match the declared controls.`,
1140
+ details: { controllerId, issueCount: parsed.error.issues.length }
1141
+ });
1142
+ return;
1143
+ }
1144
+ this.setState(
1145
+ controllerId,
1146
+ completeInputState(this.declaration, parsed.data)
1147
+ );
1148
+ }
1149
+ /** What the current step reads for a player; released and centred before any input. */
1150
+ read(controllerId) {
1151
+ return this.seats.get(controllerId)?.values ?? this.neutral;
1152
+ }
1153
+ /**
1154
+ * Applies each control's meaning for the next step and returns the seats
1155
+ * whose source state changed since the previous step.
1156
+ */
1157
+ sample() {
1158
+ const now = this.now();
1159
+ const changes = [];
1160
+ for (const [controllerId, lease] of this.leases)
1161
+ if (!lease.released && now >= lease.deadline) {
1162
+ lease.released = true;
1163
+ this.setState(controllerId, completeInputState(this.declaration, {}));
1164
+ }
1165
+ for (const [controllerId, seat] of this.seats) {
1166
+ seat.values = this.applyMeanings(seat);
1167
+ const sampled = JSON.stringify(seat.state);
1168
+ if (sampled === seat.sampled) continue;
1169
+ seat.sampled = sampled;
1170
+ changes.push({ controllerId, input: seat.state });
1171
+ }
1172
+ return changes;
1173
+ }
1174
+ clearInput(controllerId) {
1175
+ this.seats.delete(controllerId);
1176
+ this.leases.delete(controllerId);
1177
+ }
1178
+ get supportsLeasedInput() {
1179
+ return true;
1180
+ }
1181
+ describeInputSchema() {
1182
+ this.inputDescription ??= participantInputSchemaDescriptionSchema.parse({
1183
+ status: "available",
1184
+ // Zod attaches a non-enumerable Standard Schema validator; it is not wire data.
1185
+ schema: structuredClone(
1186
+ z2.toJSONSchema(this.agentSchema, { io: "input" })
1187
+ )
1188
+ });
1189
+ return this.inputDescription;
1190
+ }
1191
+ /** An agent's controls for a seat it leases, held until `ttlMs` passes. */
1192
+ setLeasedInput(controllerId, values, ttlMs) {
1193
+ const parsed = this.agentSchema.safeParse(values);
1194
+ if (!parsed.success) return false;
1195
+ const now = this.now();
1196
+ const lease = this.leases.get(controllerId);
1197
+ const previous = lease && !lease.released && now < lease.deadline ? this.seats.get(controllerId)?.state ?? null : null;
1198
+ this.leases.set(controllerId, { deadline: now + ttlMs, released: false });
1199
+ this.setState(
1200
+ controllerId,
1201
+ completeInputState(
1202
+ this.declaration,
1203
+ agentValuesToInputState(previous, parsed.data)
1204
+ )
1205
+ );
1206
+ return true;
1207
+ }
1208
+ /** A seat whose agent acts without holding input stops taking phone input. */
1209
+ claimLeasedInput(controllerId) {
1210
+ if (!this.leases.has(controllerId)) this.releaseLeasedInput(controllerId);
1211
+ }
1212
+ releaseLeasedInput(controllerId) {
1213
+ this.leases.set(controllerId, { deadline: 0, released: true });
1214
+ this.setState(controllerId, completeInputState(this.declaration, {}));
1215
+ }
1216
+ clearLeasedInputs() {
1217
+ for (const controllerId of this.leases.keys())
1218
+ this.releaseLeasedInput(controllerId);
1219
+ }
1220
+ setState(controllerId, state) {
1221
+ const seat = this.seats.get(controllerId);
1222
+ if (seat) {
1223
+ seat.state = state;
1224
+ return;
1225
+ }
1226
+ this.seats.set(controllerId, {
1227
+ state,
1228
+ consumed: /* @__PURE__ */ new Map(),
1229
+ kept: /* @__PURE__ */ new Map(),
1230
+ values: this.neutral,
1231
+ sampled: null
1232
+ });
1233
+ }
1234
+ applyMeanings(seat) {
1235
+ const values = {};
1236
+ for (const control of Object.values(this.declaration)) {
1237
+ const state = seat.state[control.name];
1238
+ if (control.kind === "button") {
1239
+ const { down, presses } = state;
1240
+ let consumed = seat.consumed.get(control.name) ?? 0;
1241
+ if (presses < consumed) consumed = 0;
1242
+ const pressed = presses > consumed;
1243
+ seat.consumed.set(control.name, pressed ? consumed + 1 : consumed);
1244
+ values[control.name] = control.mode === "pressed" ? pressed : down || pressed;
1245
+ } else if (control.kind === "stick" && control.keepDirection) {
1246
+ const vector = state;
1247
+ if (vector.x !== 0 || vector.y !== 0)
1248
+ seat.kept.set(control.name, vector);
1249
+ values[control.name] = seat.kept.get(control.name) ?? vector;
1250
+ } else values[control.name] = state;
1251
+ }
1252
+ return values;
1253
+ }
1254
+ };
1255
+
1256
+ // src/core/host-runtime.ts
1257
+ var followRoom = (room, changed) => {
1258
+ const releases = [room.on("seats", changed), room.on("status", changed)];
1259
+ return () => {
1260
+ for (const release of releases) release();
1261
+ };
1262
+ };
1263
+ var ROOM_GONE = /* @__PURE__ */ new Set(["not-found", "closed"]);
1264
+ var HostRuntime = class {
1265
+ /**
1266
+ * Settles once the declared simulation is loaded, at once when it needs no
1267
+ * loading, and rejects if loading fails.
1268
+ */
1269
+ ready;
1270
+ store;
1271
+ /** The input lane; null when the game declares no controls. */
1272
+ input;
1273
+ hostSettings;
1274
+ settings;
1275
+ timeline = null;
1276
+ stepAt = 0;
1277
+ recorder;
1278
+ seed;
1279
+ config;
1280
+ orientation;
1281
+ environment;
1282
+ stores;
1283
+ declaresSimulation;
1284
+ simulationDeclaration = null;
1285
+ clock = null;
1286
+ frameFault = null;
1287
+ stopFrames = null;
1288
+ agent;
1289
+ capture = null;
1290
+ clips = new HostClipRecorder({
1291
+ capture: () => this.capture,
1292
+ now: () => this.environment.now(),
1293
+ onCaptureError: (error) => this.emitRuntimeEvent({
1294
+ event: AIRJAM_DEV_LOG_EVENTS.runtime.clipCaptureFailed,
1295
+ code: "clip_capture_failed",
1296
+ level: "error",
1297
+ message: error instanceof Error ? error.message : String(error),
1298
+ roomId: this.roomId ?? void 0
1299
+ })
1300
+ });
1301
+ options;
1302
+ running = false;
1303
+ currentRoom = null;
1304
+ releaseRoom = null;
1305
+ /** The room's copies from this page's first welcome, taken back once. */
1306
+ restorable = null;
1307
+ restorers = /* @__PURE__ */ new Map();
1308
+ answerers = /* @__PURE__ */ new Map();
1309
+ /** Every channel's latest document, so a new room starts with all of them. */
1310
+ published = /* @__PURE__ */ new Map();
1311
+ knownSeats = /* @__PURE__ */ new Map();
1312
+ joinUrlKey = null;
1313
+ releaseRoomControl = null;
1314
+ releaseObservation = null;
1315
+ constructor(dependencies, options = {}) {
1316
+ this.hostSettings = new HostSettings(
1317
+ dependencies.settings,
1318
+ options.settings
1319
+ );
1320
+ this.settings = Object.freeze({
1321
+ declaration: this.hostSettings.declaration,
1322
+ read: this.hostSettings.read,
1323
+ subscribe: this.hostSettings.subscribe
1324
+ });
1325
+ this.config = dependencies.config;
1326
+ this.store = dependencies.store;
1327
+ if (dependencies.input && !dependencies.simulation)
1328
+ throw new Error(
1329
+ "A game reads its declared input in simulation steps. Declare a simulation with defineAirJamGame({ simulation })."
1330
+ );
1331
+ this.input = dependencies.input ? new HostInput(dependencies.input, () => this.environment.now()) : null;
1332
+ this.recorder = dependencies.simulation ? new InputRecorder() : null;
1333
+ this.timeline = dependencies.simulation ? new HostTimeline(Date.now()) : null;
1334
+ this.environment = dependencies.environment;
1335
+ this.stores = dependencies.stores;
1336
+ this.agent = dependencies.agent;
1337
+ this.options = options;
1338
+ this.orientation = dependencies.fixedControllerOrientation ?? "portrait";
1339
+ const seed = options.seed ?? dependencies.environment.seed();
1340
+ this.seed = seed;
1341
+ const install = (simulation) => {
1342
+ this.simulationDeclaration = simulation;
1343
+ this.timeline?.start(Date.now());
1344
+ const clock = new SimulationClock(
1345
+ simulation,
1346
+ {
1347
+ beginStep: (tick) => {
1348
+ this.stepAt = Date.now();
1349
+ const changes = this.input?.sample() ?? [];
1350
+ this.recorder?.flush(
1351
+ tick,
1352
+ changes.map(({ controllerId, input }) => ({
1353
+ event: "input",
1354
+ payload: structuredClone({ seat: controllerId, input })
1355
+ })),
1356
+ simulation.stepMs
1357
+ );
1358
+ },
1359
+ input: (controllerId) => this.input?.read(controllerId) ?? {},
1360
+ players: () => this.store.getState().players,
1361
+ reconnectingPlayerIds: () => getReconnectingPlayerIds(this.store.getState().players),
1362
+ settings: () => this.settings.read().values,
1363
+ runtimeState: () => this.store.getState().runtimeState
1364
+ },
1365
+ seed
1366
+ );
1367
+ this.clock = clock;
1368
+ clock.onEvent((event) => {
1369
+ this.timeline?.moment(
1370
+ simulation.moment?.(event),
1371
+ clock.ticks,
1372
+ this.stepAt
1373
+ );
1374
+ });
1375
+ };
1376
+ const declared = dependencies.simulation;
1377
+ this.declaresSimulation = Boolean(declared);
1378
+ if (typeof declared === "function")
1379
+ this.ready = declared().then((simulation) => {
1380
+ install(simulation);
1381
+ if (!this.running) return;
1382
+ this.stopFrames = this.startFrames();
1383
+ const roomId = this.roomId;
1384
+ if (roomId) this.bindObservation(roomId);
1385
+ });
1386
+ else {
1387
+ if (declared) install(declared);
1388
+ this.ready = Promise.resolve();
1389
+ }
1390
+ }
1391
+ /** The exception that stopped this host's display loop, if any. */
1392
+ get fault() {
1393
+ return this.frameFault;
1394
+ }
1395
+ /** The game's simulation clock; null while it loads or when the game declares none. */
1396
+ get simulation() {
1397
+ return this.clock;
1398
+ }
1399
+ /**
1400
+ * The room this host holds while it runs: what a launcher serves its
1401
+ * embedded game's frame from, and what it tells which activity is on screen.
1402
+ */
1403
+ get room() {
1404
+ return this.currentRoom;
1405
+ }
1406
+ /**
1407
+ * Game time in milliseconds: the simulation's time when the game declares
1408
+ * one (zero while it loads), else the host's clock.
1409
+ */
1410
+ now = () => this.declaresSimulation ? this.clock?.timeMs ?? 0 : this.environment.now();
1411
+ /** Whether this match's input log has reached its time or entry limit. */
1412
+ get inputLogFull() {
1413
+ return this.recorder?.full ?? false;
1414
+ }
1415
+ /** Everything that reached this simulated game, from its real seed. */
1416
+ inputLog(cut) {
1417
+ if (!this.recorder)
1418
+ throw new Error(
1419
+ "replay_unsupported: This game has no simulation, so its matches cannot be replayed; record a clip instead."
1420
+ );
1421
+ const simulation = this.simulationDeclaration;
1422
+ if (!simulation)
1423
+ throw new Error(
1424
+ "replay_loading: This game's simulation is still loading."
1425
+ );
1426
+ return this.recorder.log(
1427
+ {
1428
+ seed: this.seed,
1429
+ settings: this.hostSettings.initial,
1430
+ stepMs: simulation.stepMs,
1431
+ storeDomain: this.environment.defaultStoreDomain
1432
+ },
1433
+ cut
1434
+ );
1435
+ }
1436
+ updateSettings = (patch, expectedRevision) => {
1437
+ if (this.clock?.stepping)
1438
+ throw new Error(
1439
+ "AJ_SETTING_INVALID: Settings change between simulation steps."
1440
+ );
1441
+ if (this.declaresSimulation && !this.clock)
1442
+ throw new Error(
1443
+ "AJ_SETTING_INVALID: Settings change once the game's simulation has loaded."
1444
+ );
1445
+ return this.hostSettings.update(patch, expectedRevision, (revision) => {
1446
+ this.recordRoomEvent("settings", { patch: { ...patch }, revision });
1447
+ });
1448
+ };
1449
+ /** The room this host is in or asking for, if any. */
1450
+ get roomId() {
1451
+ return this.currentRoom?.code ?? this.requestedCode ?? null;
1452
+ }
1453
+ /** The code the page asked for, which a local server honours. */
1454
+ get requestedCode() {
1455
+ if (this.environment.requestedRoomId)
1456
+ return this.environment.requestedRoomId;
1457
+ if (this.options.roomId)
1458
+ return roomCodeSchema.parse(this.options.roomId.toUpperCase());
1459
+ return void 0;
1460
+ }
1461
+ setOptions(options) {
1462
+ this.options = options;
1463
+ }
1464
+ /** Opens or reclaims the room and keeps it until the returned stop is called. */
1465
+ start() {
1466
+ if (this.running) throw new Error("Host runtime is already running.");
1467
+ this.running = true;
1468
+ const initial = this.store.getState();
1469
+ initial.setMode(this.environment.runMode);
1470
+ initial.setRole("host");
1471
+ initial.setError(void 0);
1472
+ this.environment.setDevLogContext({
1473
+ role: "host",
1474
+ roomId: this.roomId ?? void 0
1475
+ });
1476
+ const storeRoom = this.storeRoom();
1477
+ const detachStores = this.stores.map(
1478
+ (store) => store.attach({
1479
+ room: storeRoom,
1480
+ connection: this.store,
1481
+ defaultStoreDomain: this.environment.defaultStoreDomain,
1482
+ controlTarget: this.environment.controlTarget,
1483
+ now: this.now,
1484
+ emitDevEvent: (detail) => this.environment.emitDevEvent(detail),
1485
+ settings: () => this.settings.read().values
1486
+ })
1487
+ );
1488
+ this.publishPresentation();
1489
+ const stopRecordingActions = this.recordActions();
1490
+ this.openRoom(this.environment.readResume());
1491
+ this.refreshJoinUrl();
1492
+ this.stopFrames = this.startFrames();
1493
+ return () => {
1494
+ this.clips.dispose();
1495
+ for (const stop of stopRecordingActions) stop();
1496
+ this.stopFrames?.();
1497
+ this.stopFrames = null;
1498
+ this.closeRoom();
1499
+ for (const detach of detachStores) detach();
1500
+ this.releaseRoomControl?.();
1501
+ this.releaseRoomControl = null;
1502
+ this.joinUrlKey = null;
1503
+ this.environment.setDevLogContext({
1504
+ role: void 0,
1505
+ roomId: void 0,
1506
+ traceId: void 0
1507
+ });
1508
+ this.running = false;
1509
+ };
1510
+ }
1511
+ /**
1512
+ * Lets agents receive an image of what the host draws. Pass null when the
1513
+ * drawing surface goes away.
1514
+ */
1515
+ setObservationCapture = (capture) => {
1516
+ if (capture !== this.capture) this.clips.dispose();
1517
+ if (Boolean(capture) === Boolean(this.capture)) {
1518
+ this.capture = capture;
1519
+ return;
1520
+ }
1521
+ this.capture = capture;
1522
+ const roomId = this.roomId;
1523
+ if (this.running && roomId) this.bindObservation(roomId);
1524
+ };
1525
+ setRuntimeState = (runtimeState) => {
1526
+ const state = this.store.getState();
1527
+ const previous = state.runtimeState;
1528
+ if (previous === runtimeState) return;
1529
+ state.setRuntimeState(runtimeState);
1530
+ this.recordRoomEvent("runtime", { runtimeState });
1531
+ this.emitRuntimeEvent({
1532
+ event: AIRJAM_DEV_LOG_EVENTS.runtime.phaseTransition,
1533
+ message: "Host runtime phase transition",
1534
+ roomId: this.roomId ?? void 0,
1535
+ data: { from: previous, to: runtimeState }
1536
+ });
1537
+ this.publishPresentation();
1538
+ };
1539
+ pauseRuntime = () => this.setRuntimeState("paused");
1540
+ resumeRuntime = () => this.setRuntimeState("playing");
1541
+ sendSignal = ((type, payload, targetId) => {
1542
+ this.currentRoom?.signal(
1543
+ type === "HAPTIC" ? "haptic" : "toast",
1544
+ payload,
1545
+ targetId
1546
+ );
1547
+ });
1548
+ /** Plays a sound on one phone or every phone. */
1549
+ playSoundOnControllers = (sound, targetId) => {
1550
+ this.currentRoom?.signal("sound", sound, targetId);
1551
+ };
1552
+ /** Frees a player's seat and closes their phone for good. */
1553
+ /** Frees a player's seat; settles once the room confirms it left. */
1554
+ removeController = (controllerId) => {
1555
+ const room = this.currentRoom;
1556
+ if (!room || room.status.phase !== "open")
1557
+ return Promise.resolve({
1558
+ ok: false,
1559
+ message: "The host is not connected to a room."
1560
+ });
1561
+ if (!room.seats.some((seat) => seat.id === controllerId))
1562
+ return Promise.resolve({
1563
+ ok: false,
1564
+ message: "That player is not in the room."
1565
+ });
1566
+ const confirmation = awaitRoomConfirmation({
1567
+ follow: (changed) => followRoom(room, changed),
1568
+ confirmed: () => !room.seats.some((seat) => seat.id === controllerId),
1569
+ lost: () => room.status.phase !== "open",
1570
+ unconfirmed: "The room did not confirm the player left."
1571
+ });
1572
+ room.remove(controllerId);
1573
+ return confirmation;
1574
+ };
1575
+ /** Applies an action a recorded match applied between steps, as a replay does. */
1576
+ replayAction = (call) => {
1577
+ for (const store of this.stores) store.replayAction(call);
1578
+ };
1579
+ /**
1580
+ * Ends this room for every device and opens a new one with a new code;
1581
+ * settles once the new room welcomes this host.
1582
+ */
1583
+ resetRoom = () => {
1584
+ if (!this.running)
1585
+ return Promise.resolve({
1586
+ ok: false,
1587
+ message: "The host is not running."
1588
+ });
1589
+ this.emitRuntimeEvent({
1590
+ event: AIRJAM_DEV_LOG_EVENTS.runtime.hostResetRoomRequested,
1591
+ message: "Host ended its room to open a new one",
1592
+ roomId: this.roomId ?? void 0
1593
+ });
1594
+ this.currentRoom?.end();
1595
+ this.closeRoom();
1596
+ this.environment.writeResume(null);
1597
+ this.followSeats([]);
1598
+ this.store.getState().resetRuntimeState();
1599
+ this.publishPresentation();
1600
+ this.openRoom(null);
1601
+ const room = this.currentRoom;
1602
+ if (!room)
1603
+ return Promise.resolve({ ok: false, message: "No new room opened." });
1604
+ return awaitRoomConfirmation({
1605
+ follow: (changed) => followRoom(room, changed),
1606
+ confirmed: () => room.status.phase === "open",
1607
+ lost: () => room.status.phase === "closed",
1608
+ unconfirmed: "The new room did not open."
1609
+ });
1610
+ };
1611
+ /** The view replicated stores have of this host's room. */
1612
+ storeRoom() {
1613
+ return {
1614
+ role: "host",
1615
+ publish: (channel, document, options) => {
1616
+ this.published.set(channel, { document, options });
1617
+ this.currentRoom?.publish(channel, document, options);
1618
+ },
1619
+ onRestore: (channel, restore) => {
1620
+ this.restorers.set(channel, restore);
1621
+ return () => this.restorers.delete(channel);
1622
+ },
1623
+ answer: (channel, answer) => {
1624
+ this.answerers.set(channel, answer);
1625
+ return () => this.answerers.delete(channel);
1626
+ }
1627
+ };
1628
+ }
1629
+ publishPresentation() {
1630
+ const { runtimeState } = this.store.getState();
1631
+ const document = {
1632
+ runtimeState,
1633
+ orientation: this.orientation
1634
+ };
1635
+ this.store.getState().setControllerOrientation(this.orientation);
1636
+ const channel = this.environment.presentationChannel;
1637
+ this.published.set(channel, { document, options: {} });
1638
+ this.currentRoom?.publish(channel, document, {});
1639
+ }
1640
+ /** Opens a session to a new room, or to the one `resume` names. */
1641
+ openRoom(resume) {
1642
+ const endpoint = this.config.hostGrantEndpoint;
1643
+ const key = resume?.key ?? this.environment.createKey();
1644
+ const room = this.environment.openRoom({
1645
+ key,
1646
+ code: resume?.code ?? this.requestedCode,
1647
+ instance: resume?.instance,
1648
+ seats: this.config.maxPlayers,
1649
+ ...this.input ? { input: this.input.declaration } : {},
1650
+ ...endpoint ? {
1651
+ credential: () => this.environment.requestHostGrant(endpoint, this.config.appId)
1652
+ } : {}
1653
+ });
1654
+ this.currentRoom = room;
1655
+ this.restorable = null;
1656
+ for (const [channel, { document, options }] of this.published)
1657
+ room.publish(channel, document, options);
1658
+ const releases = [
1659
+ room.on("status", (status) => this.followStatus(room, key, status)),
1660
+ room.on("seats", (seats) => this.followSeats(seats)),
1661
+ room.on("input", ({ seat, state }) => this.input?.receive(seat, state)),
1662
+ // A seat's new page counts its presses from zero again.
1663
+ room.on("inputBaseline", (seat) => this.input?.clearInput(seat)),
1664
+ room.on("request", (request) => this.answer(room, request))
1665
+ ];
1666
+ this.releaseRoom = () => {
1667
+ for (const release of releases) release();
1668
+ room.close();
1669
+ };
1670
+ this.followStatus(room, key, room.status);
1671
+ }
1672
+ closeRoom() {
1673
+ this.releaseRoom?.();
1674
+ this.releaseRoom = null;
1675
+ this.currentRoom = null;
1676
+ }
1677
+ followStatus(room, key, status) {
1678
+ if (room !== this.currentRoom) return;
1679
+ const state = this.store.getState();
1680
+ this.emitRuntimeEvent({
1681
+ event: AIRJAM_DEV_LOG_EVENTS.runtime.roomStatus,
1682
+ message: `Host room ${status.phase}`,
1683
+ roomId: room.code ?? void 0,
1684
+ data: { ...status }
1685
+ });
1686
+ switch (status.phase) {
1687
+ case "connecting":
1688
+ state.setStatus("connecting");
1689
+ return;
1690
+ case "waiting":
1691
+ state.setStatus("connecting");
1692
+ state.setQueuePosition(status.position);
1693
+ return;
1694
+ case "reconnecting":
1695
+ state.setStatus("reconnecting");
1696
+ return;
1697
+ case "open": {
1698
+ const code = room.code;
1699
+ const instance = room.instance;
1700
+ if (!code || !instance) return;
1701
+ state.setQueuePosition(null);
1702
+ state.setError(void 0);
1703
+ state.setRoomId(code);
1704
+ state.setStatus("connected");
1705
+ this.environment.writeResume({ key, code, instance });
1706
+ this.environment.setDevLogContext({ role: "host", roomId: code });
1707
+ if (this.restorable === null) {
1708
+ this.restorable = new Map(
1709
+ room.roomCopies.map((copy) => [copy.channel, copy])
1710
+ );
1711
+ for (const [channel, restore] of this.restorers) {
1712
+ const copy = this.restorable.get(channel);
1713
+ if (copy) restore(copy);
1714
+ }
1715
+ }
1716
+ this.bindRoomControl();
1717
+ this.refreshJoinUrl();
1718
+ return;
1719
+ }
1720
+ case "closed": {
1721
+ state.setStatus("disconnected");
1722
+ state.setQueuePosition(null);
1723
+ if (status.reason === "owner") return;
1724
+ if (ROOM_GONE.has(status.reason) && this.running && !this.environment.embedded) {
1725
+ this.closeRoom();
1726
+ this.environment.writeResume(null);
1727
+ this.followSeats([]);
1728
+ this.openRoom(null);
1729
+ return;
1730
+ }
1731
+ const message = `The room closed the connection: ${status.reason}.`;
1732
+ emitAirJamDiagnostic({
1733
+ code: "AJ_HOST_BOOTSTRAP_FAILED",
1734
+ severity: "error",
1735
+ message,
1736
+ details: { reason: status.reason, roomId: room.code ?? null }
1737
+ });
1738
+ state.setError(message);
1739
+ return;
1740
+ }
1741
+ }
1742
+ }
1743
+ followSeats(seats) {
1744
+ const roomId = this.roomId;
1745
+ const next = new Map(seats.map((seat) => [seat.id, seat]));
1746
+ for (const seat of seats) {
1747
+ const known = this.knownSeats.get(seat.id);
1748
+ if (JSON.stringify(known) === JSON.stringify(seat)) continue;
1749
+ this.recordRoomEvent("seat", { seat });
1750
+ if (!seat.connected) this.input?.clearInput(seat.id);
1751
+ if (!known) setTimeout(() => this.options.onPlayerJoin?.(seat), 0);
1752
+ }
1753
+ for (const id of this.knownSeats.keys()) {
1754
+ if (next.has(id)) continue;
1755
+ this.recordRoomEvent("left", { seat: id });
1756
+ this.input?.clearInput(id);
1757
+ if (roomId)
1758
+ clearHostRuntimeParticipant(this.environment.controlTarget, roomId, id);
1759
+ this.options.onPlayerLeave?.(id);
1760
+ }
1761
+ this.knownSeats = next;
1762
+ this.store.getState().setPlayers(seats);
1763
+ }
1764
+ /** Answers a phone's request on a channel this host holds; others are not its to answer. */
1765
+ answer(room, request) {
1766
+ const respond = (result) => room.respond(request.seat, request.id, result);
1767
+ if (request.channel === this.environment.presentationChannel) {
1768
+ const parsed = presentationRequestSchema.safeParse(request.name);
1769
+ if (!parsed.success) return respond({ ok: false });
1770
+ this.setRuntimeState(parsed.data === "pause" ? "paused" : "playing");
1771
+ return respond({ runtimeState: this.store.getState().runtimeState });
1772
+ }
1773
+ if (request.channel === AIRJAM_CONTROL_CHANNEL) {
1774
+ if (request.name !== AIRJAM_LEASED_CONTROL_REQUEST) return;
1775
+ return respond(this.applyLeasedControl(request));
1776
+ }
1777
+ const answer = this.answerers.get(request.channel);
1778
+ if (!answer) return;
1779
+ respond(
1780
+ answer({
1781
+ seat: request.seat,
1782
+ name: request.name,
1783
+ payload: request.payload
1784
+ })
1785
+ );
1786
+ }
1787
+ applyLeasedControl(request) {
1788
+ const roomId = this.roomId;
1789
+ const parsed = leasedControlRequestSchema.safeParse(request.payload);
1790
+ if (!parsed.success || !roomId)
1791
+ return { status: "rejected", reason: "invalid_request" };
1792
+ const control = controllerLeasedControlSchema.safeParse({
1793
+ ...parsed.data,
1794
+ roomId,
1795
+ controllerId: request.seat
1796
+ });
1797
+ if (!control.success)
1798
+ return { status: "rejected", reason: "invalid_request" };
1799
+ try {
1800
+ return applyHostRuntimeLeasedControl(
1801
+ this.environment.controlTarget,
1802
+ control.data
1803
+ );
1804
+ } catch (error) {
1805
+ emitAirJamDiagnostic({
1806
+ code: "AJ_PARTICIPANT_CONTROL_RUNTIME_UNAVAILABLE",
1807
+ severity: "error",
1808
+ message: error instanceof Error ? error.message : "Participant control runtime is unavailable.",
1809
+ details: { roomId }
1810
+ });
1811
+ return { status: "unconfirmed", reason: "runtime_unavailable" };
1812
+ }
1813
+ }
1814
+ startFrames() {
1815
+ const clock = this.simulation;
1816
+ const frames = this.environment.frames;
1817
+ if (!clock || !frames || this.frameFault) return () => {
1818
+ };
1819
+ clock.rest();
1820
+ const tracked = trackHostSimulation(clock.pace);
1821
+ const stop = frames((now) => {
1822
+ if (this.frameFault) return;
1823
+ try {
1824
+ clock.frame(now);
1825
+ this.timeline?.frame(Date.now(), clock.pace);
1826
+ } catch (error) {
1827
+ this.frameFault = hostRuntimeFault(error);
1828
+ stop();
1829
+ this.emitRuntimeEvent({
1830
+ event: AIRJAM_DEV_LOG_EVENTS.runtime.hostFrameFault,
1831
+ level: "error",
1832
+ message: describeHostRuntimeFault(this.frameFault),
1833
+ roomId: this.roomId ?? void 0,
1834
+ data: { fault: this.frameFault }
1835
+ });
1836
+ }
1837
+ });
1838
+ return () => {
1839
+ stop();
1840
+ tracked.release();
1841
+ };
1842
+ }
1843
+ refreshJoinUrl() {
1844
+ if (!this.running) return;
1845
+ const state = this.store.getState();
1846
+ const embeddedJoinUrl = this.environment.embedded?.joinUrl;
1847
+ if (embeddedJoinUrl) {
1848
+ this.joinUrlKey = null;
1849
+ state.setJoinUrl(embeddedJoinUrl, "ready");
1850
+ return;
1851
+ }
1852
+ const roomId = this.currentRoom?.code ?? null;
1853
+ if (!roomId) {
1854
+ this.joinUrlKey = null;
1855
+ state.setJoinUrl("", "loading");
1856
+ return;
1857
+ }
1858
+ if (roomId === this.joinUrlKey) return;
1859
+ this.joinUrlKey = roomId;
1860
+ state.setJoinUrl("", "loading");
1861
+ this.environment.controllerUrl(roomId).then(
1862
+ (url) => {
1863
+ if (this.joinUrlKey === roomId)
1864
+ this.store.getState().setJoinUrl(url, "ready");
1865
+ },
1866
+ () => {
1867
+ if (this.joinUrlKey === roomId)
1868
+ this.store.getState().setJoinUrl("", "unavailable");
1869
+ }
1870
+ );
1871
+ }
1872
+ emitRuntimeEvent({
1873
+ level = "info",
1874
+ ...detail
1875
+ }) {
1876
+ this.environment.emitDevEvent({ ...detail, level, role: "host" });
1877
+ }
1878
+ /** Wall time belongs only to entries the bounded recorder actually accepted. */
1879
+ recordRoomEvent(event, payload) {
1880
+ const recorder = this.recorder;
1881
+ if (!recorder) return;
1882
+ const index = recorder.entryCount;
1883
+ recorder.record(event, payload);
1884
+ if (recorder.entryCount > index) this.timeline?.record(index, Date.now());
1885
+ }
1886
+ /** Records store actions applied between steps; a step's own actions replay with it. */
1887
+ recordActions() {
1888
+ const recorder = this.recorder;
1889
+ if (!recorder) return [];
1890
+ return this.stores.map(
1891
+ (store) => store.subscribeHostActions(
1892
+ ({ actionName, payload, storeDomain, context }) => {
1893
+ if (this.clock?.stepping) return;
1894
+ this.recordRoomEvent("action", {
1895
+ actionName,
1896
+ payload,
1897
+ storeDomain,
1898
+ actor: { id: context.actorId, role: context.role }
1899
+ });
1900
+ },
1901
+ { includeRejected: true }
1902
+ )
1903
+ );
1904
+ }
1905
+ /** Admission control for controllers this host leases to agents and tools. */
1906
+ bindRoomControl() {
1907
+ const roomId = this.roomId;
1908
+ if (!roomId) return;
1909
+ this.releaseRoomControl?.();
1910
+ this.releaseRoomControl = null;
1911
+ const target = this.environment.controlTarget;
1912
+ const unregisterContract = this.agent ? registerHostAgentContract(target, {
1913
+ roomId,
1914
+ gameId: this.agent.gameId,
1915
+ contract: this.agent.contract,
1916
+ players: () => this.store.getState().players,
1917
+ settings: { read: this.settings.read, update: this.updateSettings }
1918
+ }) : null;
1919
+ this.bindObservation(roomId);
1920
+ const unregister = registerHostRuntimeParticipantReceiver(target, roomId, {
1921
+ seats: () => {
1922
+ const room = this.currentRoom;
1923
+ return room?.instance ? { instance: room.instance, seats: this.store.getState().players } : null;
1924
+ },
1925
+ now: this.now,
1926
+ clips: this.clips,
1927
+ timeline: () => this.timeline && this.simulationDeclaration ? {
1928
+ status: "available",
1929
+ ...this.timeline.read(this.inputLog(), Date.now())
1930
+ } : {
1931
+ status: "unavailable",
1932
+ reason: this.declaresSimulation ? "simulation-loading" : "no-simulation"
1933
+ },
1934
+ inputLog: (cut) => this.inputLog(cut),
1935
+ inputLogFull: () => this.inputLogFull,
1936
+ input: this.input ?? void 0,
1937
+ readState: () => {
1938
+ const state = this.store.getState();
1939
+ return {
1940
+ runtimeState: state.runtimeState,
1941
+ connectionStatus: state.connectionStatus,
1942
+ fault: this.frameFault
1943
+ };
1944
+ },
1945
+ isParticipant: (controllerId) => this.store.getState().players.some(
1946
+ (player) => player.id === controllerId && player.connected
1947
+ )
1948
+ });
1949
+ this.releaseRoomControl = () => {
1950
+ unregister();
1951
+ this.releaseObservation?.();
1952
+ this.releaseObservation = null;
1953
+ unregisterContract?.();
1954
+ };
1955
+ }
1956
+ /** Publishes what the simulation declares agents see, and the host's image. */
1957
+ bindObservation(roomId) {
1958
+ this.clips.dispose();
1959
+ this.releaseObservation?.();
1960
+ this.releaseObservation = null;
1961
+ const simulation = this.simulationDeclaration;
1962
+ const clock = this.simulation;
1963
+ if (!clock && !this.capture) return;
1964
+ this.releaseObservation = registerHostObservationSurface(
1965
+ this.environment.controlTarget,
1966
+ roomId,
1967
+ {
1968
+ read: (context) => simulation?.observe && clock ? {
1969
+ state: simulation.observe(clock.sim, {
1970
+ ...context,
1971
+ settings: this.settings.read().values
1972
+ }),
1973
+ tick: clock.ticks
1974
+ } : { state: {}, ...clock ? { tick: clock.ticks } : {} },
1975
+ ...this.capture ? { capture: (options) => this.capture?.(options) ?? null } : {}
1976
+ }
1977
+ );
1978
+ }
1979
+ };
1980
+
1981
+ export {
1982
+ button,
1983
+ axis,
1984
+ stick,
1985
+ defineAirJamInput,
1986
+ agentValuesToInputState,
1987
+ airJamInputDescriptionSchema,
1988
+ ControllerInput,
1989
+ ControllerRuntime,
1990
+ defineAirJamSimulation,
1991
+ createSeededRandom,
1992
+ SimulationClock,
1993
+ HostRuntime
1994
+ };
1995
+ //# sourceMappingURL=chunk-BQHGPXXN.js.map