castle-web-cli 0.4.228 → 0.4.230

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 (236) hide show
  1. package/dist/agent-prompts.d.ts +11 -3
  2. package/dist/agent-prompts.js +153 -53
  3. package/dist/agent.d.ts +2 -0
  4. package/dist/agent.js +43 -33
  5. package/dist/api.d.ts +47 -2
  6. package/dist/api.js +85 -16
  7. package/dist/castle-host/host.d.ts +91 -0
  8. package/dist/castle-host/host.js +779 -3
  9. package/dist/castleJson.d.ts +59 -0
  10. package/dist/castleJson.js +267 -3
  11. package/dist/check.js +27 -1
  12. package/dist/cloudGit.d.ts +20 -1
  13. package/dist/cloudGit.js +267 -10
  14. package/dist/contentPack.d.ts +49 -0
  15. package/dist/contentPack.js +273 -0
  16. package/dist/devExperiments.d.ts +21 -0
  17. package/dist/devExperiments.js +139 -0
  18. package/dist/devHub.d.ts +55 -0
  19. package/dist/devHub.js +187 -0
  20. package/dist/devSessionChild.js +3 -1
  21. package/dist/devSessionServer.d.ts +14 -1
  22. package/dist/devSessionServer.js +229 -44
  23. package/dist/experimentAssignment.d.ts +15 -0
  24. package/dist/experimentAssignment.js +41 -0
  25. package/dist/importCheckHook.d.ts +40 -0
  26. package/dist/importCheckHook.js +171 -0
  27. package/dist/importRegression.d.ts +15 -0
  28. package/dist/importRegression.js +100 -0
  29. package/dist/importTrust.d.ts +2 -0
  30. package/dist/importTrust.js +27 -0
  31. package/dist/importUpdateHook.d.ts +18 -0
  32. package/dist/importUpdateHook.js +31 -8
  33. package/dist/importUpdateHookRunner.js +19 -7
  34. package/dist/imports.d.ts +16 -0
  35. package/dist/imports.js +145 -33
  36. package/dist/index.js +8 -1
  37. package/dist/init.d.ts +3 -0
  38. package/dist/init.js +125 -8
  39. package/dist/install.js +4 -1
  40. package/dist/localPaths.js +4 -0
  41. package/dist/login.js +2 -2
  42. package/dist/platformDoc.js +3 -8
  43. package/dist/playPagePolicy.js +3 -1
  44. package/dist/remix.js +5 -0
  45. package/dist/routerTaskReport.d.ts +28 -0
  46. package/dist/routerTaskReport.js +56 -0
  47. package/dist/save-deck.d.ts +18 -0
  48. package/dist/save-deck.js +145 -6
  49. package/dist/serve.d.ts +8 -0
  50. package/dist/serve.js +94 -13
  51. package/dist/serverBundle.d.ts +1 -1
  52. package/dist/serverBundle.js +5 -1
  53. package/dist/sourceLineage.d.ts +42 -0
  54. package/dist/sourceLineage.js +380 -0
  55. package/dist/webSourceSync.d.ts +11 -0
  56. package/dist/webSourceSync.js +26 -9
  57. package/kits/base/CLAUDE.md +2 -3
  58. package/kits/base/castle.json +1 -1
  59. package/kits/base/sdk/README.md +301 -52
  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 +6 -1
  64. package/kits/base/sdk/castle.js +3 -0
  65. package/kits/base/sdk/commands.d.ts +208 -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 +86 -6
  73. package/kits/base/sdk/multiplayer.js +157 -4
  74. package/kits/base/sdk/server/hub.d.ts +169 -0
  75. package/kits/base/sdk/server/hub.js +125 -0
  76. package/kits/base/sdk/server/platformHandle.d.ts +49 -2
  77. package/kits/base/sdk/server/storage.d.ts +55 -2
  78. package/kits/base/sdk/server/wrapper.d.ts +85 -6
  79. package/kits/base/sdk/server/wrapper.js +393 -30
  80. package/kits/base/sdk/transport.d.ts +2 -1
  81. package/kits/base/sdk/transport.js +13 -1
  82. package/kits/hub-game/.prettierrc +5 -0
  83. package/kits/hub-game/CLAUDE.md +146 -0
  84. package/kits/hub-game/blueprints/avatar-0.scene +28 -0
  85. package/kits/hub-game/blueprints/avatar-1.scene +28 -0
  86. package/kits/hub-game/blueprints/avatar-2.scene +28 -0
  87. package/kits/hub-game/blueprints/avatar-3.scene +28 -0
  88. package/kits/hub-game/blueprints/bean/avatar-0.scene +28 -0
  89. package/kits/hub-game/blueprints/bean/avatar-1.scene +28 -0
  90. package/kits/hub-game/blueprints/bean/avatar-2.scene +28 -0
  91. package/kits/hub-game/blueprints/bean/avatar-3.scene +28 -0
  92. package/kits/hub-game/blueprints/blocky/avatar-0.scene +28 -0
  93. package/kits/hub-game/blueprints/blocky/avatar-1.scene +28 -0
  94. package/kits/hub-game/blueprints/blocky/avatar-2.scene +28 -0
  95. package/kits/hub-game/blueprints/blocky/avatar-3.scene +28 -0
  96. package/kits/hub-game/blueprints/pixel/avatar-0.scene +28 -0
  97. package/kits/hub-game/blueprints/pixel/avatar-1.scene +28 -0
  98. package/kits/hub-game/blueprints/pixel/avatar-2.scene +28 -0
  99. package/kits/hub-game/blueprints/pixel/avatar-3.scene +28 -0
  100. package/kits/hub-game/castle.json +96 -0
  101. package/kits/hub-game/code/client/attention.js +133 -0
  102. package/kits/hub-game/code/client/avatar.js +288 -0
  103. package/kits/hub-game/code/client/cabinets.js +90 -0
  104. package/kits/hub-game/code/client/chat.js +135 -0
  105. package/kits/hub-game/code/client/chrome.js +1001 -0
  106. package/kits/hub-game/code/client/doorFrame.js +15 -0
  107. package/kits/hub-game/code/client/firstJoin.js +14 -0
  108. package/kits/hub-game/code/client/grab.js +241 -0
  109. package/kits/hub-game/code/client/hookLayer.js +230 -0
  110. package/kits/hub-game/code/client/idle.js +326 -0
  111. package/kits/hub-game/code/client/keys.js +48 -0
  112. package/kits/hub-game/code/client/pack.js +232 -0
  113. package/kits/hub-game/code/client/packFormat.js +397 -0
  114. package/kits/hub-game/code/client/say.js +127 -0
  115. package/kits/hub-game/code/client/sha256.js +80 -0
  116. package/kits/hub-game/code/client/sound.js +147 -0
  117. package/kits/hub-game/code/client/state.js +131 -0
  118. package/kits/hub-game/code/client/talk.js +259 -0
  119. package/kits/hub-game/code/client/together.js +365 -0
  120. package/kits/hub-game/code/client/wear.js +149 -0
  121. package/kits/hub-game/code/server/actors.js +627 -0
  122. package/kits/hub-game/code/server/blocks.js +103 -0
  123. package/kits/hub-game/code/server/cabinets.js +309 -0
  124. package/kits/hub-game/code/server/game.js +137 -0
  125. package/kits/hub-game/code/server/grab.js +247 -0
  126. package/kits/hub-game/code/server/history.js +96 -0
  127. package/kits/hub-game/code/server/hub.js +1904 -0
  128. package/kits/hub-game/code/server/idle.js +412 -0
  129. package/kits/hub-game/code/server/index.js +64 -0
  130. package/kits/hub-game/code/server/labels.js +59 -0
  131. package/kits/hub-game/code/server/manifest.js +527 -0
  132. package/kits/hub-game/code/server/npcs.js +745 -0
  133. package/kits/hub-game/code/server/party.js +381 -0
  134. package/kits/hub-game/code/server/place.js +43 -0
  135. package/kits/hub-game/code/server/say.js +83 -0
  136. package/kits/hub-game/code/server/wear.js +142 -0
  137. package/kits/hub-game/code/systems/hub.js +2230 -0
  138. package/kits/hub-game/docs/content-pack.md +151 -0
  139. package/kits/hub-game/docs/contract.md +1139 -0
  140. package/kits/hub-game/docs/style.md +137 -0
  141. package/kits/hub-game/drawings/blocky/castle-eye.sprite +58 -0
  142. package/kits/hub-game/drawings/blocky/dash.sprite +59 -0
  143. package/kits/hub-game/drawings/blocky/pom.sprite +59 -0
  144. package/kits/hub-game/drawings/blocky/tabby.sprite +59 -0
  145. package/kits/hub-game/drawings/pixel/castle-arm.sprite +13 -0
  146. package/kits/hub-game/drawings/pixel/castle-body.sprite +23 -0
  147. package/kits/hub-game/drawings/pixel/castle-leg.sprite +12 -0
  148. package/kits/hub-game/drawings/pixel/kai-arm.sprite +14 -0
  149. package/kits/hub-game/drawings/pixel/kai-head.sprite +24 -0
  150. package/kits/hub-game/drawings/pixel/kai-leg.sprite +15 -0
  151. package/kits/hub-game/drawings/pixel/kai-torso.sprite +18 -0
  152. package/kits/hub-game/drawings/pixel/mimi-arm.sprite +13 -0
  153. package/kits/hub-game/drawings/pixel/mimi-head.sprite +23 -0
  154. package/kits/hub-game/drawings/pixel/mimi-leg.sprite +15 -0
  155. package/kits/hub-game/drawings/pixel/mimi-torso.sprite +18 -0
  156. package/kits/hub-game/drawings/pixel/nox-arm.sprite +13 -0
  157. package/kits/hub-game/drawings/pixel/nox-head.sprite +21 -0
  158. package/kits/hub-game/drawings/pixel/nox-leg.sprite +14 -0
  159. package/kits/hub-game/drawings/pixel/nox-torso.sprite +18 -0
  160. package/kits/hub-game/eslint.config.js +20 -0
  161. package/kits/hub-game/fonts.generated.js +9 -0
  162. package/kits/hub-game/index.html +22 -0
  163. package/kits/hub-game/main.jsx +6 -0
  164. package/kits/hub-game/models/avatar-0.pxmodel +21 -0
  165. package/kits/hub-game/models/avatar-1.pxmodel +24 -0
  166. package/kits/hub-game/models/avatar-2.pxmodel +27 -0
  167. package/kits/hub-game/models/avatar-3.pxmodel +22 -0
  168. package/kits/hub-game/models/bean/avatar-0.pxmodel +19 -0
  169. package/kits/hub-game/models/bean/avatar-1.pxmodel +24 -0
  170. package/kits/hub-game/models/bean/avatar-2.pxmodel +22 -0
  171. package/kits/hub-game/models/bean/avatar-3.pxmodel +24 -0
  172. package/kits/hub-game/models/blocky/avatar-0.pxmodel +21 -0
  173. package/kits/hub-game/models/blocky/avatar-1.pxmodel +30 -0
  174. package/kits/hub-game/models/blocky/avatar-2.pxmodel +28 -0
  175. package/kits/hub-game/models/blocky/avatar-3.pxmodel +27 -0
  176. package/kits/hub-game/models/pixel/avatar-0.pxmodel +24 -0
  177. package/kits/hub-game/models/pixel/avatar-1.pxmodel +16 -0
  178. package/kits/hub-game/models/pixel/avatar-2.pxmodel +19 -0
  179. package/kits/hub-game/models/pixel/avatar-3.pxmodel +23 -0
  180. package/kits/hub-game/package-lock.json +365 -0
  181. package/kits/hub-game/package.json +32 -0
  182. package/kits/hub-game/scenes/main.scene +318 -0
  183. package/kits/hub-game/scripts/check.mjs +339 -0
  184. package/kits/hub-game/scripts/fixtures/sdk-stub.mjs +3 -0
  185. package/kits/hub-game/scripts/gen-avatars-bean.mjs +748 -0
  186. package/kits/hub-game/scripts/gen-avatars-blocky.mjs +607 -0
  187. package/kits/hub-game/scripts/gen-avatars-pixel.mjs +771 -0
  188. package/kits/hub-game/scripts/gen-avatars.mjs +621 -0
  189. package/kits/hub-game/scripts/pack.mjs +192 -0
  190. package/kits/hub-game/scripts/test-actors.mjs +666 -0
  191. package/kits/hub-game/scripts/test-attention.mjs +103 -0
  192. package/kits/hub-game/scripts/test-avatar.mjs +472 -0
  193. package/kits/hub-game/scripts/test-ban-join.mjs +194 -0
  194. package/kits/hub-game/scripts/test-blocks.mjs +351 -0
  195. package/kits/hub-game/scripts/test-chat.mjs +98 -0
  196. package/kits/hub-game/scripts/test-classic.mjs +590 -0
  197. package/kits/hub-game/scripts/test-door-jump.mjs +131 -0
  198. package/kits/hub-game/scripts/test-door.mjs +56 -0
  199. package/kits/hub-game/scripts/test-grab.mjs +331 -0
  200. package/kits/hub-game/scripts/test-hub-ops.mjs +835 -0
  201. package/kits/hub-game/scripts/test-hub-trip.mjs +1310 -0
  202. package/kits/hub-game/scripts/test-idle.mjs +518 -0
  203. package/kits/hub-game/scripts/test-interest.mjs +413 -0
  204. package/kits/hub-game/scripts/test-keys.mjs +50 -0
  205. package/kits/hub-game/scripts/test-manifest.mjs +224 -0
  206. package/kits/hub-game/scripts/test-no-forms.mjs +16 -0
  207. package/kits/hub-game/scripts/test-npcs.mjs +714 -0
  208. package/kits/hub-game/scripts/test-pack.mjs +424 -0
  209. package/kits/hub-game/scripts/test-party.mjs +286 -0
  210. package/kits/hub-game/scripts/test-say.mjs +149 -0
  211. package/kits/hub-game/scripts/test-together.mjs +183 -0
  212. package/kits/hub-game/theme.style +3 -0
  213. package/kits/multiplayer-3d/castle.json +5 -5
  214. package/kits/multiplayer-3d/code/client/avatars.js +101 -1
  215. package/kits/multiplayer-3d/code/server/players.js +4 -1
  216. package/kits/multiplayer-3d/code/server/sceneBodies.js +27 -6
  217. package/kits/multiplayer-3d/code/server/world.js +20 -7
  218. package/kits/multiplayer-3d/code/systems/multiplayer.js +222 -11
  219. package/kits/physics-2d/castle.json +2 -2
  220. package/kits/physics-2d/engine/art.js +13 -0
  221. package/kits/physics-2d/engine/assets.js +4 -2
  222. package/kits/physics-2d/engine/scene.js +25 -5
  223. package/kits/physics-3d/CLAUDE.md +6 -1
  224. package/kits/physics-3d/castle.json +3 -3
  225. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +32 -4
  226. package/kits/physics-3d/engine3d/artobjects.js +2 -2
  227. package/kits/physics-3d/engine3d/materials.js +29 -1
  228. package/kits/physics-3d/engine3d/world3d.js +65 -1
  229. package/kits/physics-3d/systems/physics3d.js +5 -2
  230. package/kits/real-time/castle.json +2 -2
  231. package/kits/real-time/code/client/connection.js +77 -7
  232. package/kits/real-time/code/client/gameHooks.js +63 -3
  233. package/kits/real-time/code/client/messages.js +7 -0
  234. package/kits/real-time/code/server/gameHooks.js +24 -0
  235. package/kits/real-time/code/server/session.js +390 -22
  236. 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,21 +273,111 @@ 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,
273
280
  voice: { enabled: serverConfig.voiceEnabled },
274
281
  ...(serverConfig.destinations ? { destinations: serverConfig.destinations } : {}),
275
- });
282
+ ...(serverConfig.worldNotifications
283
+ ? { worldNotifications: serverConfig.worldNotifications }
284
+ : {}),
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);
276
289
  // The server hashes what it actually stored. A mismatch means the bytes that
277
290
  // will run in sessions are not the bytes we bundled.
278
291
  if (saved && saved.sha256 !== bundle.sha256) {
279
292
  throw new Error(`Published server bundle does not match what was built ` +
280
293
  `(server ${saved.sha256}, local ${bundle.sha256}). The deck was not updated safely.`);
281
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}).`);
282
301
  writePublishedServerBundleState(projectDir, { deckId, sha256: bundle.sha256 });
283
302
  console.log(`Server bundle published${saved ? ` as ${saved.version}` : ''} (sha256 ${bundle.sha256}).`);
284
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
+ }
285
381
  async function uploadLocalCover(projectDir) {
286
382
  try {
287
383
  const selected = await selectSaveCover(projectDir, { onProgress: (message) => console.log(message) });
@@ -368,8 +464,13 @@ export async function saveDeck(dir, opts = {}) {
368
464
  }
369
465
  }
370
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);
371
471
  const castleJson = readCastleJson(projectDir);
372
472
  const existingDeckId = typeof castleJson?.deckId === 'string' && castleJson.deckId ? castleJson.deckId : null;
473
+ const experiments = checkedExperiments(castleJson);
373
474
  // A deck without an id is new: the source commit sends no precondition, as before.
374
475
  let expectedS3Key;
375
476
  let markerVia = 'save-deck';
@@ -381,13 +482,47 @@ async function saveDeckAfterValidation(dir, opts, projectDir, visibility) {
381
482
  }
382
483
  expectedS3Key = precondition.expectedS3Key;
383
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
+ }
384
506
  if (precondition.adopt) {
385
507
  console.error('Note: this folder has no record of which saved copy it came from; adopting it as the ' +
386
508
  "deck's saved copy. Later saves are refused if someone else saves this deck in between.");
387
509
  }
388
510
  }
389
511
  console.log('Bundling...');
390
- 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)}).`);
391
526
  const sizeKB = bundle.length / 1024;
392
527
  console.log(`Bundle size: ${sizeKB.toFixed(1)}KB`);
393
528
  if (sizeKB > 1024) {
@@ -488,13 +623,16 @@ async function saveDeckAfterValidation(dir, opts, projectDir, visibility) {
488
623
  else {
489
624
  console.log(`Saved "${title}" to Castle.`);
490
625
  }
626
+ const clearingExperiments = experiments ? null : startClearingExperiments(result.deckId);
627
+ if (experiments)
628
+ await publishExperiments(result.deckId, title, experiments);
491
629
  // The deck went live above, so anything failing here leaves it skewed: the
492
630
  // published client runs against whatever server was last deployed. Say that
493
631
  // in the thrown message -- it is the only line the cloud editor gets back
494
632
  // (it forwards stderr), and "not valid JSON" reads as a glitch, not as a
495
633
  // deck that is now half-published.
496
634
  try {
497
- await traceSaveStage('server_publish', () => publishServerBundle(projectDir, result.deckId));
635
+ await traceSaveStage('server_publish', () => publishServerBundle(projectDir, result.deckId, pack));
498
636
  }
499
637
  catch (e) {
500
638
  const reason = e instanceof Error ? e.message : String(e);
@@ -515,6 +653,7 @@ async function saveDeckAfterValidation(dir, opts, projectDir, visibility) {
515
653
  // The save itself succeeded; a missing marker only means the next save adopts again.
516
654
  console.error(`Could not record the saved version: ${e instanceof Error ? e.message : String(e)}`);
517
655
  }
656
+ await clearingExperiments?.settle();
518
657
  }
519
658
  catch (e) {
520
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,15 @@ 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';
29
32
  import { serveOracleStream } from './deckAgentRoute.js';
30
33
  import { ServeSecurity } from './serveSecurity.js';
31
34
  import { atomicWriteFileSync } from './atomicFile.js';
@@ -34,7 +37,7 @@ import { createAssetCompression } from './assetCompression.js';
34
37
  import { playCoverHeadInjection } from './playCoverGate.js';
35
38
  import { isPlayPageUrl, playPageHeadInjection } from './playPagePolicy.js';
36
39
  import { resolveServerConfig } from './castleJson.js';
37
- import { startDevSessionServer, } from './devSessionServer.js';
40
+ import { startDevSessionServer, devSessionIdFor, } from './devSessionServer.js';
38
41
  // The log is a tail, not an archive: append, and once it passes the cap drop
39
42
  // whole lines off the front until it is back under.
40
43
  const LOG_MAX_BYTES = 2 * 1024 * 1024;
@@ -623,7 +626,8 @@ window.__castleShellOrigin=(function(){
623
626
  const page = injectIntoHead(html, injected);
624
627
  return cover ? placeCoverBridge(page, cover) : page;
625
628
  }
626
- function castlePlugin(security, ideServer, agentServer, scriptErrors, configuredHost) {
629
+ // Exported for the tests.
630
+ export function castlePlugin(security, ideServer, agentServer, scriptErrors, projectDir, configuredHost) {
627
631
  return {
628
632
  name: 'castle-dev',
629
633
  transformIndexHtml: {
@@ -727,12 +731,22 @@ function castlePlugin(security, ideServer, agentServer, scriptErrors, configured
727
731
  if (reqPath === '/')
728
732
  req.url = `/index.html${req.url?.includes('?') ? req.url.slice(req.url.indexOf('?')) : ''}`;
729
733
  const allowedFilesRequest = isAllowedContentFilesRequest(contentRole, req.method, reqPath);
734
+ // Doors to other local decks (contentPack.ts): read-only, and limited to
735
+ // the decks this deck's castle.json lists. Either content role: a
736
+ // phone plays from the play URL.
737
+ if (reqPath.startsWith('/__castle/content-pack/')) {
738
+ void handleContentPackRequest(projectDir, req, res, reqPath);
739
+ return;
740
+ }
730
741
  const allowedVendor = reqPath.startsWith('/__castle/vendor/');
731
742
  const allowedFavicon = FAVICON_FILES.some((name) => reqPath === `/${name}`);
732
743
  if (reqPath.startsWith('/__castle/') && !allowedFilesRequest && !allowedVendor) {
733
744
  res.writeHead(403).end('content capability does not allow this endpoint');
734
745
  return;
735
746
  }
747
+ // Only a request that got this far may force an A/B arm
748
+ // (devExperiments.ts): one refused above changes nothing.
749
+ devExperimentsFor(projectDir).noteUrl(req.url);
736
750
  if ((allowedFilesRequest || allowedVendor || allowedFavicon) &&
737
751
  ideServer.handleHttpRequest(req, res, reqPath))
738
752
  return;
@@ -749,6 +763,7 @@ function castlePlugin(security, ideServer, agentServer, scriptErrors, configured
749
763
  security.rejectHttpAuth(res);
750
764
  return;
751
765
  }
766
+ devExperimentsFor(projectDir).noteUrl(req.url);
752
767
  // The split-view shell (`/`) + its static assets are served outside
753
768
  // Vite's module pipeline; the deck itself loads in the iframe via
754
769
  // `/index.html`, which Vite still serves normally.
@@ -783,19 +798,63 @@ async function devMe() {
783
798
  }
784
799
  return cachedDevMe;
785
800
  }
786
- async function devHostContext(projectDir) {
801
+ // A/B experiments per served deck (devExperiments.ts): the arms forced through
802
+ // `?experiment.<name>=` live here, for the serve's lifetime.
803
+ const devExperiments = new Map();
804
+ // Exported for the tests.
805
+ export function devExperimentsFor(projectDir) {
806
+ let experiments = devExperiments.get(projectDir);
807
+ if (!experiments) {
808
+ experiments = new DevExperiments(projectDir, (text) => console.warn(`[experiments] ${text}`));
809
+ devExperiments.set(projectDir, experiments);
810
+ }
811
+ return experiments;
812
+ }
813
+ // The SDK prefixes every request id with a value drawn once per page load
814
+ // (transport.ts), which is what makes a page load nameable here.
815
+ function commandPageLoad(requestId) {
816
+ return /^(csdk_[a-z0-9]+)_\d+$/.exec(requestId)?.[1] ?? null;
817
+ }
818
+ async function devHostContext(projectDir, requestId) {
787
819
  const ctx = readDeckContext(projectDir);
788
820
  const me = await devMe();
821
+ const userId = config.getUserId() ?? me.userId;
789
822
  return {
790
823
  deckId: ctx.deckId ?? null,
791
824
  sessionId: null,
792
- userId: config.getUserId() ?? me.userId,
825
+ userId,
793
826
  username: me.username,
827
+ // Assigned under the id local multiplayer gives this player, and held for
828
+ // the page load, so the page and the deck's server read the same arm.
829
+ experimentVariants: devExperimentsFor(projectDir).variantsForPage(commandPageLoad(requestId), userId ?? DEV_ANONYMOUS_USER_ID, ctx.deckId ?? null),
794
830
  };
795
831
  }
796
832
  // Agent.chat's route to deck-agent: the CLI's login token locally, the sandbox
797
833
  // host's llm-proxy inside a cloud sandbox (deckAgentRoute.ts).
798
834
  const oracleStream = serveOracleStream(() => config.getToken());
835
+ // Hub doors per connected page (devHub.ts), and the pads gathering across all
836
+ // of them. The local multiplayer URL depends on which origin the page came
837
+ // through, so each command hands its visit the current one.
838
+ // Play panels share the shell's socket, so a visit is per socket and panel.
839
+ const hubVisits = new WeakMap();
840
+ const devPadGroups = new Map();
841
+ function devHubVisit(ws, playSessionSlot, projectDir, multiplayer, multiplayerUrl) {
842
+ const panels = hubVisits.get(ws) ?? new Map();
843
+ hubVisits.set(ws, panels);
844
+ let entry = panels.get(playSessionSlot ?? '');
845
+ if (!entry) {
846
+ const mp = { url: multiplayerUrl };
847
+ const visit = new DevHubVisit(() => readDevHubDoors(projectDir, (text) => console.warn(`[hub] ${text}`)), {
848
+ url: () => (multiplayer ? mp.url : null),
849
+ mintNonce: (ctx, key) => multiplayer.mintNonce(devMultiplayerIdentity(ctx), key, ctx.experimentVariants ?? undefined),
850
+ sessionIdFor: (key) => devSessionIdFor(key),
851
+ }, devPadGroups);
852
+ entry = { visit, mp };
853
+ panels.set(playSessionSlot ?? '', entry);
854
+ }
855
+ entry.mp.url = multiplayerUrl;
856
+ return entry.visit;
857
+ }
799
858
  // Commands in flight on each socket, so a deck's cancel or a closed socket can
800
859
  // abort a streaming one.
801
860
  const commandAborts = new WeakMap();
@@ -815,7 +874,7 @@ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multi
815
874
  commandAborts.set(ws, aborts);
816
875
  const controller = new AbortController();
817
876
  aborts.set(requestId, controller);
818
- const ctx = await devHostContext(projectDir);
877
+ const ctx = await devHostContext(projectDir, requestId);
819
878
  const onStream = (event) => {
820
879
  if (ws.readyState === WebSocket.OPEN) {
821
880
  ws.send(JSON.stringify({ type: 'castle_command_stream', castleSdk: 1, requestId, stream: event }));
@@ -830,7 +889,8 @@ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multi
830
889
  graphqlFetch: castleGraphql,
831
890
  oracleStream,
832
891
  showLeaderboard: (payload) => broadcast({ type: 'castle_leaderboard_show', payload }),
833
- getMultiplayerSession: () => {
892
+ hub: devHubVisit(ws, playSessionSlot, projectDir, multiplayer, multiplayerUrl),
893
+ getMultiplayerSession: (request) => {
834
894
  if (!multiplayer || !multiplayerUrl) {
835
895
  return Promise.resolve({
836
896
  status: 'unavailable',
@@ -840,11 +900,13 @@ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multi
840
900
  soloReason: null,
841
901
  });
842
902
  }
903
+ // Each named key runs its own local session; public and party share 'dev'.
904
+ const key = request.mode === 'named' ? (request.key ?? null) : null;
843
905
  return Promise.resolve({
844
906
  status: 'ok',
845
907
  url: multiplayerUrl,
846
- nonce: multiplayer.mintNonce(devMultiplayerIdentity(ctx)),
847
- sessionId: multiplayer.sessionId,
908
+ nonce: multiplayer.mintNonce(devMultiplayerIdentity(ctx), key, ctx.experimentVariants ?? undefined),
909
+ sessionId: multiplayer.sessionIdFor(key),
848
910
  soloReason: null,
849
911
  ...(playSessionSlot ? { devReconnectScope: playSessionSlot } : {}),
850
912
  });
@@ -855,13 +917,18 @@ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multi
855
917
  ws.send(JSON.stringify({ type: 'castle_command_response', castleSdk: 1, requestId, ...result }));
856
918
  }
857
919
  }
920
+ const DEV_ANONYMOUS_USER_ID = 'dev-user';
858
921
  function devMultiplayerIdentity(ctx) {
859
922
  return {
860
- userId: ctx.userId ?? 'dev-user',
923
+ userId: ctx.userId ?? DEV_ANONYMOUS_USER_ID,
861
924
  username: ctx.username ?? 'Developer',
862
925
  isAnonymous: ctx.userId === null,
863
926
  };
864
927
  }
928
+ function isLoopbackRequest(req) {
929
+ const address = req.socket.remoteAddress;
930
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1';
931
+ }
865
932
  function devMultiplayerUrl(req) {
866
933
  const base = typeof req.headers.origin === 'string' ? req.headers.origin : null;
867
934
  if (!base)
@@ -1074,6 +1141,12 @@ export async function serve(dir, options = {}) {
1074
1141
  let importsChangedAtStartup = false;
1075
1142
  if (!existingServe(projectDir)) {
1076
1143
  const importsBeforeUpdate = importPinsFingerprint(projectDir);
1144
+ // A builtin kit that changed under the same CLI version replaces the deck's
1145
+ // copy here too, where nothing is running yet.
1146
+ const refreshed = await refreshStaleBuiltinImports(projectDir).catch((e) => {
1147
+ console.warn(`builtin kits: left as they are -- ${e instanceof Error ? e.message : String(e)}`);
1148
+ return [];
1149
+ });
1077
1150
  // A failure to check must never keep the deck from opening.
1078
1151
  const updated = await autoUpdateImports(projectDir).catch((e) => {
1079
1152
  console.warn(`auto-update: skipped -- ${e instanceof Error ? e.message : String(e)}`);
@@ -1082,7 +1155,9 @@ export async function serve(dir, options = {}) {
1082
1155
  // Comparing pins as well as the returned list preserves the invalidation
1083
1156
  // if a later step throws after one or more imported trees were replaced.
1084
1157
  importsChangedAtStartup =
1085
- updated.length > 0 || importsBeforeUpdate !== importPinsFingerprint(projectDir);
1158
+ refreshed.length > 0 ||
1159
+ updated.length > 0 ||
1160
+ importsBeforeUpdate !== importPinsFingerprint(projectDir);
1086
1161
  }
1087
1162
  // Start pulling the headless browser now, in the background.
1088
1163
  //
@@ -1263,7 +1338,7 @@ export async function serve(dir, options = {}) {
1263
1338
  // HMR is off (below), but Vite still injects and imports `/@vite/client`.
1264
1339
  // Serve a socket-free stub of it so no page logs a failed HMR connection.
1265
1340
  viteClientStubPlugin(),
1266
- castlePlugin(security, ideServer, agentServer, scriptErrors, options.host),
1341
+ castlePlugin(security, ideServer, agentServer, scriptErrors, projectDir, options.host),
1267
1342
  forksOverlayPlugin(),
1268
1343
  importsAliasPlugin(),
1269
1344
  sdkAliasPlugin(),
@@ -1590,7 +1665,13 @@ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security
1590
1665
  };
1591
1666
  wss.on('connection', (ws, req) => {
1592
1667
  clients.add(ws);
1593
- const multiplayerUrl = devMultiplayerUrl(req);
1668
+ // A loopback client with no Origin (a CLI or a script, which is all the
1669
+ // root path admits) has no content origin to proxy through, so it joins
1670
+ // the dev session server directly: how script-driven test players get in.
1671
+ const multiplayerUrl = devMultiplayerUrl(req) ??
1672
+ (multiplayer && !req.headers.origin && isLoopbackRequest(req)
1673
+ ? `ws://127.0.0.1:${multiplayer.port}/__castle/mp`
1674
+ : null);
1594
1675
  const legacyRole = legacyRoles.get(ws) ?? null;
1595
1676
  ws.on('message', (raw) => {
1596
1677
  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: {
@@ -0,0 +1,42 @@
1
+ import * as api from './api.js';
2
+ import type { ServerSourceVersion } from './webSourceSync.js';
3
+ export declare const LINEAGE_BUDGET_MS = 9000;
4
+ /** path (posix, relative) -> sha256 hex */
5
+ export type SourceManifest = Map<string, string>;
6
+ /** Whether a source path counts toward a match: skips noise, dotfiles at the top, `._*`. */
7
+ export declare function countsTowardMatch(rel: string): boolean;
8
+ /**
9
+ * The folder's regular files as the archive would carry them, hashed in chunks; null past the
10
+ * size caps or once `expired` says the time is up.
11
+ */
12
+ export declare function folderManifest(dir: string, expired?: () => boolean): SourceManifest | null;
13
+ /**
14
+ * The regular files of a gzipped tar, hashed as they stream (ustar, pax `path`, GNU long
15
+ * names). Links and everything else are skipped; nothing is written to disk.
16
+ */
17
+ export declare function archiveManifest(gz: Buffer, expired?: () => boolean): Promise<SourceManifest>;
18
+ /** How many files the two copies hold identically. */
19
+ export declare function matchScore(folder: SourceManifest, saved: SourceManifest): number;
20
+ export type LineageOutcome = 'current' | 'older' | 'skipped';
21
+ export interface Lineage {
22
+ outcome: LineageOutcome;
23
+ /** The version to record: the current one unless an older one matches strictly better. */
24
+ version: ServerSourceVersion;
25
+ /** Saved versions compared (the current one included). */
26
+ examined: number;
27
+ /** Why the history was not compared, or why the comparison stopped early. */
28
+ reason?: string;
29
+ }
30
+ export interface LineageDeps {
31
+ listVersions?: (deckId: string, timeoutMs: number) => Promise<api.SavedSourceVersion[]>;
32
+ fetchArchive?: (url: string, timeoutMs: number) => Promise<Buffer>;
33
+ nowMs?: () => number;
34
+ /** When the comparison must be settled by (epoch ms); defaults to now + LINEAGE_BUDGET_MS. */
35
+ deadlineMs?: number;
36
+ }
37
+ /**
38
+ * The saved version this folder descends from. Never throws: any failure (an older Ghost,
39
+ * a fetch error, the budget) settles on the current version, which is what adopt recorded
40
+ * before this existed.
41
+ */
42
+ export declare function findLineage(dir: string, deckId: string, server: ServerSourceVersion, deps?: LineageDeps): Promise<Lineage>;