castle-web-cli 0.4.142 → 0.4.145

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 (52) hide show
  1. package/dist/agent-prompts.d.ts +1 -0
  2. package/dist/agent-prompts.js +7 -2
  3. package/dist/agent.js +11 -9
  4. package/dist/imports.js +44 -4
  5. package/dist/init.d.ts +4 -0
  6. package/dist/init.js +63 -26
  7. package/dist/install.js +4 -0
  8. package/dist/platformDoc.d.ts +12 -0
  9. package/dist/platformDoc.js +236 -0
  10. package/dist/serve.d.ts +3 -0
  11. package/dist/serve.js +157 -13
  12. package/dist/serveSecurity.d.ts +5 -1
  13. package/dist/serveSecurity.js +27 -8
  14. package/dist/shell/assets/index-BaiRLZ8p.css +1 -0
  15. package/dist/shell/assets/{index-qbygvQIx.js → index-CbRAepsq.js} +68 -68
  16. package/dist/shell/index.html +2 -2
  17. package/kits/blank/CLAUDE.md +198 -0
  18. package/kits/blank/castle.json +8 -0
  19. package/kits/blank/index.html +42 -0
  20. package/kits/blank/package-lock.json +10 -0
  21. package/kits/blank/package.json +9 -0
  22. package/kits/physics-2d/CLAUDE.md +44 -4
  23. package/kits/physics-2d/behaviors/Collider.jsx +21 -0
  24. package/kits/physics-2d/behaviors/Draggable.jsx +9 -0
  25. package/kits/physics-2d/behaviors/Layout.jsx +7 -0
  26. package/kits/physics-2d/behaviors/RigidBody.jsx +6 -0
  27. package/kits/physics-2d/behaviors/Sprite.jsx +9 -4
  28. package/kits/physics-2d/editors/BlueprintLibrary.jsx +64 -32
  29. package/kits/physics-2d/editors/NewBlueprintModal.jsx +69 -0
  30. package/kits/physics-2d/editors/PlayOnly.jsx +1 -1
  31. package/kits/physics-2d/editors/SceneEditor.jsx +333 -108
  32. package/kits/physics-2d/editors/SelectionOverlay.jsx +6 -2
  33. package/kits/physics-2d/editors/behaviorRegistry.js +78 -5
  34. package/kits/physics-2d/engine/SceneUI.jsx +2 -2
  35. package/kits/physics-2d/engine/blueprint.js +212 -15
  36. package/kits/physics-2d/engine/editorFlags.js +50 -0
  37. package/kits/physics-2d/engine/files.js +9 -0
  38. package/kits/physics-2d/engine/liveReload.js +16 -4
  39. package/kits/physics-2d/engine/panelPrefs.js +78 -0
  40. package/kits/physics-2d/engine/panelSorting.jsx +84 -0
  41. package/kits/physics-2d/engine/physics/PhysicsSystem.js +5 -2
  42. package/kits/physics-2d/engine/physics/matterBridge.js +12 -2
  43. package/kits/physics-2d/engine/scene.js +94 -3
  44. package/kits/physics-2d/engine/ui.jsx +157 -4
  45. package/kits/physics-2d/engine/ui.module.css +615 -1
  46. package/kits/physics-2d/package-lock.json +78 -1
  47. package/kits/physics-2d/package.json +4 -0
  48. package/kits/physics-3d/CLAUDE.md +2 -3
  49. package/package.json +1 -1
  50. package/dist/commonInstructions.d.ts +0 -1
  51. package/dist/commonInstructions.js +0 -26
  52. package/dist/shell/assets/index-CcVJjnL3.css +0 -1
@@ -0,0 +1,236 @@
1
+ import * as crypto from 'crypto';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import { NO_DECK_DOCS } from './agent-prompts.js';
5
+ import { resolveFileTypes } from './editorConfig.js';
6
+ // The platform's own guidance to agents -- the rules identical in a bare deck
7
+ // and a kit deck: the card, touch, assets and formats, imports, reloading,
8
+ // editors. Its one home is here. The serve writes it under the deck's .castle/
9
+ // at every start (runtime state: not saved, not versioned, never edited), the
10
+ // deck's root CLAUDE.md `@`-imports the compact copy so any agent that
11
+ // auto-loads CLAUDE.md gets it for free, and backends that read no CLAUDE.md
12
+ // (cursor-agent, smith) get the same bullets in their composed prompt. Kits
13
+ // state only what is theirs; nothing below is restated in a kit's guide.
14
+ //
15
+ // The text is what was always in context before it had one home: the four
16
+ // sections `init` used to append to every CLAUDE.md, verbatim, plus the rules
17
+ // the kits' quick references used to restate (formats, install, reloading,
18
+ // editors) in their original wording. Nothing that was inlined became
19
+ // tool-call-only in the move, and nothing tool-call-only became inlined --
20
+ // that split is deliberate (memo 26-08-24-17-54) and the eval legs measured
21
+ // the vehicle, not a rewrite.
22
+ export const PLATFORM_DOCS_DIR = path.join('.castle', 'docs');
23
+ export const PLATFORM_DOC_REL = path.join(PLATFORM_DOCS_DIR, 'platform.md');
24
+ const MEDIA = {
25
+ images: ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'],
26
+ audio: ['.mp3', '.wav', '.m4a'],
27
+ video: ['.mp4'],
28
+ };
29
+ const code = (exts) => exts.map((e) => `\`${e}\``).join(' ');
30
+ // What this deck can hold: the formats that survive publishing, plus whatever
31
+ // the deck or its imports declared as a file type (a declaration is the deck
32
+ // saying it handles that format -- see editorConfig.ts). Computed per deck so
33
+ // no kit has to restate the list and no list goes stale on a deck that adds a
34
+ // type.
35
+ function mediaList(deckDir) {
36
+ const defaults = new Set([...MEDIA.images, ...MEDIA.audio, ...MEDIA.video]);
37
+ const own = (resolveFileTypes(deckDir) ?? [])
38
+ .filter((t) => !t.unsupported && !defaults.has(t.ext))
39
+ .map((t) => t.ext);
40
+ const base = `images ${code(MEDIA.images)}, audio ${code(MEDIA.audio)}, video \`.mp4\` (H.264)`;
41
+ return own.length ? `${base}, plus its own declared types ${code(own)}` : base;
42
+ }
43
+ // The ratified mode bullet (prompt-evals deliverable 4: the 169-byte line that
44
+ // is the whole difference between offering and building unasked). Verbatim.
45
+ const MODE_BULLET = "- Unprompted, an editor is an offer, never a build: when the same data keeps getting edited by hand, propose one and build on the user's yes. Never during a first build.";
46
+ // The rules that reached agents through a kit's quick reference before the
47
+ // kits stopped restating them: the physics-2d / blank wording, with the media
48
+ // list computed per deck.
49
+ export function everyDeckBullets(deckDir) {
50
+ return [
51
+ `- **Supported media formats are exactly**: ${mediaList(deckDir)}. Nothing else — a published deck inlines every asset as a \`data:\` URI, where the browser trusts the declared type instead of sniffing the bytes, so a format that merely works while serving (\`.mov\` is the classic case) can be dead once published. Convert, don't improvise.`,
52
+ "- To add an npm package, put it in `package.json` `dependencies` and run `castle-web install .` (the install `init` ran; it uses whichever package manager made the lockfile).",
53
+ "- Do not reload the deck after an edit. Nothing auto-reloads: the person applies your changes when they are ready, from the Play panel's restart button or a panel's own reload control. `npm run restart` reloads every open panel at once and breaks their flow — only when asked.",
54
+ "- The deck can define its own editors: declare a file type in `castle.json` (`editor.fileTypes`: ext, label, icon, and an `editors/` module) and the Files panel opens that type in it — whole recipe under `## Editors` in the deck's guide (its kit's `CLAUDE.md` under `imports/`). Editors under `imports/` are read-only; add or fork, don't edit.",
55
+ '- An editor is for content FILES the creator keeps coming back to (catalogs, dialogue, level tables) that nothing already opens. One-off or generated data stays code.',
56
+ MODE_BULLET,
57
+ ];
58
+ }
59
+ // The guide as a section of the prompt's "how this deck works", for the
60
+ // backends that read no CLAUDE.md. Same heading shape as an import's section.
61
+ export const PLATFORM_SECTION_HEADING = '### from the Castle platform (every deck)';
62
+ export function platformSection(deckDir) {
63
+ return `${PLATFORM_SECTION_HEADING}\n\n${platformGuide(deckDir)}`;
64
+ }
65
+ // ------------------------------------------------------------------- the gate
66
+ // Whether this serve may rewrite an EXISTING deck's root CLAUDE.md onto the
67
+ // @import. That rewrite is the one irreversible thing here, so it reaches decks
68
+ // on a gate rather than all at once; off unless the serve was told otherwise.
69
+ // Everything else is unconditional -- the guide written under .castle/docs, the
70
+ // section a new deck scaffolds with, the block spawned agents get -- because
71
+ // the kits are one shared artifact and stopped restating these rules for
72
+ // everyone at once, gate or no gate. The cloud editor sets it per user from a
73
+ // feature gate; see serveOnPort in castle-www's cloudSandbox.ts.
74
+ function mayMigrateClaudeMd() {
75
+ return process.env.CASTLE_PLATFORM_DOC === 'on';
76
+ }
77
+ // The line has to stand on its own to count: this repo's CLAUDE.md names the
78
+ // path inside a sentence, and prose about the import must not read as a deck
79
+ // carrying one.
80
+ function claudeMdImportsGuide(deckDir) {
81
+ try {
82
+ return fs
83
+ .readFileSync(path.join(deckDir, 'CLAUDE.md'), 'utf8')
84
+ .split('\n')
85
+ .some((line) => line.trim() === CLAUDE_MD_IMPORT_LINE);
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ // Resolved ONCE per deck and cached, for the reason planSession is (agent.ts):
92
+ // it decides what sits in the prompt's cached prefix, and answering a
93
+ // mid-session edit would split that cache. The serve migrates before it builds
94
+ // any prompt, so the first answer here is the post-migration one.
95
+ const guideLoaders = new Map();
96
+ function deckLoadsGuide(deckDir) {
97
+ const cached = guideLoaders.get(deckDir);
98
+ if (cached !== undefined)
99
+ return cached;
100
+ const loads = claudeMdImportsGuide(deckDir);
101
+ guideLoaders.set(deckDir, loads);
102
+ return loads;
103
+ }
104
+ // A sentence from the bullets the kits used to restate, distinctive enough to
105
+ // tell a kit guide that still carries them from one that stopped.
106
+ const RESTATEMENT_MARKER = '**Supported media formats are exactly**';
107
+ // The every-deck bullets after a quick reference that lacks them. Skipped when
108
+ // the deck's kit is pinned to a version that still restates them, which would
109
+ // otherwise say all of it twice.
110
+ function withEveryDeckBullets(deckDir, quickReference) {
111
+ const own = quickReference.trim();
112
+ if (own.includes(RESTATEMENT_MARKER))
113
+ return quickReference;
114
+ const bullets = everyDeckBullets(deckDir).join('\n');
115
+ return own ? `${own}\n\n${bullets}` : bullets;
116
+ }
117
+ // A deck's quick reference as one backend sees it. cursor-agent and smith read
118
+ // no CLAUDE.md, so the whole block goes in their prompt. claude auto-loads the
119
+ // root CLAUDE.md -- but only a deck whose file carries the @import line has the
120
+ // guide that way. A deck the migration has not reached (gated off) or refused
121
+ // ('kept' -- someone edited its sections) still has the four legacy sections
122
+ // inline and is missing just the every-deck bullets, which left the kits'
123
+ // quick reference in the same change that added the guide.
124
+ export function quickReferenceFor(deckDir, quickReference, backend) {
125
+ if (backend === 'claude') {
126
+ return deckLoadsGuide(deckDir) ? quickReference : withEveryDeckBullets(deckDir, quickReference);
127
+ }
128
+ const own = quickReference.trim();
129
+ return `${platformSection(deckDir)}\n\n${own || NO_DECK_DOCS}`;
130
+ }
131
+ // The four sections `init` appended to every deck's CLAUDE.md until 2026-08-25
132
+ // (COMMON_INSTRUCTIONS), verbatim; only the "(every deck)" heading suffix is
133
+ // gone, since the whole file is that now.
134
+ const COMMON_SECTIONS = `## Imports are read-only
135
+
136
+ - **\`imports/\` holds other decks' files and is locked read-only on disk.** Files are mode 0444 and directories 0555, so any shell command that writes, moves, or deletes inside \`imports/\` fails with \`EACCES\` / "Permission denied" — that is the lock working, not a broken checkout. Do not \`chmod\` around it, do not \`sudo\`, and do not retry the command a different way.
137
+ - **Change an import through the CLI, never the filesystem.** \`castle-web add-import <deckIdOrUrl>\` adds one and \`castle-web update-import [alias]\` re-fetches it (\`--check\` to see if it is outdated, \`--revert\` to undo). These handle the unlock/relock themselves.
138
+ - **\`castle-web list-decks [--kind mine|saved|kits]\` is how you find out WHAT can be imported** — one deck per line, starting with the id \`add-import\` takes, and marked when this deck already has it. \`imports/\` only shows what is here already; it is not a catalogue.
139
+ - **To change one file of an import, FORK it**: \`castle-web fork-import-file <path>\` takes this deck's own version of that file, and every reference to the imported path uses your version from then on (\`castle-web revert-import-file <path>\` drops it and goes back to the import's). Fork only what you actually need to change, and as few files as you can -- a forked file stops taking the import's updates, so the more you fork the less an \`update-import\` can give you. To build something of your own rather than change theirs, write an ordinary file in this deck instead -- and check first whether the kit already lets a deck file register what you want (its CLAUDE.md names those seams), since that path keeps taking updates and a fork does not. When you do fork, it is often worth forking only to add a hook or registration point and keeping the logic itself in a deck file, so later changes need no further forks; for a quick one-off tweak a plain direct fork is fine.
140
+ - **Deleting the deck directory itself needs the lock released first** (\`chmod -R u+w\` on the deck dir) — that is the one legitimate reason to touch the modes, and only for a directory being thrown away.
141
+
142
+ ## Assets
143
+
144
+ - **Load static assets (drawings, audio, etc.) through the bundler — never runtime-\`fetch\` a loose file path.** Use a static \`import\`, \`import.meta.glob('./drawings/*.svg', { eager: true, import: 'default' })\`, or inline the asset directly. The dev serve happens to serve loose files over HTTP, so \`fetch('drawings/qb.svg')\` looks like it works locally — but \`save-deck\` bundles the whole deck into a single file, loose files are no longer served, and the fetch silently fails on every platform. Kit decks: use the kit's own drawing/asset-loading APIs instead of a raw \`fetch\`.
145
+
146
+ ## Touch controls
147
+
148
+ - **Playable on a touchscreen, with only the controls the game actually needs.** Castle decks are played on phones, so whatever input a game does use must work by touch — direct tap/drag on the game itself wherever possible, and on-screen buttons only where the mechanics genuinely call for them. Do NOT add controls a game doesn't need: never drop in a generic d-pad or movement overlay by default. Prefer touching the game directly over an overlay that just mirrors keyboard keys. Keyboard input is fine to support on top for desktop play. Match the controls to the actual mechanics — a game with no directional movement should have no movement controls at all.
149
+
150
+ ## Fit the card
151
+
152
+ - **The deck plays inside a fixed 5:7 portrait card, not the full window.** The card is sized to fit the screen (at most about 450x630px), clips overflow, and does not scroll. Design the whole layout to fit inside that portrait box: size UI relative to the card with percentages, flex/grid, \`min()\`, \`clamp()\`, or viewport-relative units instead of fixed tall panels. Let playfields scale down on smaller cards rather than overflowing; anything outside the card edges is cut off. The SDK exports \`CARD_RATIO\` (= 5 / 7) if you need the exact ratio.
153
+ - **Hand-rolled \`<canvas>\` elements must account for devicePixelRatio, or the game looks blurry on phones.** Size the backing store to the CSS layout size times \`devicePixelRatio\` (e.g. \`canvas.width = rect.width * dpr\`), keep the CSS width/height as the layout size, and scale the 2D context (\`ctx.scale(dpr, dpr)\`) so drawing code stays in CSS units — re-apply on resize. Kit decks don't need to do this by hand; the kit's engine already configures its canvas for DPR.
154
+ - Exception: deliberate pixel art wants a fixed low-resolution backing store with \`image-rendering: pixelated\` CSS instead — don't DPR-scale that; the crisp chunky look is the point.
155
+ `;
156
+ export function platformGuide(deckDir) {
157
+ return `${COMMON_SECTIONS.trimEnd()}
158
+
159
+ ## Formats, reloading, editors
160
+
161
+ ${everyDeckBullets(deckDir).join('\n')}
162
+ `;
163
+ }
164
+ function platformDoc(deckDir) {
165
+ return `# Castle platform
166
+
167
+ How every Castle deck works, from the Castle CLI. Written fresh at every serve
168
+ start; the deck's own guide (its kit's CLAUDE.md under imports/) adds what its
169
+ kit provides on top of this.
170
+
171
+ ${platformGuide(deckDir)}`;
172
+ }
173
+ // Written by the serve at every start, so the copy in a deck is exactly as
174
+ // fresh as the CLI serving it.
175
+ export function writePlatformDocs(deckDir) {
176
+ fs.mkdirSync(path.join(deckDir, PLATFORM_DOCS_DIR), { recursive: true });
177
+ fs.writeFileSync(path.join(deckDir, PLATFORM_DOC_REL), platformDoc(deckDir));
178
+ }
179
+ // What the deck's root CLAUDE.md carries for the platform: one @import line
180
+ // (which claude auto-loads) inside a short section that says what it is, for
181
+ // the agents that read the file as plain text.
182
+ export const CLAUDE_MD_IMPORT_LINE = `@${PLATFORM_DOC_REL}`;
183
+ export const CLAUDE_MD_PLATFORM_SECTION = `## Platform
184
+
185
+ The rules every Castle deck plays by -- the card and touch, assets and
186
+ formats, imports, reloading, editors -- are the Castle CLI's, not this deck's.
187
+ The serve writes them fresh at every start to \`${PLATFORM_DOC_REL}\`, loaded here:
188
+
189
+ ${CLAUDE_MD_IMPORT_LINE}
190
+ `;
191
+ // ---------------------------------------------------------------- migration
192
+ // Every version of the "(every deck)" sections that `init` ever appended to a
193
+ // deck's CLAUDE.md (COMMON_INSTRUCTIONS, 2026-07 to 2026-08), as sha256 of the
194
+ // trimmed section. A deck whose sections all match one of these carried the
195
+ // platform text untouched, and the serve may replace them with the @import;
196
+ // any other section body is the deck's own and is left exactly as it is.
197
+ const LEGACY_SECTION_HASHES = new Set([
198
+ '0b7db63866c07f8346201493c45fab2ca3419f1502456dffd00a833024bc3d47', // ## Assets (every deck) @ e11bd8c
199
+ '6500b701989fb6b4dd0c2b09c7b3d38f189480c5fa7148563af894098609d5cb', // ## Castle rules (every deck) @ 289055f
200
+ '44ec1f1565f6be49f914bb7513bab37acc18ddfcb24c4d91f447a7b157d6d477', // ## Fit the card (every deck) @ 8552d0e
201
+ '97913fb5e98d7707a78db22927e8fc4a06cae8393cfdd6c61880aa100498356b', // ## Fit the card (every deck) @ 31e6897
202
+ '8a03a1826d10ba2e37ac3fc2aadc3a478051b125abf98f33073e2314e32eeae1', // ## Imports are read-only (every deck) @ 1b94488
203
+ 'daf5c57e0b14bde423efaa5c30f6f4531743be13293639b9085c14e4da0689f3', // ## Imports are read-only (every deck) @ f2d8a41
204
+ '78f0dc79715876bfb4b3b9f5f0a5469ecf8b424d995680ef28a8454293a2ff84', // ## Imports are read-only (every deck) @ 7e4a9f9
205
+ '0ae557e6602d9a03c71f45ed7516bc4808c8d166c5023512c0e6d68254704f85', // ## Touch controls (every deck) @ c9c749f
206
+ '132f2c4c13685d17cb45d775c2cce55dfbc54c79d8f9821eaea8e147567592b9', // ## Touch controls (every deck) @ bc5fbe0
207
+ ]);
208
+ const LEGACY_HEADING = /^## .*\(every deck\)\s*$/m;
209
+ const hash = (s) => crypto.createHash('sha256').update(s.trim()).digest('hex');
210
+ // Move an existing deck's root CLAUDE.md onto the @import: remove the legacy
211
+ // sections when every one of them is byte-for-byte a version this CLI shipped,
212
+ // then append the platform section. Text outside those sections is never
213
+ // touched, and a section anyone edited keeps the whole file as it is ('kept'
214
+ // -- the deck chose its text; the prompt-side block still reaches spawned
215
+ // agents). A file with no legacy sections at all just gains the section.
216
+ export function migrateClaudeMd(deckDir) {
217
+ if (!mayMigrateClaudeMd())
218
+ return 'gated';
219
+ const claudePath = path.join(deckDir, 'CLAUDE.md');
220
+ let md;
221
+ try {
222
+ md = fs.readFileSync(claudePath, 'utf8');
223
+ }
224
+ catch {
225
+ return 'absent';
226
+ }
227
+ if (md.includes(CLAUDE_MD_IMPORT_LINE))
228
+ return 'current';
229
+ const parts = md.split(/(?=^## )/m);
230
+ const legacy = parts.filter((p) => LEGACY_HEADING.test(p.split('\n')[0]));
231
+ if (legacy.some((p) => !LEGACY_SECTION_HASHES.has(hash(p))))
232
+ return 'kept';
233
+ const rest = parts.filter((p) => !legacy.includes(p)).join('').trimEnd();
234
+ fs.writeFileSync(claudePath, `${rest}\n\n${CLAUDE_MD_PLATFORM_SECTION}`);
235
+ return legacy.length ? 'migrated' : 'added';
236
+ }
package/dist/serve.d.ts CHANGED
@@ -1,5 +1,8 @@
1
+ import * as http from 'http';
1
2
  export declare function appendCapped(file: string, line: string): void;
3
+ export declare function isViteClientUpgrade(req: http.IncomingMessage): boolean;
2
4
  export declare function isAllowedShellHost(hostHeader: string | undefined, configuredHost?: string): boolean;
5
+ export declare function isAllowedContentFilesRequest(role: 'edit' | 'play' | null, method: string | undefined, reqPath: string): boolean;
3
6
  export declare function serve(dir: string, options?: {
4
7
  port?: string;
5
8
  host?: string;
package/dist/serve.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import * as fs from 'fs';
2
+ import * as http from 'http';
2
3
  import * as net from 'net';
3
4
  import * as path from 'path';
4
5
  import { spawn } from 'child_process';
5
- import { createServer, } from 'vite';
6
+ import { createServer as createViteServer, } from 'vite';
6
7
  import { WebSocketServer, WebSocket } from 'ws';
7
8
  import { isIP } from 'net';
8
9
  import { createIdeServer, FAVICON_FILES, FAVICON_LINK_TAGS } from './ide.js';
@@ -10,11 +11,13 @@ import { createAgentServer } from './agent.js';
10
11
  import { sceneFilesPlugin, importsAliasPlugin, forksOverlayPlugin } from './vitePlugins.js';
11
12
  import { installFilesChangedWatcher } from './filesChanged.js';
12
13
  import { autoUpdateImports, IMPORTS_DIR, lockImportTree } from './imports.js';
14
+ import { ensureAgentsSymlink } from './init.js';
15
+ import { migrateClaudeMd, PLATFORM_DOC_REL, writePlatformDocs } from './platformDoc.js';
13
16
  import { FORKS_DIR, ownForkFile, splitImportRel } from './forks.js';
14
17
  import * as config from './config.js';
15
18
  import { graphql as castleGraphql } from './api.js';
16
19
  import { executeCommand } from './castle-host/host.js';
17
- import { ServeSecurity } from './serveSecurity.js';
20
+ import { ServeSecurity, } from './serveSecurity.js';
18
21
  import { isSameOriginUpgrade } from './wsOrigin.js';
19
22
  // The log is a tail, not an archive: append, and once it passes the cap drop
20
23
  // whole lines off the front until it is back under.
@@ -51,6 +54,110 @@ async function findFreePorts(startPort) {
51
54
  }
52
55
  throw new Error(`No free port pair found starting from ${startPort}`);
53
56
  }
57
+ async function findLocalContentPorts(startPort, reserved) {
58
+ const free = [];
59
+ for (let port = startPort; port < startPort + 100 && free.length < 2; port++) {
60
+ if (!reserved.has(port) && (await isPortFree(port)))
61
+ free.push(port);
62
+ }
63
+ if (free.length !== 2)
64
+ throw new Error(`No free local content ports found from ${startPort}`);
65
+ return { edit: free[0], play: free[1] };
66
+ }
67
+ function listenLocalContentServer(upstreamHost, upstreamPort, port, role, security) {
68
+ const upstreamHeaders = (req) => ({
69
+ ...req.headers,
70
+ ...security.localContentProxyHeaders(role),
71
+ host: `localhost:${upstreamPort}`,
72
+ });
73
+ const server = http.createServer((req, res) => {
74
+ const upstream = http.request({
75
+ hostname: upstreamHost,
76
+ port: upstreamPort,
77
+ method: req.method,
78
+ path: req.url,
79
+ headers: upstreamHeaders(req),
80
+ }, (upstreamRes) => {
81
+ res.writeHead(upstreamRes.statusCode || 502, upstreamRes.headers);
82
+ upstreamRes.pipe(res);
83
+ });
84
+ upstream.on('error', () => {
85
+ if (!res.headersSent)
86
+ res.writeHead(502);
87
+ res.end('local content upstream unavailable');
88
+ });
89
+ req.pipe(upstream);
90
+ });
91
+ server.on('upgrade', (req, socket, head) => {
92
+ if (!isViteClientUpgrade(req)) {
93
+ socket.destroy();
94
+ return;
95
+ }
96
+ proxyViteClientUpgrade(req, socket, head, upstreamHost, upstreamPort, upstreamHeaders(req));
97
+ });
98
+ return new Promise((resolve, reject) => {
99
+ server.once('error', reject);
100
+ server.listen(port, '127.0.0.1', () => {
101
+ server.off('error', reject);
102
+ resolve(server);
103
+ });
104
+ });
105
+ }
106
+ function proxyViteClientUpgrade(req, socket, head, upstreamHost, upstreamPort, headers) {
107
+ const upstream = http.request({
108
+ hostname: upstreamHost,
109
+ port: upstreamPort,
110
+ method: req.method,
111
+ path: req.url,
112
+ headers,
113
+ });
114
+ upstream.on('upgrade', (response, upstreamSocket, upstreamHead) => {
115
+ const responseHeaders = [];
116
+ for (let i = 0; i < response.rawHeaders.length; i += 2) {
117
+ responseHeaders.push(`${response.rawHeaders[i]}: ${response.rawHeaders[i + 1]}`);
118
+ }
119
+ socket.write(`HTTP/1.1 ${response.statusCode || 101} ${response.statusMessage || 'Switching Protocols'}\r\n${responseHeaders.join('\r\n')}\r\n\r\n`);
120
+ if (upstreamHead.length)
121
+ socket.write(upstreamHead);
122
+ if (head.length)
123
+ upstreamSocket.write(head);
124
+ socket.pipe(upstreamSocket).pipe(socket);
125
+ });
126
+ upstream.on('response', (response) => {
127
+ socket.write(`HTTP/1.1 ${response.statusCode || 502} ${response.statusMessage || ''}\r\n\r\n`);
128
+ response.pipe(socket);
129
+ });
130
+ upstream.on('error', () => socket.destroy());
131
+ upstream.end();
132
+ }
133
+ export function isViteClientUpgrade(req) {
134
+ const protocol = req.headers['sec-websocket-protocol'];
135
+ if (protocol !== 'vite-hmr' && protocol !== 'vite-ping')
136
+ return false;
137
+ try {
138
+ return new URL(req.url || '/', 'http://localhost').pathname === '/';
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ }
144
+ async function startLocalContentServers(upstreamHost, upstreamPort, ports, security) {
145
+ const servers = [];
146
+ try {
147
+ for (const [role, port] of [
148
+ ['edit', ports.edit],
149
+ ['play', ports.play],
150
+ ]) {
151
+ servers.push(await listenLocalContentServer(upstreamHost, upstreamPort, port, role, security));
152
+ }
153
+ return servers;
154
+ }
155
+ catch (error) {
156
+ for (const server of servers)
157
+ server.close();
158
+ throw error;
159
+ }
160
+ }
54
161
  // Injected into the deck iframe (only when it carries `?logs=1`, i.e. the
55
162
  // editor's builtin Play panel) to forward the deck's console output to the
56
163
  // shell via postMessage, where the builtin Play panel renders a logs drawer.
@@ -100,6 +207,16 @@ export function isAllowedShellHost(hostHeader, configuredHost) {
100
207
  const configured = configuredHost ? hostnameFromHeader(configuredHost) : '';
101
208
  return configured !== '' && configured !== '0.0.0.0' && configured !== '::' && host === configured;
102
209
  }
210
+ const EDIT_CONTENT_READ_ENDPOINTS = new Set([
211
+ '/__castle/files/raw',
212
+ '/__castle/files/read',
213
+ '/__castle/files/info',
214
+ '/__castle/files/list',
215
+ '/__castle/files/forks',
216
+ ]);
217
+ export function isAllowedContentFilesRequest(role, method, reqPath) {
218
+ return role === 'edit' && method === 'GET' && EDIT_CONTENT_READ_ENDPOINTS.has(reqPath);
219
+ }
103
220
  function castlePlugin(security, ideServer, agentServer, configuredHost) {
104
221
  return {
105
222
  name: 'castle-dev',
@@ -162,14 +279,14 @@ window.__castleShellOrigin=(function(){
162
279
  if (content) {
163
280
  if (reqPath === '/')
164
281
  req.url = `/index.html${req.url?.includes('?') ? req.url.slice(req.url.indexOf('?')) : ''}`;
165
- const allowedRaw = verifiedRole === 'edit' && reqPath === '/__castle/files/raw';
282
+ const allowedFilesRequest = isAllowedContentFilesRequest(verifiedRole, req.method, reqPath);
166
283
  const allowedVendor = reqPath.startsWith('/__castle/vendor/');
167
284
  const allowedFavicon = FAVICON_FILES.some((name) => reqPath === `/${name}`);
168
- if (reqPath.startsWith('/__castle/') && !allowedRaw && !allowedVendor) {
285
+ if (reqPath.startsWith('/__castle/') && !allowedFilesRequest && !allowedVendor) {
169
286
  res.writeHead(403).end('content capability does not allow this endpoint');
170
287
  return;
171
288
  }
172
- if ((allowedRaw || allowedVendor || allowedFavicon) && ideServer.handleHttpRequest(req, res, reqPath))
289
+ if ((allowedFilesRequest || allowedVendor || allowedFavicon) && ideServer.handleHttpRequest(req, res, reqPath))
173
290
  return;
174
291
  next();
175
292
  return;
@@ -392,20 +509,27 @@ export async function serve(dir, options = {}) {
392
509
  const { port, wsPort } = options.port
393
510
  ? { port: startPort, wsPort: startPort + 1 }
394
511
  : await findFreePorts(startPort);
395
- const security = new ServeSecurity(port);
512
+ const localContentPorts = await findLocalContentPorts(port + 2, new Set([port, wsPort]));
513
+ const security = new ServeSecurity(port, localContentPorts);
396
514
  // Local WebSocket server for SDK communication
397
515
  const castleDir = path.join(projectDir, '.castle');
398
516
  if (!fs.existsSync(castleDir))
399
517
  fs.mkdirSync(castleDir, { recursive: true });
518
+ // The platform guide, fresh from this CLI, and the root CLAUDE.md's @import
519
+ // of it (platformDoc.ts). After autoUpdateImports, so the guide's media list
520
+ // sees the imports this serve will run with.
521
+ writePlatformDocs(projectDir);
522
+ const migration = migrateClaudeMd(projectDir);
523
+ ensureAgentsSymlink(projectDir);
524
+ if (migration === 'migrated' || migration === 'added') {
525
+ console.log(`CLAUDE.md now loads the platform guide from ${PLATFORM_DOC_REL}`);
526
+ }
527
+ else if (migration === 'kept') {
528
+ console.log(`CLAUDE.md has hand-edited platform sections; left as they are (the platform guide is at ${PLATFORM_DOC_REL})`);
529
+ }
400
530
  const logFile = path.join(castleDir, 'logs.txt');
401
531
  const screenshotsDir = path.join(castleDir, 'screenshots');
402
532
  const serveJsonPath = path.join(castleDir, 'serve.json');
403
- fs.writeFileSync(serveJsonPath, JSON.stringify({
404
- port,
405
- wsPort,
406
- pid: process.pid,
407
- contentPlayUrl: security.localContentOrigin('play'),
408
- }) + '\n');
409
533
  process.on('exit', () => {
410
534
  try {
411
535
  fs.unlinkSync(serveJsonPath);
@@ -465,7 +589,7 @@ export async function serve(dir, options = {}) {
465
589
  authorizeUpgrade: (req) => security.consumeTicket(req, 'agent'),
466
590
  });
467
591
  process.on('exit', () => agentServer.shutdown());
468
- const vite = await createServer({
592
+ const vite = await createViteServer({
469
593
  root: projectDir,
470
594
  plugins: [
471
595
  castlePlugin(security, ideServer, agentServer, options.host),
@@ -506,7 +630,27 @@ export async function serve(dir, options = {}) {
506
630
  invalidate: (paths) => invalidateModuleCaches(vite, paths),
507
631
  log: (line) => appendCapped(logFile, line),
508
632
  });
633
+ // Bring content up first so `--open` cannot race an iframe against a port
634
+ // that is not listening yet. Vite opens the shell from inside `vite.listen()`.
635
+ const upstreamHost = !options.host || options.host === 'localhost'
636
+ ? 'localhost'
637
+ : options.host === '0.0.0.0'
638
+ ? '127.0.0.1'
639
+ : options.host === '::'
640
+ ? '::1'
641
+ : options.host;
642
+ const localContentServers = await startLocalContentServers(upstreamHost, port, localContentPorts, security);
643
+ process.on('exit', () => {
644
+ for (const server of localContentServers)
645
+ server.close();
646
+ });
509
647
  await vite.listen();
648
+ fs.writeFileSync(serveJsonPath, JSON.stringify({
649
+ port,
650
+ wsPort,
651
+ pid: process.pid,
652
+ contentPlayUrl: security.localContentOrigin('play'),
653
+ }) + '\n');
510
654
  // The PTY WebSocket upgrade is handled directly on Vite's HTTP server rather
511
655
  // than through Vite's proxy (Vite's ws proxy didn't forward this path).
512
656
  if (vite.httpServer) {
@@ -1,6 +1,7 @@
1
1
  import type * as http from 'http';
2
2
  export type ContentRole = 'edit' | 'play';
3
3
  export type SocketEndpoint = 'serve' | 'pty' | 'agent';
4
+ export type LocalContentPorts = Record<ContentRole, number>;
4
5
  export declare function mintContentGrantLabel(grant: {
5
6
  role: ContentRole;
6
7
  publicPort: number;
@@ -10,11 +11,13 @@ export declare function mintContentGrantLabel(grant: {
10
11
  }, signingKey: string): string;
11
12
  export declare class ServeSecurity {
12
13
  private readonly publicPort;
14
+ private readonly localContentPorts;
13
15
  readonly serveToken: string;
16
+ private readonly contentProxyToken;
14
17
  private readonly signingKey;
15
18
  private readonly serveNonce;
16
19
  private readonly tickets;
17
- constructor(publicPort: number);
20
+ constructor(publicPort: number, localContentPorts?: LocalContentPorts);
18
21
  authorizeHttp(req: http.IncomingMessage): boolean;
19
22
  issueTicket(endpoint: SocketEndpoint): string;
20
23
  consumeTicket(req: http.IncomingMessage, endpoint: SocketEndpoint): boolean;
@@ -25,6 +28,7 @@ export declare class ServeSecurity {
25
28
  playOrigin: string;
26
29
  };
27
30
  localContentOrigin(role: ContentRole): string;
31
+ localContentProxyHeaders(role: ContentRole): Record<string, string>;
28
32
  verifyContentRequest(req: http.IncomingMessage): ContentRole | null;
29
33
  shellOrigin(req: http.IncomingMessage): string;
30
34
  private mintContentLabel;
@@ -49,12 +49,18 @@ export function mintContentGrantLabel(grant, signingKey) {
49
49
  }
50
50
  export class ServeSecurity {
51
51
  publicPort;
52
+ localContentPorts;
52
53
  serveToken = randomBytes(32).toString('base64url');
54
+ contentProxyToken = randomBytes(32).toString('base64url');
53
55
  signingKey = process.env.CASTLE_AGENT_TOKEN || randomBytes(32).toString('base64url');
54
56
  serveNonce = base32Lower(randomBytes(8));
55
57
  tickets = new Map();
56
- constructor(publicPort) {
58
+ constructor(publicPort, localContentPorts = {
59
+ edit: publicPort + 2,
60
+ play: publicPort + 3,
61
+ }) {
57
62
  this.publicPort = publicPort;
63
+ this.localContentPorts = localContentPorts;
58
64
  }
59
65
  authorizeHttp(req) {
60
66
  const value = req.headers['x-castle-serve-token'];
@@ -138,24 +144,37 @@ window.fetch=function(input,init){
138
144
  ? 'sandboxes-staging.castlexyz.com'
139
145
  : cloud
140
146
  ? 'sandboxes.castlexyz.com'
141
- : 'localhost';
147
+ : null;
142
148
  // Leave room for small positive clock skew at the control plane. Ghost still
143
149
  // enforces the hard 12-hour maximum when it resolves the capability.
144
150
  const expiresAtSeconds = Math.floor(Date.now() / 1000) + MAX_GRANT_SECONDS - GRANT_CLOCK_SKEW_SECONDS;
145
151
  const originFor = (role) => {
152
+ // Safari on macOS 15 asks DNS to resolve `*.localhost`, where it fails.
153
+ // Dedicated loopback ports are still distinct browser origins and need no DNS.
154
+ if (!cloud || !contentDomain)
155
+ return this.localContentOrigin(role);
146
156
  const label = this.mintContentLabel(role, sandboxId, expiresAtSeconds);
147
- return cloud
148
- ? `https://${label}.${contentDomain}`
149
- : `${requestOrigin(req).split('://')[0]}://${label}.localhost:${this.publicPort}`;
157
+ return `https://${label}.${contentDomain}`;
150
158
  };
151
159
  return { editOrigin: originFor('edit'), playOrigin: originFor('play') };
152
160
  }
153
161
  localContentOrigin(role) {
154
- const expiresAtSeconds = Math.floor(Date.now() / 1000) + MAX_GRANT_SECONDS - GRANT_CLOCK_SKEW_SECONDS;
155
- const label = this.mintContentLabel(role, 'localdev000000', expiresAtSeconds);
156
- return `http://${label}.localhost:${this.publicPort}`;
162
+ return `http://127.0.0.1:${this.localContentPorts[role]}`;
163
+ }
164
+ localContentProxyHeaders(role) {
165
+ return {
166
+ 'x-castle-content-role': role,
167
+ 'x-castle-content-proxy-token': this.contentProxyToken,
168
+ };
157
169
  }
158
170
  verifyContentRequest(req) {
171
+ const proxyRole = req.headers['x-castle-content-role'];
172
+ const proxyToken = req.headers['x-castle-content-proxy-token'];
173
+ if ((proxyRole === 'edit' || proxyRole === 'play') &&
174
+ typeof proxyToken === 'string' &&
175
+ safeEqual(proxyToken, this.contentProxyToken)) {
176
+ return proxyRole;
177
+ }
159
178
  const host = hostWithoutPort(req.headers.host || '');
160
179
  const label = host.split('.')[0];
161
180
  const match = CONTENT_LABEL_RE.exec(label);