castle-web-cli 0.4.193 → 0.4.194

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 (75) hide show
  1. package/dist/agent.js +87 -4
  2. package/dist/api.d.ts +1 -0
  3. package/dist/api.js +5 -0
  4. package/dist/bundle.js +2 -1
  5. package/dist/castleJson.d.ts +1 -0
  6. package/dist/check.js +14 -6
  7. package/dist/devSessionServer.d.ts +6 -0
  8. package/dist/devSessionServer.js +23 -1
  9. package/dist/filesChanged.js +7 -3
  10. package/dist/importUpdateHook.d.ts +31 -0
  11. package/dist/importUpdateHook.js +135 -0
  12. package/dist/importUpdateHookRunner.d.ts +2 -0
  13. package/dist/importUpdateHookRunner.js +24 -0
  14. package/dist/imports.js +56 -6
  15. package/dist/index.js +58 -7
  16. package/dist/init.d.ts +1 -0
  17. package/dist/init.js +6 -1
  18. package/dist/native/loop.js +29 -9
  19. package/dist/platformDoc.js +4 -4
  20. package/dist/remix.js +4 -1
  21. package/dist/serve.js +133 -32
  22. package/dist/serverBundle.js +1 -1
  23. package/dist/versions.d.ts +14 -0
  24. package/dist/versions.js +21 -0
  25. package/dist/vitePlugins.d.ts +1 -0
  26. package/dist/vitePlugins.js +18 -0
  27. package/kits/multiplayer-2d/CLAUDE.md +9 -2
  28. package/kits/multiplayer-2d/blueprints/crate.scene +32 -4
  29. package/kits/multiplayer-2d/blueprints/other-player.scene +31 -4
  30. package/kits/multiplayer-2d/blueprints/player.scene +38 -6
  31. package/kits/multiplayer-2d/blueprints/wall.scene +25 -3
  32. package/kits/multiplayer-2d/castle.json +3 -3
  33. package/kits/multiplayer-2d/test/two-client-test.mjs +4 -4
  34. package/kits/multiplayer-3d/CLAUDE.md +5 -2
  35. package/kits/multiplayer-3d/castle.json +3 -3
  36. package/kits/multiplayer-3d/scenes/main.scene +128 -0
  37. package/kits/physics-2d/CLAUDE.md +11 -5
  38. package/kits/physics-2d/behaviors/Camera.jsx +5 -6
  39. package/kits/physics-2d/behaviors/Goal.jsx +5 -2
  40. package/kits/physics-2d/behaviors/Joints.jsx +4 -3
  41. package/kits/physics-2d/behaviors/Layout.jsx +120 -3
  42. package/kits/physics-2d/behaviors/Sprite.jsx +9 -9
  43. package/kits/physics-2d/behaviors/Style.jsx +22 -15
  44. package/kits/physics-2d/behaviors/Text.jsx +7 -6
  45. package/kits/physics-2d/blueprints/ball.scene +27 -5
  46. package/kits/physics-2d/blueprints/block.scene +16 -3
  47. package/kits/physics-2d/blueprints/cauldron.scene +3 -1
  48. package/kits/physics-2d/blueprints/crate.scene +23 -4
  49. package/kits/physics-2d/blueprints/goal.scene +12 -2
  50. package/kits/physics-2d/blueprints/text.scene +13 -3
  51. package/kits/physics-2d/castle.json +2 -1
  52. package/kits/physics-2d/editors/SceneEditor.jsx +26 -2
  53. package/kits/physics-2d/editors/SelectionOverlay.jsx +27 -20
  54. package/kits/physics-2d/engine/blueprint.js +111 -54
  55. package/kits/physics-2d/engine/blueprintCore.js +59 -0
  56. package/kits/physics-2d/engine/collider.js +28 -17
  57. package/kits/physics-2d/engine/layout.js +61 -0
  58. package/kits/physics-2d/engine/layoutOriginMigration.js +223 -0
  59. package/kits/physics-2d/engine/physics/PhysicsSystem.js +11 -7
  60. package/kits/physics-2d/engine/physics/controls.js +4 -8
  61. package/kits/physics-2d/engine/physics/matterBridge.js +13 -8
  62. package/kits/physics-2d/engine/scene.js +38 -34
  63. package/kits/physics-2d/engine/spriteGeometry.js +17 -9
  64. package/kits/physics-2d/engine/tap.js +4 -3
  65. package/kits/physics-2d/scenes/main.scene +59 -6
  66. package/kits/physics-2d/scenes/sandbox.scene +69 -7
  67. package/kits/physics-2d/scripts/onUpdate.mjs +199 -0
  68. package/kits/real-time/castle.json +2 -2
  69. package/kits/real-time/code/server/persist.js +14 -0
  70. package/kits/turn-based/CLAUDE.md +12 -7
  71. package/kits/turn-based/blueprints/board.scene +3 -1
  72. package/kits/turn-based/blueprints/square.scene +3 -1
  73. package/kits/turn-based/castle.json +5 -3
  74. package/kits/turn-based/code/behaviors/Board.jsx +33 -21
  75. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -13,6 +13,9 @@ import { check } from './check.js';
13
13
  import { forkImportFile, revertImportFile } from './forks.js';
14
14
  import { connectWS, takeScreenshot } from './preview.js';
15
15
  import { listVersions, restoreVersion, saveVersion, showVersion } from './versions.js';
16
+ import { getKitsDir } from './localPaths.js';
17
+ import * as api from './api.js';
18
+ import * as config from './config.js';
16
19
  const args = process.argv.slice(2);
17
20
  const command = args[0];
18
21
  const FLAGS_WITH_VALUES = new Set([
@@ -91,10 +94,49 @@ function getServeSocketPort(dir) {
91
94
  return fromServe;
92
95
  return 3738;
93
96
  }
97
+ const FALLBACK_KITS = [
98
+ 'base',
99
+ 'multiplayer-2d',
100
+ 'multiplayer-3d',
101
+ 'physics-2d',
102
+ 'physics-3d',
103
+ 'real-time',
104
+ 'turn-based',
105
+ ];
106
+ const KIT_DESCRIPTIONS = {
107
+ base: 'Library kit: shared SDK, editor host, and authoring guide imported by every deck.',
108
+ 'multiplayer-2d': 'Real-time multiplayer over physics-2d: a shared matter world with an authoritative server already written.',
109
+ 'multiplayer-3d': 'Real-time multiplayer over physics-3d: a shared rapier world with an authoritative server already written.',
110
+ 'physics-2d': 'Actor / behavior / scene framework for 2D games with matter-js physics. Default if --kit is omitted.',
111
+ 'physics-3d': 'The same model in 3D with three.js rendering, rapier physics, and scene and model editors.',
112
+ 'real-time': 'Library kit: shared transport, clock, smoothing, ownership, and session process for the multiplayer kits.',
113
+ 'turn-based': 'Seats, spectators, and reconnects for games where players take turns, over physics-2d.',
114
+ };
115
+ function availableKits() {
116
+ try {
117
+ const kitsDir = getKitsDir();
118
+ return fs
119
+ .readdirSync(kitsDir, { withFileTypes: true })
120
+ .filter((entry) => entry.isDirectory())
121
+ .map((entry) => entry.name)
122
+ .sort();
123
+ }
124
+ catch {
125
+ return FALLBACK_KITS;
126
+ }
127
+ }
94
128
  function usage() {
129
+ const kits = availableKits();
130
+ const scaffoldKits = kits.filter((kit) => kit !== 'base' && kit !== 'real-time');
131
+ const initKits = [...scaffoldKits, 'none'].join(', ');
132
+ const kitNameWidth = Math.max('none'.length, ...kits.map((kit) => kit.length));
133
+ const kitLines = [
134
+ ...kits.map((kit) => ` ${kit.padEnd(kitNameWidth)} ${KIT_DESCRIPTIONS[kit] ?? 'Scaffold kit.'}`),
135
+ ` ${'none'.padEnd(kitNameWidth)} Minimal vite + canvas setup with the castle-web SDK and no kit.`,
136
+ ].join('\n');
95
137
  console.log(`Usage:
96
- castle-web init <dir> [--deck-id ID] [--card-id ID] [--kit NAME] (kits: physics-2d (default), physics-3d, none)
97
- castle-web init <dir> --remix <deckId> [--deck-id ID] [--card-id ID] (starts from a published deck instead of a kit)
138
+ castle-web init <dir> [--deck-id ID] [--card-id ID] [--kit NAME] [--port PORT] (kits: ${initKits}; default physics-2d)
139
+ castle-web init <dir> --remix <deckId> [--deck-id ID] [--card-id ID] [--port PORT] (starts from a published deck instead of a kit)
98
140
  castle-web serve [dir] [--port PORT] [--host HOST] [--open] [--detach]
99
141
  castle-web restart [--port PORT]
100
142
  castle-web screenshot [--out FILE] [--port PORT]
@@ -106,18 +148,17 @@ function usage() {
106
148
  castle-web revert-import-file <imports/...> [dir]
107
149
  castle-web update-import [alias] [dir] [--check] [--revert] (re-fetches imports; no alias means all)
108
150
  castle-web install [dir]
109
- castle-web check [dir] (bundles the deck, the same build save-deck runs)
151
+ castle-web check [dir] (bundles the deck and its server, the same builds save-deck runs)
110
152
  castle-web save-version [-m MESSAGE] [paths...] [--dir DIR] (no paths saves the whole deck)
111
153
  castle-web list-versions [version] [--dir DIR] (defaults to the latest version)
112
154
  castle-web show-version <version> [--dir DIR] (diffs of the files that version changed)
113
155
  castle-web restore-version <version> [--force] [--dir DIR]
114
156
  castle-web login
157
+ castle-web whoami
115
158
  castle-web --version
116
159
 
117
160
  Kits:
118
- physics-2d Actor / behavior / scene framework for 2D games with matter-js physics (RigidBody / Collider / Joints on top of Layout / Drawing / Camera). Default if --kit is omitted.
119
- physics-3d The same model in 3D: three.js rendering and rapier physics, with a scene editor and a model editor. Built on physics-2d, which it imports.
120
- none Minimal vite + canvas setup with the castle-web SDK and no kit.
161
+ ${kitLines}
121
162
 
122
163
  After init, read the scaffolded deck's CLAUDE.md (also AGENTS.md) for the kit's full author guide.`);
123
164
  process.exit(1);
@@ -134,13 +175,14 @@ async function main() {
134
175
  case 'init': {
135
176
  const dir = findPositionalDir();
136
177
  if (dir === '.') {
137
- console.error('Usage: castle-web init <dir> [--deck-id ID] [--card-id ID] [--kit NAME | --remix DECK_ID]');
178
+ console.error('Usage: castle-web init <dir> [--deck-id ID] [--card-id ID] [--kit NAME | --remix DECK_ID] [--port PORT]');
138
179
  process.exit(1);
139
180
  }
140
181
  const kit = getFlagValue('--kit');
141
182
  await init(dir, {
142
183
  kit,
143
184
  serve: !hasFlag('--no-serve'),
185
+ port: getFlagValue('--port'),
144
186
  remixOf: getFlagValue('--remix'),
145
187
  // The identity the server minted for this remix. Omitted outside the
146
188
  // cloud flow, where the next save-deck creates a deck of its own.
@@ -301,6 +343,15 @@ async function main() {
301
343
  case 'login':
302
344
  await login();
303
345
  break;
346
+ case 'whoami': {
347
+ if (!config.getToken())
348
+ throw new Error('Not logged in. Run `castle-web login`.');
349
+ const user = await api.whoAmI();
350
+ if (!user)
351
+ throw new Error('Not logged in. Run `castle-web login`.');
352
+ console.log(`Logged in as @${user.username} (userId: ${user.userId})`);
353
+ break;
354
+ }
304
355
  default:
305
356
  usage();
306
357
  }
package/dist/init.d.ts CHANGED
@@ -17,6 +17,7 @@ export declare function retargetBareClaudeMd(deckDir: string, alias: string): vo
17
17
  export declare function init(dir: string, opts?: {
18
18
  kit?: string;
19
19
  serve?: boolean;
20
+ port?: string;
20
21
  /** Remix this published deck instead of starting from a kit. */
21
22
  remixOf?: string;
22
23
  /** The identity the server already minted for this new deck. */
package/dist/init.js CHANGED
@@ -708,7 +708,12 @@ export async function init(dir, opts = {}) {
708
708
  const noOpen = process.env.CASTLE_WEB_CLI_NO_OPEN === '1' ||
709
709
  !!process.env.SSH_CONNECTION ||
710
710
  !!process.env.SSH_TTY;
711
- await serve(projectDir, { host: '0.0.0.0', detach: true, open: !noOpen });
711
+ await serve(projectDir, {
712
+ port: opts.port,
713
+ host: '0.0.0.0',
714
+ detach: true,
715
+ open: !noOpen,
716
+ });
712
717
  return;
713
718
  }
714
719
  console.log('');
@@ -29,13 +29,25 @@ function playtestFrameList(frames) {
29
29
  }
30
30
  // -- run logging ----------------------------------------------------------------
31
31
  // Structured JSONL, one event per line, appended (task retry attempts share
32
- // one log.jsonl, same as the CLI backends). Bulky free-text fields (tool
33
- // args/results) are truncated to LOG_FIELD_CAP chars -- the log is for
34
- // diagnosing a bad run's shape, not replaying its full payloads. Assistant
35
- // message text is NOT truncated: it is the narrative the user saw and is
36
- // already bounded by the model's own output.
37
- const LOG_FIELD_CAP = 2_000;
38
- function truncateForLog(raw) {
32
+ // one log.jsonl, same as the CLI backends).
33
+ //
34
+ // These logs are a permanent training corpus, not just a debugging aid, so
35
+ // every model-facing field is recorded EXACTLY: the prompt and system text the
36
+ // run was given (the init event), the tool-call arguments the model itself
37
+ // emitted, the tool output the model was shown on its next turn, and the
38
+ // assistant text it produced. Nothing here may be summarized or elided -- a
39
+ // truncated field is a corrupted training example, not a shorter one.
40
+ //
41
+ // LOG_FIELD_CAP is therefore a safety valve, NOT a display budget: it exists
42
+ // only so one pathological tool (a runaway bash command, a huge grep) cannot
43
+ // write an unbounded line into a file we ship whole. At 1 MiB it is far above
44
+ // anything a real turn produces -- if it ever fires, the payload was already
45
+ // too big to have been useful context.
46
+ const LOG_FIELD_CAP = 1024 * 1024; // 1 MiB per field -- see above.
47
+ // Identity for every realistic field; only a pathological payload is clipped,
48
+ // and it says so in-band so a reader (or a corpus filter) can drop the example
49
+ // rather than mistake the clipped text for what the model saw.
50
+ function capForLog(raw) {
39
51
  if (raw.length <= LOG_FIELD_CAP)
40
52
  return raw;
41
53
  return `${raw.slice(0, LOG_FIELD_CAP)}... (+${raw.length - LOG_FIELD_CAP} chars)`;
@@ -438,7 +450,7 @@ async function runToolCalls(toolCalls, role, ctx, playtestFrames, labels, imageL
438
450
  id: call.id,
439
451
  name,
440
452
  ok: result.ok,
441
- output: truncateForLog(result.output),
453
+ output: capForLog(result.output),
442
454
  ...(result.images && result.images.length > 0
443
455
  ? {
444
456
  imageCount: result.images.length,
@@ -484,6 +496,14 @@ export async function runAgentNative(opts) {
484
496
  model: opts.model,
485
497
  tools: toolSchemas.map((t) => t.function.name),
486
498
  promptChars: opts.prompt.length,
499
+ // The two halves of what this run was actually asked, verbatim: the user
500
+ // message (opts.prompt) and the system message exactly as buildSystemMessage
501
+ // assembles it for the messages array -- role framing + the router's stable
502
+ // part (opts.system) + a task's appended reminder (opts.systemReminder),
503
+ // whichever of those are present. Without these the log records the model's
504
+ // answers with the question missing, which is useless as training data.
505
+ prompt: opts.prompt,
506
+ systemPrompt: buildSystemMessage(opts),
487
507
  ...(opts.attachments && opts.attachments.length > 0 ? { attachments: opts.attachments } : {}),
488
508
  });
489
509
  try {
@@ -662,7 +682,7 @@ async function runLoop(opts, toolSchemas, log) {
662
682
  toolCalls: toolCalls.map((tc) => ({
663
683
  id: tc.id,
664
684
  name: tc.function.name,
665
- args: truncateForLog(tc.function.arguments),
685
+ args: capForLog(tc.function.arguments),
666
686
  })),
667
687
  }
668
688
  : {}),
@@ -214,7 +214,7 @@ const COMMON_SECTIONS = `## Imports are read-only
214
214
 
215
215
  ## Multiplayer
216
216
 
217
- - **A deck becomes multiplayer by having a \`server/index.js\`** — no flag, no dashboard. The file's presence is the opt-in, and deleting it turns multiplayer off on the next \`save-deck\`. Castle runs that file as a real server process, one per session, shared by the players in it. Options live in \`castle.json\` under \`server\`: \`main\` (defaults to \`server/index.js\`), \`maxPlayers\` (max 24), and \`tickRate\` (max 30; 0, the default, means no tick).
217
+ - **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
218
  - **The server module default-exports lifecycle callbacks**, each taking the session first:
219
219
 
220
220
  \`\`\`js
@@ -223,7 +223,7 @@ const COMMON_SECTIONS = `## Imports are read-only
223
223
  onPlayerJoin(session, player) {}, // player: { playerId, userId, username, isAnonymous }
224
224
  onPlayerLeave(session, player) {},
225
225
  onMessage(session, player, data) {}, // data is what the client sent, already parsed
226
- onTick(session, dtSeconds) {}, // only when castle.json sets server.tickRate > 0
226
+ onTick(session) {}, // only when castle.json sets server.tickRate > 0
227
227
  onReplaced(session) {}, // you published a new version; this session keeps the old one
228
228
  async onShutdown(session) {}, // the session is ending; awaited, so a save here lands
229
229
  };
@@ -259,8 +259,8 @@ const COMMON_SECTIONS = `## Imports are read-only
259
259
  - **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
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.
261
261
  - **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
- - **Test multiplayer locally with no setup.** \`castle-web serve\` runs your server file alongside the deck; open the play URL in two tabs and they share a session. Editing anything under \`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
- - **Publishing does not disturb games in progress.** \`save-deck\` bundles and publishes \`server/\`, 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.
262
+ - **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
+ - **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.
264
264
  `;
265
265
  export function platformGuide(deckDir) {
266
266
  return `${COMMON_SECTIONS.trimEnd()}
package/dist/remix.js CHANGED
@@ -4,7 +4,9 @@ import * as api from './api.js';
4
4
  import { downloadSourceArchive, runTar } from './save-deck.js';
5
5
  // Scaffolding a deck from another published deck, for `init --remix`.
6
6
  // Dropped from the copied castle.json. `autoUpdateWhenImported` is the parent's
7
- // promise to ITS importers, which a remix hasn't made.
7
+ // promise to ITS importers, which a remix hasn't made -- and `onUpdate` is the
8
+ // migration it runs in them, naming a module the remix keeps as ordinary source
9
+ // rather than as a hook.
8
10
  const PARENT_ONLY_KEYS = [
9
11
  'deckId',
10
12
  'cardId',
@@ -12,6 +14,7 @@ const PARENT_ONLY_KEYS = [
12
14
  'caption',
13
15
  'publishedVersion',
14
16
  'autoUpdateWhenImported',
17
+ 'onUpdate',
15
18
  ];
16
19
  function parseJson(text) {
17
20
  try {
package/dist/serve.js CHANGED
@@ -18,6 +18,7 @@ import * as config from './config.js';
18
18
  import { graphql as castleGraphql } from './api.js';
19
19
  import { executeCommand } from './castle-host/host.js';
20
20
  import { ServeSecurity } from './serveSecurity.js';
21
+ import { atomicWriteFileSync } from './atomicFile.js';
21
22
  import { isSameOriginUpgrade } from './wsOrigin.js';
22
23
  import { createAssetCompression } from './assetCompression.js';
23
24
  import { resolveServerConfig } from './castleJson.js';
@@ -40,18 +41,59 @@ export function appendCapped(file, line) {
40
41
  // logging must never take the serve down
41
42
  }
42
43
  }
43
- function isPortFree(port) {
44
- return new Promise((resolve) => {
45
- const srv = net.createServer();
46
- srv.once('error', () => resolve(false));
47
- srv.listen(port, () => {
48
- srv.close(() => resolve(true));
44
+ const PORT_PROBE_TIMEOUT_MS = 300;
45
+ const PORT_PROBE_FREE_ERRORS = new Set([
46
+ 'ECONNREFUSED',
47
+ 'EHOSTUNREACH',
48
+ 'EADDRNOTAVAIL',
49
+ 'EAFNOSUPPORT',
50
+ ]);
51
+ // A wildcard or localhost serve is reached as http://localhost:<port>, which
52
+ // resolves to either loopback family, so a listener on just one of them still
53
+ // makes the port unusable (two decks answered on one hostname that way).
54
+ function connectProbeHosts(host) {
55
+ return !host || host === 'localhost' || host === '0.0.0.0' || host === '::'
56
+ ? ['127.0.0.1', '::1']
57
+ : [host];
58
+ }
59
+ function canConnectToPort(port, host) {
60
+ return new Promise((resolve, reject) => {
61
+ const socket = net.createConnection({ port, host });
62
+ socket.setTimeout(PORT_PROBE_TIMEOUT_MS);
63
+ socket.once('connect', () => {
64
+ socket.destroy();
65
+ resolve(true);
66
+ });
67
+ // A loopback connect that neither completes nor is refused is
68
+ // indeterminate; treat it as occupied so findFreePort moves on and an
69
+ // explicit port fails here rather than deeper in vite.
70
+ socket.once('timeout', () => {
71
+ socket.destroy();
72
+ resolve(true);
73
+ });
74
+ socket.once('error', (error) => {
75
+ if (error.code && PORT_PROBE_FREE_ERRORS.has(error.code))
76
+ resolve(false);
77
+ else
78
+ reject(error);
49
79
  });
50
80
  });
51
81
  }
52
- async function findFreePort(startPort) {
82
+ async function isPortFree(port, host) {
83
+ for (const probeHost of connectProbeHosts(host)) {
84
+ if (await canConnectToPort(port, probeHost))
85
+ return false;
86
+ }
87
+ return true;
88
+ }
89
+ async function requireFreePort(port, host) {
90
+ if (await isPortFree(port, host))
91
+ return;
92
+ throw new Error(`Port ${port} is already in use. Try another port with --port <n>.`);
93
+ }
94
+ async function findFreePort(startPort, host) {
53
95
  for (let port = startPort; port < startPort + 100; port += 1) {
54
- if (await isPortFree(port))
96
+ if (await isPortFree(port, host))
55
97
  return port;
56
98
  }
57
99
  throw new Error(`No free port found starting from ${startPort}`);
@@ -383,8 +425,7 @@ window.__castleShellOrigin=(function(){
383
425
  res.end(JSON.stringify({ path: `${LEGACY_CONTENT_WS_PATH}?ticket=${ticket}` }));
384
426
  return;
385
427
  }
386
- if (reqPath === '/__castle/auth' ||
387
- reqPath === '/__castle/context') {
428
+ if (reqPath === '/__castle/auth' || reqPath === '/__castle/context') {
388
429
  res.writeHead(404).end();
389
430
  return;
390
431
  }
@@ -557,13 +598,64 @@ function readServeJson(projectDir) {
557
598
  return null;
558
599
  }
559
600
  }
601
+ function removeServeJsonIfOwned(serveJsonPath, pid) {
602
+ try {
603
+ const before = fs.statSync(serveJsonPath);
604
+ const info = JSON.parse(fs.readFileSync(serveJsonPath, 'utf8'));
605
+ if (info.pid !== pid)
606
+ return;
607
+ const after = fs.statSync(serveJsonPath);
608
+ if (before.dev !== after.dev || before.ino !== after.ino)
609
+ return;
610
+ // The final stat-to-unlink race remains, but this narrow window is accepted.
611
+ fs.unlinkSync(serveJsonPath);
612
+ }
613
+ catch {
614
+ // Missing, malformed, or replaced by another serve: leave it alone.
615
+ }
616
+ }
617
+ function removeStaleServeJson(serveJsonPath) {
618
+ try {
619
+ const raw = fs.readFileSync(serveJsonPath, 'utf8');
620
+ let pid = null;
621
+ try {
622
+ const info = JSON.parse(raw);
623
+ if (typeof info.pid === 'number' && Number.isInteger(info.pid) && info.pid > 0) {
624
+ pid = info.pid;
625
+ }
626
+ }
627
+ catch {
628
+ // An unreadable record cannot name a live owner.
629
+ }
630
+ if (pid !== null) {
631
+ if (isPidAlive(pid))
632
+ return;
633
+ removeServeJsonIfOwned(serveJsonPath, pid);
634
+ return;
635
+ }
636
+ // Do not unlink a valid record that replaced the malformed one we read.
637
+ if (fs.readFileSync(serveJsonPath, 'utf8') === raw)
638
+ fs.unlinkSync(serveJsonPath);
639
+ }
640
+ catch {
641
+ // No stale record to remove, or another process changed it concurrently.
642
+ }
643
+ }
560
644
  function isPidAlive(pid) {
561
645
  try {
562
646
  process.kill(pid, 0);
563
647
  return true;
564
648
  }
649
+ catch (error) {
650
+ return error.code === 'EPERM';
651
+ }
652
+ }
653
+ function readLogTail(logPath, maxLines) {
654
+ try {
655
+ return fs.readFileSync(logPath, 'utf8').trimEnd().split(/\r?\n/).slice(-maxLines).join('\n');
656
+ }
565
657
  catch {
566
- return false;
658
+ return '';
567
659
  }
568
660
  }
569
661
  // Return the live serve already owning this deck, if any. Lets repeated
@@ -633,6 +725,9 @@ export async function serve(dir, options = {}) {
633
725
  return;
634
726
  }
635
727
  }
728
+ const explicitPort = options.port ? Number.parseInt(options.port, 10) : undefined;
729
+ if (explicitPort !== undefined)
730
+ await requireFreePort(explicitPort, options.host);
636
731
  // --detach is kept for back-compat. Agent evals (and any harness running
637
732
  // castle-web in a context that can't manage a foreground process) should
638
733
  // prefer the CASTLE_WEB_CLI_DETACH=1 env var instead.
@@ -693,8 +788,8 @@ export async function serve(dir, options = {}) {
693
788
  // already destroyed / inaccessible
694
789
  }
695
790
  }
696
- const startPort = parseInt(options.port ?? String(DEFAULT_PORT), 10);
697
- const port = options.port ? startPort : await findFreePort(startPort);
791
+ const startPort = explicitPort ?? DEFAULT_PORT;
792
+ const port = explicitPort ?? (await findFreePort(startPort, options.host));
698
793
  const security = new ServeSecurity(port);
699
794
  // Local WebSocket server for SDK communication
700
795
  const castleDir = path.join(projectDir, '.castle');
@@ -716,12 +811,7 @@ export async function serve(dir, options = {}) {
716
811
  const screenshotsDir = path.join(castleDir, 'screenshots');
717
812
  const serveJsonPath = path.join(castleDir, 'serve.json');
718
813
  process.on('exit', () => {
719
- try {
720
- fs.unlinkSync(serveJsonPath);
721
- }
722
- catch {
723
- // already removed / never written
724
- }
814
+ removeServeJsonIfOwned(serveJsonPath, process.pid);
725
815
  });
726
816
  process.on('SIGINT', () => process.exit());
727
817
  process.on('SIGTERM', () => process.exit());
@@ -910,7 +1000,9 @@ export async function serve(dir, options = {}) {
910
1000
  // Bring content up first so `--open` cannot race an iframe against a port
911
1001
  // that is not listening yet. Vite opens the shell from inside `vite.listen()`.
912
1002
  await vite.listen();
913
- fs.writeFileSync(serveJsonPath, JSON.stringify({
1003
+ // Atomic so a replacement lands under a new inode: the owned-removal check
1004
+ // in removeServeJsonIfOwned compares inodes to tell a rewrite apart.
1005
+ atomicWriteFileSync(serveJsonPath, JSON.stringify({
914
1006
  port,
915
1007
  // Kept for older CLI commands: they connect to this port's root path.
916
1008
  // New clients use wsPath. Both routes reach the same noServer WSS.
@@ -990,13 +1082,9 @@ async function serveDetached(projectDir, options) {
990
1082
  if (!fs.existsSync(castleDir))
991
1083
  fs.mkdirSync(castleDir, { recursive: true });
992
1084
  const serveJsonPath = path.join(castleDir, 'serve.json');
993
- // Clear stale serve.json before spawning so we wait for the new one.
994
- try {
995
- fs.unlinkSync(serveJsonPath);
996
- }
997
- catch {
998
- // no stale serve.json — fine
999
- }
1085
+ // Clear only a stale record. A live serve owns its file even when this
1086
+ // explicit invocation is going to attempt a second serve for the deck.
1087
+ removeStaleServeJson(serveJsonPath);
1000
1088
  const logPath = path.join(castleDir, 'serve.log');
1001
1089
  const logFd = fs.openSync(logPath, 'a');
1002
1090
  // Re-exec this CLI with the same args minus --detach. process.argv[0] is
@@ -1027,16 +1115,29 @@ async function serveDetached(projectDir, options) {
1027
1115
  stdio: ['ignore', logFd, logFd],
1028
1116
  env: childEnv,
1029
1117
  });
1030
- child.unref();
1031
1118
  fs.closeSync(logFd);
1032
- // Wait up to 15s for serve.json to appear so we can print the URL.
1033
- const deadline = Date.now() + 15_000;
1119
+ const childPid = child.pid;
1120
+ if (childPid === undefined)
1121
+ throw new Error('detached serve did not start a child process');
1122
+ child.unref();
1123
+ // Import auto-update happens in the child before it binds and can be slow on
1124
+ // the network. Wait while that child is alive, with a generous final bound.
1125
+ const deadline = Date.now() + 120_000;
1034
1126
  while (Date.now() < deadline) {
1127
+ if (!isPidAlive(childPid)) {
1128
+ const tail = readLogTail(logPath, 10);
1129
+ throw new Error(`Detached serve process ${childPid} exited before writing ${serveJsonPath}.\n` +
1130
+ `Last lines of ${logPath}:\n${tail || '(no log output)'}`);
1131
+ }
1035
1132
  if (fs.existsSync(serveJsonPath)) {
1036
1133
  try {
1037
1134
  const info = JSON.parse(fs.readFileSync(serveJsonPath, 'utf8'));
1135
+ if (info.pid !== childPid || typeof info.port !== 'number') {
1136
+ await new Promise((r) => setTimeout(r, 200));
1137
+ continue;
1138
+ }
1038
1139
  console.log(`Started serve in background: http://localhost:${info.port}`);
1039
- console.log(`PID: ${child.pid}`);
1140
+ console.log(`PID: ${childPid}`);
1040
1141
  console.log(`Logs: ${logPath}`);
1041
1142
  return;
1042
1143
  }
@@ -1046,7 +1147,7 @@ async function serveDetached(projectDir, options) {
1046
1147
  }
1047
1148
  await new Promise((r) => setTimeout(r, 200));
1048
1149
  }
1049
- throw new Error(`Detached serve did not write ${serveJsonPath} within 15s; check ${logPath} for startup errors.`);
1150
+ throw new Error(`Detached serve did not write ${serveJsonPath} within 120s; check ${logPath} for startup errors.`);
1050
1151
  }
1051
1152
  // Answered by the SERVE itself (the agent server owns the warm Chromium),
1052
1153
  // unlike screenshot_request which a browser tab answers -- so no
@@ -69,7 +69,7 @@ export async function bundleServerModule(projectDir, config, minify) {
69
69
  assetsInlineLimit: Number.MAX_SAFE_INTEGER,
70
70
  rollupOptions: {
71
71
  input: VIRTUAL_ENTRY,
72
- output: { format: 'es', inlineDynamicImports: true },
72
+ output: { format: 'es', codeSplitting: false },
73
73
  },
74
74
  },
75
75
  });
@@ -35,6 +35,20 @@ export declare function pendingChanges(projectDir: string): {
35
35
  path: string;
36
36
  kind: ChangeKind;
37
37
  }[];
38
+ /**
39
+ * Put the working tree back at head, throwing away everything not saved. The
40
+ * paths it touched, as a list.
41
+ *
42
+ * `applyVersionRestore` cannot express this: head IS the target, so it returns
43
+ * `alreadyThere` without looking at the tree. This is the rollback for an
44
+ * operation that saved a version and then wrote deck files -- see
45
+ * importUpdateHook.ts, where a kit's migration failing halfway has to leave the
46
+ * deck's own files exactly as the update found them.
47
+ *
48
+ * The cover is exempt for the same reason it is everywhere else (it is dirty by
49
+ * construction), which `pendingChanges` already handles.
50
+ */
51
+ export declare function discardPendingChanges(projectDir: string): string[];
38
52
  /**
39
53
  * The deck's history newest first. From head (no `fromId`): the chain forward
40
54
  * from head -- marked `later` -- then head, then its ancestors. From a named
package/dist/versions.js CHANGED
@@ -155,6 +155,27 @@ export function pendingChanges(projectDir) {
155
155
  .filter(([path]) => isReportableChange(path))
156
156
  .map(([path, change]) => ({ path, kind: changeKind(change) }));
157
157
  }
158
+ /**
159
+ * Put the working tree back at head, throwing away everything not saved. The
160
+ * paths it touched, as a list.
161
+ *
162
+ * `applyVersionRestore` cannot express this: head IS the target, so it returns
163
+ * `alreadyThere` without looking at the tree. This is the rollback for an
164
+ * operation that saved a version and then wrote deck files -- see
165
+ * importUpdateHook.ts, where a kit's migration failing halfway has to leave the
166
+ * deck's own files exactly as the update found them.
167
+ *
168
+ * The cover is exempt for the same reason it is everywhere else (it is dirty by
169
+ * construction), which `pendingChanges` already handles.
170
+ */
171
+ export function discardPendingChanges(projectDir) {
172
+ const headFiles = store.parentManifest(projectDir, store.readHead(projectDir));
173
+ const actions = pendingChanges(projectDir)
174
+ .map(({ path: rel }) => [rel, headFiles[rel] ?? null])
175
+ .sort((a, b) => a[0].localeCompare(b[0]));
176
+ applyRestore(projectDir, actions);
177
+ return actions.map(([rel]) => rel);
178
+ }
158
179
  function toSummary(version, later) {
159
180
  return {
160
181
  id: version.id,
@@ -1,5 +1,6 @@
1
1
  import type { Plugin } from 'vite';
2
2
  export declare function importsAliasPlugin(): Plugin;
3
3
  export declare function sdkAliasPlugin(): Plugin;
4
+ export declare function singleFileBuildCompatPlugin(): Plugin;
4
5
  export declare function forksOverlayPlugin(): Plugin;
5
6
  export declare function sceneFilesPlugin(): Plugin;
@@ -89,6 +89,24 @@ export function sdkAliasPlugin() {
89
89
  },
90
90
  };
91
91
  }
92
+ // vite-plugin-singlefile still writes Rollup's deprecated inlineDynamicImports
93
+ // option. Rolldown's equivalent keeps the one-chunk output without the warning.
94
+ export function singleFileBuildCompatPlugin() {
95
+ return {
96
+ name: 'castle-single-file-build-compat',
97
+ enforce: 'post',
98
+ config(config) {
99
+ const output = config.build?.rollupOptions?.output;
100
+ if (!output)
101
+ return;
102
+ const outputs = Array.isArray(output) ? output : [output];
103
+ for (const options of outputs) {
104
+ delete options.inlineDynamicImports;
105
+ options.codeSplitting = false;
106
+ }
107
+ },
108
+ };
109
+ }
92
110
  // `<path>?raw` -> ['<path>', '?raw']; no query -> ['<path>', ''].
93
111
  function splitQuery(id) {
94
112
  const at = id.indexOf('?');
@@ -67,8 +67,11 @@ then `Smoothing.smooth(…)`. File names stay lowercase.
67
67
  Identity comes from `player.playerId` / `player.userId`, never from a body.
68
68
  - The kit ships `code/systems/multiplayer.js`, the frame loop. A deck that writes
69
69
  its own file of that path gets its own instead; most decks should not.
70
- - Two players is the test that matters: `castle-web serve`, then the play URL in
71
- two tabs. The room persists in deck storage across serve restarts; a fresh one
70
+ - Two players is the test that matters: run `castle-web serve`, open the shell
71
+ URL it prints in two tabs, and open the Play panel in each. If you use
72
+ `.castle/serve.json`'s `contentPlayUrl` directly, open `/index.html?edit=0`;
73
+ its bare origin is the edit surface, where multiplayer does not join. The room
74
+ persists in deck storage across serve restarts; a fresh one
72
75
  means removing its `world:<room>`, `game:<room>` and `player:<room>:*` rows
73
76
  (the local serve's room is `dev`).
74
77
 
@@ -172,6 +175,10 @@ node ../../cli/dist/index.js serve . --port 5762 --detach
172
175
  node test/two-client-test.mjs
173
176
  ```
174
177
 
178
+ The test resolves `playwright-core` from this repo's `cli/package.json`, so run
179
+ the repo's normal `npm install` first; no machine-specific checkout path or
180
+ global Playwright install is required.
181
+
175
182
  The room's state persists, so crates stay where the last run pushed them. Each
176
183
  client publishes what it believes about the room on `globalThis.__multiplayer`,
177
184
  which is what the test reads.