castle-web-cli 0.4.229 → 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 (232) 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 +779 -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/devSessionChild.js +3 -1
  19. package/dist/devSessionServer.d.ts +14 -1
  20. package/dist/devSessionServer.js +229 -44
  21. package/dist/experimentAssignment.d.ts +15 -0
  22. package/dist/experimentAssignment.js +41 -0
  23. package/dist/importCheckHook.d.ts +40 -0
  24. package/dist/importCheckHook.js +171 -0
  25. package/dist/importRegression.d.ts +15 -0
  26. package/dist/importRegression.js +100 -0
  27. package/dist/importTrust.d.ts +2 -0
  28. package/dist/importTrust.js +27 -0
  29. package/dist/importUpdateHook.d.ts +18 -0
  30. package/dist/importUpdateHook.js +31 -8
  31. package/dist/importUpdateHookRunner.js +19 -7
  32. package/dist/imports.d.ts +16 -0
  33. package/dist/imports.js +141 -31
  34. package/dist/index.js +3 -1
  35. package/dist/init.d.ts +3 -0
  36. package/dist/init.js +125 -8
  37. package/dist/install.js +4 -1
  38. package/dist/localPaths.js +4 -0
  39. package/dist/login.js +2 -2
  40. package/dist/platformDoc.js +3 -8
  41. package/dist/playPagePolicy.js +3 -1
  42. package/dist/remix.js +5 -0
  43. package/dist/routerTaskReport.d.ts +28 -0
  44. package/dist/routerTaskReport.js +56 -0
  45. package/dist/save-deck.d.ts +18 -0
  46. package/dist/save-deck.js +142 -6
  47. package/dist/serve.d.ts +8 -0
  48. package/dist/serve.js +94 -13
  49. package/dist/serverBundle.d.ts +1 -1
  50. package/dist/serverBundle.js +5 -1
  51. package/dist/webSourceSync.d.ts +2 -0
  52. package/dist/webSourceSync.js +2 -0
  53. package/kits/base/CLAUDE.md +2 -3
  54. package/kits/base/castle.json +1 -1
  55. package/kits/base/sdk/README.md +258 -52
  56. package/kits/base/sdk/agent.js +4 -4
  57. package/kits/base/sdk/avatar.d.ts +12 -0
  58. package/kits/base/sdk/avatar.js +23 -0
  59. package/kits/base/sdk/castle.d.ts +5 -0
  60. package/kits/base/sdk/castle.js +3 -0
  61. package/kits/base/sdk/commands.d.ts +208 -0
  62. package/kits/base/sdk/commands.js +16 -0
  63. package/kits/base/sdk/context.d.ts +6 -0
  64. package/kits/base/sdk/experiments.d.ts +15 -0
  65. package/kits/base/sdk/experiments.js +83 -0
  66. package/kits/base/sdk/hub.d.ts +85 -0
  67. package/kits/base/sdk/hub.js +107 -0
  68. package/kits/base/sdk/multiplayer.d.ts +45 -1
  69. package/kits/base/sdk/multiplayer.js +106 -4
  70. package/kits/base/sdk/server/hub.d.ts +169 -0
  71. package/kits/base/sdk/server/hub.js +125 -0
  72. package/kits/base/sdk/server/platformHandle.d.ts +42 -1
  73. package/kits/base/sdk/server/storage.d.ts +55 -2
  74. package/kits/base/sdk/server/wrapper.d.ts +32 -2
  75. package/kits/base/sdk/server/wrapper.js +90 -11
  76. package/kits/base/sdk/transport.d.ts +2 -1
  77. package/kits/base/sdk/transport.js +13 -1
  78. package/kits/hub-game/.prettierrc +5 -0
  79. package/kits/hub-game/CLAUDE.md +146 -0
  80. package/kits/hub-game/blueprints/avatar-0.scene +28 -0
  81. package/kits/hub-game/blueprints/avatar-1.scene +28 -0
  82. package/kits/hub-game/blueprints/avatar-2.scene +28 -0
  83. package/kits/hub-game/blueprints/avatar-3.scene +28 -0
  84. package/kits/hub-game/blueprints/bean/avatar-0.scene +28 -0
  85. package/kits/hub-game/blueprints/bean/avatar-1.scene +28 -0
  86. package/kits/hub-game/blueprints/bean/avatar-2.scene +28 -0
  87. package/kits/hub-game/blueprints/bean/avatar-3.scene +28 -0
  88. package/kits/hub-game/blueprints/blocky/avatar-0.scene +28 -0
  89. package/kits/hub-game/blueprints/blocky/avatar-1.scene +28 -0
  90. package/kits/hub-game/blueprints/blocky/avatar-2.scene +28 -0
  91. package/kits/hub-game/blueprints/blocky/avatar-3.scene +28 -0
  92. package/kits/hub-game/blueprints/pixel/avatar-0.scene +28 -0
  93. package/kits/hub-game/blueprints/pixel/avatar-1.scene +28 -0
  94. package/kits/hub-game/blueprints/pixel/avatar-2.scene +28 -0
  95. package/kits/hub-game/blueprints/pixel/avatar-3.scene +28 -0
  96. package/kits/hub-game/castle.json +96 -0
  97. package/kits/hub-game/code/client/attention.js +133 -0
  98. package/kits/hub-game/code/client/avatar.js +288 -0
  99. package/kits/hub-game/code/client/cabinets.js +90 -0
  100. package/kits/hub-game/code/client/chat.js +135 -0
  101. package/kits/hub-game/code/client/chrome.js +1001 -0
  102. package/kits/hub-game/code/client/doorFrame.js +15 -0
  103. package/kits/hub-game/code/client/firstJoin.js +14 -0
  104. package/kits/hub-game/code/client/grab.js +241 -0
  105. package/kits/hub-game/code/client/hookLayer.js +230 -0
  106. package/kits/hub-game/code/client/idle.js +326 -0
  107. package/kits/hub-game/code/client/keys.js +48 -0
  108. package/kits/hub-game/code/client/pack.js +232 -0
  109. package/kits/hub-game/code/client/packFormat.js +397 -0
  110. package/kits/hub-game/code/client/say.js +127 -0
  111. package/kits/hub-game/code/client/sha256.js +80 -0
  112. package/kits/hub-game/code/client/sound.js +147 -0
  113. package/kits/hub-game/code/client/state.js +131 -0
  114. package/kits/hub-game/code/client/talk.js +259 -0
  115. package/kits/hub-game/code/client/together.js +365 -0
  116. package/kits/hub-game/code/client/wear.js +149 -0
  117. package/kits/hub-game/code/server/actors.js +627 -0
  118. package/kits/hub-game/code/server/blocks.js +103 -0
  119. package/kits/hub-game/code/server/cabinets.js +309 -0
  120. package/kits/hub-game/code/server/game.js +137 -0
  121. package/kits/hub-game/code/server/grab.js +247 -0
  122. package/kits/hub-game/code/server/history.js +96 -0
  123. package/kits/hub-game/code/server/hub.js +1904 -0
  124. package/kits/hub-game/code/server/idle.js +412 -0
  125. package/kits/hub-game/code/server/index.js +64 -0
  126. package/kits/hub-game/code/server/labels.js +59 -0
  127. package/kits/hub-game/code/server/manifest.js +527 -0
  128. package/kits/hub-game/code/server/npcs.js +745 -0
  129. package/kits/hub-game/code/server/party.js +381 -0
  130. package/kits/hub-game/code/server/place.js +43 -0
  131. package/kits/hub-game/code/server/say.js +83 -0
  132. package/kits/hub-game/code/server/wear.js +142 -0
  133. package/kits/hub-game/code/systems/hub.js +2230 -0
  134. package/kits/hub-game/docs/content-pack.md +151 -0
  135. package/kits/hub-game/docs/contract.md +1139 -0
  136. package/kits/hub-game/docs/style.md +137 -0
  137. package/kits/hub-game/drawings/blocky/castle-eye.sprite +58 -0
  138. package/kits/hub-game/drawings/blocky/dash.sprite +59 -0
  139. package/kits/hub-game/drawings/blocky/pom.sprite +59 -0
  140. package/kits/hub-game/drawings/blocky/tabby.sprite +59 -0
  141. package/kits/hub-game/drawings/pixel/castle-arm.sprite +13 -0
  142. package/kits/hub-game/drawings/pixel/castle-body.sprite +23 -0
  143. package/kits/hub-game/drawings/pixel/castle-leg.sprite +12 -0
  144. package/kits/hub-game/drawings/pixel/kai-arm.sprite +14 -0
  145. package/kits/hub-game/drawings/pixel/kai-head.sprite +24 -0
  146. package/kits/hub-game/drawings/pixel/kai-leg.sprite +15 -0
  147. package/kits/hub-game/drawings/pixel/kai-torso.sprite +18 -0
  148. package/kits/hub-game/drawings/pixel/mimi-arm.sprite +13 -0
  149. package/kits/hub-game/drawings/pixel/mimi-head.sprite +23 -0
  150. package/kits/hub-game/drawings/pixel/mimi-leg.sprite +15 -0
  151. package/kits/hub-game/drawings/pixel/mimi-torso.sprite +18 -0
  152. package/kits/hub-game/drawings/pixel/nox-arm.sprite +13 -0
  153. package/kits/hub-game/drawings/pixel/nox-head.sprite +21 -0
  154. package/kits/hub-game/drawings/pixel/nox-leg.sprite +14 -0
  155. package/kits/hub-game/drawings/pixel/nox-torso.sprite +18 -0
  156. package/kits/hub-game/eslint.config.js +20 -0
  157. package/kits/hub-game/fonts.generated.js +9 -0
  158. package/kits/hub-game/index.html +22 -0
  159. package/kits/hub-game/main.jsx +6 -0
  160. package/kits/hub-game/models/avatar-0.pxmodel +21 -0
  161. package/kits/hub-game/models/avatar-1.pxmodel +24 -0
  162. package/kits/hub-game/models/avatar-2.pxmodel +27 -0
  163. package/kits/hub-game/models/avatar-3.pxmodel +22 -0
  164. package/kits/hub-game/models/bean/avatar-0.pxmodel +19 -0
  165. package/kits/hub-game/models/bean/avatar-1.pxmodel +24 -0
  166. package/kits/hub-game/models/bean/avatar-2.pxmodel +22 -0
  167. package/kits/hub-game/models/bean/avatar-3.pxmodel +24 -0
  168. package/kits/hub-game/models/blocky/avatar-0.pxmodel +21 -0
  169. package/kits/hub-game/models/blocky/avatar-1.pxmodel +30 -0
  170. package/kits/hub-game/models/blocky/avatar-2.pxmodel +28 -0
  171. package/kits/hub-game/models/blocky/avatar-3.pxmodel +27 -0
  172. package/kits/hub-game/models/pixel/avatar-0.pxmodel +24 -0
  173. package/kits/hub-game/models/pixel/avatar-1.pxmodel +16 -0
  174. package/kits/hub-game/models/pixel/avatar-2.pxmodel +19 -0
  175. package/kits/hub-game/models/pixel/avatar-3.pxmodel +23 -0
  176. package/kits/hub-game/package-lock.json +365 -0
  177. package/kits/hub-game/package.json +32 -0
  178. package/kits/hub-game/scenes/main.scene +318 -0
  179. package/kits/hub-game/scripts/check.mjs +339 -0
  180. package/kits/hub-game/scripts/fixtures/sdk-stub.mjs +3 -0
  181. package/kits/hub-game/scripts/gen-avatars-bean.mjs +748 -0
  182. package/kits/hub-game/scripts/gen-avatars-blocky.mjs +607 -0
  183. package/kits/hub-game/scripts/gen-avatars-pixel.mjs +771 -0
  184. package/kits/hub-game/scripts/gen-avatars.mjs +621 -0
  185. package/kits/hub-game/scripts/pack.mjs +192 -0
  186. package/kits/hub-game/scripts/test-actors.mjs +666 -0
  187. package/kits/hub-game/scripts/test-attention.mjs +103 -0
  188. package/kits/hub-game/scripts/test-avatar.mjs +472 -0
  189. package/kits/hub-game/scripts/test-ban-join.mjs +194 -0
  190. package/kits/hub-game/scripts/test-blocks.mjs +351 -0
  191. package/kits/hub-game/scripts/test-chat.mjs +98 -0
  192. package/kits/hub-game/scripts/test-classic.mjs +590 -0
  193. package/kits/hub-game/scripts/test-door-jump.mjs +131 -0
  194. package/kits/hub-game/scripts/test-door.mjs +56 -0
  195. package/kits/hub-game/scripts/test-grab.mjs +331 -0
  196. package/kits/hub-game/scripts/test-hub-ops.mjs +835 -0
  197. package/kits/hub-game/scripts/test-hub-trip.mjs +1310 -0
  198. package/kits/hub-game/scripts/test-idle.mjs +518 -0
  199. package/kits/hub-game/scripts/test-interest.mjs +413 -0
  200. package/kits/hub-game/scripts/test-keys.mjs +50 -0
  201. package/kits/hub-game/scripts/test-manifest.mjs +224 -0
  202. package/kits/hub-game/scripts/test-no-forms.mjs +16 -0
  203. package/kits/hub-game/scripts/test-npcs.mjs +714 -0
  204. package/kits/hub-game/scripts/test-pack.mjs +424 -0
  205. package/kits/hub-game/scripts/test-party.mjs +286 -0
  206. package/kits/hub-game/scripts/test-say.mjs +149 -0
  207. package/kits/hub-game/scripts/test-together.mjs +183 -0
  208. package/kits/hub-game/theme.style +3 -0
  209. package/kits/multiplayer-3d/castle.json +5 -5
  210. package/kits/multiplayer-3d/code/client/avatars.js +101 -1
  211. package/kits/multiplayer-3d/code/server/players.js +4 -1
  212. package/kits/multiplayer-3d/code/server/sceneBodies.js +27 -6
  213. package/kits/multiplayer-3d/code/server/world.js +20 -7
  214. package/kits/multiplayer-3d/code/systems/multiplayer.js +222 -11
  215. package/kits/physics-2d/castle.json +2 -2
  216. package/kits/physics-2d/engine/art.js +13 -0
  217. package/kits/physics-2d/engine/assets.js +4 -2
  218. package/kits/physics-2d/engine/scene.js +25 -5
  219. package/kits/physics-3d/CLAUDE.md +6 -1
  220. package/kits/physics-3d/castle.json +3 -3
  221. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +32 -4
  222. package/kits/physics-3d/engine3d/artobjects.js +2 -2
  223. package/kits/physics-3d/engine3d/materials.js +29 -1
  224. package/kits/physics-3d/engine3d/world3d.js +65 -1
  225. package/kits/physics-3d/systems/physics3d.js +5 -2
  226. package/kits/real-time/castle.json +2 -2
  227. package/kits/real-time/code/client/connection.js +77 -7
  228. package/kits/real-time/code/client/gameHooks.js +63 -3
  229. package/kits/real-time/code/client/messages.js +7 -0
  230. package/kits/real-time/code/server/gameHooks.js +24 -0
  231. package/kits/real-time/code/server/session.js +390 -22
  232. package/package.json +2 -2
@@ -18,7 +18,12 @@ let nextCharacterStatusRequestId = 1;
18
18
  let activeConnection = null;
19
19
  let latestJoinAttempt = 0;
20
20
  let pendingDestinationJoin = null;
21
- export const Multiplayer = { join, joinHint, joinDestination };
21
+ export const Multiplayer = {
22
+ placeCharacters: true,
23
+ join,
24
+ joinHint,
25
+ joinDestination,
26
+ };
22
27
  async function joinHint() {
23
28
  try {
24
29
  return await hostRequest("multiplayer.getJoinHint", {});
@@ -30,18 +35,70 @@ async function joinHint() {
30
35
  }
31
36
  }
32
37
  async function join(options) {
33
- const params = joinParams(options);
38
+ const hub = hubJoin(options);
39
+ const request = hub
40
+ ? { command: "hub", nonce: hub.nonce }
41
+ : { command: "multiplayer.getSession", params: joinParams(options) };
34
42
  latestJoinAttempt += 1;
35
43
  cancelPendingDestinationJoin();
36
44
  activeConnection?.leave();
37
- const connection = new MultiplayerConnectionImpl({ command: "multiplayer.getSession", params }, () => {
45
+ const connection = new MultiplayerConnectionImpl(request, () => {
38
46
  if (activeConnection === connection)
39
47
  activeConnection = null;
40
48
  });
41
49
  activeConnection = connection;
42
- await connection.start();
50
+ await connection.start(hub ?? undefined);
51
+ // The host moves its place (and every place-scoped command with it) when the
52
+ // trip commits; the deck gets the connection once it has. A trip that did not
53
+ // commit leaves the player where they were, so its connection is closed.
54
+ if (!(await connection.hubCommitted())) {
55
+ connection.leave();
56
+ throw multiplayerError("MULTIPLAYER_UNAVAILABLE", "The hub trip could not be completed; the player is still where they were.", "Multiplayer.join");
57
+ }
43
58
  return connection;
44
59
  }
60
+ // A hub handoff is joined as it was acquired; it cannot be acquired again.
61
+ // The host answers `unavailable` while ghost is busy with this player; the
62
+ // trip stays pending there, so asking again is safe.
63
+ const HUB_COMMIT_RETRY_MS = [1_000, 2_000, 4_000, 8_000];
64
+ async function commitHubTrip(nonce, sessionId) {
65
+ for (let attempt = 0;; attempt++) {
66
+ let status;
67
+ try {
68
+ status = (await hostRequest("hub.commit", { nonce })).status;
69
+ }
70
+ catch (error) {
71
+ status = error instanceof CastleError ? error.code : "unavailable";
72
+ }
73
+ if (status === "committed")
74
+ return true;
75
+ const delay = HUB_COMMIT_RETRY_MS[attempt];
76
+ if ((status !== "unavailable" && status !== "CASTLE_HOST_UNAVAILABLE") || delay === undefined) {
77
+ console.warn(`Castle hub trip to ${sessionId} was not committed: ${status}`);
78
+ return false;
79
+ }
80
+ await pause(delay);
81
+ }
82
+ }
83
+ function hubJoin(options) {
84
+ if (!options || typeof options !== "object" || options.mode !== "hub")
85
+ return null;
86
+ const handoff = options.handoff;
87
+ if (!handoff ||
88
+ handoff.status !== "ok" ||
89
+ typeof handoff.url !== "string" ||
90
+ typeof handoff.nonce !== "string" ||
91
+ typeof handoff.sessionId !== "string") {
92
+ throw multiplayerError("INVALID_ARGUMENT", "Multiplayer.join({ mode: \"hub\" }) requires an ok result from Hub.go or Hub.back.", "Multiplayer.join");
93
+ }
94
+ return {
95
+ status: "ok",
96
+ url: handoff.url,
97
+ nonce: handoff.nonce,
98
+ sessionId: handoff.sessionId,
99
+ soloReason: null,
100
+ };
101
+ }
45
102
  async function joinDestination(options) {
46
103
  const params = destinationParams(options);
47
104
  const attempt = ++latestJoinAttempt;
@@ -129,6 +186,8 @@ class MultiplayerConnectionImpl {
129
186
  keepalive = null;
130
187
  reAcquisitionUsed = false;
131
188
  recovering = false;
189
+ hubSettled = false;
190
+ hubCommit = Promise.resolve(true);
132
191
  roster = null;
133
192
  sharedCharactersSupported = false;
134
193
  pendingCharacterRequests = new Map();
@@ -160,6 +219,9 @@ class MultiplayerConnectionImpl {
160
219
  get soloReason() {
161
220
  return this.currentSoloReason;
162
221
  }
222
+ get sharedCharacters() {
223
+ return this.sharedCharactersSupported;
224
+ }
163
225
  get voice() {
164
226
  return this.voiceImpl;
165
227
  }
@@ -168,6 +230,7 @@ class MultiplayerConnectionImpl {
168
230
  await this.acquire(initial);
169
231
  }
170
232
  catch (error) {
233
+ this.settleHub("cancel");
171
234
  const castleError = asCastleError(error);
172
235
  if (this.currentState !== "closed") {
173
236
  this.finish({ type: "error", error: castleError });
@@ -265,8 +328,26 @@ class MultiplayerConnectionImpl {
265
328
  leave() {
266
329
  if (this.currentState === "closed")
267
330
  return;
331
+ this.settleHub("cancel");
268
332
  this.finish({ type: "left" });
269
333
  }
334
+ // A hub trip is the host's to commit or cancel, once: committed when the
335
+ // destination first says hello, cancelled if the join ends before that. The
336
+ // acquisition is named by its nonce, which no other acquisition shares.
337
+ settleHub(outcome) {
338
+ if (this.request.command !== "hub" || this.hubSettled)
339
+ return;
340
+ this.hubSettled = true;
341
+ const nonce = this.request.nonce;
342
+ if (outcome === "cancel") {
343
+ hostRequest("hub.cancel", { nonce }).catch(() => { });
344
+ return;
345
+ }
346
+ this.hubCommit = commitHubTrip(nonce, this.currentSessionId);
347
+ }
348
+ hubCommitted() {
349
+ return this.hubCommit;
350
+ }
270
351
  matchesDestination(params) {
271
352
  return (this.currentState !== "closed" &&
272
353
  this.request.command === "multiplayer.joinDestination" &&
@@ -329,6 +410,8 @@ class MultiplayerConnectionImpl {
329
410
  }
330
411
  connectSolo(result) {
331
412
  this.solo = true;
413
+ // A solo session has no host, so no characters, whatever the last socket's hello offered.
414
+ this.sharedCharactersSupported = false;
332
415
  this.currentSoloReason = result.soloReason ?? "unavailable";
333
416
  this.currentPlayerId = "solo";
334
417
  this.currentSessionId = result.sessionId ?? "solo";
@@ -422,6 +505,7 @@ class MultiplayerConnectionImpl {
422
505
  // is backgrounded many times in a play, and each of those is its own outage;
423
506
  // without this the second one finds the budget spent and closes for good.
424
507
  this.reAcquisitionUsed = false;
508
+ this.settleHub("commit");
425
509
  this.transition("connected");
426
510
  this.startKeepalive();
427
511
  void this.voiceImpl.attach();
@@ -685,6 +769,11 @@ function cancelPendingDestinationJoin() {
685
769
  pending?.connection?.leave();
686
770
  }
687
771
  async function requestAcquisition(request) {
772
+ if (request.command === "hub") {
773
+ // The nonce was single-use and the trip is the host's; a hub session that
774
+ // cannot be reconnected to is left by going back through the door.
775
+ throw multiplayerError("MULTIPLAYER_CONNECTION_LOST", "A hub session cannot be acquired again. Go back through the door.");
776
+ }
688
777
  if (request.command === "multiplayer.getSession") {
689
778
  return hostRequest(request.command, request.params);
690
779
  }
@@ -778,6 +867,7 @@ function normalizeWorldCharacterCommandRequest(request) {
778
867
  type: "record_event",
779
868
  eventTypeId: boundedCharacterText(command.eventTypeId, 128, "command.eventTypeId", WORLD_CHARACTER_ID_MAX_CHARACTERS),
780
869
  ...(command.data === undefined ? {} : { data: normalizeJson(command.data, "command.data") }),
870
+ ...(command.witnesses === undefined ? {} : { witnesses: normalizeWitnesses(command.witnesses) }),
781
871
  },
782
872
  };
783
873
  }
@@ -843,8 +933,20 @@ function normalizeWorldCharacterReadRequest(request) {
843
933
  },
844
934
  };
845
935
  }
936
+ if (query.type === "actions") {
937
+ if (query.after !== undefined && (typeof query.after !== "string" || !/^\d{1,18}$/.test(query.after))) {
938
+ throw characterError("INVALID_ARGUMENT", "Character actions cursor must be a sequence string.");
939
+ }
940
+ return { requestId, query: { type: "actions", ...(query.after === undefined ? {} : { after: query.after }) } };
941
+ }
846
942
  throw characterError("INVALID_ARGUMENT", "Unknown shared character query type.");
847
943
  }
944
+ function normalizeWitnesses(value) {
945
+ if (!Array.isArray(value) || value.length > 4) {
946
+ throw characterError("INVALID_ARGUMENT", "command.witnesses must be at most 4 character ids.");
947
+ }
948
+ return value.map((item, index) => boundedCharacterText(item, 128, `command.witnesses[${index}]`, WORLD_CHARACTER_ID_MAX_CHARACTERS));
949
+ }
848
950
  function normalizeJson(value, field) {
849
951
  try {
850
952
  const text = JSON.stringify(value);
@@ -0,0 +1,169 @@
1
+ import type { PlatformHandle, PlatformHubResultShape } from "./platformHandle";
2
+ export type MultiplayerHubOutcome = "win" | "lose" | "draw";
3
+ export type MultiplayerHubResultShape = PlatformHubResultShape;
4
+ /** Where a player came in through a hub door: ghost's word, never a client's. */
5
+ export interface MultiplayerHubArrival {
6
+ /** The deck of the place the player came from. */
7
+ readonly fromDeckId: string;
8
+ /** The door of this place the player arrived by, when the door row names one. */
9
+ readonly doorId: string | null;
10
+ }
11
+ export interface MultiplayerHubResultInput {
12
+ /** This session's place; refused when it names another. */
13
+ place?: string;
14
+ outcome: MultiplayerHubOutcome;
15
+ score?: number;
16
+ stats?: Record<string, number | string>;
17
+ }
18
+ export interface MultiplayerHubRecord {
19
+ deckId: string;
20
+ place: string;
21
+ title: string | null;
22
+ plays: number;
23
+ outcomes: {
24
+ win: number;
25
+ lose: number;
26
+ draw: number;
27
+ };
28
+ bestScore: number | null;
29
+ unit: string | null;
30
+ better: "higher" | "lower" | null;
31
+ winStreak: number;
32
+ lastOutcome: MultiplayerHubOutcome | null;
33
+ lastScore: number | null;
34
+ lastAt: string;
35
+ }
36
+ export interface MultiplayerHubResultRow {
37
+ deckId: string;
38
+ place: string;
39
+ title: string | null;
40
+ outcome: MultiplayerHubOutcome;
41
+ score: number | null;
42
+ unit: string | null;
43
+ better: "higher" | "lower" | null;
44
+ stats: Record<string, number | string>;
45
+ at: string;
46
+ }
47
+ export interface MultiplayerHubReportReceipt {
48
+ recorded: boolean;
49
+ /** Why nothing was recorded: ghost already holds this visit's result. */
50
+ reason?: "duplicate";
51
+ record?: MultiplayerHubRecord;
52
+ }
53
+ /**
54
+ * A wearable on the player's platform avatar, drawn by the hub kit in every hub
55
+ * place: `kind` matches /^[a-z][a-z0-9-]{0,23}$/ (the kit draws the kinds it
56
+ * knows), `color` is '#rrggbb', `rarity` an integer 0-9.
57
+ */
58
+ export interface MultiplayerHubWearable {
59
+ kind: string;
60
+ color: string;
61
+ rarity: number;
62
+ }
63
+ export interface MultiplayerHubWearReceipt {
64
+ /** What the player now wears; null when cleared. */
65
+ wearable: MultiplayerHubWearable | null;
66
+ }
67
+ export interface MultiplayerHubPadUpdateInput {
68
+ /** A pad door of this place, from ghost's door table. */
69
+ doorId: string;
70
+ /** This gathering's id; a fired pad's group is fixed, so the next one needs a new id. */
71
+ padId: string;
72
+ /** Who stands on the pad. The host keeps only players connected to this session. */
73
+ memberUserIds: readonly string[];
74
+ /** Send the pad's players through the door now. */
75
+ fire?: boolean;
76
+ }
77
+ export interface MultiplayerHubPadUpdateResult {
78
+ status: "gathering" | "fired";
79
+ members: string[];
80
+ }
81
+ export interface MultiplayerHubResultsReadInput {
82
+ /** Players of this session to read; anyone not connected is dropped by the host. */
83
+ userIds?: readonly string[];
84
+ /** Doors of this place whose best scores to read, at most 16. */
85
+ doorIds?: readonly string[];
86
+ }
87
+ export interface MultiplayerHubPlayerResults {
88
+ /** Newest five results from the last hour. */
89
+ recent: MultiplayerHubResultRow[];
90
+ /** Newest twenty per-place records. */
91
+ records: MultiplayerHubRecord[];
92
+ /** The player's platform avatar, chosen or default; null when ghost has none to say. */
93
+ avatar: number | null;
94
+ /** The player's wearable; null when none. Absent from a ghost older than wearables. */
95
+ wearable?: MultiplayerHubWearable | null;
96
+ }
97
+ export interface MultiplayerHubBoard {
98
+ toDeckId: string;
99
+ title: string | null;
100
+ unit: string | null;
101
+ better: "higher" | "lower" | null;
102
+ top: {
103
+ userId: string;
104
+ username: string;
105
+ score: number;
106
+ at: string;
107
+ }[];
108
+ /** Featured today (the daily rotation, or set by hand). */
109
+ featured?: boolean;
110
+ /**
111
+ * The door row's group: the pad's minimum, the most that go through, and whether
112
+ * later arrivals join a running instance. Null where the row does not say; absent
113
+ * from a ghost older than these fields.
114
+ */
115
+ minPlayers?: number | null;
116
+ maxPlayers?: number | null;
117
+ lateJoin?: boolean;
118
+ /**
119
+ * Live presence behind the door, counts only and never who: players in the
120
+ * destination's public sessions from every town layer and entry, and how many of
121
+ * those sessions are open. Zero when nobody is inside; for an event gate, the
122
+ * current event's game. Absent from a ghost older than these fields.
123
+ */
124
+ playersInside?: number;
125
+ instancesOpen?: number;
126
+ }
127
+ export interface MultiplayerHubResultsRead {
128
+ players: Record<string, MultiplayerHubPlayerResults>;
129
+ boards: Record<string, MultiplayerHubBoard>;
130
+ }
131
+ /**
132
+ * The hub place this session runs, as ghost pinned it from the deck's published
133
+ * castle.json `hub` block. `session.hub` is null on a host without hub support
134
+ * and for a deck that declares no hub block.
135
+ */
136
+ export interface MultiplayerServerHub {
137
+ readonly place: string | null;
138
+ readonly title: string | null;
139
+ readonly result: MultiplayerHubResultShape | null;
140
+ /** How this player came in, when ghost placed them through a door; null otherwise. */
141
+ arrival(playerId: string): MultiplayerHubArrival | null;
142
+ /**
143
+ * Records a signed-in player's result for this visit, once. The host checks it
144
+ * against the published shape; ghost keeps it only for a place behind a curated
145
+ * door. Rejects with the platform's `CAULDRON_HUB_*` code.
146
+ */
147
+ reportResult(playerId: string, result: MultiplayerHubResultInput): Promise<MultiplayerHubReportReceipt>;
148
+ /** Names who stands on a pad, and fires it. */
149
+ updatePad(input: MultiplayerHubPadUpdateInput): Promise<MultiplayerHubPadUpdateResult>;
150
+ /** Results, avatars and wearables of players here, and the boards of this place's doors. */
151
+ readResults(input?: MultiplayerHubResultsReadInput): Promise<MultiplayerHubResultsRead>;
152
+ /**
153
+ * Puts a wearable on a signed-in player's platform avatar in every hub place, or
154
+ * clears it with null; latest wins. Castle takes it only from a curated hub place.
155
+ * Rejects with a `CAULDRON_HUB_*` code (`CAULDRON_HUB_UNAVAILABLE` on a runtime
156
+ * without it).
157
+ */
158
+ wear(playerId: string, wearable: MultiplayerHubWearable | null): Promise<MultiplayerHubWearReceipt>;
159
+ /**
160
+ * Whether a block hides these two players from each other: either one blocked
161
+ * the other, in either direction. Symmetric. The block lists themselves stay
162
+ * with the host and this wrapper; a place server learns only the pair, and
163
+ * only for players who are both here. False on hosts that send none.
164
+ */
165
+ hiddenPair(playerIdA: string, playerIdB: string): boolean;
166
+ }
167
+ export declare function hubArrival(raw: unknown): MultiplayerHubArrival | null;
168
+ export declare function recordHiddenUserIds(hidden: Map<string, ReadonlySet<string>>, playerId: string, raw: unknown): void;
169
+ export declare function createServerHub(platformHandle: PlatformHandle, arrivals: ReadonlyMap<string, MultiplayerHubArrival>, hiddenPair?: (playerIdA: string, playerIdB: string) => boolean): MultiplayerServerHub | null;
@@ -0,0 +1,125 @@
1
+ import { CastleError } from "../errors";
2
+ const DOOR_ID = /^[A-Za-z0-9_.:-]{1,64}$/;
3
+ export function hubArrival(raw) {
4
+ if (!raw || typeof raw !== "object")
5
+ return null;
6
+ const { fromDeckId, doorId } = raw;
7
+ if (typeof fromDeckId !== "string" || fromDeckId.length === 0 || fromDeckId.length > 64) {
8
+ return null;
9
+ }
10
+ return Object.freeze({
11
+ fromDeckId,
12
+ doorId: typeof doorId === "string" && DOOR_ID.test(doorId) ? doorId : null,
13
+ });
14
+ }
15
+ // The co-present users a block hides from a joining hub player, as the host
16
+ // sends them on the join (`player.hiddenUserIds`): decimal user ids, or null
17
+ // when there are none or the list is malformed.
18
+ const HIDDEN_USER_ID = /^\d{1,20}$/;
19
+ const HIDDEN_USER_IDS_MAX = 1000;
20
+ export function recordHiddenUserIds(hidden, playerId, raw) {
21
+ const ids = hubHiddenUserIds(raw);
22
+ if (ids) {
23
+ hidden.set(playerId, ids);
24
+ }
25
+ else {
26
+ hidden.delete(playerId);
27
+ }
28
+ }
29
+ function hubHiddenUserIds(raw) {
30
+ if (!raw || typeof raw !== "object")
31
+ return null;
32
+ const list = raw.hiddenUserIds;
33
+ if (!Array.isArray(list) || list.length === 0)
34
+ return null;
35
+ const ids = new Set();
36
+ for (const id of list.slice(0, HIDDEN_USER_IDS_MAX)) {
37
+ if (typeof id === "string" && HIDDEN_USER_ID.test(id))
38
+ ids.add(id);
39
+ }
40
+ return ids.size > 0 ? ids : null;
41
+ }
42
+ export function createServerHub(platformHandle, arrivals, hiddenPair = () => false) {
43
+ const pinned = platformHandle.hub;
44
+ if (!pinned ||
45
+ typeof platformHandle.hubResult !== "function" ||
46
+ typeof platformHandle.hubPadUpdate !== "function" ||
47
+ typeof platformHandle.hubResultsRead !== "function") {
48
+ return null;
49
+ }
50
+ const call = async (op, args) => {
51
+ const raw = await platformHandle[op](JSON.stringify(args));
52
+ let parsed;
53
+ try {
54
+ parsed = JSON.parse(raw);
55
+ }
56
+ catch {
57
+ parsed = null;
58
+ }
59
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
60
+ throw new CastleError({
61
+ code: "CAULDRON_HUB_INVALID_RESPONSE",
62
+ message: `The platform returned an invalid ${op} response.`,
63
+ operation: `session.hub.${op}`,
64
+ });
65
+ }
66
+ return parsed;
67
+ };
68
+ return Object.freeze({
69
+ place: typeof pinned.place === "string" ? pinned.place : null,
70
+ title: typeof pinned.title === "string" ? pinned.title : null,
71
+ result: pinned.result ?? null,
72
+ arrival(playerId) {
73
+ return arrivals.get(playerId) ?? null;
74
+ },
75
+ hiddenPair(playerIdA, playerIdB) {
76
+ return hiddenPair(playerIdA, playerIdB);
77
+ },
78
+ async reportResult(playerId, result) {
79
+ const { place, outcome, score, stats } = result ?? {};
80
+ return (await call("hubResult", {
81
+ playerId,
82
+ ...(place === undefined ? {} : { place }),
83
+ outcome,
84
+ ...(score === undefined || score === null ? {} : { score }),
85
+ ...(stats === undefined ? {} : { stats }),
86
+ }));
87
+ },
88
+ async updatePad(input) {
89
+ return (await call("hubPadUpdate", {
90
+ doorId: input?.doorId,
91
+ padId: input?.padId,
92
+ memberUserIds: [...(input?.memberUserIds ?? [])],
93
+ ...(input?.fire === true ? { fire: true } : {}),
94
+ }));
95
+ },
96
+ async readResults(input = {}) {
97
+ const read = await call("hubResultsRead", {
98
+ ...(input.userIds ? { userIds: [...input.userIds] } : {}),
99
+ ...(input.doorIds ? { doorIds: [...input.doorIds] } : {}),
100
+ });
101
+ return {
102
+ players: (read.players ?? {}),
103
+ boards: (read.boards ?? {}),
104
+ };
105
+ },
106
+ async wear(playerId, wearable) {
107
+ if (typeof platformHandle.hubWear !== "function") {
108
+ throw new CastleError({
109
+ code: "CAULDRON_HUB_UNAVAILABLE",
110
+ message: "This host's runtime cannot change wearables.",
111
+ operation: "session.hub.hubWear",
112
+ });
113
+ }
114
+ const receipt = await call("hubWear", {
115
+ playerId,
116
+ wearable: wearable === null || wearable === undefined
117
+ ? null
118
+ : { kind: wearable.kind, color: wearable.color, rarity: wearable.rarity },
119
+ });
120
+ return {
121
+ wearable: (receipt.wearable ?? null),
122
+ };
123
+ },
124
+ });
125
+ }
@@ -14,6 +14,16 @@ export interface PlatformSessionConfig {
14
14
  readonly tickRate: number;
15
15
  readonly maxPlayers: number;
16
16
  readonly world?: PlatformWorldSnapshot;
17
+ /**
18
+ * True when the host brokers a hub place's shared characters into this
19
+ * session without a world (a layer of the place). Absent on hosts that do not.
20
+ */
21
+ readonly placeCharacters?: boolean;
22
+ /**
23
+ * The place this session was started for, stamped by a host that placed it
24
+ * through a door (the hub's door table). Absent on hosts that do not.
25
+ */
26
+ readonly place?: string;
17
27
  }
18
28
  export interface PlatformWorldCheckpoint {
19
29
  version: number;
@@ -34,7 +44,7 @@ export interface PlatformHandle {
34
44
  sendBinary?(connId: string, bytes: Uint8Array | ArrayBuffer): void;
35
45
  broadcastBinary?(bytes: Uint8Array | ArrayBuffer): void;
36
46
  disconnect(connId: string, code: string | number): void;
37
- on(event: "join", callback: (connId: string, player: PlayerIdentity) => unknown): void;
47
+ on(event: "join", callback: (connId: string, player: PlayerIdentity, arrival?: PlatformHubArrival, experimentVariants?: Record<string, string>) => unknown): void;
38
48
  on(event: "leave", callback: (connId: string) => unknown): void;
39
49
  on(event: "message", callback: (connId: string, text: string) => unknown): void;
40
50
  on(event: "binaryMessage", callback: (connId: string, bytes: Uint8Array) => unknown): void;
@@ -64,8 +74,39 @@ export interface PlatformHandle {
64
74
  worldCharacterRuntimeCreate?(argsJson: string): Promise<string>;
65
75
  worldCharacterRuntimeList?(): Promise<string>;
66
76
  worldCharacterReject?(grantId: string, code?: string): void;
77
+ /**
78
+ * The hub place this session runs, as ghost pinned it from the published
79
+ * castle.json `hub` block. Present only when the host services the hub ops
80
+ * below, so a deck without a hub block never sees any of them.
81
+ */
82
+ readonly hub?: Readonly<PlatformHubPlace>;
83
+ hubResult?(argsJson: string): Promise<string>;
84
+ hubPadUpdate?(argsJson: string): Promise<string>;
85
+ hubResultsRead?(argsJson: string): Promise<string>;
86
+ /** Absent on a runtime older than wearables (contract v1.4). */
87
+ hubWear?(argsJson: string): Promise<string>;
67
88
  readonly config: PlatformSessionConfig;
68
89
  }
90
+ export interface PlatformHubResultShape {
91
+ outcomes: ("win" | "lose" | "draw")[];
92
+ score: {
93
+ unit: "ms" | "s" | "points";
94
+ better: "higher" | "lower";
95
+ min: number;
96
+ max: number;
97
+ } | null;
98
+ stats: Record<string, "number" | "string">;
99
+ }
100
+ export interface PlatformHubPlace {
101
+ place?: string;
102
+ title?: string | null;
103
+ result?: PlatformHubResultShape | null;
104
+ }
105
+ /** Where a player came in, when ghost placed them through a hub door. Ghost's word, not a client's. */
106
+ export interface PlatformHubArrival {
107
+ fromDeckId: string;
108
+ doorId?: string;
109
+ }
69
110
  export interface PlatformWorldCharacterCommand {
70
111
  grantId: string;
71
112
  requestId: string;
@@ -95,6 +95,59 @@ export interface DeliverCharacterKnowledgeInput {
95
95
  claimIds: string[];
96
96
  source: CharacterKnowledgeSource;
97
97
  }
98
+ /**
99
+ * A character acting on its own after a command woke it (autonomous character
100
+ * actions, bundles with `characterActions`). `declined` covers choosing
101
+ * nothing, too little confidence for its temperament, and an action no longer
102
+ * eligible when it committed; `failed` is a decision-model error.
103
+ */
104
+ export type CharacterActionNotice = {
105
+ characterId: string;
106
+ /** `id` is the event occurrence, routine, or promise id. */
107
+ trigger: {
108
+ type: "witnessed" | "routine" | "promise_due";
109
+ id: string;
110
+ };
111
+ outcome: "acted" | "declined" | "failed";
112
+ /** When acted. */
113
+ actionId?: string;
114
+ /** When acted with a parameterized action's variant. */
115
+ variantId?: string;
116
+ /** The action's world event, when it has one. */
117
+ eventOccurrenceId?: string;
118
+ /** The decision model's probability for its choice. */
119
+ probability?: number;
120
+ };
121
+ export type CharacterGameStateResult = {
122
+ revision: number;
123
+ state: {
124
+ [key: string]: string | number | boolean;
125
+ };
126
+ promiseOutcomes: Array<{
127
+ id: string;
128
+ status: "fulfilled" | "broken";
129
+ due: number;
130
+ resolvedAtGameTime: number;
131
+ }>;
132
+ /** At most 8, omitted when no character acted, declined, or failed. */
133
+ characterActions?: CharacterActionNotice[];
134
+ };
135
+ export type CharacterGameStateOperation = Omit<CharacterOperation, "result"> & {
136
+ result: CharacterGameStateResult | null;
137
+ };
138
+ export type CharacterKnowledgeDeliveryResult = {
139
+ deliveryId: string;
140
+ recipientCharacterId: string;
141
+ eventOccurrenceId: string;
142
+ claimIds: string[];
143
+ source: CharacterKnowledgeSource;
144
+ deliveredAt: string;
145
+ /** At most 8, omitted when no character acted, declined, or failed. */
146
+ characterActions?: CharacterActionNotice[];
147
+ };
148
+ export type CharacterKnowledgeDeliveryOperation = Omit<CharacterOperation, "result"> & {
149
+ result: CharacterKnowledgeDeliveryResult | null;
150
+ };
98
151
  export interface CompleteCharacterBeatInput {
99
152
  operationId: string;
100
153
  characterId: string;
@@ -189,10 +242,10 @@ export interface ServerPlaythroughCharacters {
189
242
  /** Queues a funded turn whose admitted listeners are fixed at enqueue time. */
190
243
  send(input: SendCharacterInput): Promise<CharacterOperation>;
191
244
  recordEvent(input: RecordCharacterEventInput): Promise<CharacterOperation>;
192
- setGameState(input: SetCharacterGameStateInput): Promise<CharacterOperation>;
245
+ setGameState(input: SetCharacterGameStateInput): Promise<CharacterGameStateOperation>;
193
246
  shareClaim(input: ShareCharacterClaimInput): Promise<CharacterOperation>;
194
247
  inspect(): Promise<Json>;
195
- deliverKnowledge(input: DeliverCharacterKnowledgeInput): Promise<CharacterOperation>;
248
+ deliverKnowledge(input: DeliverCharacterKnowledgeInput): Promise<CharacterKnowledgeDeliveryOperation>;
196
249
  completeBeat(input: CompleteCharacterBeatInput): Promise<CharacterOperation>;
197
250
  evaluateInformation(input: EvaluateCharacterInformationInput): Promise<CharacterInformationEvaluationOperation>;
198
251
  evaluateBeats(input: EvaluateCharacterBeatsInput): Promise<CharacterBeatEvaluationOperation>;