castle-web-cli 0.4.238 → 0.4.239

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 (51) hide show
  1. package/dist/castle-host/host.js +55 -0
  2. package/dist/index.js +16 -0
  3. package/dist/init.js +1 -1
  4. package/dist/multiplayerDoc.d.ts +1 -1
  5. package/dist/multiplayerDoc.js +9 -0
  6. package/dist/platformDoc.js +2 -1
  7. package/dist/playPagePolicy.d.ts +1 -0
  8. package/dist/playPagePolicy.js +8 -3
  9. package/dist/roomLogs.d.ts +39 -0
  10. package/dist/roomLogs.js +166 -0
  11. package/kits/base/CLAUDE.md +1 -0
  12. package/kits/base/castle.json +1 -1
  13. package/kits/base/sdk/README.md +66 -2
  14. package/kits/base/sdk/castle.d.ts +3 -1
  15. package/kits/base/sdk/castle.js +1 -0
  16. package/kits/base/sdk/commands.d.ts +31 -0
  17. package/kits/base/sdk/multiplayer.js +30 -0
  18. package/kits/base/sdk/rooms.d.ts +11 -0
  19. package/kits/base/sdk/rooms.js +22 -0
  20. package/kits/base/sdk/store.d.ts +8 -2
  21. package/kits/base/sdk/store.js +5 -1
  22. package/kits/hub-game/castle.json +4 -4
  23. package/kits/hub-game/code/client/chrome.js +3 -2
  24. package/kits/hub-game/code/client/menuRows.js +8 -2
  25. package/kits/hub-game/code/client/vehicle.js +3 -1
  26. package/kits/hub-game/code/client/worldLabels.js +10 -1
  27. package/kits/hub-game/code/server/analytics.js +5 -12
  28. package/kits/hub-game/code/server/doorAnalytics.js +2 -5
  29. package/kits/hub-game/code/server/hub.js +3 -0
  30. package/kits/hub-game/code/server/loadAbandon.js +2 -5
  31. package/kits/hub-game/code/server/trackQueue.js +29 -0
  32. package/kits/hub-game/code/systems/hub.js +10 -3
  33. package/kits/hub-game/docs/analytics.md +4 -1
  34. package/kits/hub-game/package.json +1 -1
  35. package/kits/hub-game/scripts/test-analytics.mjs +1 -1
  36. package/kits/hub-game/scripts/test-door-analytics.mjs +1 -1
  37. package/kits/hub-game/scripts/test-hub-ops.mjs +28 -0
  38. package/kits/hub-game/scripts/test-hub-trip.mjs +20 -1
  39. package/kits/hub-game/scripts/test-load-abandon.mjs +2 -2
  40. package/kits/hub-game/scripts/test-menu-client.mjs +1 -1
  41. package/kits/hub-game/scripts/test-resync.mjs +13 -0
  42. package/kits/hub-game/scripts/test-role-client.mjs +8 -2
  43. package/kits/hub-game/scripts/test-track-queue.mjs +64 -0
  44. package/kits/hub-game/scripts/test-vehicle-client.mjs +9 -0
  45. package/kits/hub-game/scripts/test-world-labels.mjs +40 -0
  46. package/kits/hub-game/tools/hubScene/test/export-fixture.mjs +12 -0
  47. package/kits/hub-game/tools/hubScene/validate-manifest.mjs +12 -2
  48. package/kits/multiplayer-3d/castle.json +4 -4
  49. package/kits/physics-3d/castle.json +2 -2
  50. package/kits/real-time/castle.json +2 -2
  51. package/package.json +1 -1
@@ -99,6 +99,7 @@ const COMMAND_NAMES = [
99
99
  "cauldronStorage.boardTop",
100
100
  "cauldronStorage.boardGet",
101
101
  "cauldronStorage.usage",
102
+ "rooms.list",
102
103
  "lifecycle.restoreState",
103
104
  "localCache.get",
104
105
  "localCache.set",
@@ -339,6 +340,8 @@ function runCommand(ctx, command, params, caps, options) {
339
340
  return cauldronStorageBoardGet(ctx, params, gql);
340
341
  case "cauldronStorage.usage":
341
342
  return cauldronStorageUsage(ctx, gql);
343
+ case "rooms.list":
344
+ return roomsList(ctx, gql);
342
345
  // Platform commands are handled above; listed here to keep the switch
343
346
  // exhaustive over CommandName.
344
347
  case "pass.offer":
@@ -2396,6 +2399,45 @@ async function cauldronStorageUsage(ctx, gql) {
2396
2399
  const data = await graphql(gql, CAULDRON_STORAGE_USAGE_QUERY, { deckId }, "cauldronStorage.usage");
2397
2400
  return { usage: data.cauldronStorageUsage };
2398
2401
  }
2402
+ async function roomsList(ctx, gql) {
2403
+ const deckId = requireDeckId(ctx, "rooms.list");
2404
+ const data = await graphql(gql, ROOMS_LIST_QUERY, { deckId }, "rooms.list");
2405
+ // Ghost answers null to anyone but the deck's owner, a Castle admin or a
2406
+ // member of the presence gate, and for a deck the player cannot see.
2407
+ const presence = data.cauldronDeckPresence;
2408
+ if (typeof presence !== "object" || presence === null)
2409
+ return null;
2410
+ const record = presence;
2411
+ const rooms = Array.isArray(record.routes) ? record.routes.flatMap(publicRoomSummary) : [];
2412
+ const total = record.total;
2413
+ return {
2414
+ total: isCount(total) ? total : rooms.reduce((sum, room) => sum + room.players, 0),
2415
+ rooms,
2416
+ };
2417
+ }
2418
+ function publicRoomSummary(raw) {
2419
+ if (typeof raw !== "object" || raw === null)
2420
+ return [];
2421
+ const record = raw;
2422
+ const sessionId = asOptionalString(record.sessionId);
2423
+ const { players, maxPlayers } = record;
2424
+ if (!sessionId || !isCount(players) || !isCount(maxPlayers))
2425
+ return [];
2426
+ const routeId = asOptionalString(record.routeId);
2427
+ const slot = asOptionalString(record.slot);
2428
+ return [
2429
+ {
2430
+ sessionId,
2431
+ ...(routeId ? { routeId } : {}),
2432
+ ...(slot ? { slot } : {}),
2433
+ players,
2434
+ maxPlayers,
2435
+ },
2436
+ ];
2437
+ }
2438
+ function isCount(value) {
2439
+ return Number.isSafeInteger(value) && value >= 0;
2440
+ }
2399
2441
  const CHARACTER_OPERATION_FIELDS = `
2400
2442
  operationId
2401
2443
  characterId
@@ -2997,11 +3039,24 @@ const CAULDRON_STORAGE_BOARD_TOP_QUERY = `
2997
3039
  }
2998
3040
  }
2999
3041
  `;
3042
+ const ROOMS_LIST_QUERY = `
3043
+ query CastleRoomsList($deckId: ID!) {
3044
+ cauldronDeckPresence(deckId: $deckId) {
3045
+ total
3046
+ routes { sessionId routeId slot players maxPlayers }
3047
+ }
3048
+ }
3049
+ `;
3000
3050
  const CAULDRON_STORAGE_USAGE_QUERY = `
3001
3051
  query CastleCauldronStorageUsage($deckId: ID!) {
3002
3052
  cauldronStorageUsage(deckId: $deckId) {
3003
3053
  player { keyCount keyLimit byteCount byteLimit }
3004
3054
  shared { keyCount keyLimit byteCount byteLimit }
3055
+ rate {
3056
+ callerClass
3057
+ caller { opsUsed opsLimit bytesUsed bytesLimit }
3058
+ deck { opsUsed opsLimit bytesUsed bytesLimit }
3059
+ }
3005
3060
  }
3006
3061
  }
3007
3062
  `;
package/dist/index.js CHANGED
@@ -39,6 +39,8 @@ const FLAGS_WITH_VALUES = new Set([
39
39
  '--reason',
40
40
  '--remote',
41
41
  '--base-url',
42
+ '--deck',
43
+ '--room',
42
44
  ]);
43
45
  // `--foo` is always a flag; a single dash only when it is one we know (`-m`).
44
46
  // Anything else starting with `-` is a positional -- a path can begin with one,
@@ -190,6 +192,7 @@ function usage() {
190
192
  castle-web get-deck <dir> --side [--deck-id ID] [--json] (fetches the saved copy into <dir>/.castle/agent/saved-source/<stamp>/, touching nothing else)
191
193
  castle-web source-status <dir> [--adopt] [--notify] [--json] (whether the deck's saved copy is newer than this folder)
192
194
  castle-web list-decks [dir] [--kind mine|saved|kits] (decks this one could import; ids are what add-import takes)
195
+ castle-web logs [dir] [--deck ID] [--room ROOM] [--rooms] [--json] [--staging] (a published deck's multiplayer room: state, end reason, exit code, out-of-memory kill and its last server log lines; no --room means the newest room; --rooms lists recent rooms; creator only)
193
196
  castle-web reset-leaderboards [dir] [--deck-id ID] [--yes] (clears every leaderboard on the deck, for good; creator only; --yes skips the prompt)
194
197
  castle-web add-import <deckId|url|kit> [dir] [--as ALIAS] (adds another deck, or a kit this CLI ships, as a read-only dependency in imports/)
195
198
  castle-web fork-import-file <imports/...> [dir] (this deck's own version of one imported file)
@@ -720,6 +723,19 @@ async function main() {
720
723
  await runMcpPlaytestServer(path.resolve(dir), getFlagValue('--task-id'));
721
724
  return;
722
725
  }
726
+ case 'logs': {
727
+ // `castle-web logs [dir] [--deck ID] [--room SESSION] [--rooms] [--json] [--staging]`
728
+ const { roomLogsCommand } = await import('./roomLogs.js');
729
+ await roomLogsCommand({
730
+ dir: path.resolve(findPositionalDir()),
731
+ deckId: getFlagValue('--deck') ?? getFlagValue('--deck-id'),
732
+ sessionId: getFlagValue('--room'),
733
+ listRooms: hasFlag('--rooms'),
734
+ json: hasFlag('--json'),
735
+ staging: hasFlag('--staging'),
736
+ });
737
+ break;
738
+ }
723
739
  case 'git':
724
740
  await gitCommand();
725
741
  break;
package/dist/init.js CHANGED
@@ -64,7 +64,7 @@ const BARE_SCAFFOLDS = [
64
64
  // Registry version of castle-web-sdk to inject when scaffolding from a
65
65
  // globally-installed castle-web (not from inside the workspace). Bumped
66
66
  // alongside cli/sdk version bumps.
67
- const PUBLISHED_SDK_VERSION = '0.4.51';
67
+ const PUBLISHED_SDK_VERSION = '0.4.52';
68
68
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
69
69
  // face can ship without a cli release, and a caret range means an existing
70
70
  // deck's next install picks it up. Nothing here has to move when it does.
@@ -1 +1 @@
1
- export declare const MULTIPLAYER_DOC = "# Multiplayer, in practice\n\nRead this before writing or changing a server entry or client netcode by hand.\nWritten fresh by the Castle CLI at every serve start; the full API reference is\nthe SDK's own, at `imports/castle.base/sdk/README.md`.\n\n## Reach for a kit first\n\n`castle.multiplayer-2d` and `castle.multiplayer-3d` (both on `castle.real-time`)\nalready do everything below: a server-authoritative world, one snapshot per\ntick, pose interpolation, roster handling, reconnects, ownership of loose\nobjects. `castle.turn-based` does the same for games played in turns, with\nseats, spectators and idle clearing. A deck on one of those kits normally\nwrites nothing against the raw session API, and the right move is usually to\nadd a rule to the deck's own game hooks rather than a message of your own.\n\nHand-roll only when the game genuinely does not fit them -- and then keep the\nshape below, because it is the shape the platform's limits ask for.\n\n## The outbound budget\n\nA session may send about `40 + 40 x connected players` frames per second, with\nroughly two seconds of burst, and about 1 MiB/s of bytes. What a frame costs:\n\n| call | frames |\n|---|---|\n| `session.send(playerId, data)` | 1 |\n| `session.broadcast(data)` | 1, whatever the player count |\n| `session.broadcast(data, { except })` | one per recipient -- it is a loop of sends |\n\nFrames over the budget are **dropped silently**. The session keeps running and\na dropped frame is never retried, so the symptom is not an error: it is a\nclient whose world quietly stops matching everyone else's. Only sustained abuse\nat several times the budget ends a session.\n\nThe arithmetic that matters, at `tickRate: 20`:\n\n- 4 players, one `send` per player per tick: 80 frames/s of a 200 budget --\n before a single hit, join, chat or one-off frame.\n- 8 players, same: 160 of 360. A second per-player message per tick makes it\n 320, and at `tickRate: 30` that is 480 -- over, and frames start dropping.\n- Either, with one `broadcast` per tick: 20 frames/s. The budget stops being\n something you have to think about.\n\nPer-player sends also send the same bytes N times toward the byte budget. The\nlocal serve does not drop anything, but it warns when a 1-second window goes\nover -- `[multiplayer] server sent ...` in `.castle/logs.txt` and in the serve's\nown output (`.castle/serve.log` when it was detached).\n\n## The snapshot pattern\n\nAuthoritative state lives on the server. `onTick` builds ONE snapshot of every\nplayer and broadcasts it once.\n\nEvery client reads EVERY entry in that snapshot, **including its own** -- the\ndifference is only what it does with each:\n\n- **Other players' entries** drive what it draws for them (interpolated between\n snapshots), and are how it learns someone left or went silent.\n- **Its own entry** is the server's verdict on itself. Take hp, alive/wrecked,\n kills, score and the match state from it every tick, exactly as if it were\n someone else's. The one field it does NOT overwrite each tick is its own pose:\n the local player moves on its own input so the game stays responsive, and the\n client only snaps to the server's position when the two have drifted far\n apart. Ignoring the rest of its own entry is how a player ends up alive on\n their own screen and dead on everyone else's.\n\n```js\nconst state = { matchNumber: 1, players: {}, parked: new Map() };\n\nexport default {\n onPlayerJoin(session, player) {\n state.players[player.playerId] = { x: 0, y: 0, hp: 100, kills: 0, alive: true };\n },\n onMessage(session, player, data) {\n if (data.t === 'move') applyMove(state.players[player.playerId], data);\n },\n onTick(session) {\n // One frame per tick, for any number of players.\n session.broadcast({ t: 'snap', n: state.matchNumber, players: state.players });\n },\n};\n```\n\n```js\nconnection.onMessage((msg) => {\n if (msg.t !== 'snap') return;\n match.setNumber(msg.n); // a new match number means: reset, the round moved on\n for (const [id, p] of Object.entries(msg.players)) {\n if (id === connection.playerId) {\n // My own entry: the server owns all of it except where I am right now.\n Object.assign(me, { hp: p.hp, kills: p.kills, alive: p.alive });\n if (Math.hypot(p.x - me.x, p.y - me.y) > SNAP_DISTANCE) {\n me.x = p.x; // drifted too far to argue; the server is right\n me.y = p.y;\n }\n continue;\n }\n remote.set(id, { ...p, seenAt: performance.now() });\n }\n});\n```\n\nDo not build a per-player payload (\"everyone except you\") on the server: the\nclient needs its own entry anyway, and one tailored message per player costs N\nframes where the shared snapshot costs 1.\n\n## One-off events must be self-healing\n\nA dropped or missed event frame is gone for good. So an event may carry an\neffect, never the only copy of a result:\n\n- `{ t: 'hit', target, dmg }` -- fine for a flash, a sound, a particle.\n- The hp it produced, whether the player is alive or wrecked, the kill count,\n the match number: all of that belongs in the periodic snapshot, and the\n client reconciles from the snapshot every tick.\n\nWrite the client so that receiving zero events and only snapshots still\nproduces a correct, playable screen. Then a dropped frame costs one missing\nspark instead of a player who is dead everywhere but on their own device.\n\n## Connection loss has to be visible\n\nTwo independent things can go quiet: the socket, and a player.\n\n```js\nconnection.onStateChange((state, meta) => {\n // 'acquiring' | 'connecting' | 'connected' | 'reconnecting' | 'closed'\n // meta?.type: 'connectionLost' | 'replaced' | 'bye' | 'left' | 'error'\n hud.setConnection(state, meta?.type);\n});\n```\n\n- Show `reconnecting` and `closed` in the deck's own UI. A player staring at a\n frozen game with no explanation assumes the game is broken.\n- Expire a remote player whose last snapshot is older than a few seconds\n (`performance.now() - p.seenAt > 3000`) and stop drawing them. This must run\n off the client's own clock, not off an event -- if the server or the socket\n goes silent, no message will ever arrive to tell you, and every remote player\n stays frozen mid-stride forever.\n- The SDK reconnects short drops by itself and `send` is safe to call while the\n socket is down (those messages are dropped), so the client's job is to show\n the state and recover, not to manage the socket.\n\n## Reconnects: park match state, never delete it\n\n`playerId` is stable across a platform reconnect, but the server still sees\n`onPlayerLeave` and then `onPlayerJoin`. A server that deletes the player's row\non leave silently drops a reconnecting player out of the match while their\nclient happily thinks it is still playing.\n\n```js\nonPlayerLeave(session, player) {\n const parked = state.players[player.playerId];\n delete state.players[player.playerId];\n if (parked) state.parked.set(player.playerId, { at: Date.now(), parked }); // or by userId\n},\nonPlayerJoin(session, player) {\n const held = state.parked.get(player.playerId);\n state.parked.delete(player.playerId);\n state.players[player.playerId] =\n held && Date.now() - held.at < 60_000 ? held.parked : freshPlayer();\n session.send(player.playerId, { t: 'full', ...fullState() }); // 1 frame, once\n},\n```\n\nPark for about 60 seconds (the platform's own reconnect window), keyed by\n`playerId`, or by `userId` when the match should survive a genuinely new\nconnection from the same account. Sweep expired entries on a tick.\n\nOn the client, after a state change back to `connected`, ask for full state\nonce and rebuild from the answer rather than assuming the world is as you left\nit.\n\n## The server ignores and tells\n\nWhen the server refuses a message because the player is not in the state the\nclient assumed -- not in the match, already dead, not their turn -- do not just\n`return`. The client believes something false and nothing will correct it.\n\n```js\nonMessage(session, player, data) {\n const me = state.players[player.playerId];\n if (!me || !me.alive) {\n session.send(player.playerId, { t: 'full', ...fullState() }); // authoritative answer\n return;\n }\n ...\n}\n```\n\nOne frame, and the client resyncs instead of arguing with itself. Rate-limit\nthat reply (once per player per second is plenty) so a looping client cannot\nspend the whole budget on corrections.\n\n## Client to server\n\nClient frames are capped at 16 KB and about 30 messages per second; **exceeding\nthe rate closes the socket**, which is much harsher than the server side's\nsilent drop.\n\n- Throttle pose/input sends to a fixed rate. 8-15 per second is plenty when the\n client interpolates between samples (the real-time kit reports at 20). Never\n send once per animation frame -- 60/s closes the connection.\n- Send intent (\"I am holding left\", \"I fired\"), not results. The server decides\n what happened.\n- Coalesce: one message per send tick carrying the latest pose beats three\n messages describing how it got there.\n\n## Testing it\n\n- Open **four or more** tabs, not two. Every budget and roster bug scales with\n the player count, and two tabs is exactly the case that never reproduces one.\n- Reload tabs mid-match to exercise leave/rejoin, and leave one tab idle to see\n what a silent player looks like to everyone else.\n- Kill and restart the serve (or edit the server entry, which restarts it) to\n see the disconnected state the deck shows.\n- Watch the serve log for the `[multiplayer]` budget warning and for dropped\n oversize frames while you play.\n";
1
+ export declare const MULTIPLAYER_DOC = "# Multiplayer, in practice\n\nRead this before writing or changing a server entry or client netcode by hand.\nWritten fresh by the Castle CLI at every serve start; the full API reference is\nthe SDK's own, at `imports/castle.base/sdk/README.md`.\n\n## Reach for a kit first\n\n`castle.multiplayer-2d` and `castle.multiplayer-3d` (both on `castle.real-time`)\nalready do everything below: a server-authoritative world, one snapshot per\ntick, pose interpolation, roster handling, reconnects, ownership of loose\nobjects. `castle.turn-based` does the same for games played in turns, with\nseats, spectators and idle clearing. A deck on one of those kits normally\nwrites nothing against the raw session API, and the right move is usually to\nadd a rule to the deck's own game hooks rather than a message of your own.\n\nHand-roll only when the game genuinely does not fit them -- and then keep the\nshape below, because it is the shape the platform's limits ask for.\n\n## The outbound budget\n\nA session may send about `40 + 40 x connected players` frames per second, with\nroughly two seconds of burst, and about 1 MiB/s of bytes. What a frame costs:\n\n| call | frames |\n|---|---|\n| `session.send(playerId, data)` | 1 |\n| `session.broadcast(data)` | 1, whatever the player count |\n| `session.broadcast(data, { except })` | one per recipient -- it is a loop of sends |\n\nFrames over the budget are **dropped silently**. The session keeps running and\na dropped frame is never retried, so the symptom is not an error: it is a\nclient whose world quietly stops matching everyone else's. Only sustained abuse\nat several times the budget ends a session.\n\nThe arithmetic that matters, at `tickRate: 20`:\n\n- 4 players, one `send` per player per tick: 80 frames/s of a 200 budget --\n before a single hit, join, chat or one-off frame.\n- 8 players, same: 160 of 360. A second per-player message per tick makes it\n 320, and at `tickRate: 30` that is 480 -- over, and frames start dropping.\n- Either, with one `broadcast` per tick: 20 frames/s. The budget stops being\n something you have to think about.\n\nPer-player sends also send the same bytes N times toward the byte budget. The\nlocal serve does not drop anything, but it warns when a 1-second window goes\nover -- `[multiplayer] server sent ...` in `.castle/logs.txt` and in the serve's\nown output (`.castle/serve.log` when it was detached).\n\n## The snapshot pattern\n\nAuthoritative state lives on the server. `onTick` builds ONE snapshot of every\nplayer and broadcasts it once.\n\nEvery client reads EVERY entry in that snapshot, **including its own** -- the\ndifference is only what it does with each:\n\n- **Other players' entries** drive what it draws for them (interpolated between\n snapshots), and are how it learns someone left or went silent.\n- **Its own entry** is the server's verdict on itself. Take hp, alive/wrecked,\n kills, score and the match state from it every tick, exactly as if it were\n someone else's. The one field it does NOT overwrite each tick is its own pose:\n the local player moves on its own input so the game stays responsive, and the\n client only snaps to the server's position when the two have drifted far\n apart. Ignoring the rest of its own entry is how a player ends up alive on\n their own screen and dead on everyone else's.\n\n```js\nconst state = { matchNumber: 1, players: {}, parked: new Map() };\n\nexport default {\n onPlayerJoin(session, player) {\n state.players[player.playerId] = { x: 0, y: 0, hp: 100, kills: 0, alive: true };\n },\n onMessage(session, player, data) {\n if (data.t === 'move') applyMove(state.players[player.playerId], data);\n },\n onTick(session) {\n // One frame per tick, for any number of players.\n session.broadcast({ t: 'snap', n: state.matchNumber, players: state.players });\n },\n};\n```\n\n```js\nconnection.onMessage((msg) => {\n if (msg.t !== 'snap') return;\n match.setNumber(msg.n); // a new match number means: reset, the round moved on\n for (const [id, p] of Object.entries(msg.players)) {\n if (id === connection.playerId) {\n // My own entry: the server owns all of it except where I am right now.\n Object.assign(me, { hp: p.hp, kills: p.kills, alive: p.alive });\n if (Math.hypot(p.x - me.x, p.y - me.y) > SNAP_DISTANCE) {\n me.x = p.x; // drifted too far to argue; the server is right\n me.y = p.y;\n }\n continue;\n }\n remote.set(id, { ...p, seenAt: performance.now() });\n }\n});\n```\n\nDo not build a per-player payload (\"everyone except you\") on the server: the\nclient needs its own entry anyway, and one tailored message per player costs N\nframes where the shared snapshot costs 1.\n\n## One-off events must be self-healing\n\nA dropped or missed event frame is gone for good. So an event may carry an\neffect, never the only copy of a result:\n\n- `{ t: 'hit', target, dmg }` -- fine for a flash, a sound, a particle.\n- The hp it produced, whether the player is alive or wrecked, the kill count,\n the match number: all of that belongs in the periodic snapshot, and the\n client reconciles from the snapshot every tick.\n\nWrite the client so that receiving zero events and only snapshots still\nproduces a correct, playable screen. Then a dropped frame costs one missing\nspark instead of a player who is dead everywhere but on their own device.\n\n## Connection loss has to be visible\n\nTwo independent things can go quiet: the socket, and a player.\n\n```js\nconnection.onStateChange((state, meta) => {\n // 'acquiring' | 'connecting' | 'connected' | 'reconnecting' | 'closed'\n // meta?.type: 'connectionLost' | 'replaced' | 'bye' | 'left' | 'error'\n hud.setConnection(state, meta?.type);\n});\n```\n\n- Show `reconnecting` and `closed` in the deck's own UI. A player staring at a\n frozen game with no explanation assumes the game is broken.\n- On `closed` with `replaced`, call `Multiplayer.join` again: the creator\n published a new server. A `public` join from matchmaking lands on the new\n version; a `named` or `party` room, or a friend's public room the player\n followed, keeps the old one until Castle ends it, about ten minutes after the\n save. That ending, like a kick, arrives as `bye` with a `reason` to show\n the player; don't rejoin a `bye` automatically, or a kicked player comes\n straight back.\n- Expire a remote player whose last snapshot is older than a few seconds\n (`performance.now() - p.seenAt > 3000`) and stop drawing them. This must run\n off the client's own clock, not off an event -- if the server or the socket\n goes silent, no message will ever arrive to tell you, and every remote player\n stays frozen mid-stride forever.\n- The SDK reconnects short drops by itself and `send` is safe to call while the\n socket is down (those messages are dropped), so the client's job is to show\n the state and recover, not to manage the socket.\n\n## Reconnects: park match state, never delete it\n\n`playerId` is stable across a platform reconnect, but the server still sees\n`onPlayerLeave` and then `onPlayerJoin`. A server that deletes the player's row\non leave silently drops a reconnecting player out of the match while their\nclient happily thinks it is still playing.\n\n```js\nonPlayerLeave(session, player) {\n const parked = state.players[player.playerId];\n delete state.players[player.playerId];\n if (parked) state.parked.set(player.playerId, { at: Date.now(), parked }); // or by userId\n},\nonPlayerJoin(session, player) {\n const held = state.parked.get(player.playerId);\n state.parked.delete(player.playerId);\n state.players[player.playerId] =\n held && Date.now() - held.at < 60_000 ? held.parked : freshPlayer();\n session.send(player.playerId, { t: 'full', ...fullState() }); // 1 frame, once\n},\n```\n\nPark for about 60 seconds (the platform's own reconnect window), keyed by\n`playerId`, or by `userId` when the match should survive a genuinely new\nconnection from the same account. Sweep expired entries on a tick.\n\nOn the client, after a state change back to `connected`, ask for full state\nonce and rebuild from the answer rather than assuming the world is as you left\nit.\n\n## The server ignores and tells\n\nWhen the server refuses a message because the player is not in the state the\nclient assumed -- not in the match, already dead, not their turn -- do not just\n`return`. The client believes something false and nothing will correct it.\n\n```js\nonMessage(session, player, data) {\n const me = state.players[player.playerId];\n if (!me || !me.alive) {\n session.send(player.playerId, { t: 'full', ...fullState() }); // authoritative answer\n return;\n }\n ...\n}\n```\n\nOne frame, and the client resyncs instead of arguing with itself. Rate-limit\nthat reply (once per player per second is plenty) so a looping client cannot\nspend the whole budget on corrections.\n\n## Client to server\n\nClient frames are capped at 16 KB and about 30 messages per second; **exceeding\nthe rate closes the socket**, which is much harsher than the server side's\nsilent drop.\n\n- Throttle pose/input sends to a fixed rate. 8-15 per second is plenty when the\n client interpolates between samples (the real-time kit reports at 20). Never\n send once per animation frame -- 60/s closes the connection.\n- Send intent (\"I am holding left\", \"I fired\"), not results. The server decides\n what happened.\n- Coalesce: one message per send tick carrying the latest pose beats three\n messages describing how it got there.\n\n## Testing it\n\n- Open **four or more** tabs, not two. Every budget and roster bug scales with\n the player count, and two tabs is exactly the case that never reproduces one.\n- Reload tabs mid-match to exercise leave/rejoin, and leave one tab idle to see\n what a silent player looks like to everyone else.\n- Kill and restart the serve (or edit the server entry, which restarts it) to\n see the disconnected state the deck shows.\n- Watch the serve log for the `[multiplayer]` budget warning and for dropped\n oversize frames while you play.\n- A published room that crashed or stopped: `castle-web logs` prints its end\n reason, exit code and last server log lines (creator only; `--rooms` lists rooms).\n";
@@ -141,6 +141,13 @@ connection.onStateChange((state, meta) => {
141
141
 
142
142
  - Show \`reconnecting\` and \`closed\` in the deck's own UI. A player staring at a
143
143
  frozen game with no explanation assumes the game is broken.
144
+ - On \`closed\` with \`replaced\`, call \`Multiplayer.join\` again: the creator
145
+ published a new server. A \`public\` join from matchmaking lands on the new
146
+ version; a \`named\` or \`party\` room, or a friend's public room the player
147
+ followed, keeps the old one until Castle ends it, about ten minutes after the
148
+ save. That ending, like a kick, arrives as \`bye\` with a \`reason\` to show
149
+ the player; don't rejoin a \`bye\` automatically, or a kicked player comes
150
+ straight back.
144
151
  - Expire a remote player whose last snapshot is older than a few seconds
145
152
  (\`performance.now() - p.seenAt > 3000\`) and stop drawing them. This must run
146
153
  off the client's own clock, not off an event -- if the server or the socket
@@ -225,4 +232,6 @@ silent drop.
225
232
  see the disconnected state the deck shows.
226
233
  - Watch the serve log for the \`[multiplayer]\` budget warning and for dropped
227
234
  oversize frames while you play.
235
+ - A published room that crashed or stopped: \`castle-web logs\` prints its end
236
+ reason, exit code and last server log lines (creator only; \`--rooms\` lists rooms).
228
237
  `;
@@ -311,7 +311,8 @@ const COMMON_SECTIONS = `## Imports are read-only
311
311
  - **Limits worth designing around.** Client→server messages are capped at 16 KB and about 30 per second; server→client messages are capped at 64 KB. These limits apply to both JSON and binary frames and are measured on the frame, so a binary frame's one-byte protocol tag leaves you one byte under the cap for payload. A session may also SEND only about \`40 + 40 × connected players\` frames per second (about two seconds of burst, and about 1 MiB/s of bytes): \`session.send\` costs one frame per call, \`session.broadcast(data)\` costs ONE frame however many players are in the session, and \`session.broadcast(data, { except })\` is a loop of sends, so it costs one frame per recipient. Frames over the budget are dropped silently and never retried — the session keeps running, so the symptom is a client whose world quietly stops matching everyone else's; only sustained abuse at several times the budget ends a session. So send one \`broadcast\` per tick carrying every player's state, rather than a tailored \`send\` per player: every client reads every entry of that snapshot INCLUDING its own — it takes hp, kills and match state from its own entry and only keeps its own position locally predicted.
312
312
  - **Binary messages are opt-in per payload.** Pass any typed array, \`DataView\`, or \`ArrayBuffer\` to client \`send\`, server \`send\`, or server \`broadcast\` to send its raw bytes. \`onMessage\` always receives those bytes as a \`Uint8Array\`, while every other payload continues to use JSON. Reconstruct another view type such as \`Float32Array\` on receipt; multi-byte values use the sender platform's byte order.
313
313
  - **Test multiplayer locally with no setup.** \`castle-web serve\` runs your server file alongside the deck. Open the shell URL it prints in two tabs, then open the Play panel in each; those play surfaces share a session. If you open the content origin from \`.castle/serve.json\` directly, use \`/index.html?edit=0\`. Its bare origin loads the edit surface, where \`Multiplayer.join\` is not answered. Editing the server entry, anything beside it, or a deck-owned hook under \`server/\` or \`code/server/\` restarts it and clients reconnect, so you exercise your reconnect path constantly. Server \`console.log\` goes to the serve's logs, not the browser console.
314
- - **Publishing does not disturb games in progress.** \`save-deck\` bundles and publishes the server entry, but sessions already running keep the code they started with (they get \`onReplaced\`, so you can prompt players), and the next new session picks up the new version.
314
+ - **A published deck's server rooms have logs too.** \`castle-web logs\` (in the deck folder, signed in as its creator) shows the newest room's state, end reason, exit code, an out-of-memory kill, and its last server log lines; \`--rooms\` lists recent rooms and \`--room <id>\` picks one. Hosts keep the lines for about 30 minutes after a room ends.
315
+ - **Publishing moves players onto the new version; you don't build versioned rooms or a rejoin prompt.** \`save-deck\` bundles and publishes the server entry, and every new session runs it. A session already running keeps the code it started with: its server gets \`onReplaced\`, and each client's connection closes with \`replaced\` metadata. A deck that joins again when the connection closes (the multiplayer kits do) gets the new version at once for a \`public\` join from matchmaking, since new players are not placed in a running public session on the old code; a \`named\` or \`party\` join, or a public one that follows a friend into their room, goes back to that room, which keeps the old code until it ends. About ten minutes after the save Castle ends any ordinary session still on the old code (hub places, persistent worlds and destinations keep their own release handling), closing its connections with \`bye\` and a reason that says the game was updated; its \`onShutdown\` still runs, so a save there lands, and the next join gets the new version.
315
316
  `;
316
317
  export function platformGuide(deckDir) {
317
318
  return `${COMMON_SECTIONS.trimEnd()}
@@ -1,2 +1,3 @@
1
+ export declare const CASTLE_ASSET_HOSTS = "https://castle.imgix.net https://image.castle.xyz https://audio.castle.xyz";
1
2
  export declare function isPlayPageUrl(url: string | undefined): boolean;
2
3
  export declare function playPageHeadInjection(): string;
@@ -7,14 +7,19 @@ const CDN_HOSTS = 'https://esm.sh https://cdnjs.cloudflare.com';
7
7
  const PLAY_HOSTS = 'wss://*.play.castle.xyz';
8
8
  // Content packs a hub door mounts (kits/hub-game/docs/content-pack.md); connect-src only.
9
9
  const CONTENT_PACK_HOSTS = 'https://hosted.castle.games';
10
+ // Uploaded textures, models and songs a deck loads from Castle's own CDN instead of
11
+ // inlining them as base64. Castle-controlled hosts that answer
12
+ // `Access-Control-Allow-Origin: *`, so a fetch from the opaque srcdoc origin can read
13
+ // them. img-src, media-src and connect-src only: an asset is data, never script.
14
+ export const CASTLE_ASSET_HOSTS = 'https://castle.imgix.net https://image.castle.xyz https://audio.castle.xyz';
10
15
  const DECK_CSP = [
11
16
  "default-src 'self' data: blob:",
12
17
  `script-src 'self' 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' data: blob: ${CDN_HOSTS}`,
13
18
  "style-src 'self' 'unsafe-inline' data: blob: https://fonts.googleapis.com",
14
19
  "font-src 'self' data: blob: https://fonts.gstatic.com",
15
- "img-src 'self' data: blob:",
16
- "media-src 'self' data: blob:",
17
- `connect-src 'self' data: blob: ${CDN_HOSTS} ${PLAY_HOSTS} ${CONTENT_PACK_HOSTS}`,
20
+ `img-src 'self' data: blob: ${CASTLE_ASSET_HOSTS}`,
21
+ `media-src 'self' data: blob: ${CASTLE_ASSET_HOSTS}`,
22
+ `connect-src 'self' data: blob: ${CDN_HOSTS} ${PLAY_HOSTS} ${CONTENT_PACK_HOSTS} ${CASTLE_ASSET_HOSTS}`,
18
23
  "frame-src 'none'",
19
24
  "child-src 'self' blob:",
20
25
  "worker-src 'self' blob:",
@@ -0,0 +1,39 @@
1
+ export interface CauldronRoom {
2
+ sessionId: string;
3
+ deckId: string;
4
+ env: string;
5
+ startedAt: string;
6
+ endedAt: string | null;
7
+ numPlayers: number;
8
+ }
9
+ export interface CauldronRoomLogLine {
10
+ at: string | null;
11
+ stream: string;
12
+ text: string;
13
+ }
14
+ export interface CauldronRoomLogs extends CauldronRoom {
15
+ state: string;
16
+ logsAvailable: boolean;
17
+ logsUnavailableReason: string | null;
18
+ endReason: string | null;
19
+ exitCode: number | null;
20
+ oomKilled: boolean | null;
21
+ droppedLines: number;
22
+ lines: CauldronRoomLogLine[];
23
+ }
24
+ export interface RoomLogsOptions {
25
+ dir: string;
26
+ deckId?: string;
27
+ sessionId?: string;
28
+ listRooms: boolean;
29
+ json: boolean;
30
+ staging: boolean;
31
+ }
32
+ export declare class RoomLogsError extends Error {
33
+ }
34
+ export declare function recentRooms(deckId: string, env: string, limit?: number): Promise<CauldronRoom[]>;
35
+ export declare function roomLogs(deckId: string, sessionId: string, env: string): Promise<CauldronRoomLogs>;
36
+ export declare function visible(text: string): string;
37
+ export declare function formatRooms(deckId: string, env: string, rooms: CauldronRoom[]): string;
38
+ export declare function formatRoomLogs(logs: CauldronRoomLogs): string;
39
+ export declare function roomLogsCommand(options: RoomLogsOptions): Promise<void>;
@@ -0,0 +1,166 @@
1
+ // `castle-web logs` -- a published deck's multiplayer rooms, read by the deck's creator.
2
+ // A room is one multiplayer server session of the deck (one runtime container). Ghost's
3
+ // cauldronRoomLogs answers with the room's end reason, exit code and out-of-memory flag,
4
+ // plus its last log lines when the host that ran it still holds them (the host keeps
5
+ // them in memory, for 30 minutes after a room ends); cauldronRecentRooms lists rooms
6
+ // newest first.
7
+ //
8
+ // Only the deck's creator may read them -- not collaborators, not admins -- because a
9
+ // room's output can carry players' messages. Ghost's sandbox scope does not carry
10
+ // either query, so this works from a creator's own terminal, not a cloud sandbox.
11
+ import { graphql } from './api.js';
12
+ import { readCastleJson } from './castleJson.js';
13
+ import * as config from './config.js';
14
+ const RECENT_ROOMS_LIMIT = 20;
15
+ const ROOM_FIELDS = 'sessionId deckId env startedAt endedAt numPlayers';
16
+ const UNAVAILABLE_REASONS = {
17
+ host_missing: 'the server host that ran this room is gone (hosts are replaced over time), so its logs went with it',
18
+ host_stale: 'the server host that ran this room has stopped reporting in, so its logs cannot be read',
19
+ no_capability: 'the server host that ran this room predates room logs',
20
+ host_timeout: 'the server host did not answer in time; try again',
21
+ host_error: 'the server host could not hand over its logs; try again',
22
+ not_found: 'the server host has no logs for this room -- it may have ended more than 30 minutes ago, or the host predates room logs',
23
+ };
24
+ // Plain words for Ghost's error codes. Anything else is shown with its code.
25
+ const ERROR_CODES = {
26
+ LOGIN_REQUIRED: 'Not logged in. Run `castle-web login`.',
27
+ DECK_INVALID_PERMISSIONS: "Only the deck's creator can read its room logs.",
28
+ DECK_NOT_FOUND: 'No such deck.',
29
+ CAULDRON_ROOM_NOT_FOUND: 'This deck has no room with that id.',
30
+ CAULDRON_ENV_FORBIDDEN: 'Staging rooms are not open to this account.',
31
+ };
32
+ export class RoomLogsError extends Error {
33
+ }
34
+ async function query(document, variables, field) {
35
+ const response = await graphql(document, variables);
36
+ const error = response.errors?.[0];
37
+ if (error)
38
+ throw new RoomLogsError(describeError(error));
39
+ const value = response.data?.[field];
40
+ if (value === undefined || value === null) {
41
+ throw new RoomLogsError(`The server returned no ${field}.`);
42
+ }
43
+ return value;
44
+ }
45
+ function describeError(error) {
46
+ const message = error.message ?? 'GraphQL error';
47
+ // The schema is older than the CLI: the field fails validation before any resolver runs.
48
+ if (/Cannot query field "cauldron(RecentRooms|RoomLogs)"/.test(message)) {
49
+ return "Room logs aren't available on this server yet.";
50
+ }
51
+ const code = typeof error.extensions?.code === 'string' ? error.extensions.code : undefined;
52
+ if (code && ERROR_CODES[code])
53
+ return ERROR_CODES[code];
54
+ return visible(code ? `${message} [${code}]` : message);
55
+ }
56
+ export function recentRooms(deckId, env, limit = RECENT_ROOMS_LIMIT) {
57
+ return query(`query($deckId: ID!, $env: String, $limit: Int) {
58
+ cauldronRecentRooms(deckId: $deckId, env: $env, limit: $limit) {
59
+ ${ROOM_FIELDS}
60
+ }
61
+ }`, { deckId, env, limit }, 'cauldronRecentRooms');
62
+ }
63
+ export function roomLogs(deckId, sessionId, env) {
64
+ return query(`query($deckId: ID!, $sessionId: ID!, $env: String) {
65
+ cauldronRoomLogs(deckId: $deckId, sessionId: $sessionId, env: $env) {
66
+ ${ROOM_FIELDS}
67
+ state logsAvailable logsUnavailableReason endReason exitCode oomKilled droppedLines
68
+ lines { at stream text }
69
+ }
70
+ }`, { deckId, sessionId, env }, 'cauldronRoomLogs');
71
+ }
72
+ // Everything a room prints, and every string its host reports, is the author's or a
73
+ // player's text: a raw ESC, CR or BEL in it would drive the reader's terminal (move the
74
+ // cursor, rewrite earlier lines, set the clipboard through OSC 52). Human output shows
75
+ // C0 and C1 control characters and DEL as visible escapes instead; tab stays. --json is
76
+ // already escaped by JSON.stringify.
77
+ export function visible(text) {
78
+ // eslint-disable-next-line no-control-regex
79
+ return text.replace(/[\u0000-\u0008\u000a-\u001f\u007f-\u009f]/g, (c) => {
80
+ if (c === '\n')
81
+ return '\\n';
82
+ if (c === '\r')
83
+ return '\\r';
84
+ return `\\x${c.charCodeAt(0).toString(16).padStart(2, '0')}`;
85
+ });
86
+ }
87
+ // 2026-10-21T18:38:54.798Z -> 2026-10-21 18:38:54Z
88
+ function shortTime(iso) {
89
+ if (!iso)
90
+ return '';
91
+ return iso.replace('T', ' ').replace(/\.\d+Z$/, 'Z');
92
+ }
93
+ export function formatRooms(deckId, env, rooms) {
94
+ if (!rooms.length)
95
+ return `No rooms yet for deck ${deckId} (${env}).`;
96
+ const rows = rooms.map((room) => [
97
+ room.sessionId,
98
+ shortTime(room.startedAt),
99
+ room.endedAt ? shortTime(room.endedAt) : 'running',
100
+ String(room.numPlayers),
101
+ ].map((cell) => visible(String(cell))));
102
+ const header = ['ROOM', 'STARTED', 'ENDED', 'PLAYERS'];
103
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
104
+ const line = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(' ').trimEnd();
105
+ return [`Recent rooms of deck ${deckId} (${env}), newest first:`, line(header), ...rows.map(line)].join('\n');
106
+ }
107
+ export function formatRoomLogs(logs) {
108
+ const out = [
109
+ `Room ${logs.sessionId} of deck ${logs.deckId} (${logs.env})`,
110
+ ` state: ${logs.state}`,
111
+ ` started: ${shortTime(logs.startedAt)}`,
112
+ ` ended: ${logs.endedAt ? shortTime(logs.endedAt) : 'running'}`,
113
+ ` players: ${logs.numPlayers}`,
114
+ ];
115
+ if (logs.endReason)
116
+ out.push(` end reason: ${logs.endReason}`);
117
+ if (logs.exitCode !== null && logs.exitCode !== undefined)
118
+ out.push(` exit code: ${logs.exitCode}`);
119
+ if (logs.oomKilled)
120
+ out.push(' killed: out of memory');
121
+ if (!logs.logsAvailable) {
122
+ const reason = logs.logsUnavailableReason ?? '';
123
+ out.push('', `No log lines: ${UNAVAILABLE_REASONS[reason] ?? `unavailable (${reason || 'no reason given'})`}.`);
124
+ return out.map(visible).join('\n');
125
+ }
126
+ if (logs.droppedLines > 0) {
127
+ out.push(` dropped lines: ${logs.droppedLines} (older lines the host no longer holds)`);
128
+ }
129
+ out.push('');
130
+ if (!logs.lines.length) {
131
+ out.push('(the room printed nothing)');
132
+ }
133
+ else {
134
+ out.push(`Last ${logs.lines.length} line${logs.lines.length === 1 ? '' : 's'}, oldest first:`);
135
+ for (const line of logs.lines) {
136
+ const at = line.at ? `${shortTime(line.at)} ` : '';
137
+ out.push(`${at}${line.stream === 'stderr' ? '[stderr] ' : ''}${line.text}`);
138
+ }
139
+ }
140
+ return out.map(visible).join('\n');
141
+ }
142
+ export async function roomLogsCommand(options) {
143
+ const deckId = options.deckId ?? readCastleJson(options.dir)?.deckId;
144
+ if (!deckId) {
145
+ throw new RoomLogsError('No deckId. Either pass --deck <id> or run from a deck folder whose castle.json has one (it gets one on the first save-deck).');
146
+ }
147
+ if (!config.getToken())
148
+ throw new RoomLogsError(ERROR_CODES.LOGIN_REQUIRED);
149
+ const env = options.staging ? 'staging' : 'prod';
150
+ if (options.listRooms) {
151
+ const rooms = await recentRooms(deckId, env);
152
+ console.log(options.json ? JSON.stringify(rooms, null, 2) : formatRooms(deckId, env, rooms));
153
+ return;
154
+ }
155
+ let sessionId = options.sessionId;
156
+ if (!sessionId) {
157
+ const [latest] = await recentRooms(deckId, env, 1);
158
+ if (!latest) {
159
+ console.log(options.json ? 'null' : formatRooms(deckId, env, []));
160
+ return;
161
+ }
162
+ sessionId = latest.sessionId;
163
+ }
164
+ const logs = await roomLogs(deckId, sessionId, env);
165
+ console.log(options.json ? JSON.stringify(logs, null, 2) : formatRoomLogs(logs));
166
+ }
@@ -17,6 +17,7 @@ that framework provides. This one is true either way.
17
17
  - `import { setup, initCard } from 'castle-web-sdk'`. Call `setup()` first, once; `initCard()` returns the element to render into (a React tree mounted at `#root` needs no `initCard`). Castle services — `Store`, `Leaderboard`, `Time`, `User`, `Haptics`, `Pass`, `Snapshot`, `Portal`, `Multiplayer`, `Lifecycle` — come from the same package. `Store` is how a deck saves anything; the older `Storage`/`SharedStorage` still work but should not be used in new decks; the full reference is `imports/castle.base/sdk/README.md`.
18
18
  - `Agent.chat({ messages, tools?, toolChoice?, model?, maxTokens?, reasoning?, onDelta?, signal? })` gets one chat completion from a language model (OpenAI message and tool format, default model `meta/muse-spark-1.3-contributor`; any OpenRouter model id with a per-token price) through Castle's deck-agent service, paid from the player's daily play allowance that characters share. `onDelta` streams text and reasoning pieces and each finished tool call; `signal` cancels; `reasoning: { effort: 'minimal' | 'low' | 'medium' | 'high' }` sets how hard the model thinks, and minimal answers soonest. It resolves with the whole `message`: the deck runs any `tool_calls` itself, appends the message unchanged (it can carry the model's `reasoning_details`) and the `tool` results, and calls again. Castle admins and players given access only: other players get `refused`; a player whose allowance for the day is spent gets `allowance_exhausted` (it resets at midnight UTC).
19
19
  - `Decks.mine({ limit? })` and `Decks.saved({ limit? })` list decks a portal can lead to (the player's published decks; their bookmarks and playlists) as `{ deckId, title, creator, coverUrl }`, with `coverUrl` a `data:` url. Use them to offer a portal destination picker. Admin only: other players get a `PERMISSION_DENIED` error.
20
+ - `Rooms.list()` returns this deck's public multiplayer rooms as `{ total, rooms: [{ sessionId, routeId?, slot?, players, maxPlayers }] }`, counted about every 10 s, so a lobby needs no per-room player count in `Store`. The deck's owner and Castle admins always get a list and other players only as far as Castle has rolled presence out; a player under 13 or kept out of multiplayer, a player outside that rollout, and an app built before the call get `null` ("not available", not "no rooms").
20
21
  - What each service cannot do is in that README beside the service: `Store` / `Storage` size caps (no media in storage), the Castle app build a command needs (older builds reject it with `UNKNOWN_COMMAND`), no clipboard command, no call that sets the deck's cover. Read it before telling someone a service can or cannot do something.
21
22
  - The SDK is a file of this import, not an npm package: `castle-web-sdk` resolves here. Nothing needs installing, and nothing in a deck's `package.json` names it.
22
23
  - Vite serves and bundles the deck: ES modules, JSX, JSON, CSS and npm packages all work with no build step of your own — don't add one.
@@ -82,7 +82,7 @@
82
82
  "title": "base",
83
83
  "deckId": "yRcmH4_aYllE",
84
84
  "cardId": "zkFdingmIm3m",
85
- "publishedVersion": "2026-10-21T18:36:51.857Z",
85
+ "publishedVersion": "2026-10-23T12:08:44.010Z",
86
86
  "provides": [
87
87
  "castle-web-sdk"
88
88
  ]
@@ -28,6 +28,7 @@ import { setup, initCard, Store, Leaderboard } from "castle-web-sdk";
28
28
  - [Snapshot](#snapshot)
29
29
  - [Portal](#portal)
30
30
  - [Social](#social)
31
+ - [Rooms](#rooms)
31
32
  - [Party](#party)
32
33
  - [Hub](#hub)
33
34
  - [Decks](#decks)
@@ -539,6 +540,28 @@ the page made before calling it, even ones still being batched; await an
539
540
  `increment` or a board `submit` first if the answer should include it. A player can only ever see their own usage, not
540
541
  another player's.
541
542
 
543
+ `rate` says how much of the per-second rate limits (the last two rows of
544
+ the table below) is spent right now, so a deck that writes often can back
545
+ off before a call is refused rather than after:
546
+
547
+ ```js
548
+ const { rate } = await Store.usage();
549
+ if (rate && rate.caller.opsUsed > rate.caller.opsLimit * 0.8) {
550
+ // Close to this player's calls-per-second limit: batch or slow down.
551
+ }
552
+ ```
553
+
554
+ - `rate.caller` is the current player's own limit, and `rate.deck` is the
555
+ one every player of the deck shares.
556
+ - Each has `opsUsed`, `opsLimit`, `bytesUsed` and `bytesLimit`, counted
557
+ over the current one-second window, and the `usage` call itself is
558
+ counted in them.
559
+ - `rate.callerClass` names which limit `caller` is: `"client"` for a
560
+ page.
561
+
562
+ `rate` is missing when the app is older than it, so check for it before
563
+ reading it.
564
+
542
565
  An app too old to know `usage` rejects with a `CastleError` whose `code`
543
566
  is `UNKNOWN_COMMAND`.
544
567
 
@@ -1247,6 +1270,45 @@ const friends = await Social.friends();
1247
1270
  const playingHere = await Social.presence();
1248
1271
  ```
1249
1272
 
1273
+ ## Rooms
1274
+
1275
+ ### `Rooms.list(): Promise<RoomsListResult | null>`
1276
+
1277
+ This deck's public multiplayer rooms and how many players are in each, for a
1278
+ lobby, a room picker or a "12 playing now" line. No room has to write its own
1279
+ count to `Store` for a menu to read.
1280
+
1281
+ ```js
1282
+ import { Rooms } from "castle-web-sdk";
1283
+
1284
+ const list = await Rooms.list();
1285
+ if (list) {
1286
+ label.textContent = `${list.total} playing now`;
1287
+ for (const room of list.rooms) {
1288
+ // { sessionId, routeId?, slot?, players, maxPlayers }
1289
+ }
1290
+ }
1291
+ ```
1292
+
1293
+ - `total` is the players across every listed room; `rooms` is one entry per
1294
+ room, with `routeId` and `slot` as the deck passed them to
1295
+ `Multiplayer.joinDestination` (absent for a room `Multiplayer.join`
1296
+ opened).
1297
+ - It resolves `null` when Castle will not list the deck's rooms for this
1298
+ player. The deck's owner and Castle admins always get a list; whether
1299
+ other players do depends on how far Castle has rolled presence out, so
1300
+ handle `null` for any player. A player under 13, or one Castle keeps out
1301
+ of multiplayer, gets `null` even on their own deck. Treat `null` as "not available", never as "no
1302
+ rooms": a deck nobody is playing answers `{ total: 0, rooms: [] }`.
1303
+ - An app built before the call also resolves `null` rather than throwing
1304
+ `UNKNOWN_COMMAND`. An unsaved deck throws `MISSING_DECK_ID`.
1305
+ - Counts come from a rollup Castle refreshes about every 10 seconds, so a
1306
+ player who joined or left in the last few seconds may not show yet. Poll it
1307
+ no more than every 10 seconds; there is no event.
1308
+ - Only public rooms are listed. Private, party and named rooms are not.
1309
+ - A local `castle-web serve` lists the saved deck's rooms on Castle, not the
1310
+ rooms of the local serve.
1311
+
1250
1312
  ## Party
1251
1313
 
1252
1314
  `Party` creates and drives Castle parties with the signed-in player's account.
@@ -1951,8 +2013,10 @@ load its assets through the bundler instead.
1951
2013
  A multiplayer socket closed before its first hello reports its WebSocket close
1952
2014
  code in `error.extensions.closeCode` when available. Code `4404` means the
1953
2015
  play proxy could not route the session (`not_running`); it does not prove the
1954
- runtime ended. A failed hub join cancels its handoff, so retrying a door requires
1955
- a fresh `Hub.go` acquisition.
2016
+ runtime ended. A hub join refused this way tries the same handoff again for a
2017
+ few seconds, since a session ghost has just started can briefly be unroutable;
2018
+ the error is reported only when those tries run out. A failed hub join cancels
2019
+ its handoff, so retrying a door after that requires a fresh `Hub.go` acquisition.
1956
2020
 
1957
2021
  Every error the SDK throws is a `CastleError`. Check `code` to tell
1958
2022
  the kinds apart.
@@ -14,6 +14,8 @@ export { Haptics } from "./haptics";
14
14
  export type { CastleHapticsApi, HapticsResult, HapticsStatus, HapticStyle } from "./haptics";
15
15
  export { Hub } from "./hub";
16
16
  export type { CastleHubApi, HubBackResult, HubCancelResult, HubCancelStatus, HubChatMessage, HubChatResult, HubDoor, HubDoorsResult, HubFriend, HubFriendsResult, HubInviteResult, HubCanInviteResult, HubInviteArrivalResult, HubHeartsResult, HubGoParams, HubGoRequest, HubSignInParams, HubSignInResult, HubGoResult, HubHandoffResult, HubHandoffStatus, HubJumpResult, HubPlacementKind, HubReportResult, HubSayResult, } from "./hub";
17
+ export { Rooms } from "./rooms";
18
+ export type { CastleRoomsApi, RoomSummary, RoomsListResult } from "./rooms";
17
19
  export { Social } from "./social";
18
20
  export type { CastleSocialApi, SocialFriend, SocialPresence } from "./social";
19
21
  export { Party } from "./party";
@@ -46,7 +48,7 @@ export { LocalCache } from "./localCache";
46
48
  export type { LocalCacheApi } from "./localCache";
47
49
  export { SharedStorage, Storage } from "./storage";
48
50
  export { Store } from "./store";
49
- export type { CastleStoreApi, StoreBoardApi, StoreBoardScore, StoreListEntry, StoreListOptions, StoreListPage, StoreAllowance, StoreScopeApi, StoreUsage, } from "./store";
51
+ export type { CastleStoreApi, StoreBoardApi, StoreBoardScore, StoreListEntry, StoreListOptions, StoreListPage, StoreAllowance, StoreRateBudget, StoreRateUsage, StoreScopeApi, StoreUsage, } from "./store";
50
52
  export { Time } from "./time";
51
53
  export type { CastleClockZone, CastleDateParts, CastleTimeApi } from "./time";
52
54
  export type { Json } from "./types";
@@ -9,6 +9,7 @@ export { experiment, experiments, experimentsReady } from "./experiments";
9
9
  export { deckPrefixOf, IMPORTS_DIR, IMPORTS_PREFIX, isImportedFile, resolveDeckFile, } from "./files";
10
10
  export { Haptics } from "./haptics";
11
11
  export { Hub } from "./hub";
12
+ export { Rooms } from "./rooms";
12
13
  export { Social } from "./social";
13
14
  export { Party } from "./party";
14
15
  export { Leaderboard } from "./leaderboard";