castle-web-cli 0.4.229 → 0.4.231

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 (259) hide show
  1. package/dist/agent-prompts.d.ts +2 -0
  2. package/dist/agent-prompts.js +16 -8
  3. package/dist/agent.d.ts +2 -0
  4. package/dist/agent.js +21 -21
  5. package/dist/api.d.ts +28 -2
  6. package/dist/api.js +74 -16
  7. package/dist/castle-host/host.d.ts +91 -0
  8. package/dist/castle-host/host.js +860 -3
  9. package/dist/castleJson.d.ts +44 -0
  10. package/dist/castleJson.js +131 -0
  11. package/dist/check.js +27 -1
  12. package/dist/contentPack.d.ts +49 -0
  13. package/dist/contentPack.js +273 -0
  14. package/dist/devExperiments.d.ts +21 -0
  15. package/dist/devExperiments.js +139 -0
  16. package/dist/devHub.d.ts +55 -0
  17. package/dist/devHub.js +187 -0
  18. package/dist/devSaveStorage.d.ts +36 -0
  19. package/dist/devSaveStorage.js +469 -0
  20. package/dist/devSessionChild.js +25 -13
  21. package/dist/devSessionServer.d.ts +14 -1
  22. package/dist/devSessionServer.js +237 -46
  23. package/dist/devSessionStorage.d.ts +9 -0
  24. package/dist/devSessionStorage.js +66 -1
  25. package/dist/experimentAssignment.d.ts +15 -0
  26. package/dist/experimentAssignment.js +41 -0
  27. package/dist/importCheckHook.d.ts +40 -0
  28. package/dist/importCheckHook.js +171 -0
  29. package/dist/importRegression.d.ts +15 -0
  30. package/dist/importRegression.js +100 -0
  31. package/dist/importTrust.d.ts +2 -0
  32. package/dist/importTrust.js +27 -0
  33. package/dist/importUpdateHook.d.ts +18 -0
  34. package/dist/importUpdateHook.js +31 -8
  35. package/dist/importUpdateHookRunner.js +19 -7
  36. package/dist/imports.d.ts +16 -0
  37. package/dist/imports.js +141 -31
  38. package/dist/index.js +3 -1
  39. package/dist/init.d.ts +3 -0
  40. package/dist/init.js +126 -9
  41. package/dist/install.js +4 -1
  42. package/dist/localPaths.js +4 -0
  43. package/dist/login.js +2 -2
  44. package/dist/platformDoc.js +3 -8
  45. package/dist/playPagePolicy.js +3 -1
  46. package/dist/remix.js +5 -0
  47. package/dist/routerTaskReport.d.ts +28 -0
  48. package/dist/routerTaskReport.js +56 -0
  49. package/dist/save-deck.d.ts +18 -0
  50. package/dist/save-deck.js +142 -6
  51. package/dist/serve.d.ts +8 -0
  52. package/dist/serve.js +99 -14
  53. package/dist/serverBundle.d.ts +1 -1
  54. package/dist/serverBundle.js +5 -1
  55. package/dist/webSourceSync.d.ts +2 -0
  56. package/dist/webSourceSync.js +2 -0
  57. package/kits/base/CLAUDE.md +2 -3
  58. package/kits/base/castle.json +1 -1
  59. package/kits/base/sdk/README.md +406 -53
  60. package/kits/base/sdk/agent.js +4 -4
  61. package/kits/base/sdk/avatar.d.ts +12 -0
  62. package/kits/base/sdk/avatar.js +23 -0
  63. package/kits/base/sdk/castle.d.ts +9 -0
  64. package/kits/base/sdk/castle.js +5 -0
  65. package/kits/base/sdk/commands.d.ts +223 -0
  66. package/kits/base/sdk/commands.js +16 -0
  67. package/kits/base/sdk/context.d.ts +6 -0
  68. package/kits/base/sdk/experiments.d.ts +15 -0
  69. package/kits/base/sdk/experiments.js +83 -0
  70. package/kits/base/sdk/hub.d.ts +85 -0
  71. package/kits/base/sdk/hub.js +107 -0
  72. package/kits/base/sdk/multiplayer.d.ts +45 -1
  73. package/kits/base/sdk/multiplayer.js +158 -8
  74. package/kits/base/sdk/save.d.ts +197 -0
  75. package/kits/base/sdk/save.js +525 -0
  76. package/kits/base/sdk/saveCoordinator.d.ts +39 -0
  77. package/kits/base/sdk/saveCoordinator.js +252 -0
  78. package/kits/base/sdk/server/hub.d.ts +169 -0
  79. package/kits/base/sdk/server/hub.js +125 -0
  80. package/kits/base/sdk/server/platformHandle.d.ts +42 -1
  81. package/kits/base/sdk/server/storage.d.ts +58 -4
  82. package/kits/base/sdk/server/storage.js +25 -5
  83. package/kits/base/sdk/server/wrapper.d.ts +36 -2
  84. package/kits/base/sdk/server/wrapper.js +92 -11
  85. package/kits/base/sdk/store.d.ts +3 -2
  86. package/kits/base/sdk/store.js +5 -0
  87. package/kits/base/sdk/transport.d.ts +2 -1
  88. package/kits/base/sdk/transport.js +13 -1
  89. package/kits/hub-game/.prettierrc +5 -0
  90. package/kits/hub-game/CLAUDE.md +149 -0
  91. package/kits/hub-game/blueprints/avatar-0.scene +28 -0
  92. package/kits/hub-game/blueprints/avatar-1.scene +28 -0
  93. package/kits/hub-game/blueprints/avatar-2.scene +28 -0
  94. package/kits/hub-game/blueprints/avatar-3.scene +28 -0
  95. package/kits/hub-game/blueprints/bean/avatar-0.scene +28 -0
  96. package/kits/hub-game/blueprints/bean/avatar-1.scene +28 -0
  97. package/kits/hub-game/blueprints/bean/avatar-2.scene +28 -0
  98. package/kits/hub-game/blueprints/bean/avatar-3.scene +28 -0
  99. package/kits/hub-game/blueprints/blocky/avatar-0.scene +28 -0
  100. package/kits/hub-game/blueprints/blocky/avatar-1.scene +28 -0
  101. package/kits/hub-game/blueprints/blocky/avatar-2.scene +28 -0
  102. package/kits/hub-game/blueprints/blocky/avatar-3.scene +28 -0
  103. package/kits/hub-game/blueprints/pixel/avatar-0.scene +28 -0
  104. package/kits/hub-game/blueprints/pixel/avatar-1.scene +28 -0
  105. package/kits/hub-game/blueprints/pixel/avatar-2.scene +28 -0
  106. package/kits/hub-game/blueprints/pixel/avatar-3.scene +28 -0
  107. package/kits/hub-game/castle.json +96 -0
  108. package/kits/hub-game/code/client/attention.js +133 -0
  109. package/kits/hub-game/code/client/avatar.js +288 -0
  110. package/kits/hub-game/code/client/cabinets.js +90 -0
  111. package/kits/hub-game/code/client/chat.js +135 -0
  112. package/kits/hub-game/code/client/chrome.js +1035 -0
  113. package/kits/hub-game/code/client/doorFrame.js +15 -0
  114. package/kits/hub-game/code/client/firstJoin.js +14 -0
  115. package/kits/hub-game/code/client/grab.js +376 -0
  116. package/kits/hub-game/code/client/hookLayer.js +236 -0
  117. package/kits/hub-game/code/client/idle.js +326 -0
  118. package/kits/hub-game/code/client/keys.js +48 -0
  119. package/kits/hub-game/code/client/pack.js +232 -0
  120. package/kits/hub-game/code/client/packFormat.js +397 -0
  121. package/kits/hub-game/code/client/say.js +127 -0
  122. package/kits/hub-game/code/client/sha256.js +80 -0
  123. package/kits/hub-game/code/client/sound.js +147 -0
  124. package/kits/hub-game/code/client/state.js +143 -0
  125. package/kits/hub-game/code/client/talk.js +233 -0
  126. package/kits/hub-game/code/client/tiers.js +480 -0
  127. package/kits/hub-game/code/client/together.js +440 -0
  128. package/kits/hub-game/code/client/wear.js +149 -0
  129. package/kits/hub-game/code/server/actors.js +627 -0
  130. package/kits/hub-game/code/server/blocks.js +103 -0
  131. package/kits/hub-game/code/server/cabinets.js +309 -0
  132. package/kits/hub-game/code/server/game.js +137 -0
  133. package/kits/hub-game/code/server/grab.js +248 -0
  134. package/kits/hub-game/code/server/history.js +96 -0
  135. package/kits/hub-game/code/server/hub.js +1998 -0
  136. package/kits/hub-game/code/server/idle.js +412 -0
  137. package/kits/hub-game/code/server/index.js +64 -0
  138. package/kits/hub-game/code/server/labels.js +59 -0
  139. package/kits/hub-game/code/server/manifest.js +554 -0
  140. package/kits/hub-game/code/server/npcs.js +733 -0
  141. package/kits/hub-game/code/server/party.js +439 -0
  142. package/kits/hub-game/code/server/place.js +43 -0
  143. package/kits/hub-game/code/server/say.js +83 -0
  144. package/kits/hub-game/code/server/wear.js +142 -0
  145. package/kits/hub-game/code/systems/hub.js +2347 -0
  146. package/kits/hub-game/docs/content-pack.md +151 -0
  147. package/kits/hub-game/docs/contract.md +1209 -0
  148. package/kits/hub-game/docs/style.md +137 -0
  149. package/kits/hub-game/drawings/blocky/castle-eye.sprite +58 -0
  150. package/kits/hub-game/drawings/blocky/dash.sprite +59 -0
  151. package/kits/hub-game/drawings/blocky/pom.sprite +59 -0
  152. package/kits/hub-game/drawings/blocky/tabby.sprite +59 -0
  153. package/kits/hub-game/drawings/pixel/castle-arm.sprite +13 -0
  154. package/kits/hub-game/drawings/pixel/castle-body.sprite +23 -0
  155. package/kits/hub-game/drawings/pixel/castle-leg.sprite +12 -0
  156. package/kits/hub-game/drawings/pixel/kai-arm.sprite +14 -0
  157. package/kits/hub-game/drawings/pixel/kai-head.sprite +24 -0
  158. package/kits/hub-game/drawings/pixel/kai-leg.sprite +15 -0
  159. package/kits/hub-game/drawings/pixel/kai-torso.sprite +18 -0
  160. package/kits/hub-game/drawings/pixel/mimi-arm.sprite +13 -0
  161. package/kits/hub-game/drawings/pixel/mimi-head.sprite +23 -0
  162. package/kits/hub-game/drawings/pixel/mimi-leg.sprite +15 -0
  163. package/kits/hub-game/drawings/pixel/mimi-torso.sprite +18 -0
  164. package/kits/hub-game/drawings/pixel/nox-arm.sprite +13 -0
  165. package/kits/hub-game/drawings/pixel/nox-head.sprite +21 -0
  166. package/kits/hub-game/drawings/pixel/nox-leg.sprite +14 -0
  167. package/kits/hub-game/drawings/pixel/nox-torso.sprite +18 -0
  168. package/kits/hub-game/eslint.config.js +20 -0
  169. package/kits/hub-game/fonts.generated.js +9 -0
  170. package/kits/hub-game/index.html +22 -0
  171. package/kits/hub-game/main.jsx +6 -0
  172. package/kits/hub-game/models/avatar-0.pxmodel +21 -0
  173. package/kits/hub-game/models/avatar-1.pxmodel +24 -0
  174. package/kits/hub-game/models/avatar-2.pxmodel +27 -0
  175. package/kits/hub-game/models/avatar-3.pxmodel +22 -0
  176. package/kits/hub-game/models/bean/avatar-0.pxmodel +19 -0
  177. package/kits/hub-game/models/bean/avatar-1.pxmodel +24 -0
  178. package/kits/hub-game/models/bean/avatar-2.pxmodel +22 -0
  179. package/kits/hub-game/models/bean/avatar-3.pxmodel +24 -0
  180. package/kits/hub-game/models/blocky/avatar-0.pxmodel +21 -0
  181. package/kits/hub-game/models/blocky/avatar-1.pxmodel +30 -0
  182. package/kits/hub-game/models/blocky/avatar-2.pxmodel +28 -0
  183. package/kits/hub-game/models/blocky/avatar-3.pxmodel +27 -0
  184. package/kits/hub-game/models/pixel/avatar-0.pxmodel +24 -0
  185. package/kits/hub-game/models/pixel/avatar-1.pxmodel +16 -0
  186. package/kits/hub-game/models/pixel/avatar-2.pxmodel +19 -0
  187. package/kits/hub-game/models/pixel/avatar-3.pxmodel +23 -0
  188. package/kits/hub-game/package-lock.json +365 -0
  189. package/kits/hub-game/package.json +32 -0
  190. package/kits/hub-game/scenes/main.scene +318 -0
  191. package/kits/hub-game/scripts/check.mjs +339 -0
  192. package/kits/hub-game/scripts/fixtures/sdk-stub.mjs +3 -0
  193. package/kits/hub-game/scripts/gen-avatars-bean.mjs +748 -0
  194. package/kits/hub-game/scripts/gen-avatars-blocky.mjs +607 -0
  195. package/kits/hub-game/scripts/gen-avatars-pixel.mjs +771 -0
  196. package/kits/hub-game/scripts/gen-avatars.mjs +621 -0
  197. package/kits/hub-game/scripts/pack.mjs +192 -0
  198. package/kits/hub-game/scripts/test-actors.mjs +666 -0
  199. package/kits/hub-game/scripts/test-attention.mjs +103 -0
  200. package/kits/hub-game/scripts/test-avatar.mjs +472 -0
  201. package/kits/hub-game/scripts/test-ban-join.mjs +194 -0
  202. package/kits/hub-game/scripts/test-blocks.mjs +351 -0
  203. package/kits/hub-game/scripts/test-chat.mjs +98 -0
  204. package/kits/hub-game/scripts/test-classic.mjs +590 -0
  205. package/kits/hub-game/scripts/test-door-jump.mjs +131 -0
  206. package/kits/hub-game/scripts/test-door.mjs +56 -0
  207. package/kits/hub-game/scripts/test-grab-client.mjs +328 -0
  208. package/kits/hub-game/scripts/test-grab.mjs +331 -0
  209. package/kits/hub-game/scripts/test-hub-ops.mjs +835 -0
  210. package/kits/hub-game/scripts/test-hub-trip.mjs +1518 -0
  211. package/kits/hub-game/scripts/test-idle.mjs +518 -0
  212. package/kits/hub-game/scripts/test-interest.mjs +413 -0
  213. package/kits/hub-game/scripts/test-keys.mjs +50 -0
  214. package/kits/hub-game/scripts/test-manifest.mjs +270 -0
  215. package/kits/hub-game/scripts/test-no-forms.mjs +16 -0
  216. package/kits/hub-game/scripts/test-npcs.mjs +724 -0
  217. package/kits/hub-game/scripts/test-pack.mjs +424 -0
  218. package/kits/hub-game/scripts/test-party.mjs +369 -0
  219. package/kits/hub-game/scripts/test-say.mjs +149 -0
  220. package/kits/hub-game/scripts/test-tiers.mjs +666 -0
  221. package/kits/hub-game/scripts/test-together.mjs +215 -0
  222. package/kits/hub-game/theme.style +3 -0
  223. package/kits/multiplayer-3d/castle.json +5 -5
  224. package/kits/multiplayer-3d/code/client/avatars.js +101 -1
  225. package/kits/multiplayer-3d/code/server/players.js +4 -1
  226. package/kits/multiplayer-3d/code/server/sceneBodies.js +27 -6
  227. package/kits/multiplayer-3d/code/server/world.js +20 -7
  228. package/kits/multiplayer-3d/code/systems/multiplayer.js +222 -11
  229. package/kits/physics-2d/CLAUDE.md +2 -0
  230. package/kits/physics-2d/castle.json +2 -2
  231. package/kits/physics-2d/engine/art.js +13 -0
  232. package/kits/physics-2d/engine/assets.js +4 -2
  233. package/kits/physics-2d/engine/scene.js +117 -5
  234. package/kits/physics-2d/package.json +1 -1
  235. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +254 -0
  236. package/kits/physics-3d/CLAUDE.md +285 -1
  237. package/kits/physics-3d/behaviors/Player.jsx +74 -1
  238. package/kits/physics-3d/castle.json +3 -3
  239. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +33 -5
  240. package/kits/physics-3d/engine3d/actornode.js +253 -0
  241. package/kits/physics-3d/engine3d/artobjects.js +2 -2
  242. package/kits/physics-3d/engine3d/materials.js +29 -1
  243. package/kits/physics-3d/engine3d/nearshadows.js +600 -0
  244. package/kits/physics-3d/engine3d/unchanged.js +153 -0
  245. package/kits/physics-3d/engine3d/world3d.js +527 -5
  246. package/kits/physics-3d/package.json +1 -1
  247. package/kits/physics-3d/scripts/test-camera-follow.mjs +533 -0
  248. package/kits/physics-3d/scripts/test-near-shadows.mjs +1073 -0
  249. package/kits/physics-3d/scripts/test-static-actors.mjs +662 -0
  250. package/kits/physics-3d/scripts/test-static-passes.mjs +459 -0
  251. package/kits/physics-3d/scripts/test-static-physics.mjs +128 -0
  252. package/kits/physics-3d/systems/physics3d.js +187 -5
  253. package/kits/real-time/castle.json +2 -2
  254. package/kits/real-time/code/client/connection.js +77 -7
  255. package/kits/real-time/code/client/gameHooks.js +63 -3
  256. package/kits/real-time/code/client/messages.js +7 -0
  257. package/kits/real-time/code/server/gameHooks.js +24 -0
  258. package/kits/real-time/code/server/session.js +390 -22
  259. package/package.json +2 -2
@@ -31,13 +31,27 @@ const COMMAND_NAMES = [
31
31
  "leaderboard.show",
32
32
  "user.getCurrent",
33
33
  "user.get",
34
+ "experiments.get",
34
35
  "time.getServerTime",
35
36
  "pass.has",
37
+ "avatar.get",
38
+ "avatar.set",
36
39
  "pass.offer",
37
40
  "snapshot.offer",
38
41
  "portal.open",
39
42
  "portal.prefetch",
40
43
  "portal.info",
44
+ "hub.go",
45
+ "hub.back",
46
+ "hub.doors",
47
+ "hub.friends",
48
+ "hub.jump",
49
+ "hub.report",
50
+ "hub.chat",
51
+ "hub.say",
52
+ "hub.reportChat",
53
+ "hub.commit",
54
+ "hub.cancel",
41
55
  "haptics.play",
42
56
  "multiplayer.getSession",
43
57
  "multiplayer.getJoinHint",
@@ -52,6 +66,11 @@ const COMMAND_NAMES = [
52
66
  "characters.status",
53
67
  "characters.history",
54
68
  "characters.reset",
69
+ "cauldronStorage.snapshot",
70
+ "cauldronStorage.operation",
71
+ "cauldronStorage.transaction",
72
+ "cauldronStorage.claim",
73
+ "cauldronStorage.initialize",
55
74
  "cauldronStorage.get",
56
75
  "cauldronStorage.set",
57
76
  "cauldronStorage.delete",
@@ -135,12 +154,24 @@ export async function executeCommand(ctx, command, params, capabilities, options
135
154
  }
136
155
  try {
137
156
  const data = await runCommand(ctx, command, (params ?? {}), capabilities, options);
157
+ noteAcquiredSession(ctx, command, data, capabilities);
138
158
  return { ok: true, data };
139
159
  }
140
160
  catch (error) {
141
161
  return { ok: false, error: toSerializedError(error, command) };
142
162
  }
143
163
  }
164
+ // A door's source is the session the deck last acquired in its place.
165
+ function noteAcquiredSession(ctx, command, data, caps) {
166
+ if (!caps.hub?.sessionAcquired ||
167
+ (command !== "multiplayer.getSession" && command !== "multiplayer.joinDestination")) {
168
+ return;
169
+ }
170
+ const result = data;
171
+ if (result?.status === "ok" && typeof result.sessionId === "string" && result.sessionId) {
172
+ caps.hub.sessionAcquired(result.sessionId, ctx);
173
+ }
174
+ }
144
175
  function runCommand(ctx, command, params, caps, options) {
145
176
  if (command === "multiplayer.getSession" && caps.getMultiplayerSession) {
146
177
  return caps.getMultiplayerSession(multiplayerSessionRequest(params), ctx);
@@ -181,12 +212,31 @@ function runCommand(ctx, command, params, caps, options) {
181
212
  return Promise.resolve(userGetCurrent(ctx));
182
213
  case "user.get":
183
214
  return userGet(params, gql);
215
+ case "experiments.get":
216
+ return Promise.resolve(experimentsGet(ctx));
184
217
  case "portal.info":
185
218
  return portalInfo(params, gql);
219
+ // Dormant `unavailable` on a host without `caps.hub`.
220
+ case "hub.go":
221
+ case "hub.back":
222
+ case "hub.doors":
223
+ case "hub.friends":
224
+ case "hub.jump":
225
+ case "hub.report":
226
+ case "hub.chat":
227
+ case "hub.say":
228
+ case "hub.reportChat":
229
+ case "hub.commit":
230
+ case "hub.cancel":
231
+ return runHubCommand(ctx, command, params, caps, options.signal);
186
232
  case "time.getServerTime":
187
233
  return timeGetServerTime(gql);
188
234
  case "pass.has":
189
235
  return passHas(ctx, params, caps);
236
+ case "avatar.get":
237
+ return avatarGet(gql);
238
+ case "avatar.set":
239
+ return avatarSet(ctx, params, gql);
190
240
  case "multiplayer.getSession":
191
241
  return multiplayerGetSession(ctx, params, caps);
192
242
  case "multiplayer.getJoinHint":
@@ -211,6 +261,12 @@ function runCommand(ctx, command, params, caps, options) {
211
261
  return charactersHistory(ctx, params, gql);
212
262
  case "characters.reset":
213
263
  return charactersReset(ctx, params, gql);
264
+ case "cauldronStorage.snapshot":
265
+ case "cauldronStorage.operation":
266
+ case "cauldronStorage.transaction":
267
+ case "cauldronStorage.claim":
268
+ case "cauldronStorage.initialize":
269
+ return cauldronSave(ctx, command, params, gql);
214
270
  case "cauldronStorage.get":
215
271
  return cauldronStorageGet(ctx, params, gql);
216
272
  case "cauldronStorage.set":
@@ -421,6 +477,61 @@ async function passHas(ctx, params, caps) {
421
477
  const match = (data.passesForDeck ?? []).find((p) => p?.passId === passId);
422
478
  return { hasPass: match?.isActive === true };
423
479
  }
480
+ // The platform avatar: ghost keeps it per account (anonymous accounts too), so
481
+ // these are plain GraphQL with the player's own auth. A signed-out visitor has
482
+ // no account to keep one on, which is `unavailable`, not an error: the deck
483
+ // picks its own. Only a curated hub place may change it: the host names the
484
+ // place the player is in (ctx.deckId, never the deck's word) and ghost refuses
485
+ // any other deck, which is `unavailable` too.
486
+ const AVATAR_QUERY = `query CastleAvatar { cauldronHubAvatar { avatar chosen } }`;
487
+ const SET_AVATAR_MUTATION = `mutation CastleSetAvatar($deckId: ID!, $avatar: Int!) {
488
+ setCauldronHubAvatar(deckId: $deckId, avatar: $avatar) { avatar chosen }
489
+ }`;
490
+ const AVATAR_UNAVAILABLE_CODES = new Set([
491
+ "LOGIN_REQUIRED",
492
+ "CAULDRON_HUB_AVATAR_NOT_A_PLACE",
493
+ ]);
494
+ // Bounds the argument only; ghost holds the real template count.
495
+ const AVATAR_MAX = 255;
496
+ function avatarResult(raw) {
497
+ const avatar = raw?.avatar;
498
+ return typeof avatar === "number" && Number.isInteger(avatar) && avatar >= 0
499
+ ? { status: "ok", avatar, chosen: raw?.chosen === true }
500
+ : unavailableAvatar();
501
+ }
502
+ function unavailableAvatar() {
503
+ return { status: "unavailable", avatar: null, chosen: false };
504
+ }
505
+ async function avatarGet(gql) {
506
+ try {
507
+ const data = await graphql(gql, AVATAR_QUERY, {}, "avatar.get");
508
+ return avatarResult(data.cauldronHubAvatar);
509
+ }
510
+ catch (error) {
511
+ if (error instanceof HostCommandError && AVATAR_UNAVAILABLE_CODES.has(error.code)) {
512
+ return unavailableAvatar();
513
+ }
514
+ throw error;
515
+ }
516
+ }
517
+ async function avatarSet(ctx, params, gql) {
518
+ const avatar = params.avatar;
519
+ if (typeof avatar !== "number" || !Number.isInteger(avatar) || avatar < 0 || avatar > AVATAR_MAX) {
520
+ throw new HostCommandError("INVALID_ARGUMENT", "avatar must be a template index.", "avatar.set");
521
+ }
522
+ if (!ctx.deckId)
523
+ return unavailableAvatar();
524
+ try {
525
+ const data = await graphql(gql, SET_AVATAR_MUTATION, { deckId: ctx.deckId, avatar }, "avatar.set");
526
+ return avatarResult(data.setCauldronHubAvatar);
527
+ }
528
+ catch (error) {
529
+ if (error instanceof HostCommandError && AVATAR_UNAVAILABLE_CODES.has(error.code)) {
530
+ return unavailableAvatar();
531
+ }
532
+ throw error;
533
+ }
534
+ }
424
535
  // A session id is ghost's: a deck id plus a short suffix, or a nanoid.
425
536
  const VOICE_SESSION_ID_MAX_LENGTH = 256;
426
537
  // A room holds at most 24 players; anything past this is a confused deck.
@@ -1076,6 +1187,16 @@ function userGetCurrent(ctx) {
1076
1187
  user: { userId: ctx.userId, username: ctx.username, isAnonymous: ctx.isAnonymous === true },
1077
1188
  };
1078
1189
  }
1190
+ // Answered from what the host already resolved, like the current user. Only
1191
+ // string variants are passed on, so a malformed context cannot reach the deck.
1192
+ function experimentsGet(ctx) {
1193
+ const source = ctx.experimentVariants;
1194
+ if (!source || typeof source !== "object" || Array.isArray(source))
1195
+ return { variants: {} };
1196
+ return {
1197
+ variants: Object.fromEntries(Object.entries(source).filter((entry) => typeof entry[1] === "string")),
1198
+ };
1199
+ }
1079
1200
  // One user's public profile, or null when there is no such user. The photo and
1080
1201
  // frame are fetched here and handed over as data: urls, since a deck's CSP
1081
1202
  // allows no image host and the host is outside it.
@@ -1403,7 +1524,7 @@ async function decksSaved(ctx, params, gql) {
1403
1524
  const playlists = await Promise.all(playlistIds.map((id) => feedDecks(gql, `playlist:${id}`, command).catch(() => [])));
1404
1525
  return decksResult([bookmarks, ...playlists].flat(), limit);
1405
1526
  }
1406
- // Decks is limited to Castle admins for now, like Agent.chat.
1527
+ // Decks is limited to Castle admins for now.
1407
1528
  async function requireDecksAdmin(gql, command) {
1408
1529
  if (!(await isCastleAdmin(gql, command))) {
1409
1530
  throw new HostCommandError("PERMISSION_DENIED", "Decks is limited to Castle admins.", command);
@@ -1489,8 +1610,9 @@ const DECKS_PLAYLISTS_QUERY = `
1489
1610
  // Agent chat.
1490
1611
  //
1491
1612
  // The deck-agent service is Castle's proxy to OpenRouter for decks. It decides
1492
- // who may call a model (Castle admins, for now), picks the default model, and
1493
- // charges each call to the player's daily play allowance, which Castle funds.
1613
+ // who may call a model (Castle admins and the players given access), picks the
1614
+ // default model, and charges each call to the player's daily play allowance,
1615
+ // which Castle funds.
1494
1616
  // It refuses before streaming with a status: 403 for a player it will not
1495
1617
  // serve, 429 once the allowance is spent. Otherwise it answers with a
1496
1618
  // server-sent event stream: OpenRouter's chunks, a heartbeat event every 15
@@ -2000,6 +2122,33 @@ function asStoreEntries(value, command) {
2000
2122
  };
2001
2123
  });
2002
2124
  }
2125
+ // A save is one GraphQL call taking its request as JSON. The deck's params are
2126
+ // that request; the deck id comes from the host.
2127
+ async function cauldronSave(ctx, command, params, gql) {
2128
+ const { field, query } = CAULDRON_SAVE_DOCUMENTS[command];
2129
+ const deckId = requireDeckId(ctx, command);
2130
+ const variables = command === "cauldronStorage.operation"
2131
+ ? { deckId, operationId: params.operationId }
2132
+ : { deckId, input: params };
2133
+ // One client charge cannot exceed the whole 512 KiB/s byte-rate window, so a
2134
+ // bigger request can never succeed.
2135
+ const encodedBytes = new TextEncoder().encode(JSON.stringify({ query, variables })).length;
2136
+ if (encodedBytes > CLIENT_SAVE_REQUEST_MAX_BYTES) {
2137
+ throw new HostCommandError("CAULDRON_STORAGE_TOO_LARGE", `The save request is ${encodedBytes} bytes, over the ${CLIENT_SAVE_REQUEST_MAX_BYTES} a client may send.`, command, {
2138
+ operationId: params.operationId,
2139
+ retryable: false,
2140
+ committed: false,
2141
+ encodedBytes,
2142
+ limitBytes: CLIENT_SAVE_REQUEST_MAX_BYTES,
2143
+ });
2144
+ }
2145
+ const data = await graphql(gql, query, variables, command);
2146
+ const result = data[field];
2147
+ if (result === null || result === undefined) {
2148
+ throw new HostCommandError("CAULDRON_STORAGE_INVALID_RESPONSE", "Storage returned no save result.", command, { operationId: params.operationId, retryable: false, committed: "unknown" });
2149
+ }
2150
+ return result;
2151
+ }
2003
2152
  async function cauldronStorageGet(ctx, params, gql) {
2004
2153
  const deckId = requireDeckId(ctx, "cauldronStorage.get");
2005
2154
  const data = await graphql(gql, CAULDRON_STORAGE_GET_QUERY, {
@@ -2506,6 +2655,49 @@ const CAULDRON_MULTIPLAYER_DESTINATION_SESSION_QUERY = `
2506
2655
  }
2507
2656
  }
2508
2657
  `;
2658
+ const CLIENT_SAVE_REQUEST_MAX_BYTES = 512 * 1024;
2659
+ const CAULDRON_SAVE_DOCUMENTS = {
2660
+ "cauldronStorage.snapshot": {
2661
+ field: "cauldronStorageSnapshot",
2662
+ query: `
2663
+ query CastleCauldronStorageSnapshot($deckId: ID!, $input: Json!) {
2664
+ cauldronStorageSnapshot(deckId: $deckId, input: $input)
2665
+ }
2666
+ `,
2667
+ },
2668
+ "cauldronStorage.operation": {
2669
+ field: "cauldronStorageOperation",
2670
+ query: `
2671
+ query CastleCauldronStorageOperation($deckId: ID!, $operationId: String!) {
2672
+ cauldronStorageOperation(deckId: $deckId, operationId: $operationId)
2673
+ }
2674
+ `,
2675
+ },
2676
+ "cauldronStorage.transaction": {
2677
+ field: "cauldronStorageTransaction",
2678
+ query: `
2679
+ mutation CastleCauldronStorageTransaction($deckId: ID!, $input: Json!) {
2680
+ cauldronStorageTransaction(deckId: $deckId, input: $input)
2681
+ }
2682
+ `,
2683
+ },
2684
+ "cauldronStorage.claim": {
2685
+ field: "cauldronStorageClaim",
2686
+ query: `
2687
+ mutation CastleCauldronStorageClaim($deckId: ID!, $input: Json!) {
2688
+ cauldronStorageClaim(deckId: $deckId, input: $input)
2689
+ }
2690
+ `,
2691
+ },
2692
+ "cauldronStorage.initialize": {
2693
+ field: "cauldronStorageInitialize",
2694
+ query: `
2695
+ mutation CastleCauldronStorageInitialize($deckId: ID!, $input: Json!) {
2696
+ cauldronStorageInitialize(deckId: $deckId, input: $input)
2697
+ }
2698
+ `,
2699
+ },
2700
+ };
2509
2701
  const CAULDRON_STORAGE_GET_QUERY = `
2510
2702
  query CastleCauldronStorageGet(
2511
2703
  $deckId: ID!
@@ -2650,3 +2842,668 @@ const CAULDRON_STORAGE_BOARD_GET_QUERY = `
2650
2842
  }
2651
2843
  }
2652
2844
  `;
2845
+ // What a host posts to the deck (web: postMessage to the iframe; mobile:
2846
+ // window.__castleSdkHost.receive) when the player presses its Back control.
2847
+ export function hubBackEnvelope() {
2848
+ return { castleSdk: 1, hub: { type: "back" } };
2849
+ }
2850
+ // Ghost's source check reads the session's heartbeat roster, which can lag an
2851
+ // arrival by up to 15 s: a door used in that window answers `forbidden`.
2852
+ const HUB_ROSTER_LAG_MS = 16_000;
2853
+ const HUB_FORBIDDEN_RETRY_MS = 1_000;
2854
+ const HUB_BUSY_ATTEMPTS = 8;
2855
+ const HUB_BUSY_RETRY_MS = 250;
2856
+ // Ghost keeps a stack of four return tickets; the trail mirrors it.
2857
+ const HUB_TRAIL_MAX = 4;
2858
+ // A deck stops waiting for `hub.go` after 30 s and never hears a later answer.
2859
+ // A cabinet's trip is committed by the host, so one acquired this long after
2860
+ // the deck asked is given back instead: committing it could leave the host in
2861
+ // a classic deck the place never learns it went to.
2862
+ const HUB_CLASSIC_COMMIT_DEADLINE_MS = 20_000;
2863
+ // And a commit that only lands this late is not followed: the deck may already
2864
+ // have stopped waiting, so the host stays in the place. Ghost then holds a
2865
+ // visit and a ticket for a trip nobody made, which the next trip replaces.
2866
+ const HUB_CLASSIC_ANSWER_DEADLINE_MS = 28_000;
2867
+ const HUB_DOOR_ID_PATTERN = /^[A-Za-z0-9_.:-]{1,64}$/;
2868
+ const HUB_USER_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
2869
+ const HUB_HANDOFF_FIELDS = "status kind deckId url nonce sessionId bundleHash contentUrl transitionId arrivalDoorId";
2870
+ const CAULDRON_HUB_DOORS_QUERY = `query CastleHubDoors($deckId: ID!, $env: String) {
2871
+ cauldronHubDoors(deckId: $deckId, env: $env) {
2872
+ doorId
2873
+ toDeckId
2874
+ launcherKind
2875
+ placementKind
2876
+ placement
2877
+ padSize
2878
+ enabled
2879
+ featured
2880
+ status { playersInside friendsInside }
2881
+ }
2882
+ }`;
2883
+ const CAULDRON_HUB_GO_MUTATION = `mutation CastleHubGo($fromDeckId: ID!, $fromSessionId: ID!, $doorId: String!, $partyId: ID, $env: String) {
2884
+ acquireCauldronHubDoor(fromDeckId: $fromDeckId, fromSessionId: $fromSessionId, doorId: $doorId, partyId: $partyId, env: $env) { ${HUB_HANDOFF_FIELDS} }
2885
+ }`;
2886
+ const CAULDRON_HUB_BACK_MUTATION = `mutation CastleHubBack($fromDeckId: ID!, $partyId: ID, $env: String) {
2887
+ acquireCauldronHubReturn(fromDeckId: $fromDeckId, partyId: $partyId, env: $env) { ${HUB_HANDOFF_FIELDS} }
2888
+ }`;
2889
+ const CAULDRON_HUB_FRIENDS_QUERY = `query CastleHubFriends($deckId: ID!, $sessionId: ID, $env: String) {
2890
+ cauldronHubFriends(deckId: $deckId, sessionId: $sessionId, env: $env, behindDoors: true) { userId username here door }
2891
+ }`;
2892
+ const CAULDRON_HUB_JUMP_MUTATION = `mutation CastleHubJump($fromDeckId: ID!, $fromSessionId: ID!, $friendUserId: ID!, $partyId: ID, $env: String) {
2893
+ acquireCauldronHubFriend(fromDeckId: $fromDeckId, fromSessionId: $fromSessionId, friendUserId: $friendUserId, partyId: $partyId, env: $env) { ${HUB_HANDOFF_FIELDS} }
2894
+ }`;
2895
+ const CAULDRON_HUB_REPORT_MUTATION = `mutation CastleHubReport($deckId: ID!, $sessionId: ID!, $userId: ID!, $reason: String, $env: String) {
2896
+ reportCauldronHubPlayer(deckId: $deckId, sessionId: $sessionId, userId: $userId, reason: $reason, env: $env)
2897
+ }`;
2898
+ // A report's reason is a short note, never a transcript.
2899
+ const HUB_REPORT_REASON_MAX = 500;
2900
+ const CAULDRON_HUB_CHAT_QUERY = `query CastleHubChat($deckId: ID!, $sessionId: ID!, $after: String, $env: String) {
2901
+ cauldronHubChat(deckId: $deckId, sessionId: $sessionId, after: $after, env: $env) {
2902
+ canChat peers cursor messages { id fromUserId fromUsername text at }
2903
+ }
2904
+ }`;
2905
+ const CAULDRON_HUB_SAY_MUTATION = `mutation CastleHubSay($deckId: ID!, $sessionId: ID!, $text: String!, $env: String) {
2906
+ sendCauldronHubChat(deckId: $deckId, sessionId: $sessionId, text: $text, env: $env) { status id }
2907
+ }`;
2908
+ const CAULDRON_HUB_REPORT_CHAT_MUTATION = `mutation CastleHubReportChat($deckId: ID!, $sessionId: ID!, $messageId: ID!, $env: String) {
2909
+ reportCauldronHubChatMessage(deckId: $deckId, sessionId: $sessionId, messageId: $messageId, env: $env)
2910
+ }`;
2911
+ // Ghost's own limits, held here too so a wrong answer cannot flood a deck.
2912
+ const HUB_CHAT_TEXT_MAX = 200;
2913
+ const HUB_CHAT_MESSAGES_MAX = 50;
2914
+ const HUB_CHAT_PEERS_MAX = 200;
2915
+ // A cursor or a message id is ghost's own string handed back: bounded, opaque.
2916
+ const HUB_CHAT_TOKEN_MAX = 512;
2917
+ const HUB_SAY_STATUSES = new Set(["sent", "none", "refused", "limited"]);
2918
+ const CAULDRON_HUB_COMMIT_MUTATION = `mutation CastleHubCommit($transitionId: ID!, $env: String) {
2919
+ commitCauldronHubTransition(transitionId: $transitionId, env: $env) { status }
2920
+ }`;
2921
+ const CAULDRON_HUB_CANCEL_MUTATION = `mutation CastleHubCancel($transitionId: ID!, $env: String) {
2922
+ cancelCauldronHubTransition(transitionId: $transitionId, env: $env) { status }
2923
+ }`;
2924
+ const HUB_FAILURE_STATUSES = new Set([
2925
+ "cancelled",
2926
+ "full",
2927
+ "unavailable",
2928
+ "not_found",
2929
+ "forbidden",
2930
+ "party_required",
2931
+ ]);
2932
+ export function unavailableHubHandoff() {
2933
+ return hubFailure("unavailable");
2934
+ }
2935
+ function hubFailure(status) {
2936
+ return { status, url: null, nonce: null, sessionId: null, bundleHash: null, contentUrl: null };
2937
+ }
2938
+ function defaultHubSleep(ms, signal) {
2939
+ return new Promise((resolve) => {
2940
+ if (signal?.aborted) {
2941
+ resolve();
2942
+ return;
2943
+ }
2944
+ const timer = setTimeout(done, ms);
2945
+ function done() {
2946
+ clearTimeout(timer);
2947
+ signal?.removeEventListener("abort", done);
2948
+ resolve();
2949
+ }
2950
+ signal?.addEventListener("abort", done, { once: true });
2951
+ });
2952
+ }
2953
+ export function createGhostHubVisit(options) {
2954
+ const visit = new GhostHubVisitImpl(options);
2955
+ return {
2956
+ go: (doorId, ctx, signal) => visit.go(doorId, ctx, signal),
2957
+ back: (ctx, signal) => visit.back(ctx, signal),
2958
+ doors: () => visit.doors(),
2959
+ friends: () => visit.friends(),
2960
+ jump: (userId, ctx, signal) => visit.jump(userId, ctx, signal),
2961
+ report: (userId, reason) => visit.report(userId, reason),
2962
+ chat: (after) => visit.chat(after),
2963
+ say: (text) => visit.say(text),
2964
+ reportChat: (messageId) => visit.reportChat(messageId),
2965
+ commit: (nonce) => visit.commit(nonce),
2966
+ cancel: (nonce) => visit.cancel(nonce),
2967
+ sessionAcquired: (sessionId) => visit.sessionAcquired(sessionId),
2968
+ placeDeckId: () => visit.place,
2969
+ state: () => visit.state(),
2970
+ };
2971
+ }
2972
+ // Every operation that reads or moves the visit runs one at a time, in the
2973
+ // order the deck asked, so a slow acquisition or commit can never land on top of
2974
+ // a newer one. Only a cancel reaches past the queue, to stop an acquisition
2975
+ // still in flight (one waiting out the roster lag can take 15 s).
2976
+ class GhostHubVisitImpl {
2977
+ options;
2978
+ place;
2979
+ gql;
2980
+ env;
2981
+ now;
2982
+ sleep;
2983
+ trail = [];
2984
+ arrivalDoorId = null;
2985
+ placeKind = "place";
2986
+ session = null;
2987
+ pending = null;
2988
+ queue = Promise.resolve();
2989
+ inFlight = new Set();
2990
+ // Door rows of the place they were read for: the fallback for a go's
2991
+ // destination when ghost does not name it.
2992
+ rows = null;
2993
+ constructor(options) {
2994
+ this.options = options;
2995
+ this.gql = options.graphqlFetch;
2996
+ this.env = options.env ?? null;
2997
+ this.now = options.now ?? (() => Date.now());
2998
+ this.sleep = options.sleep ?? defaultHubSleep;
2999
+ this.place = options.homeDeckId;
3000
+ }
3001
+ state() {
3002
+ const pending = this.pending;
3003
+ return {
3004
+ placeDeckId: this.place,
3005
+ placeKind: this.placeKind,
3006
+ trail: this.trail.slice(),
3007
+ arrivalDoorId: this.arrivalDoorId,
3008
+ pending: pending
3009
+ ? { kind: pending.kind, sessionId: pending.sessionId, toDeckId: pending.toDeckId }
3010
+ : null,
3011
+ };
3012
+ }
3013
+ sessionAcquired(sessionId) {
3014
+ this.session = { sessionId, at: this.now() };
3015
+ }
3016
+ go(doorId, ctx, signal) {
3017
+ if (!HUB_DOOR_ID_PATTERN.test(doorId))
3018
+ return Promise.resolve(hubFailure("not_found"));
3019
+ const asked = this.now();
3020
+ return this.acquisition(signal, (abort) => this.goNow(doorId, ctx, abort, asked));
3021
+ }
3022
+ back(ctx, signal) {
3023
+ return this.acquisition(signal, (abort) => this.backNow(ctx, abort));
3024
+ }
3025
+ doors() {
3026
+ return this.serial(async () => {
3027
+ const raw = await this.readDoors("hub.doors");
3028
+ return { status: "ok", doors: raw.flatMap(publicHubDoor) };
3029
+ });
3030
+ }
3031
+ // A read of who is where, outside the queue: it moves nothing, and must not
3032
+ // wait behind an acquisition sitting out the roster lag.
3033
+ async friends() {
3034
+ const data = await graphql(this.gql, CAULDRON_HUB_FRIENDS_QUERY, { deckId: this.place, sessionId: this.session?.sessionId ?? null, env: this.env }, "hub.friends");
3035
+ const raw = Array.isArray(data.cauldronHubFriends) ? data.cauldronHubFriends : [];
3036
+ return { status: "ok", friends: raw.flatMap(publicHubFriend) };
3037
+ }
3038
+ jump(userId, ctx, signal) {
3039
+ if (!HUB_USER_ID_PATTERN.test(userId))
3040
+ return Promise.resolve(hubFailure("not_found"));
3041
+ return this.acquisition(signal, (abort) => this.jumpNow(userId, ctx, abort));
3042
+ }
3043
+ // Outside the queue, like friends: it moves nothing. The place and session
3044
+ // are the host's own, never the deck's.
3045
+ async report(userId, reason) {
3046
+ const session = this.session;
3047
+ if (!HUB_USER_ID_PATTERN.test(userId) || !session)
3048
+ return { status: "unavailable" };
3049
+ const note = reason?.trim().slice(0, HUB_REPORT_REASON_MAX) || null;
3050
+ const data = await graphql(this.gql, CAULDRON_HUB_REPORT_MUTATION, { deckId: this.place, sessionId: session.sessionId, userId, reason: note, env: this.env }, "hub.report");
3051
+ return { status: data.reportCauldronHubPlayer === true ? "ok" : "unavailable" };
3052
+ }
3053
+ // Chat is outside the queue too: reading and saying move nothing. Ghost
3054
+ // decides who may chat with whom; the deck names no place, session or reader.
3055
+ async chat(after) {
3056
+ const session = this.session;
3057
+ if (!session)
3058
+ return unavailableHubChat();
3059
+ const data = await graphql(this.gql, CAULDRON_HUB_CHAT_QUERY, {
3060
+ deckId: this.place,
3061
+ sessionId: session.sessionId,
3062
+ after: after && after.length <= HUB_CHAT_TOKEN_MAX ? after : null,
3063
+ env: this.env,
3064
+ }, "hub.chat");
3065
+ return publicHubChat(data.cauldronHubChat);
3066
+ }
3067
+ async say(text) {
3068
+ const session = this.session;
3069
+ if (!session)
3070
+ return { status: "unavailable", id: null };
3071
+ const said = text.trim().slice(0, HUB_CHAT_TEXT_MAX);
3072
+ if (!said)
3073
+ return { status: "refused", id: null };
3074
+ const data = await graphql(this.gql, CAULDRON_HUB_SAY_MUTATION, { deckId: this.place, sessionId: session.sessionId, text: said, env: this.env }, "hub.say");
3075
+ return publicHubSay(data.sendCauldronHubChat);
3076
+ }
3077
+ async reportChat(messageId) {
3078
+ const session = this.session;
3079
+ if (!session || messageId.length > HUB_CHAT_TOKEN_MAX)
3080
+ return { status: "unavailable" };
3081
+ const data = await graphql(this.gql, CAULDRON_HUB_REPORT_CHAT_MUTATION, { deckId: this.place, sessionId: session.sessionId, messageId, env: this.env }, "hub.reportChat");
3082
+ return { status: data.reportCauldronHubChatMessage === true ? "ok" : "unavailable" };
3083
+ }
3084
+ commit(nonce) {
3085
+ return this.serial(() => this.commitNow(nonce));
3086
+ }
3087
+ cancel(nonce) {
3088
+ if (nonce === null) {
3089
+ for (const controller of this.inFlight)
3090
+ controller.abort();
3091
+ }
3092
+ return this.serial(() => this.cancelNow(nonce));
3093
+ }
3094
+ serial(work) {
3095
+ const run = this.queue.then(work, work);
3096
+ this.queue = run.catch(() => { });
3097
+ return run;
3098
+ }
3099
+ acquisition(signal, work) {
3100
+ const controller = new AbortController();
3101
+ const forward = () => controller.abort();
3102
+ if (signal?.aborted)
3103
+ controller.abort();
3104
+ signal?.addEventListener("abort", forward, { once: true });
3105
+ this.inFlight.add(controller);
3106
+ return this.serial(() => work(controller.signal)).finally(() => {
3107
+ this.inFlight.delete(controller);
3108
+ signal?.removeEventListener("abort", forward);
3109
+ });
3110
+ }
3111
+ async goNow(doorId, ctx, signal, asked) {
3112
+ for (;;) {
3113
+ if (signal.aborted)
3114
+ return hubFailure("cancelled");
3115
+ const source = this.session;
3116
+ if (!source)
3117
+ return hubFailure("forbidden");
3118
+ const data = await graphql(this.gql, CAULDRON_HUB_GO_MUTATION, {
3119
+ fromDeckId: this.place,
3120
+ fromSessionId: source.sessionId,
3121
+ doorId,
3122
+ partyId: ctx.partyId ?? null,
3123
+ env: this.env,
3124
+ }, "hub.go");
3125
+ const raw = data.acquireCauldronHubDoor;
3126
+ // Just arrived: ghost has not seen this player in the session yet.
3127
+ if (raw?.status === "forbidden" &&
3128
+ this.now() - source.at < HUB_ROSTER_LAG_MS &&
3129
+ !signal.aborted) {
3130
+ await this.sleep(HUB_FORBIDDEN_RETRY_MS, signal);
3131
+ continue;
3132
+ }
3133
+ return this.accept("go", raw, () => this.destinationOf(doorId), signal, asked);
3134
+ }
3135
+ }
3136
+ // Into the layer a friend is in: the same place, another session. Ghost names
3137
+ // the place (`deckId` is the one left); the trail and return tickets stay.
3138
+ async jumpNow(userId, ctx, signal) {
3139
+ for (;;) {
3140
+ if (signal.aborted)
3141
+ return hubFailure("cancelled");
3142
+ const source = this.session;
3143
+ if (!source)
3144
+ return hubFailure("forbidden");
3145
+ const place = this.place;
3146
+ const data = await graphql(this.gql, CAULDRON_HUB_JUMP_MUTATION, {
3147
+ fromDeckId: place,
3148
+ fromSessionId: source.sessionId,
3149
+ friendUserId: userId,
3150
+ partyId: ctx.partyId ?? null,
3151
+ env: this.env,
3152
+ }, "hub.jump");
3153
+ const raw = data.acquireCauldronHubFriend;
3154
+ if (raw?.status === "forbidden" &&
3155
+ this.now() - source.at < HUB_ROSTER_LAG_MS &&
3156
+ !signal.aborted) {
3157
+ await this.sleep(HUB_FORBIDDEN_RETRY_MS, signal);
3158
+ continue;
3159
+ }
3160
+ return this.accept("jump", raw, () => Promise.resolve(place), signal);
3161
+ }
3162
+ }
3163
+ async backNow(ctx, signal) {
3164
+ if (signal.aborted)
3165
+ return hubFailure("cancelled");
3166
+ const data = await graphql(this.gql, CAULDRON_HUB_BACK_MUTATION, { fromDeckId: this.place, partyId: ctx.partyId ?? null, env: this.env }, "hub.back");
3167
+ // Without ghost naming it, the way back leads to the place this host saw
3168
+ // the player leave.
3169
+ const to = this.trail.at(-1) ?? null;
3170
+ return this.accept("back", data.acquireCauldronHubReturn, () => Promise.resolve(to), signal);
3171
+ }
3172
+ async commitNow(nonce) {
3173
+ const trip = this.pending;
3174
+ if (!trip || trip.nonce !== nonce)
3175
+ return { status: "none" };
3176
+ let status;
3177
+ try {
3178
+ status = await this.transition("commit", trip.transitionId);
3179
+ }
3180
+ catch {
3181
+ // The commit may have landed with its answer lost; ghost answers a retry
3182
+ // of a commit that landed with `committed`.
3183
+ return { status: "unavailable" };
3184
+ }
3185
+ // Still pending: the SDK asks again.
3186
+ if (status === "busy")
3187
+ return { status: "unavailable" };
3188
+ this.pending = null;
3189
+ if (status === "committed")
3190
+ this.arrive(trip);
3191
+ this.changed();
3192
+ if (status === "committed" || status === "superseded" || status === "cancelled") {
3193
+ return { status };
3194
+ }
3195
+ return { status: "expired" };
3196
+ }
3197
+ async cancelNow(nonce) {
3198
+ const trip = this.pending;
3199
+ if (!trip || (nonce !== null && trip.nonce !== nonce))
3200
+ return { status: "none" };
3201
+ let status;
3202
+ try {
3203
+ status = await this.transition("cancel", trip.transitionId);
3204
+ }
3205
+ catch {
3206
+ return { status: "unavailable" };
3207
+ }
3208
+ // Kept pending so a later cancel can still reach ghost.
3209
+ if (status === "busy")
3210
+ return { status: "unavailable" };
3211
+ if (this.pending === trip)
3212
+ this.pending = null;
3213
+ this.changed();
3214
+ return { status: status === "cancelled" ? "cancelled" : "expired" };
3215
+ }
3216
+ // A classic place (a cabinet's deck) has no session.
3217
+ arrive(trip) {
3218
+ // A jump changes the session, not the way back.
3219
+ if (trip.kind === "go") {
3220
+ this.trail.push(this.place);
3221
+ if (this.trail.length > HUB_TRAIL_MAX)
3222
+ this.trail.shift();
3223
+ }
3224
+ else if (trip.kind === "back") {
3225
+ this.trail.pop();
3226
+ }
3227
+ if (trip.toDeckId !== this.place)
3228
+ this.rows = null;
3229
+ this.place = trip.toDeckId;
3230
+ this.placeKind = trip.classic ? "classic" : "place";
3231
+ this.arrivalDoorId = trip.arrivalDoorId;
3232
+ this.session = trip.sessionId ? { sessionId: trip.sessionId, at: this.now() } : null;
3233
+ }
3234
+ changed() {
3235
+ try {
3236
+ this.options.onChange?.(this.state());
3237
+ }
3238
+ catch (error) {
3239
+ console.error("Castle hub onChange threw:", error);
3240
+ }
3241
+ }
3242
+ async readDoors(command) {
3243
+ const deckId = this.place;
3244
+ const data = await graphql(this.gql, CAULDRON_HUB_DOORS_QUERY, { deckId, env: this.env }, command);
3245
+ const doors = Array.isArray(data.cauldronHubDoors) ? data.cauldronHubDoors : [];
3246
+ if (this.place === deckId)
3247
+ this.rows = { deckId, doors };
3248
+ return doors;
3249
+ }
3250
+ async destinationOf(doorId) {
3251
+ const find = (doors) => asOptionalString(doors.find((door) => door.doorId === doorId)?.toDeckId);
3252
+ const cached = this.rows?.deckId === this.place ? find(this.rows.doors) : null;
3253
+ return cached ?? find(await this.readDoors("hub.go"));
3254
+ }
3255
+ async transition(kind, transitionId) {
3256
+ const field = kind === "commit" ? "commitCauldronHubTransition" : "cancelCauldronHubTransition";
3257
+ for (let attempt = 1;; attempt++) {
3258
+ const data = await graphql(this.gql, kind === "commit" ? CAULDRON_HUB_COMMIT_MUTATION : CAULDRON_HUB_CANCEL_MUTATION, { transitionId, env: this.env }, kind === "commit" ? "hub.commit" : "hub.cancel");
3259
+ const status = data[field]?.status ?? "expired";
3260
+ if (status !== "busy" || attempt >= HUB_BUSY_ATTEMPTS)
3261
+ return status;
3262
+ await this.sleep(HUB_BUSY_RETRY_MS);
3263
+ }
3264
+ }
3265
+ // Anything acquired that will not be joined is given back, so it neither
3266
+ // waits out its TTL as the pending one nor commits later by accident.
3267
+ async release(transitionId) {
3268
+ try {
3269
+ await this.transition("cancel", transitionId);
3270
+ }
3271
+ catch {
3272
+ // It expires on its own.
3273
+ }
3274
+ }
3275
+ // An ok handoff becomes the pending trip (ghost keeps one per player, so it
3276
+ // supersedes any earlier one); the deck gets only its public half.
3277
+ async accept(kind, raw, fallbackDestination, signal, asked) {
3278
+ const status = raw?.status ?? "unavailable";
3279
+ const transitionId = asOptionalString(raw?.transitionId);
3280
+ if (status !== "ok") {
3281
+ return hubFailure(HUB_FAILURE_STATUSES.has(status) ? status : "unavailable");
3282
+ }
3283
+ if (kind === "go" && raw?.kind === "classic") {
3284
+ return this.acceptClassic(raw, signal, asked ?? this.now());
3285
+ }
3286
+ const url = asOptionalString(raw?.url);
3287
+ const nonce = asOptionalString(raw?.nonce);
3288
+ const sessionId = asOptionalString(raw?.sessionId);
3289
+ if (!transitionId || !url || !nonce || !sessionId) {
3290
+ if (transitionId)
3291
+ await this.release(transitionId);
3292
+ return hubFailure("unavailable");
3293
+ }
3294
+ const destination = signal.aborted
3295
+ ? null
3296
+ : asOptionalString(raw?.deckId) ?? await fallbackDestination();
3297
+ if (signal.aborted || !destination) {
3298
+ await this.release(transitionId);
3299
+ return hubFailure(signal.aborted ? "cancelled" : "not_found");
3300
+ }
3301
+ this.pending = {
3302
+ kind,
3303
+ transitionId,
3304
+ nonce,
3305
+ sessionId,
3306
+ toDeckId: destination,
3307
+ arrivalDoorId: asOptionalString(raw?.arrivalDoorId),
3308
+ };
3309
+ this.changed();
3310
+ return {
3311
+ status: "ok",
3312
+ url,
3313
+ nonce,
3314
+ sessionId,
3315
+ bundleHash: asOptionalString(raw?.bundleHash) ?? "",
3316
+ contentUrl: asOptionalString(raw?.contentUrl),
3317
+ };
3318
+ }
3319
+ // A cabinet: the door leads to a classic deck, which the host plays itself.
3320
+ // No socket will ever say hello, so the host commits the trip here and the
3321
+ // deck gets a handoff with nothing to join. Anything short of a commit gives
3322
+ // the transition back.
3323
+ async acceptClassic(raw, signal, asked) {
3324
+ const transitionId = asOptionalString(raw.transitionId);
3325
+ const deckId = asOptionalString(raw.deckId);
3326
+ if (!transitionId)
3327
+ return hubFailure("unavailable");
3328
+ if (!deckId || signal.aborted || this.now() - asked > HUB_CLASSIC_COMMIT_DEADLINE_MS) {
3329
+ await this.release(transitionId);
3330
+ return hubFailure(signal.aborted ? "cancelled" : "unavailable");
3331
+ }
3332
+ if ((await this.commitClassic(transitionId)) !== "committed") {
3333
+ await this.release(transitionId);
3334
+ return hubFailure("unavailable");
3335
+ }
3336
+ if (this.now() - asked > HUB_CLASSIC_ANSWER_DEADLINE_MS)
3337
+ return hubFailure("unavailable");
3338
+ // Ghost keeps one transition per player: this one took the place of any
3339
+ // acquisition still waiting for its join.
3340
+ this.pending = null;
3341
+ this.arrive({
3342
+ kind: "go",
3343
+ toDeckId: deckId,
3344
+ arrivalDoorId: asOptionalString(raw.arrivalDoorId),
3345
+ sessionId: null,
3346
+ classic: true,
3347
+ });
3348
+ this.changed();
3349
+ return {
3350
+ status: "ok",
3351
+ kind: "classic",
3352
+ url: null,
3353
+ nonce: null,
3354
+ sessionId: null,
3355
+ bundleHash: "",
3356
+ contentUrl: null,
3357
+ };
3358
+ }
3359
+ // The commit's answer can be lost after it landed; ghost answers a retry of
3360
+ // one that landed with `committed`, so a failed request is asked once more.
3361
+ async commitClassic(transitionId) {
3362
+ for (let attempt = 1;; attempt++) {
3363
+ try {
3364
+ return await this.transition("commit", transitionId);
3365
+ }
3366
+ catch {
3367
+ if (attempt >= 2)
3368
+ return "unavailable";
3369
+ }
3370
+ }
3371
+ }
3372
+ }
3373
+ function publicHubDoor(raw) {
3374
+ const doorId = asOptionalString(raw.doorId);
3375
+ const placementKind = raw.placementKind;
3376
+ if (!doorId ||
3377
+ (placementKind !== "layer" && placementKind !== "pad" && placementKind !== "exact")) {
3378
+ return [];
3379
+ }
3380
+ return [
3381
+ {
3382
+ doorId,
3383
+ launcherKind: asOptionalString(raw.launcherKind) ?? "door",
3384
+ placementKind,
3385
+ placement: raw.placement ?? {},
3386
+ padSize: asOptionalNumber(raw.padSize),
3387
+ enabled: raw.enabled === true,
3388
+ featured: raw.featured === true,
3389
+ status: {
3390
+ playersInside: asOptionalNumber(raw.status?.playersInside) ?? 0,
3391
+ friendsInside: asOptionalNumber(raw.status?.friendsInside) ?? 0,
3392
+ },
3393
+ },
3394
+ ];
3395
+ }
3396
+ function publicHubFriend(raw) {
3397
+ if (typeof raw !== "object" || raw === null)
3398
+ return [];
3399
+ const record = raw;
3400
+ const userId = asOptionalString(record.userId);
3401
+ if (!userId)
3402
+ return [];
3403
+ // A door is one of this place's own ids, or nothing.
3404
+ const door = asOptionalString(record.door);
3405
+ return [
3406
+ {
3407
+ userId,
3408
+ username: asOptionalString(record.username),
3409
+ here: record.here === true,
3410
+ door: door && HUB_DOOR_ID_PATTERN.test(door) ? door : null,
3411
+ },
3412
+ ];
3413
+ }
3414
+ function unavailableHubChat() {
3415
+ return { status: "unavailable", canChat: false, peers: null, messages: null, cursor: null };
3416
+ }
3417
+ function publicHubChat(raw) {
3418
+ if (typeof raw !== "object" || raw === null)
3419
+ return unavailableHubChat();
3420
+ const record = raw;
3421
+ const peers = Array.isArray(record.peers) ? record.peers : [];
3422
+ const messages = Array.isArray(record.messages) ? record.messages : [];
3423
+ return {
3424
+ status: "ok",
3425
+ canChat: record.canChat === true,
3426
+ peers: peers
3427
+ .filter((peer) => typeof peer === "string" && peer.length > 0)
3428
+ .slice(0, HUB_CHAT_PEERS_MAX),
3429
+ messages: messages.flatMap(publicHubChatMessage).slice(-HUB_CHAT_MESSAGES_MAX),
3430
+ cursor: asOptionalString(record.cursor),
3431
+ };
3432
+ }
3433
+ function publicHubChatMessage(raw) {
3434
+ if (typeof raw !== "object" || raw === null)
3435
+ return [];
3436
+ const record = raw;
3437
+ const id = asOptionalString(record.id);
3438
+ const fromUserId = asOptionalString(record.fromUserId);
3439
+ const text = asOptionalString(record.text);
3440
+ const at = asOptionalString(record.at);
3441
+ if (!id || !fromUserId || !text || !at)
3442
+ return [];
3443
+ return [
3444
+ {
3445
+ id,
3446
+ fromUserId,
3447
+ fromUsername: asOptionalString(record.fromUsername),
3448
+ text: text.slice(0, HUB_CHAT_TEXT_MAX),
3449
+ at,
3450
+ },
3451
+ ];
3452
+ }
3453
+ function publicHubSay(raw) {
3454
+ const record = (typeof raw === "object" && raw !== null ? raw : {});
3455
+ const status = typeof record.status === "string" && HUB_SAY_STATUSES.has(record.status)
3456
+ ? record.status
3457
+ : "refused";
3458
+ return { status, id: status === "sent" ? asOptionalString(record.id) : null };
3459
+ }
3460
+ function runHubCommand(ctx, command, params, caps, signal) {
3461
+ const hub = caps.hub;
3462
+ switch (command) {
3463
+ case "hub.go": {
3464
+ const doorId = asString(params.doorId, "doorId", command);
3465
+ return hub ? hub.go(doorId, ctx, signal) : Promise.resolve(unavailableHubHandoff());
3466
+ }
3467
+ case "hub.back":
3468
+ return hub ? hub.back(ctx, signal) : Promise.resolve(unavailableHubHandoff());
3469
+ case "hub.doors":
3470
+ return hub ? hub.doors(ctx) : Promise.resolve({ status: "unavailable", doors: null });
3471
+ case "hub.friends":
3472
+ return hub?.friends
3473
+ ? hub.friends(ctx)
3474
+ : Promise.resolve({ status: "unavailable", friends: null });
3475
+ case "hub.jump": {
3476
+ const userId = asString(params.userId, "userId", command);
3477
+ return hub?.jump ? hub.jump(userId, ctx, signal) : Promise.resolve(unavailableHubHandoff());
3478
+ }
3479
+ case "hub.report": {
3480
+ const userId = asString(params.userId, "userId", command);
3481
+ const reason = asOptionalString(params.reason);
3482
+ return hub?.report
3483
+ ? hub.report(userId, reason, ctx)
3484
+ : Promise.resolve({ status: "unavailable" });
3485
+ }
3486
+ case "hub.chat":
3487
+ return hub?.chat
3488
+ ? hub.chat(asOptionalString(params.after), ctx)
3489
+ : Promise.resolve(unavailableHubChat());
3490
+ case "hub.say": {
3491
+ const text = asString(params.text, "text", command);
3492
+ return hub?.say ? hub.say(text, ctx) : Promise.resolve({ status: "unavailable", id: null });
3493
+ }
3494
+ case "hub.reportChat": {
3495
+ const messageId = asString(params.messageId, "messageId", command);
3496
+ return hub?.reportChat
3497
+ ? hub.reportChat(messageId, ctx)
3498
+ : Promise.resolve({ status: "unavailable" });
3499
+ }
3500
+ case "hub.commit": {
3501
+ const nonce = asString(params.nonce, "nonce", command);
3502
+ return hub ? hub.commit(nonce, ctx) : Promise.resolve({ status: "unavailable" });
3503
+ }
3504
+ case "hub.cancel":
3505
+ return hub
3506
+ ? hub.cancel(asOptionalString(params.nonce), ctx)
3507
+ : Promise.resolve({ status: "unavailable" });
3508
+ }
3509
+ }