castle-web-cli 0.4.229 → 0.4.231

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 (259) hide show
  1. package/dist/agent-prompts.d.ts +2 -0
  2. package/dist/agent-prompts.js +16 -8
  3. package/dist/agent.d.ts +2 -0
  4. package/dist/agent.js +21 -21
  5. package/dist/api.d.ts +28 -2
  6. package/dist/api.js +74 -16
  7. package/dist/castle-host/host.d.ts +91 -0
  8. package/dist/castle-host/host.js +860 -3
  9. package/dist/castleJson.d.ts +44 -0
  10. package/dist/castleJson.js +131 -0
  11. package/dist/check.js +27 -1
  12. package/dist/contentPack.d.ts +49 -0
  13. package/dist/contentPack.js +273 -0
  14. package/dist/devExperiments.d.ts +21 -0
  15. package/dist/devExperiments.js +139 -0
  16. package/dist/devHub.d.ts +55 -0
  17. package/dist/devHub.js +187 -0
  18. package/dist/devSaveStorage.d.ts +36 -0
  19. package/dist/devSaveStorage.js +469 -0
  20. package/dist/devSessionChild.js +25 -13
  21. package/dist/devSessionServer.d.ts +14 -1
  22. package/dist/devSessionServer.js +237 -46
  23. package/dist/devSessionStorage.d.ts +9 -0
  24. package/dist/devSessionStorage.js +66 -1
  25. package/dist/experimentAssignment.d.ts +15 -0
  26. package/dist/experimentAssignment.js +41 -0
  27. package/dist/importCheckHook.d.ts +40 -0
  28. package/dist/importCheckHook.js +171 -0
  29. package/dist/importRegression.d.ts +15 -0
  30. package/dist/importRegression.js +100 -0
  31. package/dist/importTrust.d.ts +2 -0
  32. package/dist/importTrust.js +27 -0
  33. package/dist/importUpdateHook.d.ts +18 -0
  34. package/dist/importUpdateHook.js +31 -8
  35. package/dist/importUpdateHookRunner.js +19 -7
  36. package/dist/imports.d.ts +16 -0
  37. package/dist/imports.js +141 -31
  38. package/dist/index.js +3 -1
  39. package/dist/init.d.ts +3 -0
  40. package/dist/init.js +126 -9
  41. package/dist/install.js +4 -1
  42. package/dist/localPaths.js +4 -0
  43. package/dist/login.js +2 -2
  44. package/dist/platformDoc.js +3 -8
  45. package/dist/playPagePolicy.js +3 -1
  46. package/dist/remix.js +5 -0
  47. package/dist/routerTaskReport.d.ts +28 -0
  48. package/dist/routerTaskReport.js +56 -0
  49. package/dist/save-deck.d.ts +18 -0
  50. package/dist/save-deck.js +142 -6
  51. package/dist/serve.d.ts +8 -0
  52. package/dist/serve.js +99 -14
  53. package/dist/serverBundle.d.ts +1 -1
  54. package/dist/serverBundle.js +5 -1
  55. package/dist/webSourceSync.d.ts +2 -0
  56. package/dist/webSourceSync.js +2 -0
  57. package/kits/base/CLAUDE.md +2 -3
  58. package/kits/base/castle.json +1 -1
  59. package/kits/base/sdk/README.md +406 -53
  60. package/kits/base/sdk/agent.js +4 -4
  61. package/kits/base/sdk/avatar.d.ts +12 -0
  62. package/kits/base/sdk/avatar.js +23 -0
  63. package/kits/base/sdk/castle.d.ts +9 -0
  64. package/kits/base/sdk/castle.js +5 -0
  65. package/kits/base/sdk/commands.d.ts +223 -0
  66. package/kits/base/sdk/commands.js +16 -0
  67. package/kits/base/sdk/context.d.ts +6 -0
  68. package/kits/base/sdk/experiments.d.ts +15 -0
  69. package/kits/base/sdk/experiments.js +83 -0
  70. package/kits/base/sdk/hub.d.ts +85 -0
  71. package/kits/base/sdk/hub.js +107 -0
  72. package/kits/base/sdk/multiplayer.d.ts +45 -1
  73. package/kits/base/sdk/multiplayer.js +158 -8
  74. package/kits/base/sdk/save.d.ts +197 -0
  75. package/kits/base/sdk/save.js +525 -0
  76. package/kits/base/sdk/saveCoordinator.d.ts +39 -0
  77. package/kits/base/sdk/saveCoordinator.js +252 -0
  78. package/kits/base/sdk/server/hub.d.ts +169 -0
  79. package/kits/base/sdk/server/hub.js +125 -0
  80. package/kits/base/sdk/server/platformHandle.d.ts +42 -1
  81. package/kits/base/sdk/server/storage.d.ts +58 -4
  82. package/kits/base/sdk/server/storage.js +25 -5
  83. package/kits/base/sdk/server/wrapper.d.ts +36 -2
  84. package/kits/base/sdk/server/wrapper.js +92 -11
  85. package/kits/base/sdk/store.d.ts +3 -2
  86. package/kits/base/sdk/store.js +5 -0
  87. package/kits/base/sdk/transport.d.ts +2 -1
  88. package/kits/base/sdk/transport.js +13 -1
  89. package/kits/hub-game/.prettierrc +5 -0
  90. package/kits/hub-game/CLAUDE.md +149 -0
  91. package/kits/hub-game/blueprints/avatar-0.scene +28 -0
  92. package/kits/hub-game/blueprints/avatar-1.scene +28 -0
  93. package/kits/hub-game/blueprints/avatar-2.scene +28 -0
  94. package/kits/hub-game/blueprints/avatar-3.scene +28 -0
  95. package/kits/hub-game/blueprints/bean/avatar-0.scene +28 -0
  96. package/kits/hub-game/blueprints/bean/avatar-1.scene +28 -0
  97. package/kits/hub-game/blueprints/bean/avatar-2.scene +28 -0
  98. package/kits/hub-game/blueprints/bean/avatar-3.scene +28 -0
  99. package/kits/hub-game/blueprints/blocky/avatar-0.scene +28 -0
  100. package/kits/hub-game/blueprints/blocky/avatar-1.scene +28 -0
  101. package/kits/hub-game/blueprints/blocky/avatar-2.scene +28 -0
  102. package/kits/hub-game/blueprints/blocky/avatar-3.scene +28 -0
  103. package/kits/hub-game/blueprints/pixel/avatar-0.scene +28 -0
  104. package/kits/hub-game/blueprints/pixel/avatar-1.scene +28 -0
  105. package/kits/hub-game/blueprints/pixel/avatar-2.scene +28 -0
  106. package/kits/hub-game/blueprints/pixel/avatar-3.scene +28 -0
  107. package/kits/hub-game/castle.json +96 -0
  108. package/kits/hub-game/code/client/attention.js +133 -0
  109. package/kits/hub-game/code/client/avatar.js +288 -0
  110. package/kits/hub-game/code/client/cabinets.js +90 -0
  111. package/kits/hub-game/code/client/chat.js +135 -0
  112. package/kits/hub-game/code/client/chrome.js +1035 -0
  113. package/kits/hub-game/code/client/doorFrame.js +15 -0
  114. package/kits/hub-game/code/client/firstJoin.js +14 -0
  115. package/kits/hub-game/code/client/grab.js +376 -0
  116. package/kits/hub-game/code/client/hookLayer.js +236 -0
  117. package/kits/hub-game/code/client/idle.js +326 -0
  118. package/kits/hub-game/code/client/keys.js +48 -0
  119. package/kits/hub-game/code/client/pack.js +232 -0
  120. package/kits/hub-game/code/client/packFormat.js +397 -0
  121. package/kits/hub-game/code/client/say.js +127 -0
  122. package/kits/hub-game/code/client/sha256.js +80 -0
  123. package/kits/hub-game/code/client/sound.js +147 -0
  124. package/kits/hub-game/code/client/state.js +143 -0
  125. package/kits/hub-game/code/client/talk.js +233 -0
  126. package/kits/hub-game/code/client/tiers.js +480 -0
  127. package/kits/hub-game/code/client/together.js +440 -0
  128. package/kits/hub-game/code/client/wear.js +149 -0
  129. package/kits/hub-game/code/server/actors.js +627 -0
  130. package/kits/hub-game/code/server/blocks.js +103 -0
  131. package/kits/hub-game/code/server/cabinets.js +309 -0
  132. package/kits/hub-game/code/server/game.js +137 -0
  133. package/kits/hub-game/code/server/grab.js +248 -0
  134. package/kits/hub-game/code/server/history.js +96 -0
  135. package/kits/hub-game/code/server/hub.js +1998 -0
  136. package/kits/hub-game/code/server/idle.js +412 -0
  137. package/kits/hub-game/code/server/index.js +64 -0
  138. package/kits/hub-game/code/server/labels.js +59 -0
  139. package/kits/hub-game/code/server/manifest.js +554 -0
  140. package/kits/hub-game/code/server/npcs.js +733 -0
  141. package/kits/hub-game/code/server/party.js +439 -0
  142. package/kits/hub-game/code/server/place.js +43 -0
  143. package/kits/hub-game/code/server/say.js +83 -0
  144. package/kits/hub-game/code/server/wear.js +142 -0
  145. package/kits/hub-game/code/systems/hub.js +2347 -0
  146. package/kits/hub-game/docs/content-pack.md +151 -0
  147. package/kits/hub-game/docs/contract.md +1209 -0
  148. package/kits/hub-game/docs/style.md +137 -0
  149. package/kits/hub-game/drawings/blocky/castle-eye.sprite +58 -0
  150. package/kits/hub-game/drawings/blocky/dash.sprite +59 -0
  151. package/kits/hub-game/drawings/blocky/pom.sprite +59 -0
  152. package/kits/hub-game/drawings/blocky/tabby.sprite +59 -0
  153. package/kits/hub-game/drawings/pixel/castle-arm.sprite +13 -0
  154. package/kits/hub-game/drawings/pixel/castle-body.sprite +23 -0
  155. package/kits/hub-game/drawings/pixel/castle-leg.sprite +12 -0
  156. package/kits/hub-game/drawings/pixel/kai-arm.sprite +14 -0
  157. package/kits/hub-game/drawings/pixel/kai-head.sprite +24 -0
  158. package/kits/hub-game/drawings/pixel/kai-leg.sprite +15 -0
  159. package/kits/hub-game/drawings/pixel/kai-torso.sprite +18 -0
  160. package/kits/hub-game/drawings/pixel/mimi-arm.sprite +13 -0
  161. package/kits/hub-game/drawings/pixel/mimi-head.sprite +23 -0
  162. package/kits/hub-game/drawings/pixel/mimi-leg.sprite +15 -0
  163. package/kits/hub-game/drawings/pixel/mimi-torso.sprite +18 -0
  164. package/kits/hub-game/drawings/pixel/nox-arm.sprite +13 -0
  165. package/kits/hub-game/drawings/pixel/nox-head.sprite +21 -0
  166. package/kits/hub-game/drawings/pixel/nox-leg.sprite +14 -0
  167. package/kits/hub-game/drawings/pixel/nox-torso.sprite +18 -0
  168. package/kits/hub-game/eslint.config.js +20 -0
  169. package/kits/hub-game/fonts.generated.js +9 -0
  170. package/kits/hub-game/index.html +22 -0
  171. package/kits/hub-game/main.jsx +6 -0
  172. package/kits/hub-game/models/avatar-0.pxmodel +21 -0
  173. package/kits/hub-game/models/avatar-1.pxmodel +24 -0
  174. package/kits/hub-game/models/avatar-2.pxmodel +27 -0
  175. package/kits/hub-game/models/avatar-3.pxmodel +22 -0
  176. package/kits/hub-game/models/bean/avatar-0.pxmodel +19 -0
  177. package/kits/hub-game/models/bean/avatar-1.pxmodel +24 -0
  178. package/kits/hub-game/models/bean/avatar-2.pxmodel +22 -0
  179. package/kits/hub-game/models/bean/avatar-3.pxmodel +24 -0
  180. package/kits/hub-game/models/blocky/avatar-0.pxmodel +21 -0
  181. package/kits/hub-game/models/blocky/avatar-1.pxmodel +30 -0
  182. package/kits/hub-game/models/blocky/avatar-2.pxmodel +28 -0
  183. package/kits/hub-game/models/blocky/avatar-3.pxmodel +27 -0
  184. package/kits/hub-game/models/pixel/avatar-0.pxmodel +24 -0
  185. package/kits/hub-game/models/pixel/avatar-1.pxmodel +16 -0
  186. package/kits/hub-game/models/pixel/avatar-2.pxmodel +19 -0
  187. package/kits/hub-game/models/pixel/avatar-3.pxmodel +23 -0
  188. package/kits/hub-game/package-lock.json +365 -0
  189. package/kits/hub-game/package.json +32 -0
  190. package/kits/hub-game/scenes/main.scene +318 -0
  191. package/kits/hub-game/scripts/check.mjs +339 -0
  192. package/kits/hub-game/scripts/fixtures/sdk-stub.mjs +3 -0
  193. package/kits/hub-game/scripts/gen-avatars-bean.mjs +748 -0
  194. package/kits/hub-game/scripts/gen-avatars-blocky.mjs +607 -0
  195. package/kits/hub-game/scripts/gen-avatars-pixel.mjs +771 -0
  196. package/kits/hub-game/scripts/gen-avatars.mjs +621 -0
  197. package/kits/hub-game/scripts/pack.mjs +192 -0
  198. package/kits/hub-game/scripts/test-actors.mjs +666 -0
  199. package/kits/hub-game/scripts/test-attention.mjs +103 -0
  200. package/kits/hub-game/scripts/test-avatar.mjs +472 -0
  201. package/kits/hub-game/scripts/test-ban-join.mjs +194 -0
  202. package/kits/hub-game/scripts/test-blocks.mjs +351 -0
  203. package/kits/hub-game/scripts/test-chat.mjs +98 -0
  204. package/kits/hub-game/scripts/test-classic.mjs +590 -0
  205. package/kits/hub-game/scripts/test-door-jump.mjs +131 -0
  206. package/kits/hub-game/scripts/test-door.mjs +56 -0
  207. package/kits/hub-game/scripts/test-grab-client.mjs +328 -0
  208. package/kits/hub-game/scripts/test-grab.mjs +331 -0
  209. package/kits/hub-game/scripts/test-hub-ops.mjs +835 -0
  210. package/kits/hub-game/scripts/test-hub-trip.mjs +1518 -0
  211. package/kits/hub-game/scripts/test-idle.mjs +518 -0
  212. package/kits/hub-game/scripts/test-interest.mjs +413 -0
  213. package/kits/hub-game/scripts/test-keys.mjs +50 -0
  214. package/kits/hub-game/scripts/test-manifest.mjs +270 -0
  215. package/kits/hub-game/scripts/test-no-forms.mjs +16 -0
  216. package/kits/hub-game/scripts/test-npcs.mjs +724 -0
  217. package/kits/hub-game/scripts/test-pack.mjs +424 -0
  218. package/kits/hub-game/scripts/test-party.mjs +369 -0
  219. package/kits/hub-game/scripts/test-say.mjs +149 -0
  220. package/kits/hub-game/scripts/test-tiers.mjs +666 -0
  221. package/kits/hub-game/scripts/test-together.mjs +215 -0
  222. package/kits/hub-game/theme.style +3 -0
  223. package/kits/multiplayer-3d/castle.json +5 -5
  224. package/kits/multiplayer-3d/code/client/avatars.js +101 -1
  225. package/kits/multiplayer-3d/code/server/players.js +4 -1
  226. package/kits/multiplayer-3d/code/server/sceneBodies.js +27 -6
  227. package/kits/multiplayer-3d/code/server/world.js +20 -7
  228. package/kits/multiplayer-3d/code/systems/multiplayer.js +222 -11
  229. package/kits/physics-2d/CLAUDE.md +2 -0
  230. package/kits/physics-2d/castle.json +2 -2
  231. package/kits/physics-2d/engine/art.js +13 -0
  232. package/kits/physics-2d/engine/assets.js +4 -2
  233. package/kits/physics-2d/engine/scene.js +117 -5
  234. package/kits/physics-2d/package.json +1 -1
  235. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +254 -0
  236. package/kits/physics-3d/CLAUDE.md +285 -1
  237. package/kits/physics-3d/behaviors/Player.jsx +74 -1
  238. package/kits/physics-3d/castle.json +3 -3
  239. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +33 -5
  240. package/kits/physics-3d/engine3d/actornode.js +253 -0
  241. package/kits/physics-3d/engine3d/artobjects.js +2 -2
  242. package/kits/physics-3d/engine3d/materials.js +29 -1
  243. package/kits/physics-3d/engine3d/nearshadows.js +600 -0
  244. package/kits/physics-3d/engine3d/unchanged.js +153 -0
  245. package/kits/physics-3d/engine3d/world3d.js +527 -5
  246. package/kits/physics-3d/package.json +1 -1
  247. package/kits/physics-3d/scripts/test-camera-follow.mjs +533 -0
  248. package/kits/physics-3d/scripts/test-near-shadows.mjs +1073 -0
  249. package/kits/physics-3d/scripts/test-static-actors.mjs +662 -0
  250. package/kits/physics-3d/scripts/test-static-passes.mjs +459 -0
  251. package/kits/physics-3d/scripts/test-static-physics.mjs +128 -0
  252. package/kits/physics-3d/systems/physics3d.js +187 -5
  253. package/kits/real-time/castle.json +2 -2
  254. package/kits/real-time/code/client/connection.js +77 -7
  255. package/kits/real-time/code/client/gameHooks.js +63 -3
  256. package/kits/real-time/code/client/messages.js +7 -0
  257. package/kits/real-time/code/server/gameHooks.js +24 -0
  258. package/kits/real-time/code/server/session.js +390 -22
  259. package/package.json +2 -2
@@ -0,0 +1,56 @@
1
+ export const RESULT_SUMMARY_CHARS = 600;
2
+ // A handoff line is one fact, and a long one is a summary rather than the
3
+ // single fact the prompt asks for.
4
+ export const HANDOFF_MAX_CHARS = 200;
5
+ export const HANDOFF_MAX_LIST = 8;
6
+ export function summarizeTaskResult(finalText) {
7
+ const cutAt = finalText.length - RESULT_SUMMARY_CHARS;
8
+ return {
9
+ resultSummary: finalText.slice(-RESULT_SUMMARY_CHARS),
10
+ resultSummaryStartsMidWord: cutAt > 0
11
+ ? !/\s/.test(finalText[cutAt - 1]) && !/\s/.test(finalText[cutAt])
12
+ : undefined,
13
+ };
14
+ }
15
+ export function noDeckFiles(filesLine) {
16
+ if (!filesLine?.trim())
17
+ return false;
18
+ const none = /^none(?: changed)?(?:\s*\([^)]*\))?$/i;
19
+ if (none.test(filesLine.trim()))
20
+ return true;
21
+ return filesLine.split(',').every((entry) => {
22
+ const file = entry.trim();
23
+ return (none.test(file) ||
24
+ (file.replace(/^\.\//, '').startsWith('.castle/') && !file.split('/').includes('..')));
25
+ });
26
+ }
27
+ export function routerTaskReport(task) {
28
+ if (task.status !== 'done' || task.rejected || task.handoffNoDeckFiles !== true) {
29
+ return undefined;
30
+ }
31
+ const summary = task.resultSummary ?? '';
32
+ const report = (task.resultSummaryStartsMidWord ? summary.replace(/^\S+/, '') : summary)
33
+ .replace(/\s+/g, ' ')
34
+ .trim();
35
+ if (!report)
36
+ return undefined;
37
+ return task.resultSummaryStartsMidWord === undefined ? report : `…${report}`;
38
+ }
39
+ export function routerPromptTask(task) {
40
+ return {
41
+ id: task.id,
42
+ title: task.title,
43
+ status: task.rejected ? 'rejected by user' : task.status,
44
+ progress: task.progress,
45
+ notes: task.notes,
46
+ ...(task.model ? { model: task.model } : {}),
47
+ ...(task.effort ? { effort: task.effort } : {}),
48
+ item: task.item,
49
+ report: routerTaskReport(task),
50
+ };
51
+ }
52
+ export function quotableTaskText(row, durable) {
53
+ return [durable, row.error, row.interrupted, row.notes, row.report]
54
+ .filter((s) => s?.trim())
55
+ .join('\n');
56
+ }
@@ -1,4 +1,5 @@
1
1
  import * as api from './api.js';
2
+ import { type ExperimentConfig } from './castleJson.js';
2
3
  import { type SavePrecondition } from './webSourceSync.js';
3
4
  export { DeckTooLargeError, MAX_SCENE_DATA_BYTES, MAX_SOURCE_ARCHIVE_BYTES, sceneTooLargeMessage, sourceTooLargeMessage, } from './saveFailure.js';
4
5
  export declare const SOURCE_ARCHIVE_EXCLUDES: string[];
@@ -15,6 +16,23 @@ export declare function packSourceForSave(projectDir: string, castleJson: string
15
16
  }): Promise<Buffer>;
16
17
  export declare function uploadSource(projectDir: string, deckId: string, expectedS3Key?: string | null, archive?: Buffer): Promise<api.WebDeckSource>;
17
18
  export declare function checkSavePrecondition(projectDir: string, deckId: string, force: boolean): Promise<SavePrecondition>;
19
+ export declare function publishExperiments(deckId: string, title: string, experiments: Record<string, ExperimentConfig>): Promise<void>;
20
+ export declare const EXPERIMENTS_CLEAR_SETTLE_MS = 2000;
21
+ /**
22
+ * A deck that declares no experiments sends null, which is what ends the
23
+ * experiments of a deck whose block was removed: the folder cannot tell whether
24
+ * the saved deck still has one (it may have been saved from another machine),
25
+ * and Ghost writes nothing when there was none.
26
+ *
27
+ * That call is not the save's business, so it is started here and never
28
+ * awaited: the rest of the save goes on at once, and nothing it does can fail
29
+ * the save or print a line. `settle` is for the very end of the save: it gives
30
+ * the call a short while to finish, so the process exiting does not routinely
31
+ * cut it off, then drops it. Exported for the tests.
32
+ */
33
+ export declare function startClearingExperiments(deckId: string): {
34
+ settle(capMs?: number): Promise<void>;
35
+ };
18
36
  export type SaveVisibility = 'unlisted' | 'private';
19
37
  export interface SaveDeckOptions {
20
38
  title?: string;
package/dist/save-deck.js CHANGED
@@ -6,11 +6,15 @@ import { nanoid } from 'nanoid';
6
6
  import * as api from './api.js';
7
7
  import * as config from './config.js';
8
8
  import { bundleProject } from './bundle.js';
9
- import { resolveServerConfig } from './castleJson.js';
9
+ import { resolveServerConfig, validateExperiments } from './castleJson.js';
10
+ import { importChecksFailedMessage, runImportChecks } from './importCheckHook.js';
10
11
  import { selectSaveCover } from './saveCover.js';
11
12
  import { COVER_FILE } from './localPaths.js';
12
13
  import { buildServerBundle } from './serverBundle.js';
13
- import { decideSavePrecondition, EXIT_SAVED_DECK_NEWER, fetchServerSourceVersion, readSyncMarker, saveRefusedLine, saveRefusedMessage, WEB_DECK_SOURCE_STALE_CODE, writeSyncMarker, } from './webSourceSync.js';
14
+ import { buildContentPack } from './contentPack.js';
15
+ import { importRegressionMessage, importRegressions, savedDeckImportPins } from './importRegression.js';
16
+ import { refreshStaleBuiltinImports } from './imports.js';
17
+ import { decideSavePrecondition, EXIT_IMPORTS_OLDER, EXIT_SAVED_DECK_NEWER, fetchServerSourceVersion, readSyncMarker, saveRefusedLine, saveRefusedMessage, WEB_DECK_SOURCE_STALE_CODE, writeSyncMarker, } from './webSourceSync.js';
14
18
  import { DeckTooLargeError, MAX_SCENE_DATA_BYTES, MAX_SOURCE_ARCHIVE_BYTES, SAVE_FAILURE_ENV, classifySaveFailure, saveFailedLine, sceneTooLargeMessage, sourceTooLargeMessage, } from './saveFailure.js';
15
19
  export { DeckTooLargeError, MAX_SCENE_DATA_BYTES, MAX_SOURCE_ARCHIVE_BYTES, sceneTooLargeMessage, sourceTooLargeMessage, } from './saveFailure.js';
16
20
  // `imports/` is derived state like node_modules: a dependency's files belong to
@@ -247,9 +251,11 @@ function writePublishedServerBundleState(projectDir, state) {
247
251
  fs.mkdirSync(path.dirname(file), { recursive: true });
248
252
  fs.writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
249
253
  }
250
- async function publishServerBundle(projectDir, deckId) {
254
+ async function publishServerBundle(projectDir, deckId, pack) {
251
255
  const serverConfig = resolveServerConfig(projectDir);
252
256
  if (!serverConfig) {
257
+ if (pack)
258
+ console.log('Content pack not published: a pack is paired with a server bundle, and this deck has none.');
253
259
  const prior = readPublishedServerBundleState(projectDir);
254
260
  if (prior?.deckId !== deckId) {
255
261
  console.log('Server bundle skipped: no server entry found.');
@@ -267,6 +273,7 @@ async function publishServerBundle(projectDir, deckId) {
267
273
  console.log(`Server bundle size: ${(bundle.sizeBytes / 1024).toFixed(1)}KB`);
268
274
  const uploadConfig = await api.createCauldronServerBundleUploadConfig(deckId);
269
275
  await uploadPresignedFile(uploadConfig, new Blob([bundle.code], { type: 'application/javascript' }), 'application/javascript', 60_000, 'Server bundle upload');
276
+ const packUploadId = pack ? await uploadContentPack(deckId, pack) : null;
270
277
  const saved = await api.saveCauldronServerBundle(deckId, uploadConfig.uploadId, {
271
278
  tickRate: serverConfig.tickRate,
272
279
  maxPlayers: serverConfig.maxPlayers,
@@ -275,16 +282,102 @@ async function publishServerBundle(projectDir, deckId) {
275
282
  ...(serverConfig.worldNotifications
276
283
  ? { worldNotifications: serverConfig.worldNotifications }
277
284
  : {}),
278
- });
285
+ // Sent only for a deck whose castle.json declares a hub place, so every
286
+ // other deck's config is exactly what it was.
287
+ ...(serverConfig.hub ? { hub: serverConfig.hub } : {}),
288
+ }, packUploadId ?? undefined);
279
289
  // The server hashes what it actually stored. A mismatch means the bytes that
280
290
  // will run in sessions are not the bytes we bundled.
281
291
  if (saved && saved.sha256 !== bundle.sha256) {
282
292
  throw new Error(`Published server bundle does not match what was built ` +
283
293
  `(server ${saved.sha256}, local ${bundle.sha256}). The deck was not updated safely.`);
284
294
  }
295
+ if (packUploadId && saved?.contentPackSha256 !== pack?.sha256) {
296
+ throw new Error(`Published content pack does not match what was built ` +
297
+ `(server ${saved?.contentPackSha256 ?? 'none'}, local ${pack?.sha256}). The deck was not updated safely.`);
298
+ }
299
+ if (packUploadId)
300
+ console.log(`Content pack published with it (sha256 ${pack?.sha256}).`);
285
301
  writePublishedServerBundleState(projectDir, { deckId, sha256: bundle.sha256 });
286
302
  console.log(`Server bundle published${saved ? ` as ${saved.version}` : ''} (sha256 ${bundle.sha256}).`);
287
303
  }
304
+ // Checked before anything is bundled or published, so a block Castle would
305
+ // refuse stops the save while the live deck is still untouched.
306
+ function checkedExperiments(castleJson) {
307
+ try {
308
+ return validateExperiments(castleJson?.experiments);
309
+ }
310
+ catch (e) {
311
+ throw new Error(`castle.json ${e instanceof Error ? e.message : String(e)} Nothing was saved.`);
312
+ }
313
+ }
314
+ // castle.json `experiments` goes to Castle on every save, with or without a
315
+ // server bundle. A declared block is awaited and fails the save loudly when it
316
+ // cannot be stored. Exported for the tests.
317
+ export async function publishExperiments(deckId, title, experiments) {
318
+ let stored;
319
+ try {
320
+ stored = await api.setCauldronDeckExperiments(deckId, experiments);
321
+ }
322
+ catch (e) {
323
+ const reason = e instanceof Error ? e.message : String(e);
324
+ throw new Error(`Experiments NOT saved (${reason}). ` +
325
+ `"${title}" is live on the new client but its experiments are unchanged.`);
326
+ }
327
+ const names = Object.keys(experiments).join(', ');
328
+ console.log(stored
329
+ ? `Experiments saved (${names}).`
330
+ : `Experiments not saved (${names}): this Castle server does not support experiments yet. ` +
331
+ 'Every player reads null until it does and the deck is saved again.');
332
+ }
333
+ // How long the end of a save waits for the clearing call below.
334
+ export const EXPERIMENTS_CLEAR_SETTLE_MS = 2_000;
335
+ /**
336
+ * A deck that declares no experiments sends null, which is what ends the
337
+ * experiments of a deck whose block was removed: the folder cannot tell whether
338
+ * the saved deck still has one (it may have been saved from another machine),
339
+ * and Ghost writes nothing when there was none.
340
+ *
341
+ * That call is not the save's business, so it is started here and never
342
+ * awaited: the rest of the save goes on at once, and nothing it does can fail
343
+ * the save or print a line. `settle` is for the very end of the save: it gives
344
+ * the call a short while to finish, so the process exiting does not routinely
345
+ * cut it off, then drops it. Exported for the tests.
346
+ */
347
+ export function startClearingExperiments(deckId) {
348
+ const controller = new AbortController();
349
+ const cleared = api
350
+ .setCauldronDeckExperiments(deckId, null, { signal: controller.signal })
351
+ .then(() => undefined, () => undefined);
352
+ return {
353
+ async settle(capMs = EXPERIMENTS_CLEAR_SETTLE_MS) {
354
+ let timer;
355
+ await Promise.race([
356
+ cleared,
357
+ new Promise((resolve) => {
358
+ timer = setTimeout(resolve, capMs);
359
+ timer.unref();
360
+ }),
361
+ ]);
362
+ clearTimeout(timer);
363
+ // A request still out would hold the process open until its own timeout.
364
+ controller.abort();
365
+ },
366
+ };
367
+ }
368
+ // A content pack is published as part of the server bundle's own release
369
+ // (contentPack.ts): uploaded first, then named in the same save, so Ghost writes
370
+ // both in one row. A Ghost that does not host packs yet gets the bundle alone,
371
+ // as before; the pack stays in `.castle/content-pack/`.
372
+ async function uploadContentPack(deckId, pack) {
373
+ const config = await api.createCauldronContentPackUploadConfig(deckId);
374
+ if (!config) {
375
+ console.log(`Content pack built (${pack.sha256.slice(0, 12)}) but not published: Castle does not host content packs yet.`);
376
+ return null;
377
+ }
378
+ await uploadPresignedFile(config, new Blob([new Uint8Array(pack.bytes)], { type: 'application/json' }), 'application/json', LARGE_UPLOAD_TIMEOUT_MS, 'Content pack upload');
379
+ return config.uploadId;
380
+ }
288
381
  async function uploadLocalCover(projectDir) {
289
382
  try {
290
383
  const selected = await selectSaveCover(projectDir, { onProgress: (message) => console.log(message) });
@@ -371,8 +464,13 @@ export async function saveDeck(dir, opts = {}) {
371
464
  }
372
465
  }
373
466
  async function saveDeckAfterValidation(dir, opts, projectDir, visibility) {
467
+ // A builtin kit that changed under the same CLI version is this CLI's again
468
+ // before anything is read, packed or bundled: a save never ships a stale copy
469
+ // of it, and the pins a refreshed kit adds are in the castle.json read here.
470
+ await refreshStaleBuiltinImports(projectDir);
374
471
  const castleJson = readCastleJson(projectDir);
375
472
  const existingDeckId = typeof castleJson?.deckId === 'string' && castleJson.deckId ? castleJson.deckId : null;
473
+ const experiments = checkedExperiments(castleJson);
376
474
  // A deck without an id is new: the source commit sends no precondition, as before.
377
475
  let expectedS3Key;
378
476
  let markerVia = 'save-deck';
@@ -384,13 +482,47 @@ async function saveDeckAfterValidation(dir, opts, projectDir, visibility) {
384
482
  }
385
483
  expectedS3Key = precondition.expectedS3Key;
386
484
  markerVia = precondition.via;
485
+ if (precondition.adopt && opts.force !== true) {
486
+ // An unsynced folder adopting the saved copy: refused if it would roll an
487
+ // import back (a stale repo copy of a live deck). A check that cannot run
488
+ // (offline, an older Ghost) leaves the save to the server.
489
+ const regressions = await savedDeckImportPins(existingDeckId)
490
+ .then((saved) => (saved ? importRegressions(projectDir, (castleJson?.imports ?? {}), saved) : []))
491
+ .catch((e) => {
492
+ console.warn(`Could not compare imports with the saved deck: ${e instanceof Error ? e.message : String(e)}`);
493
+ return [];
494
+ });
495
+ if (regressions.length > 0) {
496
+ console.error(importRegressionMessage(dir, regressions));
497
+ // castle-www's cloud save understands only its own refusal (exit 5 and
498
+ // its stdout line): there this is a warning, and the save goes ahead.
499
+ if (process.env[SAVE_FAILURE_ENV] !== '1') {
500
+ process.exitCode = EXIT_IMPORTS_OLDER;
501
+ return;
502
+ }
503
+ console.error('Saving anyway (cloud save).');
504
+ }
505
+ }
387
506
  if (precondition.adopt) {
388
507
  console.error('Note: this folder has no record of which saved copy it came from; adopting it as the ' +
389
508
  "deck's saved copy. Later saves are refused if someone else saves this deck in between.");
390
509
  }
391
510
  }
392
511
  console.log('Bundling...');
393
- const bundle = await traceSaveStage('bundle', () => bundleProject(projectDir), (value) => ({ bytes: Buffer.byteLength(value) }));
512
+ // The imports' `onCheck`s run inside the bundle stage, after the bundle and
513
+ // before anything is uploaded: a deck its kit refuses is a deck that did not
514
+ // build, as far as publishing is concerned (and as castle-www's failed_at
515
+ // reports it).
516
+ const built = await traceSaveStage('bundle', async () => {
517
+ const built = await bundleProject(projectDir);
518
+ const { errors } = await runImportChecks(projectDir);
519
+ if (errors.length > 0)
520
+ throw new Error(importChecksFailedMessage(errors));
521
+ return { html: built, pack: await buildContentPack(projectDir) };
522
+ }, (value) => ({ bytes: Buffer.byteLength(value.html) }));
523
+ const { html: bundle, pack } = built;
524
+ if (pack)
525
+ console.log(`Content pack: ${pack.summary ?? `${pack.bytes.byteLength} bytes`} (${pack.sha256.slice(0, 12)}).`);
394
526
  const sizeKB = bundle.length / 1024;
395
527
  console.log(`Bundle size: ${sizeKB.toFixed(1)}KB`);
396
528
  if (sizeKB > 1024) {
@@ -491,13 +623,16 @@ async function saveDeckAfterValidation(dir, opts, projectDir, visibility) {
491
623
  else {
492
624
  console.log(`Saved "${title}" to Castle.`);
493
625
  }
626
+ const clearingExperiments = experiments ? null : startClearingExperiments(result.deckId);
627
+ if (experiments)
628
+ await publishExperiments(result.deckId, title, experiments);
494
629
  // The deck went live above, so anything failing here leaves it skewed: the
495
630
  // published client runs against whatever server was last deployed. Say that
496
631
  // in the thrown message -- it is the only line the cloud editor gets back
497
632
  // (it forwards stderr), and "not valid JSON" reads as a glitch, not as a
498
633
  // deck that is now half-published.
499
634
  try {
500
- await traceSaveStage('server_publish', () => publishServerBundle(projectDir, result.deckId));
635
+ await traceSaveStage('server_publish', () => publishServerBundle(projectDir, result.deckId, pack));
501
636
  }
502
637
  catch (e) {
503
638
  const reason = e instanceof Error ? e.message : String(e);
@@ -518,6 +653,7 @@ async function saveDeckAfterValidation(dir, opts, projectDir, visibility) {
518
653
  // The save itself succeeded; a missing marker only means the next save adopts again.
519
654
  console.error(`Could not record the saved version: ${e instanceof Error ? e.message : String(e)}`);
520
655
  }
656
+ await clearingExperiments?.settle();
521
657
  }
522
658
  catch (e) {
523
659
  const code = e?.extensions?.code ?? '';
package/dist/serve.d.ts CHANGED
@@ -1,9 +1,17 @@
1
1
  import * as http from 'http';
2
+ import { type Plugin } from 'vite';
3
+ import { type IdeServer } from './ide.js';
4
+ import { type AgentServer } from './agent.js';
5
+ import { type ScriptErrors } from './scriptErrors.js';
6
+ import { DevExperiments } from './devExperiments.js';
7
+ import { ServeSecurity } from './serveSecurity.js';
2
8
  export declare function appendCapped(file: string, line: string): void;
3
9
  export declare function isViteClientUpgrade(req: http.IncomingMessage): boolean;
4
10
  export declare function isAllowedShellHost(hostHeader: string | undefined, configuredHost?: string): boolean;
5
11
  export declare function isAllowedContentFilesRequest(role: 'edit' | 'play' | null, method: string | undefined, reqPath: string): boolean;
6
12
  export declare function injectDeckHead(html: string, play?: boolean): string;
13
+ export declare function castlePlugin(security: ServeSecurity, ideServer: IdeServer, agentServer: AgentServer, scriptErrors: ScriptErrors, projectDir: string, configuredHost?: string): Plugin;
14
+ export declare function devExperimentsFor(projectDir: string): DevExperiments;
7
15
  export declare function serve(dir: string, options?: {
8
16
  port?: string;
9
17
  host?: string;
package/dist/serve.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { handleContentPackRequest } from './contentPack.js';
1
2
  import { placeCoverBridge } from './playCoverPlacement.js';
2
3
  import * as fs from 'fs';
3
4
  import * as http from 'http';
@@ -19,13 +20,16 @@ import { createScriptErrors, scriptErrorsPlugin } from './scriptErrors.js';
19
20
  import { installFilesChangedWatcher } from './filesChanged.js';
20
21
  import { installGitHeadWatcher } from './gitHeadWatcher.js';
21
22
  import { applyDeckWrite, createTuneLedger } from './paramsTunes.js';
22
- import { autoUpdateImports, IMPORTS_DIR, lockImportTree } from './imports.js';
23
+ import { autoUpdateImports, IMPORTS_DIR, lockImportTree, refreshStaleBuiltinImports } from './imports.js';
23
24
  import { ensureAgentsSymlink } from './init.js';
24
25
  import { migrateClaudeMd, PLATFORM_DOC_REL, writePlatformDocs } from './platformDoc.js';
25
26
  import { FORKS_DIR, ownForkFile, splitImportRel } from './forks.js';
26
27
  import * as config from './config.js';
27
28
  import { graphql as castleGraphql } from './api.js';
28
29
  import { executeCommand } from './castle-host/host.js';
30
+ import { DevHubVisit, readDevHubDoors } from './devHub.js';
31
+ import { DevExperiments } from './devExperiments.js';
32
+ import { devSaveGraphql } from './devSessionStorage.js';
29
33
  import { serveOracleStream } from './deckAgentRoute.js';
30
34
  import { ServeSecurity } from './serveSecurity.js';
31
35
  import { atomicWriteFileSync } from './atomicFile.js';
@@ -34,7 +38,7 @@ import { createAssetCompression } from './assetCompression.js';
34
38
  import { playCoverHeadInjection } from './playCoverGate.js';
35
39
  import { isPlayPageUrl, playPageHeadInjection } from './playPagePolicy.js';
36
40
  import { resolveServerConfig } from './castleJson.js';
37
- import { startDevSessionServer, } from './devSessionServer.js';
41
+ import { startDevSessionServer, devSessionIdFor, } from './devSessionServer.js';
38
42
  // The log is a tail, not an archive: append, and once it passes the cap drop
39
43
  // whole lines off the front until it is back under.
40
44
  const LOG_MAX_BYTES = 2 * 1024 * 1024;
@@ -623,7 +627,8 @@ window.__castleShellOrigin=(function(){
623
627
  const page = injectIntoHead(html, injected);
624
628
  return cover ? placeCoverBridge(page, cover) : page;
625
629
  }
626
- function castlePlugin(security, ideServer, agentServer, scriptErrors, configuredHost) {
630
+ // Exported for the tests.
631
+ export function castlePlugin(security, ideServer, agentServer, scriptErrors, projectDir, configuredHost) {
627
632
  return {
628
633
  name: 'castle-dev',
629
634
  transformIndexHtml: {
@@ -727,12 +732,22 @@ function castlePlugin(security, ideServer, agentServer, scriptErrors, configured
727
732
  if (reqPath === '/')
728
733
  req.url = `/index.html${req.url?.includes('?') ? req.url.slice(req.url.indexOf('?')) : ''}`;
729
734
  const allowedFilesRequest = isAllowedContentFilesRequest(contentRole, req.method, reqPath);
735
+ // Doors to other local decks (contentPack.ts): read-only, and limited to
736
+ // the decks this deck's castle.json lists. Either content role: a
737
+ // phone plays from the play URL.
738
+ if (reqPath.startsWith('/__castle/content-pack/')) {
739
+ void handleContentPackRequest(projectDir, req, res, reqPath);
740
+ return;
741
+ }
730
742
  const allowedVendor = reqPath.startsWith('/__castle/vendor/');
731
743
  const allowedFavicon = FAVICON_FILES.some((name) => reqPath === `/${name}`);
732
744
  if (reqPath.startsWith('/__castle/') && !allowedFilesRequest && !allowedVendor) {
733
745
  res.writeHead(403).end('content capability does not allow this endpoint');
734
746
  return;
735
747
  }
748
+ // Only a request that got this far may force an A/B arm
749
+ // (devExperiments.ts): one refused above changes nothing.
750
+ devExperimentsFor(projectDir).noteUrl(req.url);
736
751
  if ((allowedFilesRequest || allowedVendor || allowedFavicon) &&
737
752
  ideServer.handleHttpRequest(req, res, reqPath))
738
753
  return;
@@ -749,6 +764,7 @@ function castlePlugin(security, ideServer, agentServer, scriptErrors, configured
749
764
  security.rejectHttpAuth(res);
750
765
  return;
751
766
  }
767
+ devExperimentsFor(projectDir).noteUrl(req.url);
752
768
  // The split-view shell (`/`) + its static assets are served outside
753
769
  // Vite's module pipeline; the deck itself loads in the iframe via
754
770
  // `/index.html`, which Vite still serves normally.
@@ -783,19 +799,63 @@ async function devMe() {
783
799
  }
784
800
  return cachedDevMe;
785
801
  }
786
- async function devHostContext(projectDir) {
802
+ // A/B experiments per served deck (devExperiments.ts): the arms forced through
803
+ // `?experiment.<name>=` live here, for the serve's lifetime.
804
+ const devExperiments = new Map();
805
+ // Exported for the tests.
806
+ export function devExperimentsFor(projectDir) {
807
+ let experiments = devExperiments.get(projectDir);
808
+ if (!experiments) {
809
+ experiments = new DevExperiments(projectDir, (text) => console.warn(`[experiments] ${text}`));
810
+ devExperiments.set(projectDir, experiments);
811
+ }
812
+ return experiments;
813
+ }
814
+ // The SDK prefixes every request id with a value drawn once per page load
815
+ // (transport.ts), which is what makes a page load nameable here.
816
+ function commandPageLoad(requestId) {
817
+ return /^(csdk_[a-z0-9]+)_\d+$/.exec(requestId)?.[1] ?? null;
818
+ }
819
+ async function devHostContext(projectDir, requestId) {
787
820
  const ctx = readDeckContext(projectDir);
788
821
  const me = await devMe();
822
+ const userId = config.getUserId() ?? me.userId;
789
823
  return {
790
824
  deckId: ctx.deckId ?? null,
791
825
  sessionId: null,
792
- userId: config.getUserId() ?? me.userId,
826
+ userId,
793
827
  username: me.username,
828
+ // Assigned under the id local multiplayer gives this player, and held for
829
+ // the page load, so the page and the deck's server read the same arm.
830
+ experimentVariants: devExperimentsFor(projectDir).variantsForPage(commandPageLoad(requestId), userId ?? DEV_ANONYMOUS_USER_ID, ctx.deckId ?? null),
794
831
  };
795
832
  }
796
833
  // Agent.chat's route to deck-agent: the CLI's login token locally, the sandbox
797
834
  // host's llm-proxy inside a cloud sandbox (deckAgentRoute.ts).
798
835
  const oracleStream = serveOracleStream(() => config.getToken());
836
+ // Hub doors per connected page (devHub.ts), and the pads gathering across all
837
+ // of them. The local multiplayer URL depends on which origin the page came
838
+ // through, so each command hands its visit the current one.
839
+ // Play panels share the shell's socket, so a visit is per socket and panel.
840
+ const hubVisits = new WeakMap();
841
+ const devPadGroups = new Map();
842
+ function devHubVisit(ws, playSessionSlot, projectDir, multiplayer, multiplayerUrl) {
843
+ const panels = hubVisits.get(ws) ?? new Map();
844
+ hubVisits.set(ws, panels);
845
+ let entry = panels.get(playSessionSlot ?? '');
846
+ if (!entry) {
847
+ const mp = { url: multiplayerUrl };
848
+ const visit = new DevHubVisit(() => readDevHubDoors(projectDir, (text) => console.warn(`[hub] ${text}`)), {
849
+ url: () => (multiplayer ? mp.url : null),
850
+ mintNonce: (ctx, key) => multiplayer.mintNonce(devMultiplayerIdentity(ctx), key, ctx.experimentVariants ?? undefined),
851
+ sessionIdFor: (key) => devSessionIdFor(key),
852
+ }, devPadGroups);
853
+ entry = { visit, mp };
854
+ panels.set(playSessionSlot ?? '', entry);
855
+ }
856
+ entry.mp.url = multiplayerUrl;
857
+ return entry.visit;
858
+ }
799
859
  // Commands in flight on each socket, so a deck's cancel or a closed socket can
800
860
  // abort a streaming one.
801
861
  const commandAborts = new WeakMap();
@@ -815,7 +875,7 @@ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multi
815
875
  commandAborts.set(ws, aborts);
816
876
  const controller = new AbortController();
817
877
  aborts.set(requestId, controller);
818
- const ctx = await devHostContext(projectDir);
878
+ const ctx = await devHostContext(projectDir, requestId);
819
879
  const onStream = (event) => {
820
880
  if (ws.readyState === WebSocket.OPEN) {
821
881
  ws.send(JSON.stringify({ type: 'castle_command_stream', castleSdk: 1, requestId, stream: event }));
@@ -827,10 +887,14 @@ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multi
827
887
  // does have: this process can't draw it, so the fetched payload goes to the
828
888
  // shell, which mounts the same panel the app and the website use.
829
889
  const result = await executeCommand(ctx, command, params, {
830
- graphqlFetch: castleGraphql,
890
+ graphqlFetch: (query, variables) => {
891
+ const save = devSaveGraphql(projectDir, ctx.userId, query, variables);
892
+ return save ? Promise.resolve(save) : castleGraphql(query, variables);
893
+ },
831
894
  oracleStream,
832
895
  showLeaderboard: (payload) => broadcast({ type: 'castle_leaderboard_show', payload }),
833
- getMultiplayerSession: () => {
896
+ hub: devHubVisit(ws, playSessionSlot, projectDir, multiplayer, multiplayerUrl),
897
+ getMultiplayerSession: (request) => {
834
898
  if (!multiplayer || !multiplayerUrl) {
835
899
  return Promise.resolve({
836
900
  status: 'unavailable',
@@ -840,11 +904,13 @@ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multi
840
904
  soloReason: null,
841
905
  });
842
906
  }
907
+ // Each named key runs its own local session; public and party share 'dev'.
908
+ const key = request.mode === 'named' ? (request.key ?? null) : null;
843
909
  return Promise.resolve({
844
910
  status: 'ok',
845
911
  url: multiplayerUrl,
846
- nonce: multiplayer.mintNonce(devMultiplayerIdentity(ctx)),
847
- sessionId: multiplayer.sessionId,
912
+ nonce: multiplayer.mintNonce(devMultiplayerIdentity(ctx), key, ctx.experimentVariants ?? undefined),
913
+ sessionId: multiplayer.sessionIdFor(key),
848
914
  soloReason: null,
849
915
  ...(playSessionSlot ? { devReconnectScope: playSessionSlot } : {}),
850
916
  });
@@ -855,13 +921,18 @@ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multi
855
921
  ws.send(JSON.stringify({ type: 'castle_command_response', castleSdk: 1, requestId, ...result }));
856
922
  }
857
923
  }
924
+ const DEV_ANONYMOUS_USER_ID = 'dev-user';
858
925
  function devMultiplayerIdentity(ctx) {
859
926
  return {
860
- userId: ctx.userId ?? 'dev-user',
927
+ userId: ctx.userId ?? DEV_ANONYMOUS_USER_ID,
861
928
  username: ctx.username ?? 'Developer',
862
929
  isAnonymous: ctx.userId === null,
863
930
  };
864
931
  }
932
+ function isLoopbackRequest(req) {
933
+ const address = req.socket.remoteAddress;
934
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1';
935
+ }
865
936
  function devMultiplayerUrl(req) {
866
937
  const base = typeof req.headers.origin === 'string' ? req.headers.origin : null;
867
938
  if (!base)
@@ -1074,6 +1145,12 @@ export async function serve(dir, options = {}) {
1074
1145
  let importsChangedAtStartup = false;
1075
1146
  if (!existingServe(projectDir)) {
1076
1147
  const importsBeforeUpdate = importPinsFingerprint(projectDir);
1148
+ // A builtin kit that changed under the same CLI version replaces the deck's
1149
+ // copy here too, where nothing is running yet.
1150
+ const refreshed = await refreshStaleBuiltinImports(projectDir).catch((e) => {
1151
+ console.warn(`builtin kits: left as they are -- ${e instanceof Error ? e.message : String(e)}`);
1152
+ return [];
1153
+ });
1077
1154
  // A failure to check must never keep the deck from opening.
1078
1155
  const updated = await autoUpdateImports(projectDir).catch((e) => {
1079
1156
  console.warn(`auto-update: skipped -- ${e instanceof Error ? e.message : String(e)}`);
@@ -1082,7 +1159,9 @@ export async function serve(dir, options = {}) {
1082
1159
  // Comparing pins as well as the returned list preserves the invalidation
1083
1160
  // if a later step throws after one or more imported trees were replaced.
1084
1161
  importsChangedAtStartup =
1085
- updated.length > 0 || importsBeforeUpdate !== importPinsFingerprint(projectDir);
1162
+ refreshed.length > 0 ||
1163
+ updated.length > 0 ||
1164
+ importsBeforeUpdate !== importPinsFingerprint(projectDir);
1086
1165
  }
1087
1166
  // Start pulling the headless browser now, in the background.
1088
1167
  //
@@ -1263,7 +1342,7 @@ export async function serve(dir, options = {}) {
1263
1342
  // HMR is off (below), but Vite still injects and imports `/@vite/client`.
1264
1343
  // Serve a socket-free stub of it so no page logs a failed HMR connection.
1265
1344
  viteClientStubPlugin(),
1266
- castlePlugin(security, ideServer, agentServer, scriptErrors, options.host),
1345
+ castlePlugin(security, ideServer, agentServer, scriptErrors, projectDir, options.host),
1267
1346
  forksOverlayPlugin(),
1268
1347
  importsAliasPlugin(),
1269
1348
  sdkAliasPlugin(),
@@ -1590,7 +1669,13 @@ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security
1590
1669
  };
1591
1670
  wss.on('connection', (ws, req) => {
1592
1671
  clients.add(ws);
1593
- const multiplayerUrl = devMultiplayerUrl(req);
1672
+ // A loopback client with no Origin (a CLI or a script, which is all the
1673
+ // root path admits) has no content origin to proxy through, so it joins
1674
+ // the dev session server directly: how script-driven test players get in.
1675
+ const multiplayerUrl = devMultiplayerUrl(req) ??
1676
+ (multiplayer && !req.headers.origin && isLoopbackRequest(req)
1677
+ ? `ws://127.0.0.1:${multiplayer.port}/__castle/mp`
1678
+ : null);
1594
1679
  const legacyRole = legacyRoles.get(ws) ?? null;
1595
1680
  ws.on('message', (raw) => {
1596
1681
  try {
@@ -5,4 +5,4 @@ export interface ServerBundle {
5
5
  sizeBytes: number;
6
6
  }
7
7
  export declare function buildServerBundle(projectDir: string): Promise<ServerBundle | null>;
8
- export declare function bundleServerModule(projectDir: string, config: ResolvedServerConfig, minify: boolean): Promise<string>;
8
+ export declare function bundleServerModule(projectDir: string, config: ResolvedServerConfig, minify: boolean, define?: Record<string, string>): Promise<string>;
@@ -33,7 +33,10 @@ export async function buildServerBundle(projectDir) {
33
33
  // Dev and publish deliberately share the synthesized entry and Vite semantics.
34
34
  // Dev keeps readable code; the published artifact is minified and checked below
35
35
  // for the single-output-file contract.
36
- export async function bundleServerModule(projectDir, config, minify) {
36
+ export async function bundleServerModule(projectDir, config, minify,
37
+ // Compile-time constants for this build only (the dev serve's
38
+ // `import.meta.env.CASTLE_DEV_DECKS`); a published bundle has none.
39
+ define = {}) {
37
40
  // The synthesized entry names the file directly, so it has to resolve here
38
41
  // rather than through the plugin: the deck's `base` import when it has one,
39
42
  // node_modules for a deck predating the move.
@@ -57,6 +60,7 @@ export async function bundleServerModule(projectDir, config, minify) {
57
60
  root: projectDir,
58
61
  configFile: false,
59
62
  logLevel: 'silent',
63
+ define,
60
64
  plugins: [forksOverlayPlugin(), importsAliasPlugin(), sdkAliasPlugin(), entryPlugin],
61
65
  ssr: { noExternal: true },
62
66
  build: {
@@ -48,6 +48,8 @@ export declare function fetchServerSourceVersion(deckId: string): Promise<Server
48
48
  export declare function humanTime(iso: string): string;
49
49
  /** save-deck's exit code when the saved copy is newer than this folder (1-4 are taken). */
50
50
  export declare const EXIT_SAVED_DECK_NEWER = 5;
51
+ /** save-deck's exit code when an unsynced folder would move the saved deck's imports back. */
52
+ export declare const EXIT_IMPORTS_OLDER = 6;
51
53
  export declare const SAVE_REFUSED_PREFIX = "CASTLE_SAVE_REFUSED ";
52
54
  export declare const SAVED_DECK_NEWER_CODE = "SAVED_DECK_NEWER";
53
55
  /** Ghost's code when its own check (primary, under lock) refuses the source commit. */
@@ -125,6 +125,8 @@ export function humanTime(iso) {
125
125
  // --- save-deck refusal --------------------------------------------------------
126
126
  /** save-deck's exit code when the saved copy is newer than this folder (1-4 are taken). */
127
127
  export const EXIT_SAVED_DECK_NEWER = 5;
128
+ /** save-deck's exit code when an unsynced folder would move the saved deck's imports back. */
129
+ export const EXIT_IMPORTS_OLDER = 6;
128
130
  export const SAVE_REFUSED_PREFIX = 'CASTLE_SAVE_REFUSED ';
129
131
  export const SAVED_DECK_NEWER_CODE = 'SAVED_DECK_NEWER';
130
132
  /** Ghost's code when its own check (primary, under lock) refuses the source commit. */