castle-web-cli 0.4.194 → 0.4.195

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 (42) hide show
  1. package/dist/agent-prompts.d.ts +1 -0
  2. package/dist/agent-prompts.js +14 -5
  3. package/dist/agent.js +14 -0
  4. package/dist/castleJson.d.ts +0 -2
  5. package/dist/castleJson.js +0 -39
  6. package/dist/devSessionFrameBudget.d.ts +14 -0
  7. package/dist/devSessionFrameBudget.js +64 -0
  8. package/dist/devSessionServer.js +15 -0
  9. package/dist/editorConfig.d.ts +1 -1
  10. package/dist/editorConfig.js +12 -4
  11. package/dist/ide.js +28 -59
  12. package/dist/imports.js +2 -4
  13. package/dist/init.js +9 -8
  14. package/dist/multiplayerDoc.d.ts +1 -0
  15. package/dist/multiplayerDoc.js +228 -0
  16. package/dist/platformDoc.d.ts +1 -0
  17. package/dist/platformDoc.js +21 -2
  18. package/dist/scriptErrors.d.ts +23 -0
  19. package/dist/scriptErrors.js +147 -0
  20. package/dist/serve.js +233 -4
  21. package/dist/shell/assets/index-kMH1qj6D.js +449 -0
  22. package/dist/shell/index.html +1 -1
  23. package/dist/viteClientStub.d.ts +18 -0
  24. package/dist/viteClientStub.js +193 -0
  25. package/kits/base/CLAUDE.md +3 -3
  26. package/kits/base/castle.json +1 -3
  27. package/kits/base/sdk/README.md +17 -0
  28. package/kits/multiplayer-2d/castle.json +0 -9
  29. package/kits/multiplayer-3d/castle.json +0 -8
  30. package/kits/physics-2d/CLAUDE.md +5 -6
  31. package/kits/physics-2d/castle.json +1 -11
  32. package/kits/physics-2d/editors/SceneEditor.jsx +42 -3
  33. package/kits/physics-2d/editors/behaviorRegistry.js +8 -2
  34. package/kits/physics-2d/engine/ErrorOverlay.jsx +69 -0
  35. package/kits/physics-2d/engine/ScenePlayer.jsx +2 -67
  36. package/kits/physics-2d/engine/liveReload.js +5 -4
  37. package/kits/physics-3d/castle.json +0 -11
  38. package/kits/real-time/castle.json +0 -6
  39. package/kits/turn-based/CLAUDE.md +6 -3
  40. package/kits/turn-based/castle.json +1 -14
  41. package/package.json +1 -1
  42. package/dist/shell/assets/index-ColHKJYj.js +0 -449
@@ -0,0 +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";
@@ -0,0 +1,228 @@
1
+ // The on-demand multiplayer guide, written beside platform.md at every serve
2
+ // start (platformDoc.ts owns both paths and the writing). Tool-call-only by
3
+ // design: platform.md carries one bullet pointing here -- see the header
4
+ // comment in platformDoc.ts about the inlined vs tool-call-only split -- and
5
+ // nothing below is inlined into any prompt. It is what an agent reads before
6
+ // hand-rolling a server entry or client netcode: the frame budget, the snapshot
7
+ // pattern, and the reconnect/disconnect handling that a hand-rolled session
8
+ // gets wrong and a multiplayer kit already does.
9
+ export const MULTIPLAYER_DOC = `# Multiplayer, in practice
10
+
11
+ Read this before writing or changing a server entry or client netcode by hand.
12
+ Written fresh by the Castle CLI at every serve start; the full API reference is
13
+ the SDK's own, at \`imports/castle.base/sdk/README.md\`.
14
+
15
+ ## Reach for a kit first
16
+
17
+ \`castle.multiplayer-2d\` and \`castle.multiplayer-3d\` (both on \`castle.real-time\`)
18
+ already do everything below: a server-authoritative world, one snapshot per
19
+ tick, pose interpolation, roster handling, reconnects, ownership of loose
20
+ objects. \`castle.turn-based\` does the same for games played in turns, with
21
+ seats, spectators and idle clearing. A deck on one of those kits normally
22
+ writes nothing against the raw session API, and the right move is usually to
23
+ add a rule to the deck's own game hooks rather than a message of your own.
24
+
25
+ Hand-roll only when the game genuinely does not fit them -- and then keep the
26
+ shape below, because it is the shape the platform's limits ask for.
27
+
28
+ ## The outbound budget
29
+
30
+ A session may send about \`40 + 40 x connected players\` frames per second, with
31
+ roughly two seconds of burst, and about 1 MiB/s of bytes. What a frame costs:
32
+
33
+ | call | frames |
34
+ |---|---|
35
+ | \`session.send(playerId, data)\` | 1 |
36
+ | \`session.broadcast(data)\` | 1, whatever the player count |
37
+ | \`session.broadcast(data, { except })\` | one per recipient -- it is a loop of sends |
38
+
39
+ Frames over the budget are **dropped silently**. The session keeps running and
40
+ a dropped frame is never retried, so the symptom is not an error: it is a
41
+ client whose world quietly stops matching everyone else's. Only sustained abuse
42
+ at several times the budget ends a session.
43
+
44
+ The arithmetic that matters, at \`tickRate: 20\`:
45
+
46
+ - 4 players, one \`send\` per player per tick: 80 frames/s of a 200 budget --
47
+ before a single hit, join, chat or one-off frame.
48
+ - 8 players, same: 160 of 360. A second per-player message per tick makes it
49
+ 320, and at \`tickRate: 30\` that is 480 -- over, and frames start dropping.
50
+ - Either, with one \`broadcast\` per tick: 20 frames/s. The budget stops being
51
+ something you have to think about.
52
+
53
+ Per-player sends also send the same bytes N times toward the byte budget. The
54
+ local serve does not drop anything, but it warns when a 1-second window goes
55
+ over -- \`[multiplayer] server sent ...\` in \`.castle/logs.txt\` and in the serve's
56
+ own output (\`.castle/serve.log\` when it was detached).
57
+
58
+ ## The snapshot pattern
59
+
60
+ Authoritative state lives on the server. \`onTick\` builds ONE snapshot of every
61
+ player and broadcasts it once.
62
+
63
+ Every client reads EVERY entry in that snapshot, **including its own** -- the
64
+ difference is only what it does with each:
65
+
66
+ - **Other players' entries** drive what it draws for them (interpolated between
67
+ snapshots), and are how it learns someone left or went silent.
68
+ - **Its own entry** is the server's verdict on itself. Take hp, alive/wrecked,
69
+ kills, score and the match state from it every tick, exactly as if it were
70
+ someone else's. The one field it does NOT overwrite each tick is its own pose:
71
+ the local player moves on its own input so the game stays responsive, and the
72
+ client only snaps to the server's position when the two have drifted far
73
+ apart. Ignoring the rest of its own entry is how a player ends up alive on
74
+ their own screen and dead on everyone else's.
75
+
76
+ \`\`\`js
77
+ const state = { matchNumber: 1, players: {}, parked: new Map() };
78
+
79
+ export default {
80
+ onPlayerJoin(session, player) {
81
+ state.players[player.playerId] = { x: 0, y: 0, hp: 100, kills: 0, alive: true };
82
+ },
83
+ onMessage(session, player, data) {
84
+ if (data.t === 'move') applyMove(state.players[player.playerId], data);
85
+ },
86
+ onTick(session) {
87
+ // One frame per tick, for any number of players.
88
+ session.broadcast({ t: 'snap', n: state.matchNumber, players: state.players });
89
+ },
90
+ };
91
+ \`\`\`
92
+
93
+ \`\`\`js
94
+ connection.onMessage((msg) => {
95
+ if (msg.t !== 'snap') return;
96
+ match.setNumber(msg.n); // a new match number means: reset, the round moved on
97
+ for (const [id, p] of Object.entries(msg.players)) {
98
+ if (id === connection.playerId) {
99
+ // My own entry: the server owns all of it except where I am right now.
100
+ Object.assign(me, { hp: p.hp, kills: p.kills, alive: p.alive });
101
+ if (Math.hypot(p.x - me.x, p.y - me.y) > SNAP_DISTANCE) {
102
+ me.x = p.x; // drifted too far to argue; the server is right
103
+ me.y = p.y;
104
+ }
105
+ continue;
106
+ }
107
+ remote.set(id, { ...p, seenAt: performance.now() });
108
+ }
109
+ });
110
+ \`\`\`
111
+
112
+ Do not build a per-player payload ("everyone except you") on the server: the
113
+ client needs its own entry anyway, and one tailored message per player costs N
114
+ frames where the shared snapshot costs 1.
115
+
116
+ ## One-off events must be self-healing
117
+
118
+ A dropped or missed event frame is gone for good. So an event may carry an
119
+ effect, never the only copy of a result:
120
+
121
+ - \`{ t: 'hit', target, dmg }\` -- fine for a flash, a sound, a particle.
122
+ - The hp it produced, whether the player is alive or wrecked, the kill count,
123
+ the match number: all of that belongs in the periodic snapshot, and the
124
+ client reconciles from the snapshot every tick.
125
+
126
+ Write the client so that receiving zero events and only snapshots still
127
+ produces a correct, playable screen. Then a dropped frame costs one missing
128
+ spark instead of a player who is dead everywhere but on their own device.
129
+
130
+ ## Connection loss has to be visible
131
+
132
+ Two independent things can go quiet: the socket, and a player.
133
+
134
+ \`\`\`js
135
+ connection.onStateChange((state, meta) => {
136
+ // 'acquiring' | 'connecting' | 'connected' | 'reconnecting' | 'closed'
137
+ // meta?.type: 'connectionLost' | 'replaced' | 'bye' | 'left' | 'error'
138
+ hud.setConnection(state, meta?.type);
139
+ });
140
+ \`\`\`
141
+
142
+ - Show \`reconnecting\` and \`closed\` in the deck's own UI. A player staring at a
143
+ frozen game with no explanation assumes the game is broken.
144
+ - Expire a remote player whose last snapshot is older than a few seconds
145
+ (\`performance.now() - p.seenAt > 3000\`) and stop drawing them. This must run
146
+ off the client's own clock, not off an event -- if the server or the socket
147
+ goes silent, no message will ever arrive to tell you, and every remote player
148
+ stays frozen mid-stride forever.
149
+ - The SDK reconnects short drops by itself and \`send\` is safe to call while the
150
+ socket is down (those messages are dropped), so the client's job is to show
151
+ the state and recover, not to manage the socket.
152
+
153
+ ## Reconnects: park match state, never delete it
154
+
155
+ \`playerId\` is stable across a platform reconnect, but the server still sees
156
+ \`onPlayerLeave\` and then \`onPlayerJoin\`. A server that deletes the player's row
157
+ on leave silently drops a reconnecting player out of the match while their
158
+ client happily thinks it is still playing.
159
+
160
+ \`\`\`js
161
+ onPlayerLeave(session, player) {
162
+ const parked = state.players[player.playerId];
163
+ delete state.players[player.playerId];
164
+ if (parked) state.parked.set(player.playerId, { at: Date.now(), parked }); // or by userId
165
+ },
166
+ onPlayerJoin(session, player) {
167
+ const held = state.parked.get(player.playerId);
168
+ state.parked.delete(player.playerId);
169
+ state.players[player.playerId] =
170
+ held && Date.now() - held.at < 60_000 ? held.parked : freshPlayer();
171
+ session.send(player.playerId, { t: 'full', ...fullState() }); // 1 frame, once
172
+ },
173
+ \`\`\`
174
+
175
+ Park for about 60 seconds (the platform's own reconnect window), keyed by
176
+ \`playerId\`, or by \`userId\` when the match should survive a genuinely new
177
+ connection from the same account. Sweep expired entries on a tick.
178
+
179
+ On the client, after a state change back to \`connected\`, ask for full state
180
+ once and rebuild from the answer rather than assuming the world is as you left
181
+ it.
182
+
183
+ ## The server ignores and tells
184
+
185
+ When the server refuses a message because the player is not in the state the
186
+ client assumed -- not in the match, already dead, not their turn -- do not just
187
+ \`return\`. The client believes something false and nothing will correct it.
188
+
189
+ \`\`\`js
190
+ onMessage(session, player, data) {
191
+ const me = state.players[player.playerId];
192
+ if (!me || !me.alive) {
193
+ session.send(player.playerId, { t: 'full', ...fullState() }); // authoritative answer
194
+ return;
195
+ }
196
+ ...
197
+ }
198
+ \`\`\`
199
+
200
+ One frame, and the client resyncs instead of arguing with itself. Rate-limit
201
+ that reply (once per player per second is plenty) so a looping client cannot
202
+ spend the whole budget on corrections.
203
+
204
+ ## Client to server
205
+
206
+ Client frames are capped at 16 KB and about 30 messages per second; **exceeding
207
+ the rate closes the socket**, which is much harsher than the server side's
208
+ silent drop.
209
+
210
+ - Throttle pose/input sends to a fixed rate. 8-15 per second is plenty when the
211
+ client interpolates between samples (the real-time kit reports at 20). Never
212
+ send once per animation frame -- 60/s closes the connection.
213
+ - Send intent ("I am holding left", "I fired"), not results. The server decides
214
+ what happened.
215
+ - Coalesce: one message per send tick carrying the latest pose beats three
216
+ messages describing how it got there.
217
+
218
+ ## Testing it
219
+
220
+ - Open **four or more** tabs, not two. Every budget and roster bug scales with
221
+ the player count, and two tabs is exactly the case that never reproduces one.
222
+ - Reload tabs mid-match to exercise leave/rejoin, and leave one tab idle to see
223
+ what a silent player looks like to everyone else.
224
+ - Kill and restart the serve (or edit the server entry, which restarts it) to
225
+ see the disconnected state the deck shows.
226
+ - Watch the serve log for the \`[multiplayer]\` budget warning and for dropped
227
+ oversize frames while you play.
228
+ `;
@@ -1,5 +1,6 @@
1
1
  export declare const PLATFORM_DOCS_DIR: string;
2
2
  export declare const PLATFORM_DOC_REL: string;
3
+ export declare const MULTIPLAYER_DOC_REL: string;
3
4
  export declare function everyDeckBullets(deckDir: string): string[];
4
5
  export type AgentRole = 'router' | 'task';
5
6
  export declare function roleLoadsClaudeMd(role: AgentRole): boolean;
@@ -2,6 +2,7 @@ import * as crypto from 'crypto';
2
2
  import * as fs from 'fs';
3
3
  import * as path from 'path';
4
4
  import { resolveFileTypes } from './editorConfig.js';
5
+ import { MULTIPLAYER_DOC } from './multiplayerDoc.js';
5
6
  // The platform's own guidance to agents -- the rules identical in a bare deck
6
7
  // and a kit deck: the card, touch, assets and formats, imports, reloading,
7
8
  // editors. Its one home is here. The serve writes it under the deck's .castle/
@@ -21,6 +22,10 @@ import { resolveFileTypes } from './editorConfig.js';
21
22
  // the vehicle, not a rewrite.
22
23
  export const PLATFORM_DOCS_DIR = path.join('.castle', 'docs');
23
24
  export const PLATFORM_DOC_REL = path.join(PLATFORM_DOCS_DIR, 'platform.md');
25
+ // The one guide that is read on demand rather than inlined: multiplayerDoc.ts
26
+ // holds its text, platform.md's Multiplayer section points at this path, and
27
+ // nothing puts it in a prompt.
28
+ export const MULTIPLAYER_DOC_REL = path.join(PLATFORM_DOCS_DIR, 'multiplayer.md');
24
29
  const MEDIA = {
25
30
  images: ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'],
26
31
  audio: ['.mp3', '.wav', '.m4a'],
@@ -51,6 +56,8 @@ export function everyDeckBullets(deckDir) {
51
56
  `- **Supported media formats are exactly**: ${mediaList(deckDir)}. Nothing else — a published deck inlines every asset as a \`data:\` URI, where the browser trusts the declared type instead of sniffing the bytes, so a format that merely works while serving (\`.mov\` is the classic case) can be dead once published. Convert, don't improvise.`,
52
57
  "- To add an npm package, put it in `package.json` `dependencies` and run `castle-web install .` (the install `init` ran; it uses whichever package manager made the lockfile).",
53
58
  "- Do not reload the deck after an edit. Nothing auto-reloads: the person applies your changes when they are ready, from the Play panel's restart button or a panel's own reload control. `npm run restart` reloads every open panel at once and breaks their flow — only when asked.",
59
+ '- If the browser console shows `[vite] failed to connect to websocket` (or a "Direct websocket connection fallback" line), ignore it. Vite HMR is deliberately off on this serve, so the line is expected and harmless: it is never why a scene is blank, a game is not running, or multiplayer is not connecting. Do not investigate or "fix" it.',
60
+ "- Never revert, replace, or re-scaffold the deck's scenes, scripts, or behaviors back to kit, starter, or imported content, and never delete or rewrite a whole scene to diagnose a problem -- those files are the person's own work. Fix forward with targeted edits, and treat a request to diagnose or explain as read-only unless they asked for a fix.",
54
61
  "- The deck can define its own editors: declare a file type in `castle.json` (`editor.fileTypes`: ext, label, icon, and an `editors/` module) and the Files panel opens that type in it — whole recipe under `## Editors` in the deck's guide (its kit's `CLAUDE.md` under `imports/`). Editors under `imports/` are read-only; add or fork, don't edit.",
55
62
  '- An editor is for content FILES the creator keeps coming back to (catalogs, dialogue, level tables) that nothing already opens. One-off or generated data stays code.',
56
63
  "- **Put the values someone would tune while playtesting in a `PARAMS` object**: `export const PARAMS = { jumpHeight: 4.2, coyoteTime: 0.08 };` near the top of the file that uses them. The Parameters panel lists every file in the deck that has one and renders their values as fields -- a number scrubs, a boolean toggles, a `'#rrggbb'` string opens a color picker -- and writes the edit back into the file. It edits every file's params in one place, so nobody has to remember which file a setting lives in, and a file that has params says so above its code with a way in. That is how a creator tunes a game on a phone without putting a cursor inside an expression. Nested one level deep (`player: { speed: 5 }`) renders as a group. **Write each value as a plain number, not as arithmetic** (`0.333`, not `1 / 3`): the panel folds arithmetic over plain numbers into a field and replaces it with the tuned literal on the first edit, so the expression you wrote does not survive the first tune. A value that NAMES something (`speed: BASE * 2`) shows read-only, as a link onto its own line in the code.",
@@ -214,6 +221,7 @@ const COMMON_SECTIONS = `## Imports are read-only
214
221
 
215
222
  ## Multiplayer
216
223
 
224
+ - **Read \`${MULTIPLAYER_DOC_REL}\` before writing or changing a server entry or client netcode by hand.** It carries what this section leaves out: the outbound frame budget in practice, the snapshot pattern, self-healing events, and the reconnect and disconnect handling a hand-rolled session gets wrong. A deck built on the \`castle.multiplayer-2d\` / \`castle.multiplayer-3d\` (or \`castle.turn-based\`) kits already does all of that and normally writes nothing against the raw session API.
217
225
  - **A deck becomes multiplayer by having a server entry** — no flag, no dashboard. The entry is \`castle.json\`'s \`server.main\` when set (a kit deck points it under \`imports/\`), otherwise the first of \`server/index.{js,ts,mjs}\` or \`code/server/index.{js,ts,mjs}\` that exists; removing the entry turns multiplayer off on the next \`save-deck\`. Castle runs that module as a real server process, one per session, shared by the players in it. Other options under \`server\`: \`maxPlayers\` (max 24), and \`tickRate\` (defaults to 20, max 30; 0 turns ticks off).
218
226
  - **The server module default-exports lifecycle callbacks**, each taking the session first:
219
227
 
@@ -257,7 +265,7 @@ const COMMON_SECTIONS = `## Imports are read-only
257
265
 
258
266
  Publishing a server takes ownership of \`deck\` scope: from then on clients read that data but no longer write it, which is what lets you keep authoritative state players cannot forge. A server can write any player's public bucket and submit any player's score, so name the player — there is no \`storage.me\`. It can never read \`private\` storage, not even for its own players.
259
267
  - **Save as things change, not only at the end.** \`onShutdown\` is awaited and a save made there does land, but it only runs on a clean stop: an out-of-memory kill or a host failing sends no shutdown at all. Treat it as the last chance rather than the plan.
260
- - **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. Sending 20–30 updates per second means sending deltas rather than whole-world snapshots, and every player's phone pays for whatever you broadcast.
268
+ - **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.
261
269
  - **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.
262
270
  - **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.
263
271
  - **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.
@@ -280,10 +288,21 @@ kit provides on top of this.
280
288
  ${platformGuide(deckDir)}`;
281
289
  }
282
290
  // Written by the serve at every start, so the copy in a deck is exactly as
283
- // fresh as the CLI serving it.
291
+ // fresh as the CLI serving it. platform.md is the always-loaded one; the
292
+ // multiplayer guide sits beside it and is read only when a deck's server or
293
+ // netcode is being written by hand.
284
294
  export function writePlatformDocs(deckDir) {
285
295
  fs.mkdirSync(path.join(deckDir, PLATFORM_DOCS_DIR), { recursive: true });
286
296
  fs.writeFileSync(path.join(deckDir, PLATFORM_DOC_REL), platformDoc(deckDir));
297
+ // Best-effort, unlike platform.md above: the serve calls this on its way up,
298
+ // and a deck missing a guide it reads on demand is a missing reference, never
299
+ // a reason to fail a serve start that would otherwise work.
300
+ try {
301
+ fs.writeFileSync(path.join(deckDir, MULTIPLAYER_DOC_REL), MULTIPLAYER_DOC);
302
+ }
303
+ catch (error) {
304
+ console.warn(`Could not write ${MULTIPLAYER_DOC_REL}: ${error instanceof Error ? error.message : String(error)}`);
305
+ }
287
306
  }
288
307
  // What the deck's root CLAUDE.md carries for the platform: one @import line
289
308
  // (which claude auto-loads) inside a short section that says what it is, for
@@ -0,0 +1,23 @@
1
+ import type { ServerResponse } from 'http';
2
+ import type { Plugin } from 'vite';
3
+ export interface ScriptError {
4
+ /** Deck-relative path of the file that failed (absolute if outside the deck). */
5
+ path: string;
6
+ message: string;
7
+ line?: number;
8
+ column?: number;
9
+ /** Vite's source excerpt around the failure, when it produced one. */
10
+ frame?: string;
11
+ }
12
+ export interface ScriptErrors {
13
+ /** Observe a failed transform. Returns what was recorded, or null if it wasn't ours. */
14
+ record(error: unknown): ScriptError | null;
15
+ /** Observe a module id transforming cleanly again. */
16
+ clearId(id: string): void;
17
+ /** The latest error per path, for `/__castle/script-errors`. */
18
+ snapshot(): Record<string, ScriptError>;
19
+ /** Answer a `/__castle/script-errors` request. */
20
+ respond(res: ServerResponse): void;
21
+ }
22
+ export declare function createScriptErrors(projectDir: string, broadcast: (message: unknown) => void): ScriptErrors;
23
+ export declare function scriptErrorsPlugin(errors: ScriptErrors): Plugin;
@@ -0,0 +1,147 @@
1
+ // Every failed module transform, remembered and announced.
2
+ //
3
+ // A syntax error in ANY module a deck's entry imports statically (a behavior in
4
+ // a kit's eager `import.meta.glob`, say) makes Vite answer that module request
5
+ // with a 500. The deck's entry then never evaluates, so nothing the deck itself
6
+ // installs -- no React error boundary, no console interception, no error
7
+ // overlay -- is there to report it. The editor's scene view goes blank and the
8
+ // play frame goes black with the only trace in the raw browser console.
9
+ //
10
+ // So the SERVE remembers instead, since it is the one place that always knows:
11
+ //
12
+ // - the error is observed from a connect ERROR middleware registered in the
13
+ // `configureServer` post hook. Vite's own `errorMiddleware` is added after
14
+ // every post hook runs, so ours sits between the transform middleware and
15
+ // Vite's: `next(err)` from a failed transform reaches us first, with the
16
+ // real error object (`id`, and `loc`/`frame` when the compiler set them --
17
+ // the fields Vite's own `prepareError` reads), and we hand it straight on
18
+ // so Vite's 500 response is unchanged. Verified against the oxc transform
19
+ // this Vite ships with, which sets `id` but leaves `loc` and `frame` empty
20
+ // and puts the position inside its formatted message instead.
21
+ // - this is deliberately NOT `server.hot.send` interception: the serve runs
22
+ // with `server.hmr: false`, so the client hot channel is a no-op and the
23
+ // `{ type: 'error' }` frame Vite sends there goes nowhere. It is also not a
24
+ // plugin `transform` wrapper, which would only see errors thrown by plugins
25
+ // that run after ours rather than "this module request failed".
26
+ // - success is observed from a `enforce: 'post'` `transform` hook, which only
27
+ // runs for a module whose whole transform chain worked.
28
+ //
29
+ // Consumers: the shell (a banner over the edit panel) and any deck frame,
30
+ // through the same `/__castle/ws` broadcast the rest of the serve uses, plus
31
+ // `GET /__castle/script-errors` for a frame that failed to boot and so has no
32
+ // socket of its own.
33
+ import * as path from 'path';
34
+ import { stripVTControlCharacters } from 'util';
35
+ // Only module requests. A 500 from anything else (an asset, a proxied route) is
36
+ // not a script that failed to compile, and claiming it would put a redbox over
37
+ // a deck that runs fine.
38
+ const SCRIPT_EXTS = ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts'];
39
+ // Big frames are source excerpts, not stacks -- a few lines. Cap anyway: this
40
+ // rides a WebSocket broadcast and an error in a generated file can be huge.
41
+ const FRAME_MAX = 2000;
42
+ // `…/behaviors/Ball.jsx:12:4` inside a compiler diagnostic. Vite's own
43
+ // `prepareError` reads `err.loc`, but the oxc transform this Vite ships with
44
+ // puts the position only in its formatted message, so the position has to be
45
+ // read back out of it when `loc` is absent.
46
+ const POSITION_RE = /([^\s[\]()]+\.(?:[cm]?[jt]sx?)):(\d+):(\d+)/;
47
+ // One line to put in a banner, out of a diagnostic that may be a whole framed
48
+ // excerpt. The oxc form is "Transform failed with N errors:" followed by
49
+ // "[PARSE_ERROR] Error: <the actual problem>"; esbuild and plugin errors are
50
+ // already a single line.
51
+ function summarize(text) {
52
+ const lines = text
53
+ .split('\n')
54
+ .map((line) => line.trim())
55
+ .filter((line) => line.length > 0);
56
+ const detail = lines.find((line) => /error/i.test(line) && !/^transform failed/i.test(line)) ?? lines[0];
57
+ return (detail ?? 'Failed to compile')
58
+ .replace(/^\[[A-Z_]+\]\s*/, '')
59
+ .replace(/^Error:\s*/, '')
60
+ .trim();
61
+ }
62
+ // `<root>/behaviors/Ball.jsx?t=1` -> `behaviors/Ball.jsx`. A file outside the
63
+ // deck (an import's node_modules, a linked SDK) keeps its absolute path: it is
64
+ // still the honest answer to "which file broke", and no consumer has to guess.
65
+ function deckRelative(projectDir, id) {
66
+ const clean = id.split('?')[0].split('#')[0];
67
+ // Virtual and internal ids (`\0`-prefixed, `/@vite/...`, `virtual:...`) name
68
+ // no file anyone can open, so there is nothing useful to report.
69
+ if (!clean || clean.includes('\0') || clean.startsWith('/@') || clean.includes(':\0'))
70
+ return null;
71
+ if (!SCRIPT_EXTS.some((ext) => clean.endsWith(ext)))
72
+ return null;
73
+ const rel = path.relative(projectDir, clean);
74
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel))
75
+ return clean;
76
+ return rel.split(path.sep).join('/');
77
+ }
78
+ export function createScriptErrors(projectDir, broadcast) {
79
+ const errors = new Map();
80
+ const snapshot = () => {
81
+ const out = {};
82
+ for (const [file, entry] of errors)
83
+ out[file] = entry;
84
+ return out;
85
+ };
86
+ return {
87
+ record(error) {
88
+ const err = (error ?? {});
89
+ const text = stripVTControlCharacters(typeof err.message === 'string' ? err.message : String(error));
90
+ const position = POSITION_RE.exec(text);
91
+ const id = err.id ?? err.loc?.file ?? '';
92
+ const file = id ? deckRelative(projectDir, id) : null;
93
+ if (!file)
94
+ return null;
95
+ // The whole diagnostic is the frame when the compiler did not hand one
96
+ // over separately: for oxc that text IS the framed source excerpt, which
97
+ // is the most useful thing a redbox can show.
98
+ const frame = typeof err.frame === 'string' && err.frame ? err.frame : text;
99
+ const entry = {
100
+ path: file,
101
+ message: summarize(text),
102
+ line: err.loc?.line ?? (position ? Number(position[2]) : undefined),
103
+ column: err.loc?.column ?? (position ? Number(position[3]) : undefined),
104
+ frame: frame.slice(0, FRAME_MAX),
105
+ };
106
+ errors.set(file, entry);
107
+ broadcast({ type: 'script_error', ...entry });
108
+ return entry;
109
+ },
110
+ clearId(id) {
111
+ const file = deckRelative(projectDir, id);
112
+ if (!file || !errors.has(file))
113
+ return;
114
+ errors.delete(file);
115
+ broadcast({ type: 'script_ok', path: file });
116
+ },
117
+ snapshot,
118
+ respond(res) {
119
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
120
+ res.end(JSON.stringify({ errors: snapshot() }));
121
+ },
122
+ };
123
+ }
124
+ export function scriptErrorsPlugin(errors) {
125
+ return {
126
+ name: 'castle-script-errors',
127
+ // `post` so this transform only runs once every other plugin's has, which
128
+ // is exactly "this module compiled".
129
+ enforce: 'post',
130
+ transform(_code, id) {
131
+ errors.clearId(id);
132
+ return null;
133
+ },
134
+ configureServer(server) {
135
+ // Returning a function defers to the POST hook phase, which runs after
136
+ // Vite installed its transform middleware and before it installs its own
137
+ // error middleware -- so this handler is the first to see a transform
138
+ // error, and passing it on leaves Vite's 500 page untouched.
139
+ return () => {
140
+ server.middlewares.use((err, _req, _res, next) => {
141
+ errors.record(err);
142
+ next(err);
143
+ });
144
+ };
145
+ },
146
+ };
147
+ }