castle-web-cli 0.4.157 → 0.4.158

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 (243) hide show
  1. package/dist/agent-failures.d.ts +1 -0
  2. package/dist/agent-failures.js +6 -4
  3. package/dist/agent-prompts.js +4 -0
  4. package/dist/agent.d.ts +11 -0
  5. package/dist/agent.js +175 -15
  6. package/dist/bundle.js +8 -2
  7. package/dist/castle-host/host.js +4 -2
  8. package/dist/castleJson.js +6 -1
  9. package/dist/check.d.ts +1 -0
  10. package/dist/check.js +25 -0
  11. package/dist/devSessionServer.js +31 -7
  12. package/dist/imports.js +1 -19
  13. package/dist/index.js +15 -1
  14. package/dist/init.d.ts +2 -2
  15. package/dist/init.js +78 -42
  16. package/dist/mcpPlaytest.d.ts +1 -0
  17. package/dist/mcpPlaytest.js +182 -0
  18. package/dist/metering.d.ts +24 -0
  19. package/dist/metering.js +87 -0
  20. package/dist/sdkResolve.d.ts +3 -0
  21. package/dist/sdkResolve.js +55 -0
  22. package/dist/serve.js +50 -4
  23. package/dist/serverBundle.js +8 -3
  24. package/dist/shell/assets/{index-DsDkYFvP.js → index-BuSYLy-C.js} +64 -64
  25. package/dist/shell/assets/{index-DwezawBs.css → index-DfZmu3XC.css} +1 -1
  26. package/dist/shell/index.html +2 -2
  27. package/dist/vitePlugins.d.ts +1 -0
  28. package/dist/vitePlugins.js +20 -0
  29. package/kits/base/CLAUDE.md +196 -0
  30. package/kits/{blank → base}/castle.json +5 -2
  31. package/kits/base/editorHost.js +172 -0
  32. package/kits/{blank → base}/node_modules/.package-lock.json +3 -2
  33. package/kits/{blank → base}/package-lock.json +7 -4
  34. package/kits/{blank → base}/package.json +4 -2
  35. package/kits/base/sdk/README.md +569 -0
  36. package/kits/base/sdk/castle.d.ts +27 -0
  37. package/kits/base/sdk/castle.js +16 -0
  38. package/kits/base/sdk/commands.d.ts +181 -0
  39. package/kits/base/sdk/commands.js +16 -0
  40. package/kits/base/sdk/context.d.ts +17 -0
  41. package/kits/base/sdk/context.js +15 -0
  42. package/kits/base/sdk/errors.d.ts +22 -0
  43. package/kits/base/sdk/errors.js +16 -0
  44. package/kits/base/sdk/files.d.ts +15 -0
  45. package/kits/base/sdk/files.js +52 -0
  46. package/kits/base/sdk/haptics.d.ts +6 -0
  47. package/kits/base/sdk/haptics.js +36 -0
  48. package/kits/base/sdk/leaderboard.d.ts +26 -0
  49. package/kits/base/sdk/leaderboard.js +296 -0
  50. package/kits/base/sdk/lifecycle.d.ts +4 -0
  51. package/kits/base/sdk/lifecycle.js +13 -0
  52. package/kits/base/sdk/multiplayer.d.ts +43 -0
  53. package/kits/base/sdk/multiplayer.js +464 -0
  54. package/kits/base/sdk/multiplayerProtocol.d.ts +51 -0
  55. package/kits/base/sdk/multiplayerProtocol.js +5 -0
  56. package/kits/base/sdk/passes.d.ts +7 -0
  57. package/kits/base/sdk/passes.js +84 -0
  58. package/kits/base/sdk/portal.d.ts +7 -0
  59. package/kits/base/sdk/portal.js +35 -0
  60. package/kits/base/sdk/runtime.d.ts +62 -0
  61. package/kits/base/sdk/runtime.js +970 -0
  62. package/kits/base/sdk/saveQueue.d.ts +27 -0
  63. package/kits/base/sdk/saveQueue.js +205 -0
  64. package/kits/base/sdk/server/platformHandle.d.ts +25 -0
  65. package/kits/base/sdk/server/platformHandle.js +1 -0
  66. package/kits/base/sdk/server/wrapper.d.ts +28 -0
  67. package/kits/base/sdk/server/wrapper.js +109 -0
  68. package/kits/base/sdk/storage.d.ts +16 -0
  69. package/kits/base/sdk/storage.js +323 -0
  70. package/kits/base/sdk/time.d.ts +17 -0
  71. package/kits/base/sdk/time.js +120 -0
  72. package/kits/base/sdk/transport.d.ts +17 -0
  73. package/kits/base/sdk/transport.js +141 -0
  74. package/kits/base/sdk/types.d.ts +3 -0
  75. package/kits/base/sdk/types.js +1 -0
  76. package/kits/base/sdk/user.d.ts +10 -0
  77. package/kits/base/sdk/user.js +45 -0
  78. package/kits/multiplayer-2d/.prettierrc +5 -0
  79. package/kits/multiplayer-2d/CLAUDE.md +129 -0
  80. package/kits/multiplayer-2d/behaviors/Box.jsx +92 -0
  81. package/kits/multiplayer-2d/behaviors/Player.jsx +86 -0
  82. package/kits/multiplayer-2d/blueprints/crate.scene +13 -0
  83. package/kits/multiplayer-2d/blueprints/other-player.scene +13 -0
  84. package/kits/multiplayer-2d/blueprints/player.scene +15 -0
  85. package/kits/multiplayer-2d/blueprints/wall.scene +12 -0
  86. package/kits/multiplayer-2d/castle.json +39 -0
  87. package/kits/multiplayer-2d/code/client/avatars.js +79 -0
  88. package/kits/multiplayer-2d/code/client/poses.js +168 -0
  89. package/kits/multiplayer-2d/code/server/index.js +26 -0
  90. package/kits/multiplayer-2d/code/server/limits.js +99 -0
  91. package/kits/multiplayer-2d/code/server/ownership.js +177 -0
  92. package/kits/multiplayer-2d/code/server/players.js +127 -0
  93. package/kits/multiplayer-2d/code/server/sceneBodies.js +98 -0
  94. package/kits/multiplayer-2d/code/server/world.js +337 -0
  95. package/kits/multiplayer-2d/code/systems/multiplayer.js +424 -0
  96. package/kits/multiplayer-2d/eslint.config.js +21 -0
  97. package/kits/multiplayer-2d/fonts.generated.js +9 -0
  98. package/kits/multiplayer-2d/index.html +25 -0
  99. package/kits/multiplayer-2d/main.jsx +10 -0
  100. package/kits/multiplayer-2d/package-lock.json +351 -0
  101. package/kits/multiplayer-2d/package.json +30 -0
  102. package/kits/multiplayer-2d/scenes/main.scene +20 -0
  103. package/kits/multiplayer-2d/test/two-client-test.mjs +341 -0
  104. package/kits/multiplayer-2d/theme.style +4 -0
  105. package/kits/multiplayer-3d/.prettierrc +5 -0
  106. package/kits/multiplayer-3d/CLAUDE.md +215 -0
  107. package/kits/multiplayer-3d/blueprints/ball.scene +21 -0
  108. package/kits/multiplayer-3d/blueprints/other-player.scene +21 -0
  109. package/kits/multiplayer-3d/castle.json +43 -0
  110. package/kits/multiplayer-3d/code/client/avatars.js +136 -0
  111. package/kits/multiplayer-3d/code/client/nameTags.js +101 -0
  112. package/kits/multiplayer-3d/code/client/poses.js +220 -0
  113. package/kits/multiplayer-3d/code/server/index.js +23 -0
  114. package/kits/multiplayer-3d/code/server/limits.js +107 -0
  115. package/kits/multiplayer-3d/code/server/ownership.js +157 -0
  116. package/kits/multiplayer-3d/code/server/players.js +114 -0
  117. package/kits/multiplayer-3d/code/server/sceneBodies.js +88 -0
  118. package/kits/multiplayer-3d/code/server/world.js +306 -0
  119. package/kits/multiplayer-3d/code/systems/multiplayer.js +427 -0
  120. package/kits/multiplayer-3d/eslint.config.js +20 -0
  121. package/kits/multiplayer-3d/fonts.generated.js +9 -0
  122. package/kits/multiplayer-3d/index.html +22 -0
  123. package/kits/multiplayer-3d/main.jsx +9 -0
  124. package/kits/multiplayer-3d/package-lock.json +368 -0
  125. package/kits/multiplayer-3d/package.json +32 -0
  126. package/kits/multiplayer-3d/scenes/main.scene +409 -0
  127. package/kits/multiplayer-3d/theme.style +3 -0
  128. package/kits/physics-2d/CLAUDE.md +6 -0
  129. package/kits/physics-2d/castle.json +7 -1
  130. package/kits/physics-2d/editors/behaviorRegistry.js +5 -0
  131. package/kits/physics-2d/editors/editorRegistry.jsx +3 -1
  132. package/kits/physics-2d/engine/files.js +9 -5
  133. package/kits/physics-2d/engine/systemRegistry.js +2 -0
  134. package/kits/physics-2d/engine/ui.module.css +11 -0
  135. package/kits/physics-2d/package-lock.json +8 -2
  136. package/kits/physics-2d/package.json +2 -2
  137. package/kits/physics-3d/CLAUDE.md +4 -4
  138. package/kits/physics-3d/behaviors/Shape.jsx +1 -1
  139. package/kits/physics-3d/blueprints/crate.scene +1 -1
  140. package/kits/physics-3d/blueprints/door.scene +4 -4
  141. package/kits/physics-3d/blueprints/pillar.scene +1 -1
  142. package/kits/physics-3d/blueprints/platform.scene +1 -1
  143. package/kits/physics-3d/blueprints/statue.scene +1 -1
  144. package/kits/physics-3d/blueprints/wall.scene +1 -1
  145. package/kits/physics-3d/castle.json +8 -11
  146. package/kits/physics-3d/docs/pxmodel-format.md +1 -1
  147. package/kits/physics-3d/engine3d/materials.js +3 -3
  148. package/kits/physics-3d/engine3d/modelFiles.js +4 -2
  149. package/kits/physics-3d/engine3d/world3d.js +1 -1
  150. package/kits/physics-3d/fonts.generated.js +9 -0
  151. package/kits/physics-3d/main.jsx +1 -1
  152. package/kits/physics-3d/package-lock.json +85 -2
  153. package/kits/physics-3d/package.json +6 -2
  154. package/kits/physics-3d/scenes/main.scene +1 -1
  155. package/kits/physics-3d/scenes/model-lab.scene +1 -1
  156. package/kits/real-time/.prettierrc +5 -0
  157. package/kits/real-time/CLAUDE.md +60 -0
  158. package/kits/real-time/castle.json +19 -0
  159. package/kits/real-time/code/client/clock.js +68 -0
  160. package/kits/real-time/code/client/connection.js +134 -0
  161. package/kits/real-time/code/client/gameHooks.js +50 -0
  162. package/kits/real-time/code/client/interpolate.js +82 -0
  163. package/kits/real-time/code/client/messages.js +55 -0
  164. package/kits/real-time/code/client/ownership.js +94 -0
  165. package/kits/real-time/code/client/smooth.js +54 -0
  166. package/kits/real-time/code/server/blockDelta.js +48 -0
  167. package/kits/real-time/code/server/gameHooks.js +47 -0
  168. package/kits/real-time/code/server/limits.js +35 -0
  169. package/kits/real-time/code/server/session.js +251 -0
  170. package/kits/real-time/eslint.config.js +22 -0
  171. package/kits/real-time/index.html +45 -0
  172. package/kits/real-time/package.json +14 -0
  173. package/kits/{tabletop → turn-based}/CLAUDE.md +42 -49
  174. package/kits/turn-based/blueprints/board.scene +15 -0
  175. package/kits/turn-based/blueprints/square.scene +25 -0
  176. package/kits/turn-based/castle.json +37 -0
  177. package/kits/turn-based/code/behaviors/Board.jsx +169 -0
  178. package/kits/turn-based/code/behaviors/Square.jsx +26 -0
  179. package/kits/turn-based/code/server/index.js +152 -0
  180. package/kits/turn-based/drawings/square.sprite +25 -0
  181. package/kits/turn-based/eslint.config.js +12 -0
  182. package/kits/turn-based/fonts.generated.js +9 -0
  183. package/kits/{tabletop → turn-based}/index.html +5 -3
  184. package/kits/{tabletop → turn-based}/main.jsx +2 -2
  185. package/kits/{tabletop → turn-based}/package-lock.json +17 -4
  186. package/kits/{tabletop → turn-based}/package.json +5 -2
  187. package/kits/turn-based/room.js +289 -0
  188. package/kits/turn-based/scenes/main.scene +227 -0
  189. package/kits/{tabletop → turn-based}/testing.js +131 -99
  190. package/kits/turn-based/theme.style +3 -0
  191. package/package.json +1 -1
  192. package/kits/blank/CLAUDE.md +0 -198
  193. package/kits/tabletop/castle.json +0 -34
  194. package/kits/tabletop/room.js +0 -269
  195. /package/kits/{blank → base}/index.html +0 -0
  196. /package/kits/{blank → base}/node_modules/castle-web-fonts/README.md +0 -0
  197. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/catalog.d.ts +0 -0
  198. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/catalog.js +0 -0
  199. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/face.d.ts +0 -0
  200. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/face.js +0 -0
  201. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Bore.d.ts +0 -0
  202. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Bore.js +0 -0
  203. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/CourierPrime.d.ts +0 -0
  204. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/CourierPrime.js +0 -0
  205. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/DMSans.d.ts +0 -0
  206. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/DMSans.js +0 -0
  207. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Glacier.d.ts +0 -0
  208. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Glacier.js +0 -0
  209. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.d.ts +0 -0
  210. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.js +0 -0
  211. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Piazzolla.d.ts +0 -0
  212. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Piazzolla.js +0 -0
  213. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Synco.d.ts +0 -0
  214. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Synco.js +0 -0
  215. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Tektur.d.ts +0 -0
  216. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Tektur.js +0 -0
  217. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/YatraOne.d.ts +0 -0
  218. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/YatraOne.js +0 -0
  219. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/index.d.ts +0 -0
  220. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/index.js +0 -0
  221. /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/CC-BY-ND-4.0.txt +0 -0
  222. /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/FONTS.md +0 -0
  223. /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/OFL-1.1.txt +0 -0
  224. /package/kits/{blank → base}/node_modules/castle-web-fonts/package.json +0 -0
  225. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Bore.woff2 +0 -0
  226. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/CourierPrime.woff2 +0 -0
  227. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/DMSans.woff2 +0 -0
  228. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Glacier.woff2 +0 -0
  229. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/HelicoCentrica.woff2 +0 -0
  230. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Piazzolla.woff2 +0 -0
  231. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/SOURCE.txt +0 -0
  232. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Synco.woff2 +0 -0
  233. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Tektur.woff2 +0 -0
  234. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/YatraOne.woff2 +0 -0
  235. /package/kits/physics-3d/drawings/{crate.pxart → crate.sprite} +0 -0
  236. /package/kits/physics-3d/drawings/{door-edge.pxart → door-edge.sprite} +0 -0
  237. /package/kits/physics-3d/drawings/{door.pxart → door.sprite} +0 -0
  238. /package/kits/physics-3d/drawings/{face.pxart → face.sprite} +0 -0
  239. /package/kits/physics-3d/drawings/{floor.pxart → floor.sprite} +0 -0
  240. /package/kits/physics-3d/drawings/{platform.pxart → platform.sprite} +0 -0
  241. /package/kits/physics-3d/drawings/{statue.pxart → statue.sprite} +0 -0
  242. /package/kits/physics-3d/drawings/{wall.pxart → wall.sprite} +0 -0
  243. /package/kits/{tabletop → turn-based}/.prettierrc +0 -0
package/dist/imports.js CHANGED
@@ -394,23 +394,6 @@ function backupImport(deckDir, alias) {
394
394
  fs.writeFileSync(path.join(dest, '.castle-import-pin.json'), JSON.stringify(pin, null, 2), 'utf-8');
395
395
  }
396
396
  }
397
- // The docs-only kit a bare scaffold imports for its agent guide. A deck that
398
- // adopts a real kit no longer has anything to say: leaving it would put two
399
- // quick references in front of the agent every turn, one of them opening "No
400
- // kit: nothing in this deck comes from a framework" about a deck that has one.
401
- function dropBareDocsImport(deckDir, alias) {
402
- const dir = path.join(deckDir, IMPORTS_DIR, alias);
403
- if (fs.existsSync(dir)) {
404
- unlockImportTree(dir);
405
- fs.rmSync(dir, { recursive: true, force: true });
406
- }
407
- const existing = readCastleJson(deckDir);
408
- if (!existing?.imports?.[alias])
409
- return;
410
- const imports = { ...existing.imports };
411
- delete imports[alias];
412
- fs.writeFileSync(path.join(deckDir, 'castle.json'), JSON.stringify({ ...existing, imports }, null, 2) + '\n', 'utf-8');
413
- }
414
397
  async function placeImport(deckDir, alias, deckId, source, via) {
415
398
  const destDir = path.join(deckDir, IMPORTS_DIR, alias);
416
399
  const replaced = fs.existsSync(destDir);
@@ -524,12 +507,11 @@ export async function addImportTo(dir, options = {}) {
524
507
  const declaredMain = tryReadCastleJson(importDir)?.main;
525
508
  let adoptedMain = null;
526
509
  if (typeof declaredMain === 'string' && declaredMain.trim()) {
527
- const { isPristineBareDeck, adoptImportEntry, writeStarterScene, writeStarterTheme, retargetBareClaudeMd, BARE_DOCS_ALIAS, } = await import('./init.js');
510
+ const { isPristineBareDeck, adoptImportEntry, writeStarterScene, writeStarterTheme, retargetBareClaudeMd, } = await import('./init.js');
528
511
  if (isPristineBareDeck(targetDir)) {
529
512
  adoptImportEntry(targetDir, alias, declaredMain.trim());
530
513
  adoptedMain = declaredMain.trim();
531
514
  retargetBareClaudeMd(targetDir, alias);
532
- dropBareDocsImport(targetDir, BARE_DOCS_ALIAS);
533
515
  // A kit's runtime with no scene to run is a blank screen, and the agent
534
516
  // has nothing to edit. Give the deck the kit's own starter, same as
535
517
  // `init --kit`. Only when the deck has no scenes -- never overwrite.
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@ import { addImport, updateImport } from './imports.js';
9
9
  import { listDecks } from './list-decks.js';
10
10
  import { getCliVersion, init } from './init.js';
11
11
  import { install } from './install.js';
12
+ import { check } from './check.js';
12
13
  import { forkImportFile, revertImportFile } from './forks.js';
13
14
  import { connectWS, takeScreenshot } from './preview.js';
14
15
  import { listVersions, restoreVersion, saveVersion, showVersion } from './versions.js';
@@ -101,6 +102,7 @@ function usage() {
101
102
  castle-web revert-import-file <imports/...> [dir]
102
103
  castle-web update-import [alias] [dir] [--check] [--revert] (re-fetches imports; no alias means all)
103
104
  castle-web install [dir]
105
+ castle-web check [dir] (bundles the deck, the same build save-deck runs)
104
106
  castle-web save-version [-m MESSAGE] [paths...] [--dir DIR] (no paths saves the whole deck)
105
107
  castle-web list-versions [version] [--dir DIR] (defaults to the latest version)
106
108
  castle-web show-version <version> [--dir DIR] (diffs of the files that version changed)
@@ -110,7 +112,7 @@ function usage() {
110
112
 
111
113
  Kits:
112
114
  physics-2d Actor / behavior / scene framework for 2D games with matter-js physics (RigidBody / Collider / Joints on top of Layout / Drawing / Camera). Default if --kit is omitted.
113
- physics-3d The same model in 3D: three.js rendering and rapier physics, with a scene editor and a voxel model editor. Built on physics-2d, which it imports.
115
+ physics-3d The same model in 3D: three.js rendering and rapier physics, with a scene editor and a model editor. Built on physics-2d, which it imports.
114
116
  none Minimal vite + canvas setup with the castle-web SDK and no kit.
115
117
 
116
118
  After init, read the scaffolded deck's CLAUDE.md (also AGENTS.md) for the kit's full author guide.`);
@@ -219,6 +221,10 @@ async function main() {
219
221
  await install(findPositionalDir());
220
222
  break;
221
223
  }
224
+ case 'check': {
225
+ await check(findPositionalDir());
226
+ break;
227
+ }
222
228
  // The version commands spend their positionals on their own arguments --
223
229
  // paths to save, a version to list from or restore to -- so the deck dir is
224
230
  // `--dir`, defaulting to the cwd.
@@ -280,6 +286,14 @@ async function main() {
280
286
  console.log(`Saved ${outFile}`);
281
287
  return;
282
288
  }
289
+ case 'mcp-playtest': {
290
+ // Spawned by a claude task agent through --mcp-config, never by hand.
291
+ // Its stdout is JSON-RPC, so nothing here may print to it.
292
+ const dir = findPositionalDir();
293
+ const { runMcpPlaytestServer } = await import('./mcpPlaytest.js');
294
+ await runMcpPlaytestServer(path.resolve(dir), getFlagValue('--task-id'));
295
+ return;
296
+ }
283
297
  case 'login':
284
298
  await login();
285
299
  break;
package/dist/init.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export declare const BARE_DOCS_KIT = "blank";
2
- export declare const BARE_DOCS_ALIAS = "castle.blank";
1
+ export declare const BASE_KIT = "base";
2
+ export declare const BASE_ALIAS = "castle.base";
3
3
  export declare function resolveScaffoldRefs(): {
4
4
  workspaceMode: boolean;
5
5
  sdkRef: string;
package/dist/init.js CHANGED
@@ -8,6 +8,18 @@ import { discardParentSource, fetchParentSource, unpackParentSource, writeRemixI
8
8
  import { getCliEntryPath, getKitsDir, getSdkPackagePath, toPosixPath, } from './localPaths.js';
9
9
  import { serve } from './serve.js';
10
10
  import { createVersion } from './versions.js';
11
+ // Default kit imported by `init` when no --kit is given. `none`/`bare` skips the
12
+ // framework and produces the minimal index.html + game.js stub below.
13
+ const DEFAULT_KIT = 'physics-2d';
14
+ // The account the first-party kits are (to be) published under, so a kit
15
+ // imported from the CLI's copy is named the same as one fetched from the server.
16
+ const KIT_AUTHOR = 'castle';
17
+ // EVERY deck imports this one, kit or not. It carries the SDK (which resolves
18
+ // out of it -- see sdkResolve.ts), the editor host a deck with no kit mounts
19
+ // its editors through, and the authoring guide every deck is written against.
20
+ // A framework kit imports it too, so a kit deck has it as well.
21
+ export const BASE_KIT = 'base';
22
+ export const BASE_ALIAS = `${KIT_AUTHOR}.${BASE_KIT}`;
11
23
  const INDEX_HTML = `<!DOCTYPE html>
12
24
  <html>
13
25
  <head>
@@ -20,33 +32,30 @@ const INDEX_HTML = `<!DOCTYPE html>
20
32
  </html>
21
33
  `;
22
34
  const GAME_JS = `import { setup, initCard } from 'castle-web-sdk';
35
+ import { mountEditorRoute } from '@imports/${BASE_ALIAS}/editorHost.js';
23
36
 
24
37
  setup();
25
- const card = initCard();
26
38
 
27
- const el = document.createElement('div');
28
- el.style.cssText = \`
29
- width: 100%; height: 100%;
30
- display: flex; align-items: center; justify-content: center;
31
- font-family: system-ui; color: #fff; font-size: 24px;
32
- \`;
33
- el.textContent = 'Hello Castle!';
34
- card.appendChild(el);
39
+ function startGame(card) {
40
+ const el = document.createElement('div');
41
+ el.style.cssText = \`
42
+ width: 100%; height: 100%;
43
+ display: flex; align-items: center; justify-content: center;
44
+ font-family: system-ui; color: #fff; font-size: 24px;
45
+ \`;
46
+ el.textContent = 'Hello Castle!';
47
+ card.appendChild(el);
48
+ }
49
+
50
+ // The shell opens a file type this deck declares (castle.json editor.fileTypes)
51
+ // as this same page with \`?file=\`, which the kit's host answers. A play load
52
+ // takes the false branch on the first line and loads none of it.
53
+ if (!(await mountEditorRoute())) startGame(initCard());
35
54
  `;
36
- // Default kit imported by `init` when no --kit is given. `none`/`bare` skip the
37
- // kit and produce the minimal index.html + game.js stub above.
38
- const DEFAULT_KIT = 'physics-2d';
39
- // A kit-less deck still imports ONE kit: a docs-only deck holding the guide to
40
- // building without a framework. It is imported rather than written into the
41
- // deck's own CLAUDE.md so it behaves like every other kit's guide -- the quick
42
- // reference reaches the agent every turn, the rest is read on demand, and the
43
- // text ships to existing decks via `autoUpdateWhenImported` instead of waiting
44
- // for whatever CLI release the deck was scaffolded by.
45
- export const BARE_DOCS_KIT = 'blank';
46
55
  // Registry version of castle-web-sdk to inject when scaffolding from a
47
56
  // globally-installed castle-web (not from inside the workspace). Bumped
48
57
  // alongside cli/sdk version bumps.
49
- const PUBLISHED_SDK_VERSION = '0.4.22';
58
+ const PUBLISHED_SDK_VERSION = '0.4.24';
50
59
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
51
60
  // face can ship without a cli release, and a caret range means an existing
52
61
  // deck's next install picks it up. Nothing here has to move when it does.
@@ -55,10 +64,6 @@ const PUBLISHED_SDK_VERSION = '0.4.22';
55
64
  // Costs a deck node_modules space and no bundle bytes: a deck inlines only the
56
65
  // faces it names (see castle-web-fonts' own scripts/verify.mjs).
57
66
  const FONTS_RANGE = '^1.0.0';
58
- // The account the first-party kits are (to be) published under, so a kit
59
- // imported from the CLI's copy is named the same as one fetched from the server.
60
- const KIT_AUTHOR = 'castle';
61
- export const BARE_DOCS_ALIAS = `${KIT_AUTHOR}.${BARE_DOCS_KIT}`;
62
67
  // Never copied into a deck's import: build/dependency junk.
63
68
  const KIT_COPY_EXCLUDE = new Set(['node_modules', '.castle', 'dist', '.git']);
64
69
  // The bare (`--kit none`) deck's default editor config: just the Files panel and
@@ -120,6 +125,7 @@ function makeKitDeckScripts(kitDir, alias, cliCommand) {
120
125
  restart: `${cliCommand} restart .`,
121
126
  screenshot: `${cliCommand} screenshot .`,
122
127
  'save-deck': `${cliCommand} save-deck .`,
128
+ check: `${cliCommand} check .`,
123
129
  };
124
130
  // `draw` is a kit script, not a CLI one, so it only exists if this kit ships
125
131
  // it -- and it runs from the deck root, where the sprites belong.
@@ -128,8 +134,12 @@ function makeKitDeckScripts(kitDir, alias, cliCommand) {
128
134
  }
129
135
  return scripts;
130
136
  }
137
+ // No `castle-web-sdk` dependency: the SDK is a file of the `base` kit this deck
138
+ // imports, and the bare specifier resolves there (sdkResolve.ts). Fonts stay a
139
+ // real package -- they are one, and every deck gets them for the reason
140
+ // FONTS_RANGE gives.
131
141
  function makePackageJson(projectDir) {
132
- const { sdkRef, cliCommand } = resolveScaffoldRefs();
142
+ const { cliCommand } = resolveScaffoldRefs();
133
143
  return {
134
144
  name: path.basename(projectDir),
135
145
  private: true,
@@ -138,10 +148,10 @@ function makePackageJson(projectDir) {
138
148
  restart: `${cliCommand} restart .`,
139
149
  screenshot: `${cliCommand} screenshot .`,
140
150
  'save-deck': `${cliCommand} save-deck .`,
151
+ check: `${cliCommand} check .`,
141
152
  },
142
153
  dependencies: {
143
154
  'castle-web-fonts': FONTS_RANGE,
144
- 'castle-web-sdk': sdkRef,
145
155
  },
146
156
  };
147
157
  }
@@ -187,15 +197,15 @@ function scaffoldBare(projectDir) {
187
197
  fs.writeFileSync(path.join(projectDir, 'index.html'), INDEX_HTML);
188
198
  fs.writeFileSync(path.join(projectDir, 'game.js'), GAME_JS);
189
199
  const pins = {};
190
- copyKitImport(projectDir, requireKitDir(BARE_DOCS_KIT), BARE_DOCS_KIT, BARE_DOCS_ALIAS, pins, new Map());
200
+ copyKitImport(projectDir, requireKitDir(BASE_KIT), BASE_KIT, BASE_ALIAS, pins, new Map());
191
201
  writeJsonFile(path.join(projectDir, 'castle.json'), { ...BARE_CASTLE_JSON, imports: pins });
192
- fs.writeFileSync(path.join(projectDir, 'CLAUDE.md'), makeBareClaudeMd(BARE_DOCS_ALIAS));
202
+ fs.writeFileSync(path.join(projectDir, 'CLAUDE.md'), makeBareClaudeMd(BASE_ALIAS));
193
203
  appendPlatformSection(projectDir);
194
204
  ensureAgentsSymlink(projectDir);
195
205
  fs.writeFileSync(path.join(projectDir, 'package.json'), JSON.stringify(makePackageJson(projectDir), null, 2) + '\n');
196
206
  // The docs kit declares no dependencies, so unlike a real kit's import there
197
207
  // is nothing to merge into package.json before the install.
198
- lockImportTree(path.join(projectDir, IMPORTS_DIR, BARE_DOCS_ALIAS));
208
+ lockImportTree(path.join(projectDir, IMPORTS_DIR, BASE_ALIAS));
199
209
  }
200
210
  // Copy a framework kit from kits/<kit>/ into the new deck dir, dropping
201
211
  // build/dependency junk and castle.json.
@@ -319,19 +329,29 @@ export function writeStarterTheme(projectDir, kitDir) {
319
329
  fs.copyFileSync(src, dest);
320
330
  }
321
331
  }
332
+ // A bare deck's own guide. Its `## Quick reference` is HERE rather than in the
333
+ // base kit for one reason: this is the only place a claim like "there is no
334
+ // scene format" is true. Every deck imports base now, kit decks included, so
335
+ // anything describing what THIS deck is made of belongs to this deck --
336
+ // and `readClaudeSectionWithImports` reads the deck's own section before any
337
+ // import's, which is what puts it in front of the backends that read no
338
+ // CLAUDE.md at all.
322
339
  function makeBareClaudeMd(alias) {
323
340
  return `# Castle deck (no kit)
324
341
 
325
- This deck is a normal browser project: \`index.html\` loads \`game.js\` as an ES
326
- module, \`package.json\` holds its scripts and any npm package it adds, and
327
- \`castle.json\` is its editor config. Nothing here comes from a framework -- there
328
- is no scene, behavior, sprite, or level format unless this deck defines one, and
329
- no editor other than the code editor unless this deck builds one. Everything it
330
- renders, it renders itself: DOM, canvas, WebGL, React, Pixi, Three, WebAssembly,
331
- whatever the web offers.
342
+ ## Quick reference
332
343
 
333
- Read \`${IMPORTS_DIR}/${alias}/CLAUDE.md\` for the authoring guide: the deck's
334
- file layout, the Castle SDK, and how to give a file type an editor of its own.
344
+ - This deck is built on **no framework**: \`index.html\` loads \`game.js\` as an ES
345
+ module, and everything it renders, it renders itself -- DOM, canvas, WebGL,
346
+ React, Pixi, Three, WebAssembly, whatever the web offers. There is no scene,
347
+ behavior, sprite, or level format unless this deck defines one, and no editor
348
+ but the code editor unless this deck builds one.
349
+ - \`npm run check\` bundles the deck (the same build \`save-deck\` runs). There is
350
+ no lint or typecheck here unless this deck adds one.
351
+ - Call \`Lifecycle.ready()\` once the first real frame is painted, so the Castle
352
+ feed reveals the deck right away instead of after a timeout.
353
+ - The authoring guide -- the SDK, the file layout, how to give a file type an
354
+ editor -- is \`${IMPORTS_DIR}/${alias}/CLAUDE.md\`.
335
355
 
336
356
  Do not edit anything under \`${IMPORTS_DIR}/\`: those files belong to the deck they
337
357
  came from, and are replaced wholesale when the import is updated.
@@ -343,6 +363,8 @@ function makeImportedKitClaudeMd(alias) {
343
363
  The engine, editors and built-in behaviors come from the **${alias}** kit, imported
344
364
  at \`${IMPORTS_DIR}/${alias}/\` and read-only. Read \`${IMPORTS_DIR}/${alias}/CLAUDE.md\`
345
365
  for the authoring guide: how scenes, blueprints, drawings and behaviors work.
366
+ The Castle SDK and the rules every deck shares come from \`${BASE_ALIAS}\`,
367
+ imported alongside it.
346
368
 
347
369
  This deck holds only its own content -- \`scenes/\`, \`drawings/\`,
348
370
  \`blueprints/\`, \`behaviors/\` -- plus \`index.html\` (which points at the kit's
@@ -361,7 +383,7 @@ something in the kit behaves, define your own behavior of the same name in
361
383
  // whatever the creator may have written here.
362
384
  export function retargetBareClaudeMd(deckDir, alias) {
363
385
  const claudePath = path.join(deckDir, 'CLAUDE.md');
364
- const scaffolded = makeBareClaudeMd(BARE_DOCS_ALIAS).trimEnd() + '\n\n' + CLAUDE_MD_PLATFORM_SECTION;
386
+ const scaffolded = makeBareClaudeMd(BASE_ALIAS).trimEnd() + '\n\n' + CLAUDE_MD_PLATFORM_SECTION;
365
387
  try {
366
388
  if (fs.readFileSync(claudePath, 'utf8') !== scaffolded)
367
389
  return;
@@ -453,6 +475,20 @@ function copyKitImport(projectDir, kitDir, kit, alias, pins, copied) {
453
475
  }
454
476
  }
455
477
  }
478
+ // The kit's server block, with `main` pointed at the copy under `imports/`. The
479
+ // kit names its own file, which is right when the kit itself is served and wrong
480
+ // in a deck, where that file only exists inside the import.
481
+ function serverForDeck(server, kitDir, alias) {
482
+ if (!server || typeof server !== 'object') {
483
+ return server;
484
+ }
485
+ const block = server;
486
+ const main = block.main;
487
+ if (typeof main !== 'string' || !fs.existsSync(path.join(kitDir, main))) {
488
+ return block;
489
+ }
490
+ return { ...block, main: `${IMPORTS_DIR}/${alias}/${main}` };
491
+ }
456
492
  function scaffoldFromKitImport(kit, projectDir) {
457
493
  const kitDir = requireKitDir(kit);
458
494
  // Qualified like any other import (`<author>.<deck>`), and qualified NOW even
@@ -480,21 +516,21 @@ function scaffoldFromKitImport(kit, projectDir) {
480
516
  // types too, which a copy taken at scaffold time never could.
481
517
  writeJsonFile(path.join(projectDir, 'castle.json'), {
482
518
  ...(kitConfig.editor ? { editor: withoutFileTypes(kitConfig.editor) } : {}),
519
+ ...(kitConfig.server ? { server: serverForDeck(kitConfig.server, kitDir, alias) } : {}),
483
520
  imports: pins,
484
521
  });
485
522
  // The kit's code runs from THIS deck's node_modules, so its dependencies are
486
523
  // declared here (see syncImportDependencies, which does the same for imports
487
524
  // added later). Every copied kit contributes, the scaffolding kit first, so
488
525
  // where two of them name the same package the one being scaffolded from wins.
489
- const { sdkRef, cliCommand } = resolveScaffoldRefs();
526
+ const { cliCommand } = resolveScaffoldRefs();
490
527
  const dependencies = {};
491
528
  for (const depKitDir of copied.values()) {
492
529
  const depPkg = readJsonFile(path.join(depKitDir, 'package.json')) ?? {};
493
530
  for (const [name, range] of Object.entries(depPkg.dependencies ?? {})) {
494
531
  if (dependencies[name] !== undefined)
495
532
  continue;
496
- dependencies[name] =
497
- name === 'castle-web-sdk' && String(range).startsWith('file:') ? sdkRef : String(range);
533
+ dependencies[name] = String(range);
498
534
  }
499
535
  }
500
536
  writeJsonFile(path.join(projectDir, 'package.json'), {
@@ -0,0 +1 @@
1
+ export declare function runMcpPlaytestServer(deckDir: string, taskId: string | undefined): Promise<void>;
@@ -0,0 +1,182 @@
1
+ // A stdio MCP server exposing ONE tool -- `playtest` -- to a spawned claude
2
+ // task agent, so the claude backend gets the capability smith already has
3
+ // natively (native/tools.ts). It owns no browser: every call is relayed to the
4
+ // running serve over its loopback control WebSocket (`playtest_request` in
5
+ // serve.ts), which is where the one warm Chromium and the task's frames dir
6
+ // live.
7
+ //
8
+ // stdout carries JSON-RPC and NOTHING else -- claude's MCP client parses every
9
+ // line, so a stray console.log breaks the session. Diagnostics go to stderr.
10
+ import * as fs from 'fs';
11
+ import * as path from 'path';
12
+ import { connectWS } from './preview.js';
13
+ import { PLAYTEST_TOOL_DESCRIPTION, PLAYTEST_TOOL_PARAMETERS, } from './native/playtest.js';
14
+ // Claude may kill the child at any time; the only shutdown we control is
15
+ // stdin closing. Long enough to cover a cold Chromium download (minutes) on
16
+ // top of navigation + settle + a full 15s session.
17
+ const PLAYTEST_CALL_TIMEOUT_MS = 10 * 60_000;
18
+ // The protocol revision we implement. A client asking for a newer one is
19
+ // answered with this; MCP lets the client decide whether that is acceptable.
20
+ const PROTOCOL_VERSION = '2024-11-05';
21
+ // The control socket is upgraded on the serve's own HTTP port now; `wsPort` is
22
+ // the pre-bridge name for it, still written so older clients keep connecting.
23
+ // Same read as index.ts's readServeSocketPort and list-decks.ts.
24
+ function serveSocketPort(deckDir) {
25
+ const raw = fs.readFileSync(path.join(deckDir, '.castle', 'serve.json'), 'utf-8');
26
+ const parsed = JSON.parse(raw);
27
+ const info = (parsed && typeof parsed === 'object' ? parsed : {});
28
+ const port = typeof info.port === 'number' ? info.port : info.wsPort;
29
+ if (typeof port !== 'number')
30
+ throw new Error('serve.json names no port');
31
+ return port;
32
+ }
33
+ async function callPlaytest(deckDir, taskId, args) {
34
+ const ws = await connectWS(serveSocketPort(deckDir));
35
+ try {
36
+ return await new Promise((resolve, reject) => {
37
+ const requestId = Math.random().toString(36).slice(2);
38
+ const cleanup = () => {
39
+ clearTimeout(timer);
40
+ ws.off('message', onMessage);
41
+ };
42
+ const timer = setTimeout(() => {
43
+ cleanup();
44
+ reject(new Error('playtest timed out waiting for the serve'));
45
+ }, PLAYTEST_CALL_TIMEOUT_MS);
46
+ const onMessage = (raw) => {
47
+ let msg;
48
+ try {
49
+ msg = JSON.parse(raw.toString());
50
+ }
51
+ catch {
52
+ return;
53
+ }
54
+ if (msg.requestId !== requestId)
55
+ return;
56
+ // Chromium's one-time download is minutes long and silent otherwise;
57
+ // relay it so the agent sees progress instead of a hung tool.
58
+ if (msg.type === 'playtest_progress') {
59
+ if (msg.label)
60
+ process.stderr.write(`[playtest] ${msg.label}\n`);
61
+ return;
62
+ }
63
+ if (msg.type !== 'playtest_response')
64
+ return;
65
+ cleanup();
66
+ resolve(msg);
67
+ };
68
+ ws.on('message', onMessage);
69
+ ws.send(JSON.stringify({ type: 'playtest_request', requestId, taskId, args }));
70
+ });
71
+ }
72
+ finally {
73
+ ws.close();
74
+ }
75
+ }
76
+ function contentFor(res) {
77
+ const content = [{ type: 'text', text: res.output ?? '' }];
78
+ for (const image of res.images ?? []) {
79
+ const dataUrl = image.dataUrl ?? '';
80
+ const comma = dataUrl.indexOf(',');
81
+ if (comma < 0)
82
+ continue;
83
+ content.push({ type: 'image', data: dataUrl.slice(comma + 1), mimeType: 'image/png' });
84
+ }
85
+ return content;
86
+ }
87
+ export async function runMcpPlaytestServer(deckDir, taskId) {
88
+ const send = (body) => {
89
+ process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', ...body })}\n`);
90
+ };
91
+ const handle = async (req) => {
92
+ // A notification (no id) is never answered -- notifications/initialized is
93
+ // the one claude actually sends.
94
+ const id = req.id;
95
+ if (id === undefined || id === null)
96
+ return;
97
+ if (req.method === 'initialize') {
98
+ send({
99
+ id,
100
+ result: {
101
+ protocolVersion: PROTOCOL_VERSION,
102
+ capabilities: { tools: {} },
103
+ serverInfo: { name: 'castle', version: '1.0.0' },
104
+ },
105
+ });
106
+ return;
107
+ }
108
+ if (req.method === 'ping') {
109
+ send({ id, result: {} });
110
+ return;
111
+ }
112
+ if (req.method === 'tools/list') {
113
+ send({
114
+ id,
115
+ result: {
116
+ tools: [
117
+ {
118
+ name: 'playtest',
119
+ description: PLAYTEST_TOOL_DESCRIPTION,
120
+ inputSchema: PLAYTEST_TOOL_PARAMETERS,
121
+ },
122
+ ],
123
+ },
124
+ });
125
+ return;
126
+ }
127
+ if (req.method === 'tools/call') {
128
+ const params = req.params ?? {};
129
+ if (params.name !== 'playtest') {
130
+ send({ id, error: { code: -32602, message: `unknown tool: ${String(params.name)}` } });
131
+ return;
132
+ }
133
+ try {
134
+ const res = await callPlaytest(deckDir, taskId, params.arguments ?? {});
135
+ send({ id, result: { content: contentFor(res), isError: res.ok === false } });
136
+ }
137
+ catch (e) {
138
+ // A transport failure is the tool's failure, not the session's: report
139
+ // it as tool content so the agent can react, never as a JSON-RPC error.
140
+ send({
141
+ id,
142
+ result: {
143
+ content: [{ type: 'text', text: `Error: ${e.message}` }],
144
+ isError: true,
145
+ },
146
+ });
147
+ }
148
+ return;
149
+ }
150
+ send({ id, error: { code: -32601, message: `unknown method: ${String(req.method)}` } });
151
+ };
152
+ let buffer = '';
153
+ // Serialize handling: claude may pipeline requests, and a playtest call is
154
+ // long -- answering out of order is legal JSON-RPC but needlessly races the
155
+ // serve's per-task call budget.
156
+ let chain = Promise.resolve();
157
+ process.stdin.setEncoding('utf8');
158
+ process.stdin.on('data', (chunk) => {
159
+ buffer += chunk;
160
+ for (;;) {
161
+ const newline = buffer.indexOf('\n');
162
+ if (newline < 0)
163
+ break;
164
+ const line = buffer.slice(0, newline).trim();
165
+ buffer = buffer.slice(newline + 1);
166
+ if (!line)
167
+ continue;
168
+ let req;
169
+ try {
170
+ req = JSON.parse(line);
171
+ }
172
+ catch {
173
+ continue;
174
+ }
175
+ chain = chain.then(() => handle(req)).catch(() => undefined);
176
+ }
177
+ });
178
+ await new Promise((resolve) => {
179
+ process.stdin.on('end', () => resolve());
180
+ process.stdin.on('close', () => resolve());
181
+ });
182
+ }
@@ -45,6 +45,30 @@ export interface CastleBudget {
45
45
  blocked: boolean;
46
46
  blockedModelPrefixes: string[];
47
47
  }
48
+ export interface AiCredits {
49
+ plan: "credits" | "daily";
50
+ rates?: {
51
+ usdPerCredit: number;
52
+ displayUnit: "credits" | "usd";
53
+ };
54
+ balanceCredits: number;
55
+ grantedCredits: number;
56
+ purchasedCredits: number;
57
+ pendingCredits: number;
58
+ dailyFreeRemainingCredits: number | null;
59
+ nextGrantAt: string | null;
60
+ lowBalance: boolean;
61
+ autoReload: {
62
+ enabled: boolean;
63
+ thresholdCredits: number | null;
64
+ amountCredits: number | null;
65
+ disabledReason: string | null;
66
+ };
67
+ }
68
+ export declare function spendableMicros(budget: CastleBudget): number | null;
69
+ export declare function castleCreditsExhausted(budget: CastleBudget, credits: AiCredits | null): boolean;
70
+ /** Rich credit state, or null when ghost/proxy cannot provide the new field. */
71
+ export declare function fetchAiCredits(): Promise<AiCredits | null>;
48
72
  /**
49
73
  * The daily Castle-paid AI budget for the user this sandbox belongs to, or null
50
74
  * when there is nothing to say: outside a sandbox, on a host whose proxy
package/dist/metering.js CHANGED
@@ -112,8 +112,95 @@ export function inCastleSandbox() {
112
112
  // Path on the proxy that reports this sandbox's daily budget. Must match
113
113
  // CASTLE_BUDGET_PATH in castle-sandboxes/shared/src/index.ts.
114
114
  const CASTLE_BUDGET_PATH = "/castle/budget";
115
+ const CASTLE_API_PATH = "/castle/api/graphql";
115
116
  // Read before a run starts, so it must not be able to hold one up for long.
116
117
  const BUDGET_FETCH_TIMEOUT_MS = 5_000;
118
+ export function spendableMicros(budget) {
119
+ if (budget.limitMicros === null)
120
+ return null;
121
+ return Math.max(0, budget.limitMicros - budget.usedMicros);
122
+ }
123
+ const EXHAUSTED_BALANCE_CREDITS = 50;
124
+ export function castleCreditsExhausted(budget, credits) {
125
+ if (!budget.blocked || credits?.plan !== "credits")
126
+ return false;
127
+ const creditsRemaining = credits.balanceCredits - credits.pendingCredits;
128
+ return (spendableMicros(budget) === 0 &&
129
+ creditsRemaining <= EXHAUSTED_BALANCE_CREDITS);
130
+ }
131
+ function isAiCredits(value) {
132
+ const credits = value;
133
+ const rates = credits?.rates;
134
+ const reload = credits?.autoReload;
135
+ return Boolean((credits?.plan === "credits" || credits?.plan === "daily") &&
136
+ (rates === undefined ||
137
+ (typeof rates.usdPerCredit === "number" &&
138
+ (rates.displayUnit === "credits" || rates.displayUnit === "usd"))) &&
139
+ typeof credits.balanceCredits === "number" &&
140
+ typeof credits.grantedCredits === "number" &&
141
+ typeof credits.purchasedCredits === "number" &&
142
+ typeof credits.pendingCredits === "number" &&
143
+ (credits.dailyFreeRemainingCredits === null ||
144
+ typeof credits.dailyFreeRemainingCredits === "number") &&
145
+ (credits.nextGrantAt === null || typeof credits.nextGrantAt === "string") &&
146
+ typeof credits.lowBalance === "boolean" &&
147
+ typeof reload?.enabled === "boolean" &&
148
+ (reload.thresholdCredits === null ||
149
+ typeof reload.thresholdCredits === "number") &&
150
+ (reload.amountCredits === null ||
151
+ typeof reload.amountCredits === "number") &&
152
+ (reload.disabledReason === null || typeof reload.disabledReason === "string"));
153
+ }
154
+ /** Rich credit state, or null when ghost/proxy cannot provide the new field. */
155
+ export async function fetchAiCredits() {
156
+ const base = process.env.CASTLE_LLM_PROXY_URL;
157
+ const token = process.env.CASTLE_LLM_PROXY_TOKEN;
158
+ if (!base || !token)
159
+ return null;
160
+ try {
161
+ // Retry without rates for a ghost version whose schema predates the field.
162
+ // GraphQL rejects the whole operation when even one selected field is unknown.
163
+ for (const ratesField of [
164
+ "rates { usdPerCredit displayUnit }",
165
+ "",
166
+ ]) {
167
+ const resp = await fetch(`${base}${CASTLE_API_PATH}`, {
168
+ method: "POST",
169
+ headers: {
170
+ "x-auth-token": token,
171
+ "content-type": "application/json",
172
+ accept: "application/json",
173
+ "x-os": "cli",
174
+ "x-cli-api-version": "2",
175
+ },
176
+ body: JSON.stringify({
177
+ query: `query {
178
+ me {
179
+ aiCredits {
180
+ plan balanceCredits grantedCredits purchasedCredits pendingCredits
181
+ dailyFreeRemainingCredits nextGrantAt lowBalance
182
+ ${ratesField}
183
+ autoReload { enabled thresholdCredits amountCredits disabledReason }
184
+ }
185
+ }
186
+ }`,
187
+ }),
188
+ signal: AbortSignal.timeout(BUDGET_FETCH_TIMEOUT_MS),
189
+ });
190
+ if (!resp.ok)
191
+ continue;
192
+ const body = (await resp.json());
193
+ if (body.errors?.length)
194
+ continue;
195
+ const credits = body.data?.me?.aiCredits;
196
+ return isAiCredits(credits) ? credits : null;
197
+ }
198
+ return null;
199
+ }
200
+ catch {
201
+ return null;
202
+ }
203
+ }
117
204
  /**
118
205
  * The daily Castle-paid AI budget for the user this sandbox belongs to, or null
119
206
  * when there is nothing to say: outside a sandbox, on a host whose proxy
@@ -0,0 +1,3 @@
1
+ export declare const SDK_PACKAGE = "castle-web-sdk";
2
+ export declare function resolveSdkSpecifier(deckDir: string, specifier: string): string | null;
3
+ export declare function hasSdkProvider(deckDir: string): boolean;