castle-web-cli 0.4.193 → 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 (101) hide show
  1. package/dist/agent-prompts.d.ts +1 -0
  2. package/dist/agent-prompts.js +14 -5
  3. package/dist/agent.js +101 -4
  4. package/dist/api.d.ts +1 -0
  5. package/dist/api.js +5 -0
  6. package/dist/bundle.js +2 -1
  7. package/dist/castleJson.d.ts +1 -2
  8. package/dist/castleJson.js +0 -39
  9. package/dist/check.js +14 -6
  10. package/dist/devSessionFrameBudget.d.ts +14 -0
  11. package/dist/devSessionFrameBudget.js +64 -0
  12. package/dist/devSessionServer.d.ts +6 -0
  13. package/dist/devSessionServer.js +38 -1
  14. package/dist/editorConfig.d.ts +1 -1
  15. package/dist/editorConfig.js +12 -4
  16. package/dist/filesChanged.js +7 -3
  17. package/dist/ide.js +28 -59
  18. package/dist/importUpdateHook.d.ts +31 -0
  19. package/dist/importUpdateHook.js +135 -0
  20. package/dist/importUpdateHookRunner.d.ts +2 -0
  21. package/dist/importUpdateHookRunner.js +24 -0
  22. package/dist/imports.js +58 -10
  23. package/dist/index.js +58 -7
  24. package/dist/init.d.ts +1 -0
  25. package/dist/init.js +15 -9
  26. package/dist/multiplayerDoc.d.ts +1 -0
  27. package/dist/multiplayerDoc.js +228 -0
  28. package/dist/native/loop.js +29 -9
  29. package/dist/platformDoc.d.ts +1 -0
  30. package/dist/platformDoc.js +25 -6
  31. package/dist/remix.js +4 -1
  32. package/dist/scriptErrors.d.ts +23 -0
  33. package/dist/scriptErrors.js +147 -0
  34. package/dist/serve.js +366 -36
  35. package/dist/serverBundle.js +1 -1
  36. package/dist/shell/assets/index-kMH1qj6D.js +449 -0
  37. package/dist/shell/index.html +1 -1
  38. package/dist/versions.d.ts +14 -0
  39. package/dist/versions.js +21 -0
  40. package/dist/viteClientStub.d.ts +18 -0
  41. package/dist/viteClientStub.js +193 -0
  42. package/dist/vitePlugins.d.ts +1 -0
  43. package/dist/vitePlugins.js +18 -0
  44. package/kits/base/CLAUDE.md +3 -3
  45. package/kits/base/castle.json +1 -3
  46. package/kits/base/sdk/README.md +17 -0
  47. package/kits/multiplayer-2d/CLAUDE.md +9 -2
  48. package/kits/multiplayer-2d/blueprints/crate.scene +32 -4
  49. package/kits/multiplayer-2d/blueprints/other-player.scene +31 -4
  50. package/kits/multiplayer-2d/blueprints/player.scene +38 -6
  51. package/kits/multiplayer-2d/blueprints/wall.scene +25 -3
  52. package/kits/multiplayer-2d/castle.json +3 -12
  53. package/kits/multiplayer-2d/test/two-client-test.mjs +4 -4
  54. package/kits/multiplayer-3d/CLAUDE.md +5 -2
  55. package/kits/multiplayer-3d/castle.json +3 -11
  56. package/kits/multiplayer-3d/scenes/main.scene +128 -0
  57. package/kits/physics-2d/CLAUDE.md +16 -11
  58. package/kits/physics-2d/behaviors/Camera.jsx +5 -6
  59. package/kits/physics-2d/behaviors/Goal.jsx +5 -2
  60. package/kits/physics-2d/behaviors/Joints.jsx +4 -3
  61. package/kits/physics-2d/behaviors/Layout.jsx +120 -3
  62. package/kits/physics-2d/behaviors/Sprite.jsx +9 -9
  63. package/kits/physics-2d/behaviors/Style.jsx +22 -15
  64. package/kits/physics-2d/behaviors/Text.jsx +7 -6
  65. package/kits/physics-2d/blueprints/ball.scene +27 -5
  66. package/kits/physics-2d/blueprints/block.scene +16 -3
  67. package/kits/physics-2d/blueprints/cauldron.scene +3 -1
  68. package/kits/physics-2d/blueprints/crate.scene +23 -4
  69. package/kits/physics-2d/blueprints/goal.scene +12 -2
  70. package/kits/physics-2d/blueprints/text.scene +13 -3
  71. package/kits/physics-2d/castle.json +2 -11
  72. package/kits/physics-2d/editors/SceneEditor.jsx +68 -5
  73. package/kits/physics-2d/editors/SelectionOverlay.jsx +27 -20
  74. package/kits/physics-2d/editors/behaviorRegistry.js +8 -2
  75. package/kits/physics-2d/engine/ErrorOverlay.jsx +69 -0
  76. package/kits/physics-2d/engine/ScenePlayer.jsx +2 -67
  77. package/kits/physics-2d/engine/blueprint.js +111 -54
  78. package/kits/physics-2d/engine/blueprintCore.js +59 -0
  79. package/kits/physics-2d/engine/collider.js +28 -17
  80. package/kits/physics-2d/engine/layout.js +61 -0
  81. package/kits/physics-2d/engine/layoutOriginMigration.js +223 -0
  82. package/kits/physics-2d/engine/liveReload.js +5 -4
  83. package/kits/physics-2d/engine/physics/PhysicsSystem.js +11 -7
  84. package/kits/physics-2d/engine/physics/controls.js +4 -8
  85. package/kits/physics-2d/engine/physics/matterBridge.js +13 -8
  86. package/kits/physics-2d/engine/scene.js +38 -34
  87. package/kits/physics-2d/engine/spriteGeometry.js +17 -9
  88. package/kits/physics-2d/engine/tap.js +4 -3
  89. package/kits/physics-2d/scenes/main.scene +59 -6
  90. package/kits/physics-2d/scenes/sandbox.scene +69 -7
  91. package/kits/physics-2d/scripts/onUpdate.mjs +199 -0
  92. package/kits/physics-3d/castle.json +0 -11
  93. package/kits/real-time/castle.json +2 -8
  94. package/kits/real-time/code/server/persist.js +14 -0
  95. package/kits/turn-based/CLAUDE.md +18 -10
  96. package/kits/turn-based/blueprints/board.scene +3 -1
  97. package/kits/turn-based/blueprints/square.scene +3 -1
  98. package/kits/turn-based/castle.json +3 -14
  99. package/kits/turn-based/code/behaviors/Board.jsx +33 -21
  100. package/package.json +1 -1
  101. package/dist/shell/assets/index-ColHKJYj.js +0 -449
package/dist/serve.js CHANGED
@@ -9,6 +9,8 @@ import { isIP } from 'net';
9
9
  import { createIdeServer, FAVICON_FILES, FAVICON_LINK_TAGS } from './ide.js';
10
10
  import { createAgentServer } from './agent.js';
11
11
  import { sceneFilesPlugin, importsAliasPlugin, forksOverlayPlugin, sdkAliasPlugin, } from './vitePlugins.js';
12
+ import { viteClientStubPlugin } from './viteClientStub.js';
13
+ import { createScriptErrors, scriptErrorsPlugin } from './scriptErrors.js';
12
14
  import { installFilesChangedWatcher } from './filesChanged.js';
13
15
  import { autoUpdateImports, IMPORTS_DIR, lockImportTree } from './imports.js';
14
16
  import { ensureAgentsSymlink } from './init.js';
@@ -18,6 +20,7 @@ import * as config from './config.js';
18
20
  import { graphql as castleGraphql } from './api.js';
19
21
  import { executeCommand } from './castle-host/host.js';
20
22
  import { ServeSecurity } from './serveSecurity.js';
23
+ import { atomicWriteFileSync } from './atomicFile.js';
21
24
  import { isSameOriginUpgrade } from './wsOrigin.js';
22
25
  import { createAssetCompression } from './assetCompression.js';
23
26
  import { resolveServerConfig } from './castleJson.js';
@@ -40,18 +43,59 @@ export function appendCapped(file, line) {
40
43
  // logging must never take the serve down
41
44
  }
42
45
  }
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));
46
+ const PORT_PROBE_TIMEOUT_MS = 300;
47
+ const PORT_PROBE_FREE_ERRORS = new Set([
48
+ 'ECONNREFUSED',
49
+ 'EHOSTUNREACH',
50
+ 'EADDRNOTAVAIL',
51
+ 'EAFNOSUPPORT',
52
+ ]);
53
+ // A wildcard or localhost serve is reached as http://localhost:<port>, which
54
+ // resolves to either loopback family, so a listener on just one of them still
55
+ // makes the port unusable (two decks answered on one hostname that way).
56
+ function connectProbeHosts(host) {
57
+ return !host || host === 'localhost' || host === '0.0.0.0' || host === '::'
58
+ ? ['127.0.0.1', '::1']
59
+ : [host];
60
+ }
61
+ function canConnectToPort(port, host) {
62
+ return new Promise((resolve, reject) => {
63
+ const socket = net.createConnection({ port, host });
64
+ socket.setTimeout(PORT_PROBE_TIMEOUT_MS);
65
+ socket.once('connect', () => {
66
+ socket.destroy();
67
+ resolve(true);
68
+ });
69
+ // A loopback connect that neither completes nor is refused is
70
+ // indeterminate; treat it as occupied so findFreePort moves on and an
71
+ // explicit port fails here rather than deeper in vite.
72
+ socket.once('timeout', () => {
73
+ socket.destroy();
74
+ resolve(true);
75
+ });
76
+ socket.once('error', (error) => {
77
+ if (error.code && PORT_PROBE_FREE_ERRORS.has(error.code))
78
+ resolve(false);
79
+ else
80
+ reject(error);
49
81
  });
50
82
  });
51
83
  }
52
- async function findFreePort(startPort) {
84
+ async function isPortFree(port, host) {
85
+ for (const probeHost of connectProbeHosts(host)) {
86
+ if (await canConnectToPort(port, probeHost))
87
+ return false;
88
+ }
89
+ return true;
90
+ }
91
+ async function requireFreePort(port, host) {
92
+ if (await isPortFree(port, host))
93
+ return;
94
+ throw new Error(`Port ${port} is already in use. Try another port with --port <n>.`);
95
+ }
96
+ async function findFreePort(startPort, host) {
53
97
  for (let port = startPort; port < startPort + 100; port += 1) {
54
- if (await isPortFree(port))
98
+ if (await isPortFree(port, host))
55
99
  return port;
56
100
  }
57
101
  throw new Error(`No free port found starting from ${startPort}`);
@@ -238,6 +282,188 @@ const CONSOLE_CAPTURE = `<script>(function(){
238
282
  };
239
283
  });
240
284
  })();</script>`;
285
+ // Injected into EVERY deck iframe (both roles, logs or not), before any module
286
+ // runs, so a page whose module graph never evaluates still says why.
287
+ //
288
+ // This is the only report there is when a module 500s: the deck's own entry
289
+ // never runs, so its React error boundary, its console interception and the
290
+ // kit's play/edit redboxes do not exist yet. A `<script type="module">` that
291
+ // fails to load fires a RESOURCE error -- no message, the event target is the
292
+ // element -- so that case asks the serve what it recorded
293
+ // (`/__castle/script-errors`, see scriptErrors.ts).
294
+ //
295
+ // Injected by dev serve only: the published bundle is built by `bundle.ts` and
296
+ // never passes through this plugin, so an end user can never see this redbox.
297
+ // Kit-agnostic and dependency-free: styled inline so it works on a bare
298
+ // `--kit none` deck, and ES5 so it needs no transform of its own.
299
+ const FRAME_ERROR_CAPTURE = `<script>(function(){
300
+ var role = 'edit';
301
+ try { role = new URLSearchParams(location.search).get('edit') === '0' ? 'play' : 'edit'; } catch (e) {}
302
+ var seen = {};
303
+ var shown = [];
304
+ var box = null;
305
+ var list = null;
306
+ var relPath = function (value) {
307
+ var text = value ? String(value) : '';
308
+ if (text.indexOf(location.origin) === 0) text = text.slice(location.origin.length);
309
+ var query = text.indexOf('?');
310
+ if (query >= 0) text = text.slice(0, query);
311
+ if (text.charAt(0) === '/') text = text.slice(1);
312
+ return text;
313
+ };
314
+ var post = function (entry) {
315
+ if (window.parent === window) return;
316
+ try {
317
+ window.parent.postMessage({
318
+ type: 'castle-frame-error',
319
+ role: role,
320
+ message: entry.message,
321
+ path: entry.path || '',
322
+ line: entry.line || 0,
323
+ column: entry.column || 0
324
+ }, window.__castleShellOrigin || '*');
325
+ } catch (e) {}
326
+ };
327
+ var mount = function () {
328
+ if (box) return;
329
+ box = document.createElement('div');
330
+ box.setAttribute('data-castle-frame-error', '1');
331
+ box.style.cssText = 'position:fixed;left:0;top:0;right:0;bottom:0;z-index:2147483000;box-sizing:border-box;padding:18px 20px;overflow:auto;background:rgba(20,8,8,0.96);color:#ffd9dc;font:13px/1.5 SFMono-Regular,Consolas,Liberation Mono,monospace';
332
+ var head = document.createElement('div');
333
+ head.style.cssText = 'display:flex;align-items:center;margin-bottom:10px';
334
+ var title = document.createElement('div');
335
+ title.style.cssText = 'font-size:15px;font-weight:700;color:#ff6b74';
336
+ title.textContent = 'Script error';
337
+ head.appendChild(title);
338
+ // Dismissable: a runtime throw in one handler should not lock a person out
339
+ // of a game that otherwise runs. A later, different error mounts it again.
340
+ var close = document.createElement('button');
341
+ close.type = 'button';
342
+ close.textContent = 'Dismiss';
343
+ close.style.cssText = 'margin-left:auto;padding:4px 12px;border:1px solid #a02828;border-radius:4px;background:#a02828;color:#fff;font:inherit;cursor:pointer';
344
+ close.onclick = function () {
345
+ if (box && box.parentNode) box.parentNode.removeChild(box);
346
+ box = null;
347
+ list = null;
348
+ };
349
+ head.appendChild(close);
350
+ box.appendChild(head);
351
+ list = document.createElement('div');
352
+ box.appendChild(list);
353
+ var hint = document.createElement('div');
354
+ hint.style.cssText = 'margin-top:12px;color:#c98a8f;font-size:12px';
355
+ hint.textContent = 'Fix the file and reload.';
356
+ box.appendChild(hint);
357
+ var attach = function () { if (document.body) document.body.appendChild(box); };
358
+ if (document.body) attach();
359
+ else document.addEventListener('DOMContentLoaded', attach);
360
+ };
361
+ var show = function (entry) {
362
+ var where = entry.path || '';
363
+ if (where && entry.line) where = where + ':' + entry.line + (entry.column ? ':' + entry.column : '');
364
+ var key = where + '|' + entry.message;
365
+ if (seen[key]) return;
366
+ seen[key] = 1;
367
+ mount();
368
+ var row = document.createElement('div');
369
+ row.style.cssText = 'margin-bottom:10px';
370
+ if (where) {
371
+ var head = document.createElement('div');
372
+ head.style.cssText = 'color:#fff;font-weight:600;word-break:break-word';
373
+ head.textContent = where;
374
+ row.appendChild(head);
375
+ }
376
+ var message = document.createElement('div');
377
+ message.style.cssText = 'word-break:break-word;white-space:pre-wrap';
378
+ message.textContent = entry.message;
379
+ row.appendChild(message);
380
+ if (entry.frame) {
381
+ var frame = document.createElement('pre');
382
+ frame.style.cssText = 'margin:6px 0 0;color:#e79aa0;font-size:12px;white-space:pre-wrap;word-break:break-word';
383
+ frame.textContent = entry.frame;
384
+ row.appendChild(frame);
385
+ }
386
+ list.appendChild(row);
387
+ shown.push(entry);
388
+ post(entry);
389
+ };
390
+ var askServe = function (src) {
391
+ var generic = function () {
392
+ show({ message: "The deck's code failed to load" + (src ? ' (' + relPath(src) + ')' : ''), path: '' });
393
+ };
394
+ var render = function (data) {
395
+ var found = data && data.errors ? data.errors : null;
396
+ var keys = found ? Object.keys(found) : [];
397
+ for (var i = 0; i < keys.length; i++) {
398
+ var entry = found[keys[i]] || {};
399
+ show({
400
+ message: entry.message || 'Failed to compile',
401
+ path: entry.path || keys[i],
402
+ line: entry.line,
403
+ column: entry.column,
404
+ frame: entry.frame
405
+ });
406
+ }
407
+ if (!keys.length) generic();
408
+ };
409
+ try {
410
+ fetch('/__castle/script-errors', { credentials: 'same-origin' }).then(function (res) {
411
+ return res.ok ? res.json() : null;
412
+ }).then(render, generic);
413
+ } catch (e) { generic(); }
414
+ };
415
+ // Capture phase: a resource error (a module script that 500s) does not
416
+ // bubble, so a listener on window only hears it on the way down. Only a
417
+ // MODULE script served from this origin counts: the deck entry and
418
+ // everything Vite serves are modules, so a CDN script, a stylesheet that
419
+ // fails offline, or a classic src script is not a transform failure.
420
+ window.addEventListener('error', function (event) {
421
+ var node = event && event.target;
422
+ if (node && node !== window && node.tagName) {
423
+ if (node.tagName === 'SCRIPT' && node.type === 'module' && node.src && node.src.indexOf(location.origin + '/') === 0) askServe(node.src);
424
+ return;
425
+ }
426
+ var error = event && event.error;
427
+ var message = (event && event.message) || (error && error.message) || String(error || 'Unknown error');
428
+ // Two browser-side non-errors that would otherwise cover a working deck:
429
+ // the benign ResizeObserver notice, and the opaque cross-origin
430
+ // "Script error." that carries nothing anyone can act on.
431
+ if (message.indexOf('ResizeObserver loop') >= 0) return;
432
+ if (message.indexOf('Script error') === 0 && !(event && event.filename)) return;
433
+ show({
434
+ message: message,
435
+ path: relPath(event && event.filename),
436
+ line: event && event.lineno,
437
+ column: event && event.colno
438
+ });
439
+ }, true);
440
+ window.addEventListener('unhandledrejection', function (event) {
441
+ var reason = event && event.reason;
442
+ var message = (reason && reason.message) || String(reason || 'Unhandled rejection');
443
+ show({ message: message, path: '' });
444
+ });
445
+ // Replay on request, because posting once loses the race both ways: the
446
+ // shell registers the frame in its iframe onLoad handler, so an error posted
447
+ // before that is dropped, and the compile-error redbox posts only after an
448
+ // async fetch of /__castle/script-errors, so it can land AFTER the readiness
449
+ // message that clears the shell's frame errors.
450
+ //
451
+ // The shell asks for readiness right after it registers the frame, which
452
+ // settles both. The announce block above registered its message listener
453
+ // first, so for one request the browser runs it first and its
454
+ // castle-content-frame-ready is posted before these re-posts: the shell
455
+ // always sees the clear followed by whatever is on screen right now. Errors
456
+ // still post immediately as well, for throws long after boot.
457
+ //
458
+ // Same sender checks as the announce block: only the parent that embeds us,
459
+ // and only from the shell origin once we know it.
460
+ window.addEventListener('message', function (event) {
461
+ var data = event && event.data;
462
+ if (event.source !== window.parent || !data || data.type !== 'castle-request-content-frame-ready') return;
463
+ if (window.__castleShellOrigin && event.origin !== window.__castleShellOrigin) return;
464
+ for (var i = 0; i < shown.length; i++) post(shown[i]);
465
+ });
466
+ })();</script>`;
241
467
  function hostnameFromHeader(value) {
242
468
  if (!value)
243
469
  return '';
@@ -272,7 +498,25 @@ const EDIT_CONTENT_READ_ENDPOINTS = new Set([
272
498
  export function isAllowedContentFilesRequest(role, method, reqPath) {
273
499
  return role === 'edit' && method === 'GET' && EDIT_CONTENT_READ_ENDPOINTS.has(reqPath);
274
500
  }
275
- function castlePlugin(security, ideServer, agentServer, configuredHost) {
501
+ // Mirrors Vite's own `injectToHead` fallback order (see
502
+ // vite/dist/node/chunks/node.js): after `<head>` when the document has one,
503
+ // else after `<html>`, else before `<body>`, else at the very top. A minimal
504
+ // deck page with no head at all still has to get the shell-origin script and
505
+ // the redbox. Replacer functions throughout, so `$&` in the injected script
506
+ // stays literal.
507
+ function injectIntoHead(html, injected) {
508
+ const head = /<head(\s[^>]*)?>/i;
509
+ if (head.test(html))
510
+ return html.replace(head, (match) => `${match}${injected}`);
511
+ const htmlTag = /<html(\s[^>]*)?>/i;
512
+ if (htmlTag.test(html))
513
+ return html.replace(htmlTag, (match) => `${match}${injected}`);
514
+ const body = /<body(\s[^>]*)?>/i;
515
+ if (body.test(html))
516
+ return html.replace(body, (match) => `${injected}${match}`);
517
+ return `${injected}${html}`;
518
+ }
519
+ function castlePlugin(security, ideServer, agentServer, scriptErrors, configuredHost) {
276
520
  return {
277
521
  name: 'castle-dev',
278
522
  transformIndexHtml: {
@@ -286,7 +530,7 @@ function castlePlugin(security, ideServer, agentServer, configuredHost) {
286
530
  const favicon = /<link[^>]+rel=["']?[^"'>]*icon/i.test(html)
287
531
  ? ''
288
532
  : `\n ${FAVICON_LINK_TAGS}`;
289
- return html.replace(/<head(\s[^>]*)?>/i, (match) => `${match}${favicon}\n <script>
533
+ const injected = `${favicon}\n <script>
290
534
  window.CastleEmbed={edit:true,host:'dev'};
291
535
  window.__castleShellOrigin=(function(){
292
536
  var h=location.hostname.toLowerCase();
@@ -313,7 +557,8 @@ window.__castleShellOrigin=(function(){
313
557
  });
314
558
  window.addEventListener('load',function(){setTimeout(announce,0);},{once:true});
315
559
  })();
316
- </script>\n ${CONSOLE_CAPTURE}`);
560
+ </script>\n ${FRAME_ERROR_CAPTURE}\n ${CONSOLE_CAPTURE}`;
561
+ return injectIntoHead(html, injected);
317
562
  },
318
563
  },
319
564
  configureServer(server) {
@@ -383,11 +628,29 @@ window.__castleShellOrigin=(function(){
383
628
  res.end(JSON.stringify({ path: `${LEGACY_CONTENT_WS_PATH}?ticket=${ticket}` }));
384
629
  return;
385
630
  }
386
- if (reqPath === '/__castle/auth' ||
387
- reqPath === '/__castle/context') {
631
+ if (reqPath === '/__castle/auth' || reqPath === '/__castle/context') {
388
632
  res.writeHead(404).end();
389
633
  return;
390
634
  }
635
+ // What failed to compile, for a frame that could not boot far enough to
636
+ // hold a socket (see FRAME_ERROR_CAPTURE). Open to BOTH content roles --
637
+ // an edit frame and a play frame are equally blank when a module 500s --
638
+ // and to the authenticated shell. Read-only, and it says nothing a
639
+ // frame could not already see in its own failed module request.
640
+ if (reqPath === '/__castle/script-errors') {
641
+ if (req.method !== 'GET') {
642
+ res.writeHead(405).end();
643
+ return;
644
+ }
645
+ if (!content &&
646
+ !security.authorizeHttp(req) &&
647
+ !security.authorizeSignedPath(req, reqPath)) {
648
+ security.rejectHttpAuth(res);
649
+ return;
650
+ }
651
+ scriptErrors.respond(res);
652
+ return;
653
+ }
391
654
  if (content) {
392
655
  if (reqPath === '/')
393
656
  req.url = `/index.html${req.url?.includes('?') ? req.url.slice(req.url.indexOf('?')) : ''}`;
@@ -557,13 +820,64 @@ function readServeJson(projectDir) {
557
820
  return null;
558
821
  }
559
822
  }
823
+ function removeServeJsonIfOwned(serveJsonPath, pid) {
824
+ try {
825
+ const before = fs.statSync(serveJsonPath);
826
+ const info = JSON.parse(fs.readFileSync(serveJsonPath, 'utf8'));
827
+ if (info.pid !== pid)
828
+ return;
829
+ const after = fs.statSync(serveJsonPath);
830
+ if (before.dev !== after.dev || before.ino !== after.ino)
831
+ return;
832
+ // The final stat-to-unlink race remains, but this narrow window is accepted.
833
+ fs.unlinkSync(serveJsonPath);
834
+ }
835
+ catch {
836
+ // Missing, malformed, or replaced by another serve: leave it alone.
837
+ }
838
+ }
839
+ function removeStaleServeJson(serveJsonPath) {
840
+ try {
841
+ const raw = fs.readFileSync(serveJsonPath, 'utf8');
842
+ let pid = null;
843
+ try {
844
+ const info = JSON.parse(raw);
845
+ if (typeof info.pid === 'number' && Number.isInteger(info.pid) && info.pid > 0) {
846
+ pid = info.pid;
847
+ }
848
+ }
849
+ catch {
850
+ // An unreadable record cannot name a live owner.
851
+ }
852
+ if (pid !== null) {
853
+ if (isPidAlive(pid))
854
+ return;
855
+ removeServeJsonIfOwned(serveJsonPath, pid);
856
+ return;
857
+ }
858
+ // Do not unlink a valid record that replaced the malformed one we read.
859
+ if (fs.readFileSync(serveJsonPath, 'utf8') === raw)
860
+ fs.unlinkSync(serveJsonPath);
861
+ }
862
+ catch {
863
+ // No stale record to remove, or another process changed it concurrently.
864
+ }
865
+ }
560
866
  function isPidAlive(pid) {
561
867
  try {
562
868
  process.kill(pid, 0);
563
869
  return true;
564
870
  }
871
+ catch (error) {
872
+ return error.code === 'EPERM';
873
+ }
874
+ }
875
+ function readLogTail(logPath, maxLines) {
876
+ try {
877
+ return fs.readFileSync(logPath, 'utf8').trimEnd().split(/\r?\n/).slice(-maxLines).join('\n');
878
+ }
565
879
  catch {
566
- return false;
880
+ return '';
567
881
  }
568
882
  }
569
883
  // Return the live serve already owning this deck, if any. Lets repeated
@@ -633,6 +947,9 @@ export async function serve(dir, options = {}) {
633
947
  return;
634
948
  }
635
949
  }
950
+ const explicitPort = options.port ? Number.parseInt(options.port, 10) : undefined;
951
+ if (explicitPort !== undefined)
952
+ await requireFreePort(explicitPort, options.host);
636
953
  // --detach is kept for back-compat. Agent evals (and any harness running
637
954
  // castle-web in a context that can't manage a foreground process) should
638
955
  // prefer the CASTLE_WEB_CLI_DETACH=1 env var instead.
@@ -693,8 +1010,8 @@ export async function serve(dir, options = {}) {
693
1010
  // already destroyed / inaccessible
694
1011
  }
695
1012
  }
696
- const startPort = parseInt(options.port ?? String(DEFAULT_PORT), 10);
697
- const port = options.port ? startPort : await findFreePort(startPort);
1013
+ const startPort = explicitPort ?? DEFAULT_PORT;
1014
+ const port = explicitPort ?? (await findFreePort(startPort, options.host));
698
1015
  const security = new ServeSecurity(port);
699
1016
  // Local WebSocket server for SDK communication
700
1017
  const castleDir = path.join(projectDir, '.castle');
@@ -716,12 +1033,7 @@ export async function serve(dir, options = {}) {
716
1033
  const screenshotsDir = path.join(castleDir, 'screenshots');
717
1034
  const serveJsonPath = path.join(castleDir, 'serve.json');
718
1035
  process.on('exit', () => {
719
- try {
720
- fs.unlinkSync(serveJsonPath);
721
- }
722
- catch {
723
- // already removed / never written
724
- }
1036
+ removeServeJsonIfOwned(serveJsonPath, process.pid);
725
1037
  });
726
1038
  process.on('SIGINT', () => process.exit());
727
1039
  process.on('SIGTERM', () => process.exit());
@@ -753,6 +1065,9 @@ export async function serve(dir, options = {}) {
753
1065
  const playtestHolder = { run: null };
754
1066
  const { broadcast, handleUpgrade: handleCastleUpgrade } = startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security, devSession, playtestHolder);
755
1067
  broadcastDevLog = broadcast;
1068
+ // Failed module transforms, remembered here so a deck whose entry never
1069
+ // evaluated can still be told what broke (scriptErrors.ts).
1070
+ const scriptErrors = createScriptErrors(projectDir, broadcast);
756
1071
  // The deck root `/` serves a split-view shell: the deck in an iframe plus a
757
1072
  // toggle button for an xterm.js terminal. The terminal's PTY is lazy -- it
758
1073
  // spawns only when a browser first opens the PTY WebSocket.
@@ -838,11 +1153,15 @@ export async function serve(dir, options = {}) {
838
1153
  // to recover from an outdated optimized-dependency response (HMR is off).
839
1154
  ...(importsChangedAtStartup ? { optimizeDeps: { force: true } } : {}),
840
1155
  plugins: [
841
- castlePlugin(security, ideServer, agentServer, options.host),
1156
+ // HMR is off (below), but Vite still injects and imports `/@vite/client`.
1157
+ // Serve a socket-free stub of it so no page logs a failed HMR connection.
1158
+ viteClientStubPlugin(),
1159
+ castlePlugin(security, ideServer, agentServer, scriptErrors, options.host),
842
1160
  forksOverlayPlugin(),
843
1161
  importsAliasPlugin(),
844
1162
  sdkAliasPlugin(),
845
1163
  sceneFilesPlugin(),
1164
+ scriptErrorsPlugin(scriptErrors),
846
1165
  ],
847
1166
  server: {
848
1167
  port,
@@ -910,7 +1229,9 @@ export async function serve(dir, options = {}) {
910
1229
  // Bring content up first so `--open` cannot race an iframe against a port
911
1230
  // that is not listening yet. Vite opens the shell from inside `vite.listen()`.
912
1231
  await vite.listen();
913
- fs.writeFileSync(serveJsonPath, JSON.stringify({
1232
+ // Atomic so a replacement lands under a new inode: the owned-removal check
1233
+ // in removeServeJsonIfOwned compares inodes to tell a rewrite apart.
1234
+ atomicWriteFileSync(serveJsonPath, JSON.stringify({
914
1235
  port,
915
1236
  // Kept for older CLI commands: they connect to this port's root path.
916
1237
  // New clients use wsPath. Both routes reach the same noServer WSS.
@@ -990,13 +1311,9 @@ async function serveDetached(projectDir, options) {
990
1311
  if (!fs.existsSync(castleDir))
991
1312
  fs.mkdirSync(castleDir, { recursive: true });
992
1313
  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
- }
1314
+ // Clear only a stale record. A live serve owns its file even when this
1315
+ // explicit invocation is going to attempt a second serve for the deck.
1316
+ removeStaleServeJson(serveJsonPath);
1000
1317
  const logPath = path.join(castleDir, 'serve.log');
1001
1318
  const logFd = fs.openSync(logPath, 'a');
1002
1319
  // Re-exec this CLI with the same args minus --detach. process.argv[0] is
@@ -1027,16 +1344,29 @@ async function serveDetached(projectDir, options) {
1027
1344
  stdio: ['ignore', logFd, logFd],
1028
1345
  env: childEnv,
1029
1346
  });
1030
- child.unref();
1031
1347
  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;
1348
+ const childPid = child.pid;
1349
+ if (childPid === undefined)
1350
+ throw new Error('detached serve did not start a child process');
1351
+ child.unref();
1352
+ // Import auto-update happens in the child before it binds and can be slow on
1353
+ // the network. Wait while that child is alive, with a generous final bound.
1354
+ const deadline = Date.now() + 120_000;
1034
1355
  while (Date.now() < deadline) {
1356
+ if (!isPidAlive(childPid)) {
1357
+ const tail = readLogTail(logPath, 10);
1358
+ throw new Error(`Detached serve process ${childPid} exited before writing ${serveJsonPath}.\n` +
1359
+ `Last lines of ${logPath}:\n${tail || '(no log output)'}`);
1360
+ }
1035
1361
  if (fs.existsSync(serveJsonPath)) {
1036
1362
  try {
1037
1363
  const info = JSON.parse(fs.readFileSync(serveJsonPath, 'utf8'));
1364
+ if (info.pid !== childPid || typeof info.port !== 'number') {
1365
+ await new Promise((r) => setTimeout(r, 200));
1366
+ continue;
1367
+ }
1038
1368
  console.log(`Started serve in background: http://localhost:${info.port}`);
1039
- console.log(`PID: ${child.pid}`);
1369
+ console.log(`PID: ${childPid}`);
1040
1370
  console.log(`Logs: ${logPath}`);
1041
1371
  return;
1042
1372
  }
@@ -1046,7 +1376,7 @@ async function serveDetached(projectDir, options) {
1046
1376
  }
1047
1377
  await new Promise((r) => setTimeout(r, 200));
1048
1378
  }
1049
- throw new Error(`Detached serve did not write ${serveJsonPath} within 15s; check ${logPath} for startup errors.`);
1379
+ throw new Error(`Detached serve did not write ${serveJsonPath} within 120s; check ${logPath} for startup errors.`);
1050
1380
  }
1051
1381
  // Answered by the SERVE itself (the agent server owns the warm Chromium),
1052
1382
  // 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
  });