@air-jam/sdk 0.9.2 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (590) hide show
  1. package/README.md +185 -242
  2. package/dist/actions-D4eh6Xaa.d.cts +72 -0
  3. package/dist/actions-D4eh6Xaa.d.ts +72 -0
  4. package/dist/{agent-tooling-BSMGBix9.d.cts → agent-contract-DfLm4Mf-.d.ts} +3 -19
  5. package/dist/{agent-tooling-BSMGBix9.d.ts → agent-contract-TINzp-5Y.d.cts} +3 -19
  6. package/dist/agent-tooling.cjs +270 -42
  7. package/dist/agent-tooling.cjs.map +1 -1
  8. package/dist/agent-tooling.d.cts +117 -2
  9. package/dist/agent-tooling.d.ts +117 -2
  10. package/dist/agent-tooling.js +150 -11
  11. package/dist/agent-tooling.js.map +1 -1
  12. package/dist/air-jam-context-BCVCWiaT.d.ts +410 -0
  13. package/dist/air-jam-context-DavligpM.d.cts +410 -0
  14. package/dist/arcade/bridge/controller.cjs +872 -582
  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 -26
  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 -21
  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 -479
  33. package/dist/arcade/host.cjs.map +1 -1
  34. package/dist/arcade/host.d.cts +1 -18
  35. package/dist/arcade/host.d.ts +1 -18
  36. package/dist/arcade/host.js +0 -13
  37. package/dist/arcade/host.js.map +1 -1
  38. package/dist/arcade/runtime.cjs +12163 -0
  39. package/dist/arcade/runtime.cjs.map +1 -0
  40. package/dist/arcade/runtime.d.cts +54 -0
  41. package/dist/arcade/runtime.d.ts +54 -0
  42. package/dist/arcade/runtime.js +45 -0
  43. package/dist/arcade/runtime.js.map +1 -0
  44. package/dist/arcade/surface.cjs +12 -35
  45. package/dist/arcade/surface.cjs.map +1 -1
  46. package/dist/arcade/surface.d.cts +19 -2
  47. package/dist/arcade/surface.d.ts +19 -2
  48. package/dist/arcade/surface.js +12 -14
  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-2QZADUGA.js +188 -0
  63. package/dist/chunk-2QZADUGA.js.map +1 -0
  64. package/dist/chunk-3LDQCQL2.js +307 -0
  65. package/dist/chunk-3LDQCQL2.js.map +1 -0
  66. package/dist/chunk-3M7656SU.js +389 -0
  67. package/dist/chunk-3M7656SU.js.map +1 -0
  68. package/dist/{chunk-ZLPL2R3R.js → chunk-5CRZFIN6.js} +2 -82
  69. package/dist/chunk-5CRZFIN6.js.map +1 -0
  70. package/dist/chunk-5TVVPBQI.js +7 -0
  71. package/dist/chunk-5TVVPBQI.js.map +1 -0
  72. package/dist/chunk-6Y3F6Y2K.js +343 -0
  73. package/dist/chunk-6Y3F6Y2K.js.map +1 -0
  74. package/dist/{chunk-EVZJA6RN.js → chunk-6ZJUA63D.js} +183 -2
  75. package/dist/chunk-6ZJUA63D.js.map +1 -0
  76. package/dist/chunk-A6EOGRRG.js +49 -0
  77. package/dist/chunk-A6EOGRRG.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-C5722GTG.js +176 -0
  81. package/dist/chunk-C5722GTG.js.map +1 -0
  82. package/dist/{chunk-DY67S3LR.js → chunk-C5GS2GMK.js} +99 -105
  83. package/dist/chunk-C5GS2GMK.js.map +1 -0
  84. package/dist/chunk-CDL7LYZH.js +19 -0
  85. package/dist/chunk-CDL7LYZH.js.map +1 -0
  86. package/dist/chunk-DA3TE4OP.js +16 -0
  87. package/dist/chunk-DA3TE4OP.js.map +1 -0
  88. package/dist/chunk-DBF7NJ3S.js +72 -0
  89. package/dist/chunk-DBF7NJ3S.js.map +1 -0
  90. package/dist/chunk-DHFKL3DI.js +2477 -0
  91. package/dist/chunk-DHFKL3DI.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-7OTQTT6H.js → chunk-EG25EXSA.js} +24 -3
  95. package/dist/chunk-EG25EXSA.js.map +1 -0
  96. package/dist/chunk-FCG42U7D.js +131 -0
  97. package/dist/chunk-FCG42U7D.js.map +1 -0
  98. package/dist/chunk-FJ4J2BEC.js +26 -0
  99. package/dist/chunk-FJ4J2BEC.js.map +1 -0
  100. package/dist/chunk-H4DEVMTO.js +221 -0
  101. package/dist/chunk-H4DEVMTO.js.map +1 -0
  102. package/dist/chunk-I6TSHJF7.js +63 -0
  103. package/dist/chunk-I6TSHJF7.js.map +1 -0
  104. package/dist/{chunk-NCL6WJCL.js → chunk-JCGTL77W.js} +32 -1
  105. package/dist/chunk-JCGTL77W.js.map +1 -0
  106. package/dist/chunk-JJVCBUYM.js +98 -0
  107. package/dist/chunk-JJVCBUYM.js.map +1 -0
  108. package/dist/chunk-K6BJJJJM.js +138 -0
  109. package/dist/chunk-K6BJJJJM.js.map +1 -0
  110. package/dist/chunk-KSYN4I5Y.js +50 -0
  111. package/dist/chunk-KSYN4I5Y.js.map +1 -0
  112. package/dist/chunk-KUGROY5S.js +265 -0
  113. package/dist/chunk-KUGROY5S.js.map +1 -0
  114. package/dist/chunk-LX6CTPDW.js +16 -0
  115. package/dist/chunk-LX6CTPDW.js.map +1 -0
  116. package/dist/{chunk-BE6Z4SIT.js → chunk-M5553I2G.js} +2 -11
  117. package/dist/chunk-M5553I2G.js.map +1 -0
  118. package/dist/{chunk-X24K52DG.js → chunk-MD25536W.js} +1 -1
  119. package/dist/chunk-MD25536W.js.map +1 -0
  120. package/dist/{chunk-3USU7GY2.js → chunk-MJAWAHLT.js} +1 -1
  121. package/dist/chunk-MJAWAHLT.js.map +1 -0
  122. package/dist/chunk-OAXCFPZ7.js +14 -0
  123. package/dist/chunk-OAXCFPZ7.js.map +1 -0
  124. package/dist/chunk-QHBRHYMV.js +81 -0
  125. package/dist/chunk-QHBRHYMV.js.map +1 -0
  126. package/dist/chunk-QTNYGAZ7.js +45 -0
  127. package/dist/chunk-QTNYGAZ7.js.map +1 -0
  128. package/dist/chunk-S3TN7Y7L.js +921 -0
  129. package/dist/chunk-S3TN7Y7L.js.map +1 -0
  130. package/dist/chunk-SMKD4JY3.js +129 -0
  131. package/dist/chunk-SMKD4JY3.js.map +1 -0
  132. package/dist/{chunk-NUJBMV3O.js → chunk-TFW4NJW2.js} +619 -646
  133. package/dist/chunk-TFW4NJW2.js.map +1 -0
  134. package/dist/chunk-UBBP2UY3.js +83 -0
  135. package/dist/chunk-UBBP2UY3.js.map +1 -0
  136. package/dist/chunk-URVBMQCK.js +802 -0
  137. package/dist/chunk-URVBMQCK.js.map +1 -0
  138. package/dist/chunk-VGX2274F.js +1995 -0
  139. package/dist/chunk-VGX2274F.js.map +1 -0
  140. package/dist/chunk-WAFGYJZN.js +1513 -0
  141. package/dist/chunk-WAFGYJZN.js.map +1 -0
  142. package/dist/chunk-WGHNGQUS.js +78 -0
  143. package/dist/chunk-WGHNGQUS.js.map +1 -0
  144. package/dist/chunk-XLY44PXZ.js +46 -0
  145. package/dist/chunk-XLY44PXZ.js.map +1 -0
  146. package/dist/connection-store-BYpQ50W2.d.ts +41 -0
  147. package/dist/connection-store-D6QqzXU1.d.cts +41 -0
  148. package/dist/control-Bv8dWjyp.d.ts +1400 -0
  149. package/dist/control-CNzybWMd.d.cts +1400 -0
  150. package/dist/controller-0CVO1t_3.d.cts +26 -0
  151. package/dist/controller-agent-vOiuK7T6.d.cts +130 -0
  152. package/dist/controller-agent-vOiuK7T6.d.ts +130 -0
  153. package/dist/controller-bridge.cjs +992 -0
  154. package/dist/controller-bridge.cjs.map +1 -0
  155. package/dist/controller-bridge.d.cts +52 -0
  156. package/dist/controller-bridge.d.ts +52 -0
  157. package/dist/controller-bridge.js +23 -0
  158. package/dist/controller-bridge.js.map +1 -0
  159. package/dist/controller-capture-2GKKGHJ2.js +8 -0
  160. package/dist/controller-capture-2GKKGHJ2.js.map +1 -0
  161. package/dist/controller-h9M2Nngd.d.ts +26 -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 +5931 -0
  167. package/dist/core.cjs.map +1 -0
  168. package/dist/core.d.cts +232 -0
  169. package/dist/core.d.ts +232 -0
  170. package/dist/core.js +906 -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-Db58JNk3.d.cts +77 -0
  179. package/dist/game-bySEy-QO.d.ts +77 -0
  180. package/dist/host-runtime-BuLhGQx5.d.ts +399 -0
  181. package/dist/host-runtime-_06jpW5v.d.cts +399 -0
  182. package/dist/index.cjs +12406 -8020
  183. package/dist/index.cjs.map +1 -1
  184. package/dist/index.d.cts +106 -973
  185. package/dist/index.d.ts +106 -973
  186. package/dist/index.js +451 -4637
  187. package/dist/index.js.map +1 -1
  188. package/dist/input-Xvs80gqG.d.cts +92 -0
  189. package/dist/input-Xvs80gqG.d.ts +92 -0
  190. package/dist/input-bindings-BaEFrgRb.d.cts +129 -0
  191. package/dist/input-bindings-BgsJRLPm.d.ts +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 -17
  197. package/dist/metadata.d.ts +6 -17
  198. package/dist/metadata.js +8 -76
  199. package/dist/metadata.js.map +1 -1
  200. package/dist/phone-room-session-Ca6rlxJr.d.ts +439 -0
  201. package/dist/phone-room-session-DkPR-K6e.d.cts +439 -0
  202. package/dist/platform-machine.cjs +248 -18
  203. package/dist/platform-machine.cjs.map +1 -1
  204. package/dist/platform-machine.d.cts +1867 -96
  205. package/dist/platform-machine.d.ts +1867 -96
  206. package/dist/platform-machine.js +206 -18
  207. package/dist/platform-machine.js.map +1 -1
  208. package/dist/{platform-settings-cuor3i11.d.cts → platform-settings-Yb0fQ1dl.d.cts} +1 -3
  209. package/dist/{platform-settings-cuor3i11.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 +2269 -774
  217. package/dist/preview.cjs.map +1 -1
  218. package/dist/preview.d.cts +195 -38
  219. package/dist/preview.d.ts +195 -38
  220. package/dist/preview.js +494 -260
  221. package/dist/preview.js.map +1 -1
  222. package/dist/protocol.cjs +705 -396
  223. package/dist/protocol.cjs.map +1 -1
  224. package/dist/protocol.d.cts +49 -100
  225. package/dist/protocol.d.ts +49 -100
  226. package/dist/protocol.js +56 -75
  227. package/dist/protocol.js.map +1 -1
  228. package/dist/release.cjs +37 -0
  229. package/dist/release.cjs.map +1 -1
  230. package/dist/release.d.cts +29 -3
  231. package/dist/release.d.ts +29 -3
  232. package/dist/release.js +13 -1
  233. package/dist/release.js.map +1 -1
  234. package/dist/replay-input-log-BvX4As2f.d.ts +31 -0
  235. package/dist/replay-input-log-Vcl0VDIy.d.cts +31 -0
  236. package/dist/room-protocol.cjs +794 -0
  237. package/dist/room-protocol.cjs.map +1 -0
  238. package/dist/room-protocol.d.cts +63 -0
  239. package/dist/room-protocol.d.ts +63 -0
  240. package/dist/room-protocol.js +143 -0
  241. package/dist/room-protocol.js.map +1 -0
  242. package/dist/room-session.cjs +2336 -0
  243. package/dist/room-session.cjs.map +1 -0
  244. package/dist/room-session.d.cts +77 -0
  245. package/dist/room-session.d.ts +77 -0
  246. package/dist/room-session.js +103 -0
  247. package/dist/room-session.js.map +1 -0
  248. package/dist/runtime/prefab-inspection-bridge.cjs +207 -0
  249. package/dist/runtime/prefab-inspection-bridge.cjs.map +1 -0
  250. package/dist/runtime/prefab-inspection-bridge.d.cts +156 -0
  251. package/dist/runtime/prefab-inspection-bridge.d.ts +156 -0
  252. package/dist/runtime/prefab-inspection-bridge.js +22 -0
  253. package/dist/runtime/prefab-inspection-bridge.js.map +1 -0
  254. package/dist/runtime-control.cjs +2150 -0
  255. package/dist/runtime-control.cjs.map +1 -0
  256. package/dist/runtime-control.d.cts +985 -0
  257. package/dist/runtime-control.d.ts +985 -0
  258. package/dist/runtime-control.js +268 -0
  259. package/dist/runtime-control.js.map +1 -0
  260. package/dist/runtime-inspection.cjs +1319 -0
  261. package/dist/runtime-inspection.cjs.map +1 -0
  262. package/dist/runtime-inspection.d.cts +555 -0
  263. package/dist/runtime-inspection.d.ts +555 -0
  264. package/dist/runtime-inspection.js +29 -0
  265. package/dist/runtime-inspection.js.map +1 -0
  266. package/dist/runtime-reporting-K_ZXpubu.d.cts +43 -0
  267. package/dist/runtime-reporting-K_ZXpubu.d.ts +43 -0
  268. package/dist/runtime-topology.cjs +2 -5
  269. package/dist/runtime-topology.cjs.map +1 -1
  270. package/dist/runtime-topology.d.cts +1 -1
  271. package/dist/runtime-topology.d.ts +1 -1
  272. package/dist/runtime-topology.js +1 -1
  273. package/dist/runtime-topology.js.map +1 -1
  274. package/dist/scoped-connector-CiiWu06D.d.ts +66 -0
  275. package/dist/scoped-connector-D7252pn0.d.cts +66 -0
  276. package/dist/sdk-channels-S6j6AH8v.d.cts +103 -0
  277. package/dist/sdk-channels-S6j6AH8v.d.ts +103 -0
  278. package/dist/simulation-BfRnC4rg.d.ts +782 -0
  279. package/dist/simulation-BwZx2pgt.d.cts +782 -0
  280. package/dist/{standard-match-phase-BucA5dYo.d.ts → standard-match-phase-D4N-AU0d.d.cts} +3 -13
  281. package/dist/{standard-match-phase-U2ra8J-0.d.cts → standard-match-phase-abt8ZjCh.d.ts} +3 -13
  282. package/dist/transport-CWF29jU6.d.cts +173 -0
  283. package/dist/transport-CWF29jU6.d.ts +173 -0
  284. package/dist/types-p28maMEo.d.cts +102 -0
  285. package/dist/types-p28maMEo.d.ts +102 -0
  286. package/dist/ui.cjs +2324 -1051
  287. package/dist/ui.cjs.map +1 -1
  288. package/dist/ui.d.cts +75 -17
  289. package/dist/ui.d.ts +75 -17
  290. package/dist/ui.js +555 -389
  291. package/dist/ui.js.map +1 -1
  292. package/package.json +88 -37
  293. package/src/agent/agent-action.ts +0 -39
  294. package/src/agent/agent-contract-conformance.ts +208 -0
  295. package/src/agent/agent-contract.ts +2 -4
  296. package/src/agent/agent-evaluator.ts +95 -0
  297. package/src/agent/capture-canvas.ts +79 -0
  298. package/src/agent/host-canvas-capture.ts +189 -0
  299. package/src/agent-tooling.ts +8 -18
  300. package/src/arcade/bridge/controller.ts +8 -11
  301. package/src/arcade/bridge/host.ts +6 -11
  302. package/src/arcade/bridge/iframe.ts +1 -50
  303. package/src/arcade/host.ts +0 -1
  304. package/src/arcade/runtime.ts +6 -0
  305. package/src/arcade/surface.ts +6 -1
  306. package/src/arcade/url.ts +2 -9
  307. package/src/audio/audio-manager.ts +23 -47
  308. package/src/audio/hooks.tsx +59 -72
  309. package/src/components/controller-player-name-field.tsx +2 -2
  310. package/src/components/controller-primary-action.tsx +1 -1
  311. package/src/components/controls.tsx +398 -0
  312. package/src/components/gamepad-layout.tsx +69 -0
  313. package/src/components/join-url-controls.tsx +5 -1
  314. package/src/components/lifecycle-action-group.tsx +1 -1
  315. package/src/components/player-avatar.tsx +50 -3
  316. package/src/components/room-qr-code.tsx +36 -77
  317. package/src/components/stage-capture-surface.tsx +91 -0
  318. package/src/components/surface-viewport.tsx +16 -3
  319. package/src/components/ui/button.tsx +1 -1
  320. package/src/constants.ts +0 -15
  321. package/src/context/air-jam-context.tsx +64 -195
  322. package/src/context/session-providers.tsx +13 -10
  323. package/src/controller-bridge.ts +7 -0
  324. package/src/core/assets.ts +48 -0
  325. package/src/core/config.ts +70 -0
  326. package/src/core/connection-store.ts +77 -0
  327. package/src/core/controller-input.ts +147 -0
  328. package/src/core/controller-runtime.ts +427 -0
  329. package/src/core/dev-events.ts +18 -0
  330. package/src/core/environment.ts +132 -0
  331. package/src/core/game-description.ts +44 -0
  332. package/src/core/game.ts +130 -0
  333. package/src/core/host-input.ts +207 -0
  334. package/src/core/host-runtime.ts +988 -0
  335. package/src/core/hosted-rooms.ts +26 -0
  336. package/src/core/input-bindings.ts +180 -0
  337. package/src/core/input-log.ts +144 -0
  338. package/src/core/input.ts +228 -0
  339. package/src/core/local-input.ts +319 -0
  340. package/src/core/replay-input-log.ts +298 -0
  341. package/src/core/replicated-store.ts +1178 -0
  342. package/src/core/room-action-ack.ts +43 -0
  343. package/src/core/settings.ts +202 -0
  344. package/src/core/simulation.ts +307 -0
  345. package/src/core/theme.ts +33 -0
  346. package/src/core.ts +162 -0
  347. package/src/dev/browser-log-sink.ts +47 -27
  348. package/src/diagnostics.ts +5 -6
  349. package/src/hooks/internal/use-controller-runtime-api.ts +58 -836
  350. package/src/hooks/internal/use-host-runtime-api.ts +98 -1013
  351. package/src/hooks/internal/use-runtime-inspection-contract.ts +14 -2
  352. package/src/hooks/use-air-jam-controller.ts +41 -62
  353. package/src/hooks/use-air-jam-host.ts +66 -107
  354. package/src/hooks/use-air-jam-settings.ts +27 -0
  355. package/src/hooks/use-controller-toasts.ts +16 -19
  356. package/src/hooks/use-host-agent-capture.ts +31 -0
  357. package/src/hooks/use-lifecycle-action-group-model.ts +1 -1
  358. package/src/hooks/use-send-signal.ts +23 -156
  359. package/src/hooks/use-simulation.ts +83 -0
  360. package/src/index.ts +26 -106
  361. package/src/lifecycle/index.ts +0 -4
  362. package/src/lifecycle/standard-match-phase.ts +1 -22
  363. package/src/metadata/manifest.ts +8 -20
  364. package/src/metadata.ts +1 -1
  365. package/src/platform-machine.ts +236 -15
  366. package/src/prefabs/types.ts +91 -20
  367. package/src/prefabs/view.ts +82 -0
  368. package/src/prefabs.ts +19 -0
  369. package/src/preview/host-workspace.tsx +4 -9
  370. package/src/preview/identity.ts +31 -23
  371. package/src/preview/layout.ts +5 -1
  372. package/src/preview/manager.ts +205 -78
  373. package/src/preview/messages.ts +47 -0
  374. package/src/preview/ownership.ts +6 -1
  375. package/src/preview/url.ts +46 -23
  376. package/src/preview/window.tsx +26 -69
  377. package/src/preview/workspace-local-seats.ts +166 -0
  378. package/src/preview/workspace.tsx +137 -66
  379. package/src/preview.ts +27 -15
  380. package/src/protocol/actions.ts +58 -0
  381. package/src/protocol/arcade-platform-actions.ts +20 -16
  382. package/src/protocol/controller.ts +15 -169
  383. package/src/protocol/core.ts +8 -15
  384. package/src/protocol/dev-log-events.ts +5 -84
  385. package/src/protocol/leased-control.ts +177 -0
  386. package/src/protocol/room/addressing.ts +35 -0
  387. package/src/protocol/room/close-codes.ts +33 -0
  388. package/src/protocol/room/frames.ts +343 -0
  389. package/src/protocol/room/input-codec.ts +182 -0
  390. package/src/protocol/room/limits.ts +58 -0
  391. package/src/protocol/room/patch.ts +135 -0
  392. package/src/protocol/room/sdk-channels.ts +81 -0
  393. package/src/protocol/room/seat-id.ts +31 -0
  394. package/src/protocol/room/transport.ts +63 -0
  395. package/src/protocol/room/weight.ts +58 -0
  396. package/src/protocol/runtime-reporting.ts +78 -0
  397. package/src/protocol/signed-envelope.ts +176 -0
  398. package/src/protocol.ts +4 -7
  399. package/src/qrcode.d.ts +3 -13
  400. package/src/release.ts +32 -0
  401. package/src/room-protocol.ts +10 -0
  402. package/src/room-session/browser-wake-events.ts +14 -0
  403. package/src/room-session/channel-state.ts +293 -0
  404. package/src/room-session/clock.ts +24 -0
  405. package/src/room-session/host-room-session.ts +379 -0
  406. package/src/room-session/input-lane.ts +125 -0
  407. package/src/room-session/listeners.ts +22 -0
  408. package/src/room-session/loopback-link.ts +58 -0
  409. package/src/room-session/phone-room-session.ts +368 -0
  410. package/src/room-session/port-link.ts +116 -0
  411. package/src/room-session/room-key.ts +9 -0
  412. package/src/room-session/roster.ts +23 -0
  413. package/src/room-session/scoped-connector.ts +577 -0
  414. package/src/room-session/session-link.ts +306 -0
  415. package/src/room-session/web-socket-link.ts +57 -0
  416. package/src/room-session.ts +12 -0
  417. package/src/runtime/air-jam-config.ts +53 -51
  418. package/src/runtime/air-jam-error-boundary.tsx +52 -2
  419. package/src/runtime/arcade-runtime-url.ts +8 -9
  420. package/src/runtime/browser-controller-environment.ts +116 -0
  421. package/src/runtime/browser-host-environment.ts +137 -0
  422. package/src/runtime/browser-replay.ts +211 -0
  423. package/src/runtime/browser-room.ts +41 -0
  424. package/src/runtime/connected-runtime-error-boundary.tsx +58 -0
  425. package/src/runtime/contracts/agent-control.ts +195 -0
  426. package/src/runtime/contracts/clip.ts +169 -0
  427. package/src/runtime/contracts/control.ts +744 -59
  428. package/src/runtime/contracts/controller-agent.ts +130 -0
  429. package/src/runtime/contracts/input-log.ts +38 -0
  430. package/src/runtime/contracts/inspection.ts +25 -22
  431. package/src/runtime/contracts/observation.ts +186 -0
  432. package/src/runtime/contracts/runtime-identity.ts +43 -0
  433. package/src/runtime/contracts/timeline.ts +59 -0
  434. package/src/runtime/controller-agent-bridge.ts +152 -0
  435. package/src/runtime/controller-bridge-context.ts +29 -0
  436. package/src/runtime/controller-capture.ts +50 -0
  437. package/src/runtime/controller-identity.ts +54 -115
  438. package/src/runtime/controller-presentation.ts +47 -17
  439. package/src/runtime/controller-press.ts +271 -0
  440. package/src/runtime/create-air-jam-app.tsx +120 -83
  441. package/src/runtime/dev-runtime-events.ts +6 -18
  442. package/src/runtime/embedded-parent.ts +22 -0
  443. package/src/runtime/embedded-runtime-adapters.ts +10 -9
  444. package/src/runtime/host-agent-bridge.ts +127 -0
  445. package/src/runtime/host-capture-boundary.tsx +92 -0
  446. package/src/runtime/host-capture-context.ts +7 -0
  447. package/src/runtime/host-clip-reader.ts +93 -0
  448. package/src/runtime/host-clip-recorder.ts +342 -0
  449. package/src/runtime/host-input-log-reader.ts +120 -0
  450. package/src/runtime/host-observation.ts +207 -0
  451. package/src/runtime/host-pace.ts +36 -0
  452. package/src/runtime/host-runtime-fault.ts +51 -0
  453. package/src/runtime/host-timeline.ts +152 -0
  454. package/src/runtime/local-players.tsx +96 -0
  455. package/src/runtime/local-reference-game-identity.ts +13 -0
  456. package/src/runtime/local-seats.ts +612 -0
  457. package/src/runtime/participant-control.ts +162 -0
  458. package/src/runtime/prefab-inspection-bridge.ts +174 -0
  459. package/src/runtime/prefab-inspection-clock.ts +12 -0
  460. package/src/runtime/prefab-inspection-context.ts +20 -0
  461. package/src/runtime/prefab-inspection-runtime.tsx +328 -0
  462. package/src/runtime/preview-inspection-bridge.ts +130 -0
  463. package/src/runtime/replay-runtime.tsx +101 -0
  464. package/src/runtime/room-bridge.ts +110 -0
  465. package/src/runtime/runtime-owner-contexts.tsx +9 -0
  466. package/src/runtime/runtime-session-params.ts +23 -86
  467. package/src/runtime/session-runtimes.tsx +231 -64
  468. package/src/runtime/stage-capture.ts +25 -0
  469. package/src/runtime-control.ts +44 -8
  470. package/src/runtime-inspection.ts +14 -7
  471. package/src/runtime-topology.ts +7 -8
  472. package/src/settings/platform-settings-runtime.tsx +48 -8
  473. package/src/settings/platform-settings.ts +0 -96
  474. package/src/store/use-air-jam-store.ts +73 -0
  475. package/src/ui.ts +3 -3
  476. package/src/utils/is-rpc-serializable.ts +11 -19
  477. package/src/utils/url-builder.ts +0 -7
  478. package/dist/arcade/bridge.cjs +0 -1067
  479. package/dist/arcade/bridge.cjs.map +0 -1
  480. package/dist/arcade/bridge.d.cts +0 -11
  481. package/dist/arcade/bridge.d.ts +0 -11
  482. package/dist/arcade/bridge.js +0 -76
  483. package/dist/arcade/bridge.js.map +0 -1
  484. package/dist/arcade-runtime-url-BW-MUAOY.d.cts +0 -28
  485. package/dist/arcade-runtime-url-l8qj01Pg.d.ts +0 -28
  486. package/dist/arcade.cjs +0 -1737
  487. package/dist/arcade.cjs.map +0 -1
  488. package/dist/arcade.d.cts +0 -18
  489. package/dist/arcade.d.ts +0 -18
  490. package/dist/arcade.js +0 -123
  491. package/dist/arcade.js.map +0 -1
  492. package/dist/capabilities.cjs +0 -39
  493. package/dist/capabilities.cjs.map +0 -1
  494. package/dist/capabilities.d.cts +0 -31
  495. package/dist/capabilities.d.ts +0 -31
  496. package/dist/capabilities.js +0 -12
  497. package/dist/capabilities.js.map +0 -1
  498. package/dist/chunk-32NYL7XI.js +0 -539
  499. package/dist/chunk-32NYL7XI.js.map +0 -1
  500. package/dist/chunk-3USU7GY2.js.map +0 -1
  501. package/dist/chunk-6CMB356F.js +0 -193
  502. package/dist/chunk-6CMB356F.js.map +0 -1
  503. package/dist/chunk-7OTQTT6H.js.map +0 -1
  504. package/dist/chunk-BE6Z4SIT.js.map +0 -1
  505. package/dist/chunk-CVYR5RJT.js +0 -184
  506. package/dist/chunk-CVYR5RJT.js.map +0 -1
  507. package/dist/chunk-DY67S3LR.js.map +0 -1
  508. package/dist/chunk-E5PVHEAX.js +0 -126
  509. package/dist/chunk-E5PVHEAX.js.map +0 -1
  510. package/dist/chunk-EDRQIOCV.js +0 -25
  511. package/dist/chunk-EDRQIOCV.js.map +0 -1
  512. package/dist/chunk-EVZJA6RN.js.map +0 -1
  513. package/dist/chunk-IKKDONQL.js +0 -1
  514. package/dist/chunk-IKKDONQL.js.map +0 -1
  515. package/dist/chunk-JO2HR5PV.js +0 -43
  516. package/dist/chunk-JO2HR5PV.js.map +0 -1
  517. package/dist/chunk-JTF47B56.js +0 -1
  518. package/dist/chunk-JTF47B56.js.map +0 -1
  519. package/dist/chunk-KOB73SPD.js +0 -216
  520. package/dist/chunk-KOB73SPD.js.map +0 -1
  521. package/dist/chunk-LIXPF4P6.js +0 -22
  522. package/dist/chunk-LIXPF4P6.js.map +0 -1
  523. package/dist/chunk-M4DKOI42.js +0 -32
  524. package/dist/chunk-M4DKOI42.js.map +0 -1
  525. package/dist/chunk-MPDMJIX5.js +0 -1
  526. package/dist/chunk-MPDMJIX5.js.map +0 -1
  527. package/dist/chunk-NCL6WJCL.js.map +0 -1
  528. package/dist/chunk-NUJBMV3O.js.map +0 -1
  529. package/dist/chunk-Q4UALQO4.js +0 -288
  530. package/dist/chunk-Q4UALQO4.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-UWJOIVON.js.map +0 -1
  534. package/dist/chunk-W2VK36RO.js +0 -11
  535. package/dist/chunk-W2VK36RO.js.map +0 -1
  536. package/dist/chunk-X24K52DG.js.map +0 -1
  537. package/dist/chunk-YXHH3MQT.js +0 -230
  538. package/dist/chunk-YXHH3MQT.js.map +0 -1
  539. package/dist/chunk-ZLPL2R3R.js.map +0 -1
  540. package/dist/chunk-ZTQ5SP4H.js +0 -9
  541. package/dist/chunk-ZTQ5SP4H.js.map +0 -1
  542. package/dist/controller-Bod8YYr1.d.cts +0 -172
  543. package/dist/controller-DxVchfiA.d.ts +0 -172
  544. package/dist/dev-log-events-CVAM29hx.d.cts +0 -123
  545. package/dist/dev-log-events-CVAM29hx.d.ts +0 -123
  546. package/dist/handshake-CC_LrK5g.d.cts +0 -31
  547. package/dist/handshake-CC_LrK5g.d.ts +0 -31
  548. package/dist/host-8hmq_Sgc.d.cts +0 -109
  549. package/dist/host-Cw-N6e-5.d.ts +0 -109
  550. package/dist/notices-CnGaaS8B.d.ts +0 -38
  551. package/dist/notices-NyDM5Mtz.d.cts +0 -38
  552. package/dist/realtime-client-Cu8yVJFw.d.cts +0 -15
  553. package/dist/realtime-client-Cu8yVJFw.d.ts +0 -15
  554. package/dist/sync-B6QsNrXz.d.cts +0 -125
  555. package/dist/sync-B6QsNrXz.d.ts +0 -125
  556. package/src/arcade/bridge.ts +0 -3
  557. package/src/arcade.ts +0 -4
  558. package/src/capabilities/manifest.ts +0 -71
  559. package/src/capabilities.ts +0 -12
  560. package/src/context/socket-manager.ts +0 -79
  561. package/src/events.ts +0 -124
  562. package/src/hooks/internal/use-runtime-control-contract.ts +0 -15
  563. package/src/hooks/internal/use-runtime-observability-contract.ts +0 -24
  564. package/src/hooks/use-connection-status.ts +0 -8
  565. package/src/hooks/use-controller-tick.ts +0 -65
  566. package/src/hooks/use-get-input.ts +0 -100
  567. package/src/hooks/use-host-arcade-restore.ts +0 -30
  568. package/src/hooks/use-host-tick.ts +0 -171
  569. package/src/hooks/use-input-writer.ts +0 -83
  570. package/src/hooks/use-players.ts +0 -12
  571. package/src/internal/input-manager.ts +0 -356
  572. package/src/protocol/errors.ts +0 -21
  573. package/src/protocol/host-grant.ts +0 -185
  574. package/src/protocol/host.ts +0 -138
  575. package/src/protocol/notices.ts +0 -43
  576. package/src/protocol/signals.ts +0 -38
  577. package/src/protocol/socket-events.ts +0 -154
  578. package/src/protocol/sync.ts +0 -121
  579. package/src/runtime/contracts/observability.ts +0 -94
  580. package/src/runtime/controller-bridge.ts +0 -451
  581. package/src/runtime/controller-realtime-client.ts +0 -591
  582. package/src/runtime/host-bridge.ts +0 -388
  583. package/src/runtime/host-realtime-client.ts +0 -550
  584. package/src/runtime/realtime-client.ts +0 -20
  585. package/src/runtime/validate-arcade-bridge-attach.ts +0 -14
  586. package/src/runtime-observability.ts +0 -9
  587. package/src/state/connection-store.ts +0 -152
  588. package/src/store/create-air-jam-store.ts +0 -1141
  589. package/src/store/index.ts +0 -1
  590. package/src/utils/ids.ts +0 -31
@@ -0,0 +1,1178 @@
1
+ import { nanoid } from "nanoid";
2
+ import { createStore, type StateCreator, type StoreApi } from "zustand/vanilla";
3
+ import { emitAirJamDiagnostic } from "../diagnostics";
4
+ import {
5
+ airJamActionInvocationResultSchema,
6
+ type AirJamActionActor,
7
+ type AirJamActionActorRole,
8
+ type AirJamActionInvocationResult,
9
+ type AirJamActionPayload,
10
+ } from "../protocol/actions";
11
+ import { AIRJAM_DEV_LOG_EVENTS } from "../protocol/dev-log-events";
12
+ import type { ChannelCopy, SeatId, StateDocument } from "../room-protocol";
13
+ import type { PublishOptions } from "../room-session/channel-state";
14
+ import type { RoomRequestOutcome } from "../room-session/phone-room-session";
15
+ import {
16
+ isHostRuntimeParticipantLeased,
17
+ registerHostRuntimeActionStore,
18
+ } from "../runtime/contracts/control";
19
+ import { isRpcSerializable } from "../utils/is-rpc-serializable";
20
+ import type { AirJamConnectionState } from "./connection-store";
21
+ import type { AirJamDevRuntimeEventDetail } from "./dev-events";
22
+ import type { SettingsValues } from "./settings";
23
+
24
+ const INTERNAL_ACTION_PREFIX = "_";
25
+
26
+ export type AirJamPrivateField<T> = {
27
+ [K in Exclude<keyof T, "actions">]: T[K] extends Record<string, unknown>
28
+ ? string extends keyof T[K]
29
+ ? K
30
+ : never
31
+ : never;
32
+ }[Exclude<keyof T, "actions">] &
33
+ string;
34
+
35
+ export type AirJamPrivateEntry<
36
+ T,
37
+ K extends AirJamPrivateField<T> = AirJamPrivateField<T>,
38
+ > = T[K] extends Record<string, infer Entry> ? Entry : never;
39
+
40
+ export interface CreateAirJamStoreOptions<
41
+ T = never,
42
+ K extends AirJamPrivateField<T> = AirJamPrivateField<T>,
43
+ > {
44
+ privateField?: K;
45
+ storeDomain?: string;
46
+ }
47
+
48
+ const isEventLikePayload = (payload: unknown): boolean => {
49
+ if (payload === null || typeof payload !== "object") {
50
+ return false;
51
+ }
52
+
53
+ const candidate = payload as Record<string, unknown>;
54
+ return (
55
+ typeof candidate.preventDefault === "function" ||
56
+ typeof candidate.stopPropagation === "function" ||
57
+ typeof candidate.persist === "function" ||
58
+ ("nativeEvent" in candidate &&
59
+ ("target" in candidate || "currentTarget" in candidate))
60
+ );
61
+ };
62
+
63
+ const isPlainActionPayload = (
64
+ payload: unknown,
65
+ ): payload is AirJamActionPayload => {
66
+ if (
67
+ payload === null ||
68
+ typeof payload !== "object" ||
69
+ Array.isArray(payload)
70
+ ) {
71
+ return false;
72
+ }
73
+
74
+ const prototype = Object.getPrototypeOf(payload);
75
+ return prototype === Object.prototype || prototype === null;
76
+ };
77
+
78
+ export interface AirJamActionContext<TSettings = Record<string, never>> {
79
+ settings: TSettings;
80
+ actorId: string;
81
+ role: AirJamActionActorRole;
82
+ connectedPlayerIds: string[];
83
+ /**
84
+ * Game time in milliseconds when the action runs: the simulation's time when
85
+ * the game declares one, else the host's clock. Read it instead of the wall
86
+ * clock so headless runs and replays see the same time.
87
+ */
88
+ now: number;
89
+ }
90
+
91
+ export interface AirJamActionRejection {
92
+ readonly __airJamActionRejection: true;
93
+ reason: string;
94
+ message: string;
95
+ details?: AirJamActionPayload;
96
+ }
97
+
98
+ export interface AirJamActionAcceptance<TResult = unknown> {
99
+ readonly __airJamActionAcceptance: true;
100
+ result?: TResult;
101
+ }
102
+
103
+ type AirJamActionHandler = {
104
+ invoke(
105
+ ctx: AirJamActionContext<SettingsValues>,
106
+ // Internal existential handler shape for heterogenous action maps.
107
+ // Store authors still get precise payload types through inference at the public API.
108
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
109
+ payload: any,
110
+ ): unknown;
111
+ }["invoke"];
112
+ export type AirJamActionMap = Record<string, AirJamActionHandler>;
113
+ export type AirJamActionName<TActions extends AirJamActionMap> = Extract<
114
+ keyof TActions,
115
+ string
116
+ >;
117
+
118
+ type IsValidActionPayloadType<TPayload> = [TPayload] extends [undefined]
119
+ ? true
120
+ : TPayload extends readonly unknown[]
121
+ ? false
122
+ : TPayload extends object
123
+ ? true
124
+ : false;
125
+
126
+ export type InvalidActionPayloadKeys<TActions extends AirJamActionMap> = {
127
+ [K in keyof TActions]: TActions[K] extends (
128
+ ctx: infer _Context,
129
+ payload: infer TPayload,
130
+ ) => unknown
131
+ ? IsValidActionPayloadType<TPayload> extends true
132
+ ? never
133
+ : K
134
+ : K;
135
+ }[keyof TActions];
136
+
137
+ type InvalidActionPayloadKeyNames<TActions extends AirJamActionMap> = Extract<
138
+ InvalidActionPayloadKeys<TActions>,
139
+ string
140
+ >;
141
+
142
+ export type AirJamInvalidActionPayloadDiagnostic<
143
+ TActions extends AirJamActionMap,
144
+ > = {
145
+ readonly __airJamInvalidActionPayloads__: InvalidActionPayloadKeyNames<TActions>;
146
+ readonly __airJamActionPayloadRule__: "Networked store action payloads must be omitted or one plain object payload. Unions like T | undefined, arrays, and primitives are not valid payload roots.";
147
+ };
148
+
149
+ export type AirJamNetworkedState<
150
+ TActions extends AirJamActionMap = AirJamActionMap,
151
+ > = {
152
+ actions: TActions;
153
+ };
154
+
155
+ export type AirJamActionDispatchMap<TActions extends AirJamActionMap> = {
156
+ [K in keyof TActions]: TActions[K] extends (
157
+ ctx: infer _Context,
158
+ payload: infer TPayload,
159
+ ) => infer TResult
160
+ ? [TPayload] extends [undefined]
161
+ ? () => Promise<
162
+ AirJamActionInvocationResult<InferAirJamActionResult<TResult>>
163
+ >
164
+ : TPayload extends readonly unknown[]
165
+ ? never
166
+ : TPayload extends object
167
+ ? (
168
+ payload: TPayload,
169
+ ) => Promise<
170
+ AirJamActionInvocationResult<InferAirJamActionResult<TResult>>
171
+ >
172
+ : never
173
+ : never;
174
+ };
175
+
176
+ export type InferAirJamActionResult<TResult> =
177
+ TResult extends AirJamActionAcceptance<infer TAccepted>
178
+ ? TAccepted
179
+ : TResult extends AirJamActionRejection
180
+ ? never
181
+ : TResult;
182
+
183
+ interface StoreRuntimeSnapshot {
184
+ room: AirJamStoreRoom | null;
185
+ roomId: string | null;
186
+ resolvedStoreDomain: string;
187
+ controllerId: string | null;
188
+ connectedPlayerIds: string[];
189
+ now: () => number;
190
+ settings?: () => SettingsValues;
191
+ }
192
+
193
+ /** One invocation of a store action, from the host itself or a phone's request. */
194
+ export interface StoreActionCall {
195
+ actionName: string;
196
+ payload: unknown;
197
+ storeDomain: string;
198
+ actor: AirJamActionActor;
199
+ }
200
+
201
+ export type AirJamHostActionEvent<
202
+ TActions extends AirJamActionMap = AirJamActionMap,
203
+ TActionName extends AirJamActionName<TActions> = AirJamActionName<TActions>,
204
+ > =
205
+ TActionName extends AirJamActionName<TActions>
206
+ ? TActions[TActionName] extends (
207
+ ctx: infer _Context,
208
+ payload: infer TPayload,
209
+ ) => infer TResult
210
+ ? {
211
+ actionName: TActionName;
212
+ payload: TPayload;
213
+ context: AirJamActionContext<SettingsValues>;
214
+ acknowledgement: AirJamActionInvocationResult<
215
+ InferAirJamActionResult<TResult>
216
+ >;
217
+ invocationKind: "local" | "rpc";
218
+ roomId: string | null;
219
+ storeDomain: string;
220
+ }
221
+ : never
222
+ : never;
223
+
224
+ export interface AirJamHostActionSubscriptionOptions<
225
+ TActions extends AirJamActionMap = AirJamActionMap,
226
+ > {
227
+ actionNames?: readonly AirJamActionName<TActions>[];
228
+ includeRejected?: boolean;
229
+ }
230
+
231
+ export type AirJamHostActionListener<
232
+ TActions extends AirJamActionMap = AirJamActionMap,
233
+ > = (event: AirJamHostActionEvent<TActions>) => void;
234
+
235
+ interface HostActionListenerRegistration<TActions extends AirJamActionMap> {
236
+ actionNames: ReadonlySet<string> | null;
237
+ includeRejected: boolean;
238
+ listener: AirJamHostActionListener<TActions>;
239
+ }
240
+
241
+ /** A phone's request on a store's channel, stamped by the room with its seat. */
242
+ export interface AirJamStoreRequest {
243
+ readonly seat: SeatId;
244
+ readonly name: string;
245
+ readonly payload: unknown;
246
+ }
247
+
248
+ /**
249
+ * The room as a replicated store sees it: on the host, the channel it
250
+ * publishes and the requests it answers; on a phone, the channel it mirrors
251
+ * and the requests it makes. The store's domain is its channel.
252
+ */
253
+ export type AirJamStoreRoom =
254
+ | {
255
+ readonly role: "host";
256
+ publish(
257
+ channel: string,
258
+ document: StateDocument,
259
+ options: PublishOptions,
260
+ ): void;
261
+ /**
262
+ * Calls `restore` once, with the room's copy of the channel, when this
263
+ * host first returns to a room that holds one.
264
+ */
265
+ onRestore(
266
+ channel: string,
267
+ restore: (copy: ChannelCopy) => void,
268
+ ): () => void;
269
+ /** Answers phones' requests on the channel with what `answer` returns. */
270
+ answer(
271
+ channel: string,
272
+ answer: (request: AirJamStoreRequest) => unknown,
273
+ ): () => void;
274
+ }
275
+ | {
276
+ readonly role: "controller";
277
+ document(channel: string): StateDocument | undefined;
278
+ /** Calls `listener` with each new copy of the channel. */
279
+ onDocument(
280
+ channel: string,
281
+ listener: (document: StateDocument) => void,
282
+ ): () => void;
283
+ request(
284
+ channel: string,
285
+ name: string,
286
+ payload: unknown,
287
+ ): Promise<RoomRequestOutcome>;
288
+ };
289
+
290
+ /** The room connection a replicated store syncs through while attached. */
291
+ export interface AirJamStoreSession {
292
+ room: AirJamStoreRoom;
293
+ connection: StoreApi<AirJamConnectionState>;
294
+ /** The store domain used when a store declares none. */
295
+ defaultStoreDomain: string;
296
+ emitDevEvent?: (detail: AirJamDevRuntimeEventDetail) => void;
297
+ /** Host only: where agent tools and devtools find this store's control. */
298
+ controlTarget: object | null;
299
+ /** The surface's game clock; actions the host runs read it as `ctx.now`. */
300
+ now: () => number;
301
+ settings?: () => SettingsValues;
302
+ }
303
+
304
+ /** What a runtime needs from a store it attaches, whatever the store holds. */
305
+ export interface AttachableStore {
306
+ attach: (session: AirJamStoreSession) => () => void;
307
+ readonly attached: boolean;
308
+ /** Runs an action a recorded match applied between steps, as its recorded actor, when it belongs to this store. */
309
+ replayAction(call: StoreActionCall): void;
310
+ subscribeHostActions(
311
+ listener: AirJamHostActionListener,
312
+ options?: AirJamHostActionSubscriptionOptions,
313
+ ): () => void;
314
+ }
315
+
316
+ /**
317
+ * A store whose state the host owns and controllers mirror. Its actions run
318
+ * on the host; controllers invoke them over the room. It syncs while a runtime
319
+ * that declares it runs; React reads it with `useAirJamStore`.
320
+ */
321
+ export interface AirJamStore<
322
+ T extends AirJamNetworkedState,
323
+ PrivateEntry = AirJamPrivateEntry<T>,
324
+ > extends AttachableStore {
325
+ readonly api: StoreApi<T>;
326
+ getState: () => T;
327
+ getPrivateState: () => PrivateEntry | undefined;
328
+ subscribe: StoreApi<T>["subscribe"];
329
+ /** Public actions dispatched as the local surface: the host runs them, a controller sends them. */
330
+ readonly actions: AirJamActionDispatchMap<T["actions"]>;
331
+ asPlayer: (controllerId: string) => AirJamActionDispatchMap<T["actions"]>;
332
+ subscribeHostActions: (
333
+ listener: AirJamHostActionListener<T["actions"]>,
334
+ options?: AirJamHostActionSubscriptionOptions<T["actions"]>,
335
+ ) => () => void;
336
+ }
337
+
338
+ export const isInternalActionName = (actionName: string): boolean =>
339
+ actionName.startsWith(INTERNAL_ACTION_PREFIX);
340
+
341
+ export const acceptAirJamAction = <TResult = unknown>(
342
+ result?: TResult,
343
+ ): AirJamActionAcceptance<TResult> => ({
344
+ __airJamActionAcceptance: true,
345
+ ...(result !== undefined ? { result } : {}),
346
+ });
347
+
348
+ export const rejectAirJamAction = (
349
+ reason: string,
350
+ message: string,
351
+ details?: AirJamActionPayload,
352
+ ): AirJamActionRejection => ({
353
+ __airJamActionRejection: true,
354
+ reason,
355
+ message,
356
+ ...(details ? { details } : {}),
357
+ });
358
+
359
+ const isAirJamActionAcceptance = (
360
+ value: unknown,
361
+ ): value is AirJamActionAcceptance<unknown> =>
362
+ typeof value === "object" &&
363
+ value !== null &&
364
+ (value as { __airJamActionAcceptance?: boolean }).__airJamActionAcceptance ===
365
+ true;
366
+
367
+ const isAirJamActionRejection = (
368
+ value: unknown,
369
+ ): value is AirJamActionRejection =>
370
+ typeof value === "object" &&
371
+ value !== null &&
372
+ (value as { __airJamActionRejection?: boolean }).__airJamActionRejection ===
373
+ true;
374
+
375
+ const createClientRejectedActionResult = (
376
+ reason: string,
377
+ message: string,
378
+ details?: AirJamActionPayload,
379
+ ): AirJamActionInvocationResult => ({
380
+ ok: false,
381
+ status: "rejected",
382
+ source: "client",
383
+ reason,
384
+ message,
385
+ ...(details ? { details } : {}),
386
+ });
387
+
388
+ const createServerRejectedActionResult = (
389
+ reason: string,
390
+ message: string,
391
+ details?: AirJamActionPayload,
392
+ ): AirJamActionInvocationResult => ({
393
+ ok: false,
394
+ status: "rejected",
395
+ source: "server",
396
+ reason,
397
+ message,
398
+ ...(details ? { details } : {}),
399
+ });
400
+
401
+ const normalizeAirJamActionInvocationResult = (
402
+ value: unknown,
403
+ source: "client" | "host",
404
+ ): AirJamActionInvocationResult => {
405
+ if (isAirJamActionRejection(value)) {
406
+ return {
407
+ ok: false,
408
+ status: "rejected",
409
+ source,
410
+ reason: value.reason,
411
+ message: value.message,
412
+ ...(value.details ? { details: value.details } : {}),
413
+ };
414
+ }
415
+
416
+ if (isAirJamActionAcceptance(value)) {
417
+ return {
418
+ ok: true,
419
+ status: "accepted",
420
+ source,
421
+ ...(value.result !== undefined ? { result: value.result } : {}),
422
+ };
423
+ }
424
+
425
+ return {
426
+ ok: true,
427
+ status: "accepted",
428
+ source,
429
+ ...(value !== undefined ? { result: value } : {}),
430
+ };
431
+ };
432
+
433
+ /** A phone's action result from how its request on the store's channel ended. */
434
+ export const airJamActionResultOf = (
435
+ outcome: RoomRequestOutcome,
436
+ ): AirJamActionInvocationResult => {
437
+ switch (outcome.status) {
438
+ case "answered": {
439
+ const parsed = airJamActionInvocationResultSchema.safeParse(
440
+ outcome.result,
441
+ );
442
+ return parsed.success
443
+ ? parsed.data
444
+ : createServerRejectedActionResult(
445
+ "invalid_answer",
446
+ "The host's answer was not an action result.",
447
+ );
448
+ }
449
+ case "refused":
450
+ return createServerRejectedActionResult(
451
+ "host_away",
452
+ "The host is away, so the action did not run.",
453
+ );
454
+ case "unconfirmed":
455
+ case "busy":
456
+ return { ok: false, status: "unconfirmed", source: "client" };
457
+ }
458
+ };
459
+
460
+ const stripActionsFromState = <T extends AirJamNetworkedState>(
461
+ data: Partial<T>,
462
+ ): Partial<T> => {
463
+ const { actions: _ignored, ...stateData } = data as Partial<T> & {
464
+ actions?: unknown;
465
+ };
466
+ return stateData as Partial<T>;
467
+ };
468
+
469
+ /**
470
+ * A store's shape as a bounded fingerprint: two FNV-1a passes over its
471
+ * canonical shape, 64 bits as hex, so any store fits the state frame.
472
+ */
473
+ const shapeFingerprintOf = (shape: string): string => {
474
+ let first = 0x811c9dc5;
475
+ let second = 0x01000193;
476
+ for (let index = 0; index < shape.length; index += 1) {
477
+ const code = shape.charCodeAt(index);
478
+ first = Math.imul(first ^ code, 0x01000193) >>> 0;
479
+ second = Math.imul(second ^ code, 0x811c9dc5) >>> 0;
480
+ }
481
+ return `${first.toString(16).padStart(8, "0")}${second.toString(16).padStart(8, "0")}`;
482
+ };
483
+
484
+ const stateShape = (value: unknown): string => {
485
+ if (value === null) return "null";
486
+ if (Array.isArray(value)) {
487
+ return `array[${[...new Set(value.map(stateShape))].sort().join(",")}]`;
488
+ }
489
+ if (typeof value === "object") {
490
+ return `object{${Object.keys(value)
491
+ .sort()
492
+ .map(
493
+ (key) =>
494
+ `${JSON.stringify(key)}:${stateShape(Reflect.get(value, key))}`,
495
+ )
496
+ .join(",")}}`;
497
+ }
498
+ return typeof value;
499
+ };
500
+
501
+ const toActionContext = (
502
+ call: StoreActionCall,
503
+ runtime: StoreRuntimeSnapshot,
504
+ ): AirJamActionContext<SettingsValues> => ({
505
+ actorId: call.actor.id,
506
+ role: call.actor.role,
507
+ connectedPlayerIds: runtime.connectedPlayerIds,
508
+ now: runtime.now(),
509
+ settings: runtime.settings?.() ?? {},
510
+ });
511
+
512
+ const detachedClock = (): number => {
513
+ throw new Error("This Air Jam store is not attached to a running session.");
514
+ };
515
+
516
+ /** How long an action called before its session connects waits for it. */
517
+ const AIR_JAM_ACTION_SESSION_WAIT_MS = 10_000;
518
+
519
+ /**
520
+ * Creates a networked Zustand store that syncs state from host to controllers.
521
+ *
522
+ * Host is the source of truth:
523
+ * - Host broadcasts state updates to all controllers.
524
+ * - Controllers invoke actions through RPC to host.
525
+ *
526
+ * `storeDomain` isolates sync and action RPC so multiple replicated stores can coexist in one room
527
+ * (e.g. arcade shell vs running game). When omitted, resolves from the runtime URL: explicit
528
+ * `aj_store_domain`, else embedded Arcade identity (`aj_arcade_*`), else the default domain.
529
+ */
530
+ /**
531
+ * Creates a networked store. The host is the source of truth: it applies
532
+ * actions and broadcasts state; controllers invoke actions through RPC and
533
+ * mirror the state. Declare the store in the game so its runtimes sync it.
534
+ *
535
+ * `storeDomain` isolates sync and action RPC so several stores can share a
536
+ * room (e.g. an Arcade shell and its game). When omitted, it follows the
537
+ * runtime's environment: an explicit `aj_store_domain`, else the embedded
538
+ * Arcade identity, else the default domain.
539
+ */
540
+ export function createAirJamStore<
541
+ T extends AirJamNetworkedState,
542
+ K extends AirJamPrivateField<T> = AirJamPrivateField<T>,
543
+ >(
544
+ initializer: InvalidActionPayloadKeys<T["actions"]> extends never
545
+ ? StateCreator<T>
546
+ : StateCreator<T> & AirJamInvalidActionPayloadDiagnostic<T["actions"]>,
547
+ options?: CreateAirJamStoreOptions<T, K>,
548
+ ): AirJamStore<T, AirJamPrivateEntry<T, K>> {
549
+ const store = createStore<T>((set, get, api) => initializer(set, get, api));
550
+ const shapeFingerprint = shapeFingerprintOf(
551
+ stateShape(stripActionsFromState<T>(store.getInitialState())),
552
+ );
553
+ const privateField = options?.privateField;
554
+ const privateEntries = (state: Partial<T>): Record<string, unknown> => {
555
+ if (!privateField) return {};
556
+ const entries = state[privateField];
557
+ if (!entries || typeof entries !== "object" || Array.isArray(entries))
558
+ throw new Error(
559
+ "A private store field must be a map keyed by controllerId.",
560
+ );
561
+ return entries as Record<string, unknown>;
562
+ };
563
+ const projectState = (state: Partial<T>, controllerId: string | null) => {
564
+ const data = { ...state };
565
+ if (privateField) {
566
+ const entry = controllerId
567
+ ? privateEntries(state)[controllerId]
568
+ : undefined;
569
+ Object.assign(data, {
570
+ [privateField]:
571
+ controllerId && entry !== undefined ? { [controllerId]: entry } : {},
572
+ });
573
+ }
574
+ return data;
575
+ };
576
+ if (privateField) privateEntries(store.getState());
577
+ const stateEpoch = nanoid();
578
+ const runtimeSnapshotRef: { current: StoreRuntimeSnapshot } = {
579
+ current: {
580
+ room: null,
581
+ roomId: null,
582
+ resolvedStoreDomain: "",
583
+ controllerId: null,
584
+ connectedPlayerIds: [],
585
+ now: detachedClock,
586
+ },
587
+ };
588
+ // Actions called before a runtime attaches the store (for example from a
589
+ // component that mounts before its runtime starts) wait for it instead of
590
+ // being dropped. Once attached, a phone's requests wait in its session
591
+ // while its link is down.
592
+ const sessionWaiters = new Set<() => void>();
593
+ const sessionReady = (runtime: StoreRuntimeSnapshot) => runtime.room !== null;
594
+ const waitForSession = () =>
595
+ new Promise<StoreRuntimeSnapshot>((resolve) => {
596
+ const finish = () => {
597
+ clearTimeout(timeout);
598
+ sessionWaiters.delete(finish);
599
+ resolve(runtimeSnapshotRef.current);
600
+ };
601
+ const timeout = setTimeout(finish, AIR_JAM_ACTION_SESSION_WAIT_MS);
602
+ sessionWaiters.add(finish);
603
+ });
604
+ const hostActionListeners = new Set<
605
+ HostActionListenerRegistration<T["actions"]>
606
+ >();
607
+
608
+ const createDispatchedActions = (
609
+ ownerStore: StoreApi<T>,
610
+ mode:
611
+ | {
612
+ kind: "default";
613
+ }
614
+ | {
615
+ kind: "player";
616
+ controllerId: string;
617
+ },
618
+ ): AirJamActionDispatchMap<T["actions"]> => {
619
+ const sourceActions = ownerStore.getState().actions;
620
+ const actionDispatch = {} as AirJamActionDispatchMap<T["actions"]>;
621
+
622
+ for (const actionName of Object.keys(sourceActions)) {
623
+ if (isInternalActionName(actionName)) {
624
+ continue;
625
+ }
626
+
627
+ const sourceAction = sourceActions[actionName];
628
+
629
+ (
630
+ actionDispatch as unknown as Record<
631
+ string,
632
+ (payload: unknown) => Promise<AirJamActionInvocationResult>
633
+ >
634
+ )[actionName] = async (
635
+ payload: unknown,
636
+ ): Promise<AirJamActionInvocationResult> => {
637
+ const normalizedPayload = isEventLikePayload(payload)
638
+ ? undefined
639
+ : payload;
640
+
641
+ if (normalizedPayload !== payload) {
642
+ emitAirJamDiagnostic({
643
+ code: "AJ_STORE_ACTION_EVENT_PAYLOAD_DROPPED",
644
+ severity: "warn",
645
+ message: `[AirJamConnectionState] Action "${actionName}" received an event-like payload. Dropping payload and continuing.`,
646
+ details: { actionName },
647
+ });
648
+ }
649
+
650
+ const runtime = sessionReady(runtimeSnapshotRef.current)
651
+ ? runtimeSnapshotRef.current
652
+ : await waitForSession();
653
+
654
+ const role = runtime.room?.role ?? null;
655
+ if (mode.kind === "player" && role !== "host") {
656
+ emitAirJamDiagnostic({
657
+ code: "AJ_STORE_PLAYER_ACTIONS_HOST_ONLY",
658
+ severity: "warn",
659
+ message: `[AirJamConnectionState] Player impersonation for action "${actionName}" is host-only.`,
660
+ details: {
661
+ actionName,
662
+ role,
663
+ controllerId: mode.controllerId,
664
+ },
665
+ });
666
+ return createClientRejectedActionResult(
667
+ "player_actions_host_only",
668
+ `Store action "${actionName}" cannot impersonate a player outside the host runtime.`,
669
+ {
670
+ actionName,
671
+ ...(role ? { role } : {}),
672
+ controllerId: mode.controllerId,
673
+ },
674
+ );
675
+ }
676
+
677
+ if (mode.kind === "player") {
678
+ const normalizedControllerId = mode.controllerId.trim();
679
+ if (normalizedControllerId.length === 0) {
680
+ emitAirJamDiagnostic({
681
+ code: "AJ_STORE_PLAYER_ACTIONS_INVALID_ACTOR_ID",
682
+ severity: "warn",
683
+ message: `[AirJamConnectionState] Player impersonation for action "${actionName}" requires a non-empty controller id.`,
684
+ details: {
685
+ actionName,
686
+ },
687
+ });
688
+ return createClientRejectedActionResult(
689
+ "player_actor_id_invalid",
690
+ `Store action "${actionName}" requires a non-empty controller id for player impersonation.`,
691
+ {
692
+ actionName,
693
+ },
694
+ );
695
+ }
696
+
697
+ if (!runtime.connectedPlayerIds.includes(normalizedControllerId)) {
698
+ emitAirJamDiagnostic({
699
+ code: "AJ_STORE_PLAYER_ACTIONS_PLAYER_NOT_CONNECTED",
700
+ severity: "warn",
701
+ message: `[AirJamConnectionState] Player impersonation for action "${actionName}" requires a currently connected controller.`,
702
+ details: {
703
+ actionName,
704
+ controllerId: normalizedControllerId,
705
+ connectedPlayerIds: runtime.connectedPlayerIds,
706
+ },
707
+ });
708
+ return createClientRejectedActionResult(
709
+ "player_not_connected",
710
+ `Store action "${actionName}" cannot impersonate controller "${normalizedControllerId}" because it is not currently connected.`,
711
+ {
712
+ actionName,
713
+ controllerId: normalizedControllerId,
714
+ },
715
+ );
716
+ }
717
+ }
718
+
719
+ if (role === "host") {
720
+ try {
721
+ const context =
722
+ mode.kind === "player"
723
+ ? ({
724
+ actorId: mode.controllerId.trim(),
725
+ role: "controller",
726
+ connectedPlayerIds: runtime.connectedPlayerIds,
727
+ now: runtime.now(),
728
+ settings: runtime.settings?.() ?? {},
729
+ } satisfies AirJamActionContext<SettingsValues>)
730
+ : ({
731
+ actorId: "host",
732
+ role: "host",
733
+ connectedPlayerIds: runtime.connectedPlayerIds,
734
+ now: runtime.now(),
735
+ settings: runtime.settings?.() ?? {},
736
+ } satisfies AirJamActionContext<SettingsValues>);
737
+ const result = sourceAction(context, normalizedPayload);
738
+ const acknowledgement = normalizeAirJamActionInvocationResult(
739
+ result,
740
+ "host",
741
+ );
742
+ const typedActionName = actionName as AirJamActionName<
743
+ T["actions"]
744
+ >;
745
+ notifyHostActionListeners({
746
+ actionName: typedActionName,
747
+ payload: normalizedPayload,
748
+ context,
749
+ acknowledgement,
750
+ invocationKind: "local",
751
+ roomId: runtime.roomId,
752
+ storeDomain: runtime.resolvedStoreDomain,
753
+ } as AirJamHostActionEvent<T["actions"], typeof typedActionName>);
754
+ return acknowledgement;
755
+ } catch (error) {
756
+ const acknowledgement = {
757
+ ok: false,
758
+ status: "rejected",
759
+ source: "host",
760
+ reason: "handler_error",
761
+ message: error instanceof Error ? error.message : String(error),
762
+ } satisfies AirJamActionInvocationResult;
763
+ const typedActionName = actionName as AirJamActionName<
764
+ T["actions"]
765
+ >;
766
+ notifyHostActionListeners({
767
+ actionName: typedActionName,
768
+ payload: normalizedPayload,
769
+ context: {
770
+ actorId:
771
+ mode.kind === "player" ? mode.controllerId.trim() : "host",
772
+ role: mode.kind === "player" ? "controller" : "host",
773
+ connectedPlayerIds: runtime.connectedPlayerIds,
774
+ now: runtime.now(),
775
+ settings: runtime.settings?.() ?? {},
776
+ },
777
+ acknowledgement,
778
+ invocationKind: "local",
779
+ roomId: runtime.roomId,
780
+ storeDomain: runtime.resolvedStoreDomain,
781
+ } as AirJamHostActionEvent<T["actions"], typeof typedActionName>);
782
+ return acknowledgement;
783
+ }
784
+ }
785
+
786
+ const room = runtime.room;
787
+ if (!room || room.role !== "controller") {
788
+ emitAirJamDiagnostic({
789
+ code: "AJ_STORE_ACTION_SESSION_NOT_READY",
790
+ severity: "error",
791
+ message: `[AirJamConnectionState] Action "${actionName}" dropped: the session was not ready within ${AIR_JAM_ACTION_SESSION_WAIT_MS / 1000} s.`,
792
+ details: { actionName },
793
+ });
794
+ return createClientRejectedActionResult(
795
+ "session_not_ready",
796
+ `Store action "${actionName}" cannot run because the controller session is not ready.`,
797
+ { actionName },
798
+ );
799
+ }
800
+
801
+ if (!isRpcSerializable(normalizedPayload)) {
802
+ emitAirJamDiagnostic({
803
+ code: "AJ_STORE_ACTION_PAYLOAD_NOT_SERIALIZABLE",
804
+ severity: "warn",
805
+ message: `[AirJamConnectionState] Action "${actionName}" blocked: payload must be RPC-serializable.`,
806
+ details: { actionName },
807
+ });
808
+ return createClientRejectedActionResult(
809
+ "payload_not_serializable",
810
+ `Store action "${actionName}" requires an RPC-serializable payload.`,
811
+ { actionName },
812
+ );
813
+ }
814
+
815
+ if (
816
+ normalizedPayload !== undefined &&
817
+ !isPlainActionPayload(normalizedPayload)
818
+ ) {
819
+ emitAirJamDiagnostic({
820
+ code: "AJ_STORE_ACTION_PAYLOAD_INVALID_SHAPE",
821
+ severity: "warn",
822
+ message: `[AirJamConnectionState] Action "${actionName}" blocked: payload must be omitted or a plain object.`,
823
+ details: { actionName },
824
+ });
825
+ return createClientRejectedActionResult(
826
+ "payload_invalid_shape",
827
+ `Store action "${actionName}" requires an omitted payload or a plain object payload.`,
828
+ { actionName },
829
+ );
830
+ }
831
+
832
+ return airJamActionResultOf(
833
+ await room.request(
834
+ runtime.resolvedStoreDomain,
835
+ actionName,
836
+ normalizedPayload,
837
+ ),
838
+ );
839
+ };
840
+ }
841
+
842
+ return actionDispatch;
843
+ };
844
+
845
+ const notifyHostActionListeners = <
846
+ TActionName extends AirJamActionName<T["actions"]>,
847
+ >(
848
+ event: AirJamHostActionEvent<T["actions"], TActionName>,
849
+ ): void => {
850
+ for (const registration of hostActionListeners) {
851
+ if (
852
+ registration.actionNames &&
853
+ !registration.actionNames.has(event.actionName)
854
+ ) {
855
+ continue;
856
+ }
857
+
858
+ if (
859
+ !registration.includeRejected &&
860
+ event.acknowledgement.status === "rejected"
861
+ ) {
862
+ continue;
863
+ }
864
+
865
+ try {
866
+ registration.listener(event);
867
+ } catch (error) {
868
+ console.error(
869
+ `[AirJamConnectionState] Host action listener for "${event.actionName}" threw.`,
870
+ error,
871
+ );
872
+ }
873
+ }
874
+ };
875
+
876
+ const dispatchActionCall = (
877
+ call: StoreActionCall,
878
+ ): AirJamActionInvocationResult => {
879
+ const { actionName } = call;
880
+ if (isInternalActionName(actionName)) {
881
+ return createServerRejectedActionResult(
882
+ "internal_action",
883
+ "Internal store actions cannot be invoked by controllers.",
884
+ );
885
+ }
886
+
887
+ const runtime = runtimeSnapshotRef.current;
888
+ const actionFn = store.getState().actions[actionName];
889
+ if (typeof actionFn !== "function") {
890
+ return createServerRejectedActionResult(
891
+ "action_not_found",
892
+ `Store action "${actionName}" is not registered on the host.`,
893
+ {
894
+ actionName,
895
+ storeDomain: call.storeDomain,
896
+ },
897
+ );
898
+ }
899
+
900
+ const context = toActionContext(call, runtime);
901
+ let acknowledgement: AirJamActionInvocationResult;
902
+ try {
903
+ acknowledgement = normalizeAirJamActionInvocationResult(
904
+ actionFn(context, call.payload),
905
+ "host",
906
+ );
907
+ } catch (error) {
908
+ acknowledgement = {
909
+ ok: false,
910
+ status: "rejected",
911
+ source: "host",
912
+ reason: "handler_error",
913
+ message: error instanceof Error ? error.message : String(error),
914
+ };
915
+ }
916
+ const typedActionName = actionName as AirJamActionName<T["actions"]>;
917
+ notifyHostActionListeners({
918
+ actionName: typedActionName,
919
+ payload: call.payload,
920
+ context,
921
+ acknowledgement,
922
+ invocationKind: "rpc",
923
+ roomId: runtime.roomId,
924
+ storeDomain: call.storeDomain,
925
+ } as AirJamHostActionEvent<T["actions"], typeof typedActionName>);
926
+ return acknowledgement;
927
+ };
928
+
929
+ /** What the host publishes: the state without its actions, private entries whole. */
930
+ const documentOf = (state: T): StateDocument =>
931
+ stripActionsFromState<T>(state) as StateDocument;
932
+ const publishOptions: PublishOptions = {
933
+ fingerprint: shapeFingerprint,
934
+ ...(privateField ? { private: privateField } : {}),
935
+ };
936
+ /** Counts the host's changes, so agents reading the store can tell one state from the next. */
937
+ let hostRevision = 0;
938
+
939
+ const bindHost = (
940
+ room: Extract<AirJamStoreRoom, { role: "host" }>,
941
+ channel: string,
942
+ session: AirJamStoreSession,
943
+ ): (() => void) => {
944
+ room.publish(channel, documentOf(store.getState()), publishOptions);
945
+ const unsubscribe = store.subscribe((state) => {
946
+ hostRevision += 1;
947
+ room.publish(channel, documentOf(state), publishOptions);
948
+ });
949
+ const stopRestore = room.onRestore(channel, (copy) => {
950
+ if (copy.fingerprint !== shapeFingerprint) {
951
+ session.emitDevEvent?.({
952
+ event: AIRJAM_DEV_LOG_EVENTS.host.stateRestoreDiscarded,
953
+ level: "info",
954
+ role: "host",
955
+ roomId: runtimeSnapshotRef.current.roomId ?? undefined,
956
+ message:
957
+ "Host kept fresh state because the restored store shape changed",
958
+ data: { storeDomain: channel, reason: "shape_changed" },
959
+ });
960
+ return;
961
+ }
962
+ store.setState(
963
+ stripActionsFromState<T>({
964
+ ...store.getState(),
965
+ ...(copy.document as Partial<T>),
966
+ }),
967
+ );
968
+ });
969
+ const stopAnswering = room.answer(channel, (request) => {
970
+ const controlTarget = session.controlTarget;
971
+ const roomId = runtimeSnapshotRef.current.roomId;
972
+ if (
973
+ controlTarget &&
974
+ roomId &&
975
+ isHostRuntimeParticipantLeased(controlTarget, roomId, request.seat)
976
+ )
977
+ return createServerRejectedActionResult(
978
+ "participant_control_leased",
979
+ "This controller is owned by a participant-control lease.",
980
+ );
981
+ return dispatchActionCall({
982
+ actionName: request.name,
983
+ payload: request.payload,
984
+ storeDomain: channel,
985
+ actor: { id: request.seat, role: "controller" },
986
+ });
987
+ });
988
+ return () => {
989
+ unsubscribe();
990
+ stopRestore();
991
+ stopAnswering();
992
+ };
993
+ };
994
+
995
+ /** Agent tools and devtools find a host's store through its room's control registry. */
996
+ const registerControl = (
997
+ controlTarget: object,
998
+ roomId: string,
999
+ channel: string,
1000
+ ): (() => void) => {
1001
+ const canUseHostControl = () => {
1002
+ const runtime = runtimeSnapshotRef.current;
1003
+ return runtime.room?.role === "host" && runtime.roomId === roomId;
1004
+ };
1005
+ return registerHostRuntimeActionStore(controlTarget, {
1006
+ roomId,
1007
+ storeDomain: channel,
1008
+ stateEpoch,
1009
+ contractStoreDomain: options?.storeDomain?.trim() || "default",
1010
+ read: (controllerId) => {
1011
+ if (!canUseHostControl()) throw new Error("host_runtime_not_ready");
1012
+ return {
1013
+ data:
1014
+ controllerId === undefined
1015
+ ? stripActionsFromState<T>(store.getState())
1016
+ : projectState(
1017
+ stripActionsFromState<T>(store.getState()),
1018
+ controllerId,
1019
+ ),
1020
+ revision: hostRevision,
1021
+ };
1022
+ },
1023
+ dispatchParticipant: ({ controllerId, actionName, payload }) => {
1024
+ if (!canUseHostControl())
1025
+ return createClientRejectedActionResult(
1026
+ "host_runtime_not_ready",
1027
+ "The owning host runtime is not ready for actions.",
1028
+ );
1029
+ return dispatchActionCall({
1030
+ actionName,
1031
+ payload,
1032
+ storeDomain: channel,
1033
+ actor: { id: controllerId, role: "controller" },
1034
+ });
1035
+ },
1036
+ invoke: async ({ actionName, payload }) => {
1037
+ if (!canUseHostControl())
1038
+ return createClientRejectedActionResult(
1039
+ "host_runtime_not_ready",
1040
+ "The owning host runtime is not ready for actions.",
1041
+ );
1042
+ const actions = createDispatchedActions(store, { kind: "default" });
1043
+ if (!Object.hasOwn(actions, actionName))
1044
+ return createClientRejectedActionResult(
1045
+ "action_not_found",
1046
+ "The requested public action is not registered on this host store.",
1047
+ );
1048
+ const invoke = actions[actionName] as (
1049
+ payload: unknown,
1050
+ ) => Promise<AirJamActionInvocationResult>;
1051
+ return invoke(payload);
1052
+ },
1053
+ });
1054
+ };
1055
+
1056
+ const bindController = (
1057
+ room: Extract<AirJamStoreRoom, { role: "controller" }>,
1058
+ channel: string,
1059
+ ): (() => void) => {
1060
+ const mirror = (document: StateDocument) =>
1061
+ store.setState(stripActionsFromState<T>(document as Partial<T>));
1062
+ const current = room.document(channel);
1063
+ if (current) mirror(current);
1064
+ return room.onDocument(channel, mirror);
1065
+ };
1066
+
1067
+ const resolveStoreDomain = (defaultStoreDomain: string): string => {
1068
+ const explicit = options?.storeDomain?.trim();
1069
+ if (!explicit) return defaultStoreDomain;
1070
+ return explicit.length > 128 ? explicit.slice(0, 128) : explicit;
1071
+ };
1072
+
1073
+ let attachedSession: AirJamStoreSession | null = null;
1074
+
1075
+ const attach = (session: AirJamStoreSession): (() => void) => {
1076
+ if (attachedSession)
1077
+ throw new Error(
1078
+ "This Air Jam store is already attached to a running session.",
1079
+ );
1080
+ attachedSession = session;
1081
+ const channel = resolveStoreDomain(session.defaultStoreDomain);
1082
+ let control: { roomId: string; release: () => void } | null = null;
1083
+
1084
+ const update = (): void => {
1085
+ const connection = session.connection.getState();
1086
+ runtimeSnapshotRef.current = {
1087
+ room: session.room,
1088
+ roomId: connection.roomId,
1089
+ resolvedStoreDomain: channel,
1090
+ controllerId: connection.controllerId,
1091
+ connectedPlayerIds: connection.players
1092
+ .filter((player) => player.connected)
1093
+ .map((player) => player.id)
1094
+ .sort(),
1095
+ now: session.now,
1096
+ settings: session.settings,
1097
+ };
1098
+ for (const release of [...sessionWaiters]) release();
1099
+ const controlTarget = session.controlTarget;
1100
+ const roomId = connection.roomId;
1101
+ if (control?.roomId === roomId) return;
1102
+ control?.release();
1103
+ control =
1104
+ controlTarget && roomId && session.room.role === "host"
1105
+ ? { roomId, release: registerControl(controlTarget, roomId, channel) }
1106
+ : null;
1107
+ };
1108
+
1109
+ const unsubscribe = session.connection.subscribe(update);
1110
+ update();
1111
+ const unbind =
1112
+ session.room.role === "host"
1113
+ ? bindHost(session.room, channel, session)
1114
+ : bindController(session.room, channel);
1115
+ return () => {
1116
+ unsubscribe();
1117
+ unbind();
1118
+ control?.release();
1119
+ control = null;
1120
+ attachedSession = null;
1121
+ runtimeSnapshotRef.current = {
1122
+ ...runtimeSnapshotRef.current,
1123
+ room: null,
1124
+ roomId: null,
1125
+ now: detachedClock,
1126
+ };
1127
+ };
1128
+ };
1129
+
1130
+ const subscribeHostActions = (
1131
+ listener: AirJamHostActionListener<T["actions"]>,
1132
+ options?: AirJamHostActionSubscriptionOptions<T["actions"]>,
1133
+ ): (() => void) => {
1134
+ const actionNames =
1135
+ options?.actionNames && options.actionNames.length > 0
1136
+ ? new Set<string>(options.actionNames)
1137
+ : null;
1138
+ const registration: HostActionListenerRegistration<T["actions"]> = {
1139
+ actionNames,
1140
+ includeRejected: options?.includeRejected ?? false,
1141
+ listener,
1142
+ };
1143
+ hostActionListeners.add(registration);
1144
+ return () => {
1145
+ hostActionListeners.delete(registration);
1146
+ };
1147
+ };
1148
+
1149
+ return {
1150
+ api: store,
1151
+ getState: store.getState,
1152
+ getPrivateState: () => {
1153
+ const controllerId = runtimeSnapshotRef.current.controllerId;
1154
+ return controllerId && privateField
1155
+ ? (privateEntries(store.getState())[controllerId] as
1156
+ | AirJamPrivateEntry<T, K>
1157
+ | undefined)
1158
+ : undefined;
1159
+ },
1160
+ subscribe: store.subscribe,
1161
+ actions: createDispatchedActions(store, { kind: "default" }),
1162
+ asPlayer: (controllerId) =>
1163
+ createDispatchedActions(store, { kind: "player", controllerId }),
1164
+ subscribeHostActions,
1165
+ attach,
1166
+ replayAction: (call) => {
1167
+ const runtime = runtimeSnapshotRef.current;
1168
+ if (
1169
+ runtime.room?.role === "host" &&
1170
+ call.storeDomain === runtime.resolvedStoreDomain
1171
+ )
1172
+ dispatchActionCall(call);
1173
+ },
1174
+ get attached() {
1175
+ return attachedSession !== null;
1176
+ },
1177
+ };
1178
+ }