castle-web-cli 0.4.228 → 0.4.230

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 (236) hide show
  1. package/dist/agent-prompts.d.ts +11 -3
  2. package/dist/agent-prompts.js +153 -53
  3. package/dist/agent.d.ts +2 -0
  4. package/dist/agent.js +43 -33
  5. package/dist/api.d.ts +47 -2
  6. package/dist/api.js +85 -16
  7. package/dist/castle-host/host.d.ts +91 -0
  8. package/dist/castle-host/host.js +779 -3
  9. package/dist/castleJson.d.ts +59 -0
  10. package/dist/castleJson.js +267 -3
  11. package/dist/check.js +27 -1
  12. package/dist/cloudGit.d.ts +20 -1
  13. package/dist/cloudGit.js +267 -10
  14. package/dist/contentPack.d.ts +49 -0
  15. package/dist/contentPack.js +273 -0
  16. package/dist/devExperiments.d.ts +21 -0
  17. package/dist/devExperiments.js +139 -0
  18. package/dist/devHub.d.ts +55 -0
  19. package/dist/devHub.js +187 -0
  20. package/dist/devSessionChild.js +3 -1
  21. package/dist/devSessionServer.d.ts +14 -1
  22. package/dist/devSessionServer.js +229 -44
  23. package/dist/experimentAssignment.d.ts +15 -0
  24. package/dist/experimentAssignment.js +41 -0
  25. package/dist/importCheckHook.d.ts +40 -0
  26. package/dist/importCheckHook.js +171 -0
  27. package/dist/importRegression.d.ts +15 -0
  28. package/dist/importRegression.js +100 -0
  29. package/dist/importTrust.d.ts +2 -0
  30. package/dist/importTrust.js +27 -0
  31. package/dist/importUpdateHook.d.ts +18 -0
  32. package/dist/importUpdateHook.js +31 -8
  33. package/dist/importUpdateHookRunner.js +19 -7
  34. package/dist/imports.d.ts +16 -0
  35. package/dist/imports.js +145 -33
  36. package/dist/index.js +8 -1
  37. package/dist/init.d.ts +3 -0
  38. package/dist/init.js +125 -8
  39. package/dist/install.js +4 -1
  40. package/dist/localPaths.js +4 -0
  41. package/dist/login.js +2 -2
  42. package/dist/platformDoc.js +3 -8
  43. package/dist/playPagePolicy.js +3 -1
  44. package/dist/remix.js +5 -0
  45. package/dist/routerTaskReport.d.ts +28 -0
  46. package/dist/routerTaskReport.js +56 -0
  47. package/dist/save-deck.d.ts +18 -0
  48. package/dist/save-deck.js +145 -6
  49. package/dist/serve.d.ts +8 -0
  50. package/dist/serve.js +94 -13
  51. package/dist/serverBundle.d.ts +1 -1
  52. package/dist/serverBundle.js +5 -1
  53. package/dist/sourceLineage.d.ts +42 -0
  54. package/dist/sourceLineage.js +380 -0
  55. package/dist/webSourceSync.d.ts +11 -0
  56. package/dist/webSourceSync.js +26 -9
  57. package/kits/base/CLAUDE.md +2 -3
  58. package/kits/base/castle.json +1 -1
  59. package/kits/base/sdk/README.md +301 -52
  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 +6 -1
  64. package/kits/base/sdk/castle.js +3 -0
  65. package/kits/base/sdk/commands.d.ts +208 -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 +86 -6
  73. package/kits/base/sdk/multiplayer.js +157 -4
  74. package/kits/base/sdk/server/hub.d.ts +169 -0
  75. package/kits/base/sdk/server/hub.js +125 -0
  76. package/kits/base/sdk/server/platformHandle.d.ts +49 -2
  77. package/kits/base/sdk/server/storage.d.ts +55 -2
  78. package/kits/base/sdk/server/wrapper.d.ts +85 -6
  79. package/kits/base/sdk/server/wrapper.js +393 -30
  80. package/kits/base/sdk/transport.d.ts +2 -1
  81. package/kits/base/sdk/transport.js +13 -1
  82. package/kits/hub-game/.prettierrc +5 -0
  83. package/kits/hub-game/CLAUDE.md +146 -0
  84. package/kits/hub-game/blueprints/avatar-0.scene +28 -0
  85. package/kits/hub-game/blueprints/avatar-1.scene +28 -0
  86. package/kits/hub-game/blueprints/avatar-2.scene +28 -0
  87. package/kits/hub-game/blueprints/avatar-3.scene +28 -0
  88. package/kits/hub-game/blueprints/bean/avatar-0.scene +28 -0
  89. package/kits/hub-game/blueprints/bean/avatar-1.scene +28 -0
  90. package/kits/hub-game/blueprints/bean/avatar-2.scene +28 -0
  91. package/kits/hub-game/blueprints/bean/avatar-3.scene +28 -0
  92. package/kits/hub-game/blueprints/blocky/avatar-0.scene +28 -0
  93. package/kits/hub-game/blueprints/blocky/avatar-1.scene +28 -0
  94. package/kits/hub-game/blueprints/blocky/avatar-2.scene +28 -0
  95. package/kits/hub-game/blueprints/blocky/avatar-3.scene +28 -0
  96. package/kits/hub-game/blueprints/pixel/avatar-0.scene +28 -0
  97. package/kits/hub-game/blueprints/pixel/avatar-1.scene +28 -0
  98. package/kits/hub-game/blueprints/pixel/avatar-2.scene +28 -0
  99. package/kits/hub-game/blueprints/pixel/avatar-3.scene +28 -0
  100. package/kits/hub-game/castle.json +96 -0
  101. package/kits/hub-game/code/client/attention.js +133 -0
  102. package/kits/hub-game/code/client/avatar.js +288 -0
  103. package/kits/hub-game/code/client/cabinets.js +90 -0
  104. package/kits/hub-game/code/client/chat.js +135 -0
  105. package/kits/hub-game/code/client/chrome.js +1001 -0
  106. package/kits/hub-game/code/client/doorFrame.js +15 -0
  107. package/kits/hub-game/code/client/firstJoin.js +14 -0
  108. package/kits/hub-game/code/client/grab.js +241 -0
  109. package/kits/hub-game/code/client/hookLayer.js +230 -0
  110. package/kits/hub-game/code/client/idle.js +326 -0
  111. package/kits/hub-game/code/client/keys.js +48 -0
  112. package/kits/hub-game/code/client/pack.js +232 -0
  113. package/kits/hub-game/code/client/packFormat.js +397 -0
  114. package/kits/hub-game/code/client/say.js +127 -0
  115. package/kits/hub-game/code/client/sha256.js +80 -0
  116. package/kits/hub-game/code/client/sound.js +147 -0
  117. package/kits/hub-game/code/client/state.js +131 -0
  118. package/kits/hub-game/code/client/talk.js +259 -0
  119. package/kits/hub-game/code/client/together.js +365 -0
  120. package/kits/hub-game/code/client/wear.js +149 -0
  121. package/kits/hub-game/code/server/actors.js +627 -0
  122. package/kits/hub-game/code/server/blocks.js +103 -0
  123. package/kits/hub-game/code/server/cabinets.js +309 -0
  124. package/kits/hub-game/code/server/game.js +137 -0
  125. package/kits/hub-game/code/server/grab.js +247 -0
  126. package/kits/hub-game/code/server/history.js +96 -0
  127. package/kits/hub-game/code/server/hub.js +1904 -0
  128. package/kits/hub-game/code/server/idle.js +412 -0
  129. package/kits/hub-game/code/server/index.js +64 -0
  130. package/kits/hub-game/code/server/labels.js +59 -0
  131. package/kits/hub-game/code/server/manifest.js +527 -0
  132. package/kits/hub-game/code/server/npcs.js +745 -0
  133. package/kits/hub-game/code/server/party.js +381 -0
  134. package/kits/hub-game/code/server/place.js +43 -0
  135. package/kits/hub-game/code/server/say.js +83 -0
  136. package/kits/hub-game/code/server/wear.js +142 -0
  137. package/kits/hub-game/code/systems/hub.js +2230 -0
  138. package/kits/hub-game/docs/content-pack.md +151 -0
  139. package/kits/hub-game/docs/contract.md +1139 -0
  140. package/kits/hub-game/docs/style.md +137 -0
  141. package/kits/hub-game/drawings/blocky/castle-eye.sprite +58 -0
  142. package/kits/hub-game/drawings/blocky/dash.sprite +59 -0
  143. package/kits/hub-game/drawings/blocky/pom.sprite +59 -0
  144. package/kits/hub-game/drawings/blocky/tabby.sprite +59 -0
  145. package/kits/hub-game/drawings/pixel/castle-arm.sprite +13 -0
  146. package/kits/hub-game/drawings/pixel/castle-body.sprite +23 -0
  147. package/kits/hub-game/drawings/pixel/castle-leg.sprite +12 -0
  148. package/kits/hub-game/drawings/pixel/kai-arm.sprite +14 -0
  149. package/kits/hub-game/drawings/pixel/kai-head.sprite +24 -0
  150. package/kits/hub-game/drawings/pixel/kai-leg.sprite +15 -0
  151. package/kits/hub-game/drawings/pixel/kai-torso.sprite +18 -0
  152. package/kits/hub-game/drawings/pixel/mimi-arm.sprite +13 -0
  153. package/kits/hub-game/drawings/pixel/mimi-head.sprite +23 -0
  154. package/kits/hub-game/drawings/pixel/mimi-leg.sprite +15 -0
  155. package/kits/hub-game/drawings/pixel/mimi-torso.sprite +18 -0
  156. package/kits/hub-game/drawings/pixel/nox-arm.sprite +13 -0
  157. package/kits/hub-game/drawings/pixel/nox-head.sprite +21 -0
  158. package/kits/hub-game/drawings/pixel/nox-leg.sprite +14 -0
  159. package/kits/hub-game/drawings/pixel/nox-torso.sprite +18 -0
  160. package/kits/hub-game/eslint.config.js +20 -0
  161. package/kits/hub-game/fonts.generated.js +9 -0
  162. package/kits/hub-game/index.html +22 -0
  163. package/kits/hub-game/main.jsx +6 -0
  164. package/kits/hub-game/models/avatar-0.pxmodel +21 -0
  165. package/kits/hub-game/models/avatar-1.pxmodel +24 -0
  166. package/kits/hub-game/models/avatar-2.pxmodel +27 -0
  167. package/kits/hub-game/models/avatar-3.pxmodel +22 -0
  168. package/kits/hub-game/models/bean/avatar-0.pxmodel +19 -0
  169. package/kits/hub-game/models/bean/avatar-1.pxmodel +24 -0
  170. package/kits/hub-game/models/bean/avatar-2.pxmodel +22 -0
  171. package/kits/hub-game/models/bean/avatar-3.pxmodel +24 -0
  172. package/kits/hub-game/models/blocky/avatar-0.pxmodel +21 -0
  173. package/kits/hub-game/models/blocky/avatar-1.pxmodel +30 -0
  174. package/kits/hub-game/models/blocky/avatar-2.pxmodel +28 -0
  175. package/kits/hub-game/models/blocky/avatar-3.pxmodel +27 -0
  176. package/kits/hub-game/models/pixel/avatar-0.pxmodel +24 -0
  177. package/kits/hub-game/models/pixel/avatar-1.pxmodel +16 -0
  178. package/kits/hub-game/models/pixel/avatar-2.pxmodel +19 -0
  179. package/kits/hub-game/models/pixel/avatar-3.pxmodel +23 -0
  180. package/kits/hub-game/package-lock.json +365 -0
  181. package/kits/hub-game/package.json +32 -0
  182. package/kits/hub-game/scenes/main.scene +318 -0
  183. package/kits/hub-game/scripts/check.mjs +339 -0
  184. package/kits/hub-game/scripts/fixtures/sdk-stub.mjs +3 -0
  185. package/kits/hub-game/scripts/gen-avatars-bean.mjs +748 -0
  186. package/kits/hub-game/scripts/gen-avatars-blocky.mjs +607 -0
  187. package/kits/hub-game/scripts/gen-avatars-pixel.mjs +771 -0
  188. package/kits/hub-game/scripts/gen-avatars.mjs +621 -0
  189. package/kits/hub-game/scripts/pack.mjs +192 -0
  190. package/kits/hub-game/scripts/test-actors.mjs +666 -0
  191. package/kits/hub-game/scripts/test-attention.mjs +103 -0
  192. package/kits/hub-game/scripts/test-avatar.mjs +472 -0
  193. package/kits/hub-game/scripts/test-ban-join.mjs +194 -0
  194. package/kits/hub-game/scripts/test-blocks.mjs +351 -0
  195. package/kits/hub-game/scripts/test-chat.mjs +98 -0
  196. package/kits/hub-game/scripts/test-classic.mjs +590 -0
  197. package/kits/hub-game/scripts/test-door-jump.mjs +131 -0
  198. package/kits/hub-game/scripts/test-door.mjs +56 -0
  199. package/kits/hub-game/scripts/test-grab.mjs +331 -0
  200. package/kits/hub-game/scripts/test-hub-ops.mjs +835 -0
  201. package/kits/hub-game/scripts/test-hub-trip.mjs +1310 -0
  202. package/kits/hub-game/scripts/test-idle.mjs +518 -0
  203. package/kits/hub-game/scripts/test-interest.mjs +413 -0
  204. package/kits/hub-game/scripts/test-keys.mjs +50 -0
  205. package/kits/hub-game/scripts/test-manifest.mjs +224 -0
  206. package/kits/hub-game/scripts/test-no-forms.mjs +16 -0
  207. package/kits/hub-game/scripts/test-npcs.mjs +714 -0
  208. package/kits/hub-game/scripts/test-pack.mjs +424 -0
  209. package/kits/hub-game/scripts/test-party.mjs +286 -0
  210. package/kits/hub-game/scripts/test-say.mjs +149 -0
  211. package/kits/hub-game/scripts/test-together.mjs +183 -0
  212. package/kits/hub-game/theme.style +3 -0
  213. package/kits/multiplayer-3d/castle.json +5 -5
  214. package/kits/multiplayer-3d/code/client/avatars.js +101 -1
  215. package/kits/multiplayer-3d/code/server/players.js +4 -1
  216. package/kits/multiplayer-3d/code/server/sceneBodies.js +27 -6
  217. package/kits/multiplayer-3d/code/server/world.js +20 -7
  218. package/kits/multiplayer-3d/code/systems/multiplayer.js +222 -11
  219. package/kits/physics-2d/castle.json +2 -2
  220. package/kits/physics-2d/engine/art.js +13 -0
  221. package/kits/physics-2d/engine/assets.js +4 -2
  222. package/kits/physics-2d/engine/scene.js +25 -5
  223. package/kits/physics-3d/CLAUDE.md +6 -1
  224. package/kits/physics-3d/castle.json +3 -3
  225. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +32 -4
  226. package/kits/physics-3d/engine3d/artobjects.js +2 -2
  227. package/kits/physics-3d/engine3d/materials.js +29 -1
  228. package/kits/physics-3d/engine3d/world3d.js +65 -1
  229. package/kits/physics-3d/systems/physics3d.js +5 -2
  230. package/kits/real-time/castle.json +2 -2
  231. package/kits/real-time/code/client/connection.js +77 -7
  232. package/kits/real-time/code/client/gameHooks.js +63 -3
  233. package/kits/real-time/code/client/messages.js +7 -0
  234. package/kits/real-time/code/server/gameHooks.js +24 -0
  235. package/kits/real-time/code/server/session.js +390 -22
  236. package/package.json +2 -2
@@ -1,6 +1,7 @@
1
1
  import { isBinaryPayload, toUint8Array, } from "../multiplayerProtocol";
2
2
  import { encodeStorageValue, storageError } from "../storageJson";
3
3
  import { createServerStorage } from "./storage";
4
+ import { createServerHub, hubArrival, recordHiddenUserIds, } from "./hub";
4
5
  // The publish bundler binds the author's default callbacks export once and
5
6
  // exports the returned one-argument function as `__castleBootSession`.
6
7
  export function createCastleSessionBoot(callbacks) {
@@ -10,19 +11,23 @@ export function createCastleSessionBoot(callbacks) {
10
11
  }
11
12
  async function bootSession(platformHandle, callbacks) {
12
13
  const players = new Map();
13
- const session = createAuthorSession(platformHandle, players);
14
+ const arrivals = new Map();
15
+ // playerId -> users a block hides from them; never on the player object.
16
+ const hidden = new Map();
17
+ // playerId -> their A/B arms while connected; never on the player object.
18
+ const variants = new Map();
19
+ const session = createAuthorSession(platformHandle, players, arrivals, hidden, variants);
14
20
  let tickTimer = null;
15
- platformHandle.on("join", async (connId, identity) => {
16
- // The compatibility branch accepts the current Node shim's legacy
17
- // single-argument SessionPlayer event while the public handle contract uses
18
- // the runtime-agnostic (connId, trusted identity) pair.
19
- const player = joinedPlayer(connId, identity);
20
- players.set(player.playerId, player);
21
- await callbacks.onPlayerJoin?.(session, player);
21
+ platformHandle.on("join", async (connId, identity, handleArrival, handleVariants) => {
22
+ const { player, arrival } = admitPlayer({ players, arrivals, hidden, variants }, connId, identity, handleArrival, handleVariants);
23
+ await callbacks.onPlayerJoin?.(session, player, arrival);
22
24
  });
23
25
  platformHandle.on("leave", async (connId) => {
24
26
  const player = players.get(connId);
25
27
  players.delete(connId);
28
+ arrivals.delete(connId);
29
+ hidden.delete(connId);
30
+ variants.delete(connId);
26
31
  if (player) {
27
32
  await callbacks.onPlayerLeave?.(session, player);
28
33
  }
@@ -103,6 +108,7 @@ async function bootSession(platformHandle, callbacks) {
103
108
  let settled = false;
104
109
  const brokerFailure = { rejection: null };
105
110
  const command = Object.freeze({
111
+ type: request.command.type,
106
112
  requestId: request.requestId,
107
113
  operationId: request.operationId,
108
114
  speaker: Object.freeze(joinedPlayer(request.speaker.playerId, request.speaker)),
@@ -202,7 +208,22 @@ async function bootSession(platformHandle, callbacks) {
202
208
  }, 1_000 / platformHandle.config.tickRate);
203
209
  }
204
210
  }
205
- function createAuthorSession(platformHandle, players) {
211
+ function createAuthorSession(platformHandle, players, arrivals, hidden, variants) {
212
+ // Lenient about what it is handed: an unknown player is in no experiment.
213
+ const variantsOf = (player) => variants.get(typeof player === "string"
214
+ ? player
215
+ : (player?.playerId ?? ""));
216
+ // The pinned place counts only where the host services the hub ops.
217
+ const hub = createServerHub(platformHandle, arrivals, (a, b) => {
218
+ if (hidden.size === 0 || a === b)
219
+ return false;
220
+ const userA = players.get(a)?.userId;
221
+ const userB = players.get(b)?.userId;
222
+ if (!userA || !userB)
223
+ return false;
224
+ return Boolean(hidden.get(a)?.has(userB) || hidden.get(b)?.has(userA));
225
+ });
226
+ const world = createServerWorld(platformHandle);
206
227
  return {
207
228
  get players() {
208
229
  return Array.from(players.values());
@@ -210,8 +231,20 @@ function createAuthorSession(platformHandle, players) {
210
231
  sessionId: platformHandle.config.sessionId,
211
232
  deckId: platformHandle.config.deckId,
212
233
  mode: platformHandle.config.mode,
234
+ place: typeof platformHandle.config.place === "string"
235
+ ? platformHandle.config.place
236
+ : hub?.place ?? null,
213
237
  storage: createServerStorage(platformHandle),
214
- world: createServerWorld(platformHandle),
238
+ world,
239
+ characters: world?.characters ?? createPlaceCharacters(platformHandle),
240
+ hub,
241
+ experiment(player, name) {
242
+ const known = variantsOf(player);
243
+ return known && Object.hasOwn(known, name) ? known[name] : null;
244
+ },
245
+ experiments(player) {
246
+ return { ...variantsOf(player) };
247
+ },
215
248
  send(playerId, data) {
216
249
  if (isBinaryPayload(data)) {
217
250
  requireSendBinary(platformHandle);
@@ -264,6 +297,24 @@ const WORLD_JOURNAL_MAX_READ_LIMIT = 128;
264
297
  const WORLD_PARTICIPANTS_MAX_READ_LIMIT = 256;
265
298
  const WORLD_JOURNAL_MAX_SEQUENCE = "9223372036854775807";
266
299
  const SAFE_WORLD_JOURNAL_KIND = /^[A-Za-z0-9_.:-]+$/;
300
+ const WORLD_NOTIFICATIONS_MAX_PARTICIPANTS = 16;
301
+ const WORLD_NOTIFICATIONS_MAX_SLOTS = 4;
302
+ const WORLD_NOTIFICATIONS_MAX_SLOT_CHARACTERS = 40;
303
+ const WORLD_NOTIFICATIONS_MAX_SCHEDULE_MS = 30 * 24 * 60 * 60 * 1_000;
304
+ const WORLD_NOTIFICATIONS_PAST_TOLERANCE_MS = 60 * 1_000;
305
+ const WORLD_CATCH_UP_DEFAULT_MAX_ELAPSED_MS = 7 * 24 * 60 * 60 * 1_000;
306
+ const SAFE_WORLD_NOTIFICATION_KEY = /^[A-Za-z0-9_-]+$/;
307
+ const CANONICAL_WORLD_NOTIFICATION_TIME = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?Z$/;
308
+ const URL_IN_WORLD_NOTIFICATION_TEXT = /(?:https?:\/\/|www\.|\b[a-z0-9-]+\.(?:app|com|dev|gg|io|net|org|xyz)\b)/i;
309
+ // A hub place's layer has no world of its own, but the host may still broker
310
+ // the place's shared characters into it (`placeCharacters` in the runtime
311
+ // init). The character API is the world one; only the binding differs, and the
312
+ // host stamps that.
313
+ function createPlaceCharacters(platformHandle) {
314
+ if (platformHandle.config.placeCharacters !== true)
315
+ return null;
316
+ return createServerWorldCharacters(platformHandle);
317
+ }
267
318
  function createServerWorld(platformHandle) {
268
319
  if (!platformHandle.config.world)
269
320
  return null;
@@ -272,36 +323,149 @@ function createServerWorld(platformHandle) {
272
323
  throw worldError("The persistent-world checkpoint broker is unavailable.", "read");
273
324
  }
274
325
  const initial = parseWorldSnapshot(platformHandle.config.world, "read");
326
+ const read = async () => {
327
+ const result = await platformHandle.worldCheckpointRead();
328
+ return parseWorldSnapshot(parsePlatformJson(result, "read"), "read");
329
+ };
330
+ const commit = async (input) => {
331
+ const expectedRevision = assertWorldRevision(input?.expectedRevision);
332
+ const operationId = assertWorldOperationId(input?.operationId);
333
+ const checkpoint = assertWorldCheckpoint(input?.checkpoint);
334
+ const raw = await platformHandle.worldCheckpointCommit(JSON.stringify({
335
+ expectedRevision,
336
+ operationId,
337
+ checkpoint,
338
+ }));
339
+ const result = parsePlatformJson(raw, "commit");
340
+ if (typeof result.replayed !== "boolean") {
341
+ throw worldError("The platform returned an invalid commit receipt.", "commit");
342
+ }
343
+ return Object.freeze({
344
+ revision: assertWorldRevision(result.revision),
345
+ replayed: result.replayed,
346
+ operationId,
347
+ });
348
+ };
275
349
  return Object.freeze({
276
350
  snapshot: initial,
277
351
  journal: createServerWorldJournal(platformHandle),
278
352
  participants: createServerWorldParticipants(platformHandle),
353
+ notifications: createServerWorldNotifications(platformHandle),
279
354
  characters: createServerWorldCharacters(platformHandle),
280
- async read() {
281
- const result = await platformHandle.worldCheckpointRead();
282
- return parseWorldSnapshot(parsePlatformJson(result, "read"), "read");
355
+ read,
356
+ commit,
357
+ async catchUp(options) {
358
+ return catchUpWorld(platformHandle.config.world?.worldTime, read, commit, options);
283
359
  },
284
- async commit(input) {
285
- const expectedRevision = assertWorldRevision(input?.expectedRevision);
286
- const operationId = assertWorldOperationId(input?.operationId);
287
- const checkpoint = assertWorldCheckpoint(input?.checkpoint);
288
- const raw = await platformHandle.worldCheckpointCommit(JSON.stringify({
289
- expectedRevision,
290
- operationId,
291
- checkpoint,
292
- }));
293
- const result = parsePlatformJson(raw, "commit");
294
- if (typeof result.replayed !== "boolean") {
295
- throw worldError("The platform returned an invalid commit receipt.", "commit");
360
+ });
361
+ }
362
+ async function catchUpWorld(worldTime, read, commit, options) {
363
+ const operation = "session.world.catchUp";
364
+ if (worldTime?.advance !== "wallClock") {
365
+ throw worldJournalArgumentError('The destination must opt in with worldTime.advance set to "wallClock".', operation);
366
+ }
367
+ assertOnlyKeys(options, ["key", "maxElapsedMs", "apply"], operation, "options");
368
+ const key = options.key === undefined
369
+ ? "advancedThroughMs"
370
+ : assertWorldCatchUpKey(options.key, operation);
371
+ const maxElapsedMs = options.maxElapsedMs === undefined
372
+ ? WORLD_CATCH_UP_DEFAULT_MAX_ELAPSED_MS
373
+ : assertBoundedInteger(options.maxElapsedMs, 0, Number.MAX_SAFE_INTEGER, "maxElapsedMs", operation);
374
+ if (typeof options.apply !== "function") {
375
+ throw worldJournalArgumentError("apply must be a function.", operation);
376
+ }
377
+ const now = Date.now();
378
+ let snapshot = await read();
379
+ for (let attempt = 0; attempt < 2; attempt += 1) {
380
+ const state = worldCatchUpState(snapshot.checkpoint, key, now, maxElapsedMs, operation);
381
+ if (state.markerExists && state.elapsedMs === 0) {
382
+ if (state.markerMs >= now) {
383
+ return Object.freeze({ applied: false, elapsedMs: 0, revision: snapshot.revision });
296
384
  }
385
+ const checkpoint = checkpointWithCatchUpMarker(snapshot.checkpoint, key, state.markerMs, now, operation);
386
+ try {
387
+ const receipt = await commit({
388
+ expectedRevision: snapshot.revision,
389
+ operationId: `catchUp:${snapshot.revision}`,
390
+ checkpoint,
391
+ });
392
+ return Object.freeze({ applied: false, elapsedMs: 0, revision: receipt.revision });
393
+ }
394
+ catch (error) {
395
+ if (attempt !== 0 || !isWorldRevisionConflict(error))
396
+ throw error;
397
+ snapshot = await read();
398
+ continue;
399
+ }
400
+ }
401
+ const returned = await options.apply(Object.freeze({
402
+ elapsedMs: state.elapsedMs,
403
+ now,
404
+ checkpoint: snapshot.checkpoint,
405
+ }));
406
+ const normalized = assertWorldCheckpoint(returned, "commit");
407
+ if (!isRecord(normalized.value)) {
408
+ throw worldJournalArgumentError("apply must return a checkpoint whose value is an object.", operation);
409
+ }
410
+ const checkpoint = checkpointWithCatchUpMarker(normalized, key, state.markerMs, now, operation);
411
+ try {
412
+ const receipt = await commit({
413
+ expectedRevision: snapshot.revision,
414
+ operationId: `catchUp:${snapshot.revision}`,
415
+ checkpoint,
416
+ });
297
417
  return Object.freeze({
298
- revision: assertWorldRevision(result.revision),
299
- replayed: result.replayed,
300
- operationId,
418
+ applied: !receipt.replayed,
419
+ elapsedMs: state.elapsedMs,
420
+ revision: receipt.revision,
301
421
  });
302
- },
422
+ }
423
+ catch (error) {
424
+ if (attempt !== 0 || !isWorldRevisionConflict(error))
425
+ throw error;
426
+ snapshot = await read();
427
+ }
428
+ }
429
+ throw new TypeError(`${operation}: unreachable catch-up state.`);
430
+ }
431
+ function assertWorldCatchUpKey(value, operation) {
432
+ if (typeof value !== "string") {
433
+ throw worldJournalArgumentError("key must be a string.", operation);
434
+ }
435
+ return value;
436
+ }
437
+ function worldCatchUpState(checkpoint, key, now, maxElapsedMs, operation) {
438
+ if (!checkpoint ||
439
+ !isRecord(checkpoint.value) ||
440
+ !Object.prototype.hasOwnProperty.call(checkpoint.value, key)) {
441
+ return { markerExists: false, markerMs: now, elapsedMs: 0 };
442
+ }
443
+ const advancedThroughMs = checkpoint.value[key];
444
+ if (!Number.isSafeInteger(advancedThroughMs) || advancedThroughMs < 0) {
445
+ throw worldJournalArgumentError(`checkpoint.value.${key} must be a non-negative integer timestamp in milliseconds.`, operation);
446
+ }
447
+ const markerMs = advancedThroughMs;
448
+ return {
449
+ markerExists: true,
450
+ markerMs,
451
+ elapsedMs: Math.min(maxElapsedMs, Math.max(0, now - markerMs)),
452
+ };
453
+ }
454
+ function checkpointWithCatchUpMarker(checkpoint, key, existingMarkerMs, now, operation) {
455
+ if (!isRecord(checkpoint.value)) {
456
+ throw worldJournalArgumentError("apply must return a checkpoint whose value is an object.", operation);
457
+ }
458
+ return Object.freeze({
459
+ version: checkpoint.version,
460
+ value: Object.freeze({
461
+ ...checkpoint.value,
462
+ [key]: Math.max(existingMarkerMs, now),
463
+ }),
303
464
  });
304
465
  }
466
+ function isWorldRevisionConflict(error) {
467
+ return isRecord(error) && error.code === "CAULDRON_WORLD_REVISION_CONFLICT";
468
+ }
305
469
  function createServerWorldJournal(platformHandle) {
306
470
  return Object.freeze({
307
471
  async append(input) {
@@ -382,6 +546,167 @@ function createServerWorldParticipants(platformHandle) {
382
546
  },
383
547
  });
384
548
  }
549
+ function createServerWorldNotifications(platformHandle) {
550
+ return Object.freeze({
551
+ async notify(input) {
552
+ const operation = "session.world.notifications.notify";
553
+ assertOnlyKeys(input, ["key", "participantIds", "templateId", "slots", "at", "expiresAt"], operation, "input");
554
+ const now = Date.now();
555
+ const key = assertWorldNotificationSafeKey(input.key, "key", operation);
556
+ const participantIds = normalizeParticipantIds(input.participantIds, WORLD_NOTIFICATIONS_MAX_PARTICIPANTS, "participantIds", operation);
557
+ const templateId = assertWorldNotificationSafeKey(input.templateId, "templateId", operation);
558
+ const slots = input.slots === undefined
559
+ ? undefined
560
+ : normalizeWorldNotificationSlots(input.slots, operation);
561
+ const at = input.at === undefined
562
+ ? undefined
563
+ : assertWorldNotificationTime(input.at, "at", operation);
564
+ const atMs = at?.milliseconds ?? now;
565
+ if (atMs < now - WORLD_NOTIFICATIONS_PAST_TOLERANCE_MS ||
566
+ atMs > now + WORLD_NOTIFICATIONS_MAX_SCHEDULE_MS) {
567
+ throw worldJournalArgumentError("at must be no more than 60 seconds in the past and at most 30 days ahead.", operation);
568
+ }
569
+ // Ghost clamps a tolerated past `at` to its own now, so expiry is judged
570
+ // against that effective time, not the original timestamp.
571
+ const effectiveAtMs = Math.max(atMs, now);
572
+ const expiresAt = input.expiresAt === undefined
573
+ ? undefined
574
+ : assertWorldNotificationTime(input.expiresAt, "expiresAt", operation);
575
+ if (expiresAt &&
576
+ (expiresAt.milliseconds <= effectiveAtMs ||
577
+ expiresAt.milliseconds > effectiveAtMs + WORLD_NOTIFICATIONS_MAX_SCHEDULE_MS)) {
578
+ throw worldJournalArgumentError("expiresAt must be after at and at most 30 days after it.", operation);
579
+ }
580
+ const args = {
581
+ key,
582
+ participantIds,
583
+ templateId,
584
+ ...(slots === undefined ? {} : { slots }),
585
+ ...(at === undefined ? {} : { at: at.value }),
586
+ ...(expiresAt === undefined ? {} : { expiresAt: expiresAt.value }),
587
+ };
588
+ const result = parseWorldNotificationResult(await callWorldNotificationStorage(platformHandle, "worldNotify", args, operation), operation);
589
+ if (result.key !== key)
590
+ throw invalidWorldNotificationResponse(operation);
591
+ return Object.freeze({
592
+ key,
593
+ accepted: parseWorldNotificationCount(result.accepted, operation),
594
+ skipped: parseWorldNotificationCount(result.skipped, operation),
595
+ limited: parseWorldNotificationCount(result.limited, operation),
596
+ });
597
+ },
598
+ async cancel(input) {
599
+ const operation = "session.world.notifications.cancel";
600
+ assertOnlyKeys(input, ["key", "participantIds"], operation, "input");
601
+ const key = assertWorldNotificationSafeKey(input.key, "key", operation);
602
+ const participantIds = input.participantIds === undefined
603
+ ? undefined
604
+ : normalizeParticipantIds(input.participantIds, WORLD_NOTIFICATIONS_MAX_PARTICIPANTS, "participantIds", operation);
605
+ const args = {
606
+ key,
607
+ ...(participantIds === undefined ? {} : { participantIds }),
608
+ };
609
+ const result = parseWorldNotificationResult(await callWorldNotificationStorage(platformHandle, "worldNotifyCancel", args, operation), operation);
610
+ return Object.freeze({
611
+ cancelled: parseWorldNotificationCount(result.cancelled, operation),
612
+ });
613
+ },
614
+ });
615
+ }
616
+ function assertWorldNotificationSafeKey(value, field, operation) {
617
+ if (typeof value !== "string" ||
618
+ worldNotificationCharacters(value) < 1 ||
619
+ worldNotificationCharacters(value) > 64 ||
620
+ !SAFE_WORLD_NOTIFICATION_KEY.test(value)) {
621
+ throw worldJournalArgumentError(`${field} must be a safe key of at most 64 characters.`, operation);
622
+ }
623
+ return value;
624
+ }
625
+ function normalizeWorldNotificationSlots(value, operation) {
626
+ if (!isRecord(value)) {
627
+ throw worldJournalArgumentError("slots must be an object.", operation);
628
+ }
629
+ const entries = Object.entries(value);
630
+ if (entries.length > WORLD_NOTIFICATIONS_MAX_SLOTS) {
631
+ throw worldJournalArgumentError(`slots may contain at most ${WORLD_NOTIFICATIONS_MAX_SLOTS} values.`, operation);
632
+ }
633
+ const normalized = {};
634
+ for (const [key, slotValue] of entries.sort(([left], [right]) => left.localeCompare(right))) {
635
+ assertWorldNotificationSafeKey(key, `slots.${key}`, operation);
636
+ if (typeof slotValue !== "string" ||
637
+ worldNotificationCharacters(slotValue) < 1 ||
638
+ worldNotificationCharacters(slotValue) > WORLD_NOTIFICATIONS_MAX_SLOT_CHARACTERS ||
639
+ slotValue.includes("\0") ||
640
+ hasUnpairedSurrogate(slotValue) ||
641
+ slotValue.includes("\n") ||
642
+ slotValue.includes("\r") ||
643
+ URL_IN_WORLD_NOTIFICATION_TEXT.test(slotValue)) {
644
+ throw worldJournalArgumentError(`slots.${key} must be 1 through ${WORLD_NOTIFICATIONS_MAX_SLOT_CHARACTERS} ` +
645
+ "characters of single-line text without a URL.", operation);
646
+ }
647
+ normalized[key] = slotValue;
648
+ }
649
+ return Object.freeze(normalized);
650
+ }
651
+ function worldNotificationCharacters(value) {
652
+ return Array.from(value).length;
653
+ }
654
+ function assertWorldNotificationTime(value, field, operation) {
655
+ if (typeof value !== "string") {
656
+ throw worldJournalArgumentError(`${field} must be a canonical ISO 8601 time with at most millisecond precision.`, operation);
657
+ }
658
+ const match = CANONICAL_WORLD_NOTIFICATION_TIME.exec(value);
659
+ const milliseconds = Date.parse(value);
660
+ if (!match || !Number.isFinite(milliseconds)) {
661
+ throw worldJournalArgumentError(`${field} must be a canonical ISO 8601 time with at most millisecond precision.`, operation);
662
+ }
663
+ const normalized = new Date(milliseconds).toISOString();
664
+ const normalizedFraction = normalized.slice(20, 23);
665
+ if (normalized.slice(0, 19) !== match[1] ||
666
+ (match[2] === undefined
667
+ ? normalizedFraction !== "000"
668
+ : normalizedFraction !== match[2].padEnd(3, "0"))) {
669
+ throw worldJournalArgumentError(`${field} must be a canonical ISO 8601 time with at most millisecond precision.`, operation);
670
+ }
671
+ return { value, milliseconds };
672
+ }
673
+ async function callWorldNotificationStorage(platformHandle, op, args, operation) {
674
+ if (typeof platformHandle.storage !== "function" || platformHandle.storageEnabled === false) {
675
+ throw worldNotificationsUnavailable(operation);
676
+ }
677
+ try {
678
+ return await platformHandle.storage(op, JSON.stringify(args));
679
+ }
680
+ catch (error) {
681
+ if (isUnknownStorageOperation(error))
682
+ throw worldNotificationsUnavailable(operation);
683
+ throw error;
684
+ }
685
+ }
686
+ function worldNotificationsUnavailable(operation) {
687
+ return storageError("CAULDRON_WORLD_NOTIFICATIONS_UNAVAILABLE", "This Castle host does not support persistent-world notifications.", operation);
688
+ }
689
+ function parseWorldNotificationResult(value, operation) {
690
+ let result;
691
+ try {
692
+ result = JSON.parse(value);
693
+ }
694
+ catch {
695
+ throw invalidWorldNotificationResponse(operation);
696
+ }
697
+ if (!isRecord(result))
698
+ throw invalidWorldNotificationResponse(operation);
699
+ return result;
700
+ }
701
+ function parseWorldNotificationCount(value, operation) {
702
+ if (!Number.isSafeInteger(value) || value < 0) {
703
+ throw invalidWorldNotificationResponse(operation);
704
+ }
705
+ return value;
706
+ }
707
+ function invalidWorldNotificationResponse(operation) {
708
+ return new TypeError(`${operation}: The platform returned an invalid response.`);
709
+ }
385
710
  function normalizeWorldJournalAppendEntry(value, index, operation) {
386
711
  const field = `entries[${index}]`;
387
712
  assertOnlyKeys(value, ["kind", "disclosure", "participantIds", "data"], operation, field);
@@ -973,13 +1298,51 @@ function requireBroadcastBinary(platformHandle) {
973
1298
  function unsupportedBinaryRuntime() {
974
1299
  throw new TypeError("This Castle runtime does not support binary multiplayer messages yet.");
975
1300
  }
1301
+ // The compatibility branch accepts the current Node shim's legacy
1302
+ // single-argument SessionPlayer event while the public handle contract uses the
1303
+ // runtime-agnostic (connId, trusted identity) pair. Either form may carry the hub
1304
+ // arrival after the player and the player's A/B arms after that, and a hub
1305
+ // player's block list on the player itself.
1306
+ function admitPlayer(state, connId, identity, handleArrival, handleVariants) {
1307
+ const player = joinedPlayer(connId, identity);
1308
+ const arrival = hubArrival(typeof connId === "string" ? handleArrival : identity);
1309
+ const known = experimentVariants(typeof connId === "string" ? handleVariants : handleArrival);
1310
+ state.players.set(player.playerId, player);
1311
+ if (known) {
1312
+ state.variants.set(player.playerId, known);
1313
+ }
1314
+ else {
1315
+ state.variants.delete(player.playerId);
1316
+ }
1317
+ recordHiddenUserIds(state.hidden, player.playerId, typeof connId === "string" ? identity : connId);
1318
+ if (arrival) {
1319
+ state.arrivals.set(player.playerId, arrival);
1320
+ }
1321
+ else {
1322
+ state.arrivals.delete(player.playerId);
1323
+ }
1324
+ return { player, arrival };
1325
+ }
1326
+ // Absent on a host that predates experiments, and for a player who is in none.
1327
+ function experimentVariants(value) {
1328
+ if (!value || typeof value !== "object" || Array.isArray(value))
1329
+ return null;
1330
+ const entries = Object.entries(value).filter((entry) => typeof entry[1] === "string");
1331
+ return entries.length > 0 ? Object.freeze(Object.fromEntries(entries)) : null;
1332
+ }
976
1333
  function joinedPlayer(connId, identity) {
977
1334
  if (typeof connId === "string") {
978
- return {
1335
+ const player = {
979
1336
  ...identity,
980
1337
  playerId: connId,
981
1338
  participantId: identity.scopedUserId ?? identity.userId,
982
1339
  };
1340
+ // A hub player's block list stays in the wrapper (`session.hub.hiddenPair`):
1341
+ // decks broadcast player objects.
1342
+ delete player.hiddenUserIds;
1343
+ // A/B arms arrive beside the player; one a host put on it stays off it too.
1344
+ delete player.experimentVariants;
1345
+ return player;
983
1346
  }
984
1347
  const legacy = connId;
985
1348
  return {
@@ -1,4 +1,4 @@
1
- import { type CommandName, type CommandParams, type CommandResult, type LifecycleEvent, type VoiceEvent } from "./commands";
1
+ import { type CommandName, type CommandParams, type CommandResult, type HubEvent, type LifecycleEvent, type VoiceEvent } from "./commands";
2
2
  type PostChannel = "mobile" | "web";
3
3
  export interface HostStreamOptions {
4
4
  onStream?: (event: unknown) => void;
@@ -21,5 +21,6 @@ export declare function hostNotify(event: LifecycleEvent): void;
21
21
  export declare function postUnloadDone(unloadId: string, state?: string): void;
22
22
  export declare function setUnloadHandler(handler: (unloadId: string) => void): void;
23
23
  export declare function setVoiceEventHandler(handler: ((event: VoiceEvent) => void) | null): void;
24
+ export declare function setHubEventHandler(handler: ((event: HubEvent) => void) | null): void;
24
25
  export declare function installHostListener(): void;
25
26
  export {};
@@ -11,7 +11,7 @@
11
11
  // A streaming command (agent.chat) gets stream envelopes on its requestId before
12
12
  // its response. Each one goes to the caller's onStream and restarts the wait,
13
13
  // and the caller's AbortSignal sends the host a cancel envelope.
14
- import { CASTLE_SDK_PROTOCOL, COMMAND_TIMEOUTS_MS, STREAM_IDLE_TIMEOUT_MS, isResponseEnvelope, isStreamEnvelope, unloadRequestId, voiceEventFrom, } from "./commands";
14
+ import { CASTLE_SDK_PROTOCOL, COMMAND_TIMEOUTS_MS, STREAM_IDLE_TIMEOUT_MS, isResponseEnvelope, isStreamEnvelope, hubEventFrom, unloadRequestId, voiceEventFrom, } from "./commands";
15
15
  import { getCastleEmbed } from "./context";
16
16
  import { CastleError } from "./errors";
17
17
  import { cancelLocalCommand, releaseLocalCommand, sendLocalCommand } from "./runtime";
@@ -35,6 +35,7 @@ const pending = new Map();
35
35
  let listenersInstalled = false;
36
36
  let unloadHandler = null;
37
37
  let voiceEventHandler = null;
38
+ let hubEventHandler = null;
38
39
  export async function hostRequest(command, params, stream = {}) {
39
40
  try {
40
41
  const env = await sendCommand(resolveChannel(), command, params, stream);
@@ -103,6 +104,12 @@ export function setVoiceEventHandler(handler) {
103
104
  if (handler)
104
105
  installHostListener();
105
106
  }
107
+ // Registered by hub.ts while the deck listens for the host's Back control.
108
+ export function setHubEventHandler(handler) {
109
+ hubEventHandler = handler;
110
+ if (handler)
111
+ installHostListener();
112
+ }
106
113
  function resolveChannel() {
107
114
  if (typeof window === "undefined")
108
115
  return "local";
@@ -233,6 +240,11 @@ function receive(message) {
233
240
  voiceEventHandler?.(voiceEvent);
234
241
  return;
235
242
  }
243
+ const hubEvent = hubEventFrom(message);
244
+ if (hubEvent) {
245
+ hubEventHandler?.(hubEvent);
246
+ return;
247
+ }
236
248
  const unloadId = unloadRequestId(message);
237
249
  if (unloadId !== null)
238
250
  unloadHandler?.(unloadId);
@@ -0,0 +1,5 @@
1
+ {
2
+ "printWidth": 100,
3
+ "tabWidth": 2,
4
+ "singleQuote": true
5
+ }