castle-web-cli 0.4.194 → 0.4.196

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 (42) hide show
  1. package/dist/agent-prompts.d.ts +1 -0
  2. package/dist/agent-prompts.js +14 -5
  3. package/dist/agent.js +60 -1
  4. package/dist/castleJson.d.ts +0 -2
  5. package/dist/castleJson.js +0 -39
  6. package/dist/devSessionFrameBudget.d.ts +14 -0
  7. package/dist/devSessionFrameBudget.js +64 -0
  8. package/dist/devSessionServer.js +15 -0
  9. package/dist/editorConfig.d.ts +1 -1
  10. package/dist/editorConfig.js +12 -4
  11. package/dist/ide.js +28 -59
  12. package/dist/imports.js +2 -4
  13. package/dist/init.js +9 -8
  14. package/dist/multiplayerDoc.d.ts +1 -0
  15. package/dist/multiplayerDoc.js +228 -0
  16. package/dist/platformDoc.d.ts +1 -0
  17. package/dist/platformDoc.js +21 -2
  18. package/dist/scriptErrors.d.ts +23 -0
  19. package/dist/scriptErrors.js +147 -0
  20. package/dist/serve.js +233 -4
  21. package/dist/shell/assets/index-kMH1qj6D.js +449 -0
  22. package/dist/shell/index.html +1 -1
  23. package/dist/viteClientStub.d.ts +18 -0
  24. package/dist/viteClientStub.js +193 -0
  25. package/kits/base/CLAUDE.md +3 -3
  26. package/kits/base/castle.json +1 -3
  27. package/kits/base/sdk/README.md +17 -0
  28. package/kits/multiplayer-2d/castle.json +0 -9
  29. package/kits/multiplayer-3d/castle.json +0 -8
  30. package/kits/physics-2d/CLAUDE.md +5 -6
  31. package/kits/physics-2d/castle.json +1 -11
  32. package/kits/physics-2d/editors/SceneEditor.jsx +42 -3
  33. package/kits/physics-2d/editors/behaviorRegistry.js +8 -2
  34. package/kits/physics-2d/engine/ErrorOverlay.jsx +69 -0
  35. package/kits/physics-2d/engine/ScenePlayer.jsx +2 -67
  36. package/kits/physics-2d/engine/liveReload.js +5 -4
  37. package/kits/physics-3d/castle.json +0 -11
  38. package/kits/real-time/castle.json +0 -6
  39. package/kits/turn-based/CLAUDE.md +6 -3
  40. package/kits/turn-based/castle.json +1 -14
  41. package/package.json +1 -1
  42. package/dist/shell/assets/index-ColHKJYj.js +0 -449
@@ -87,6 +87,7 @@ export interface RouterPromptOpts {
87
87
  tasks: PromptTask[];
88
88
  plan?: RouterPlanOpts;
89
89
  playtest?: boolean;
90
+ editorTabs?: string[];
90
91
  instruction: string;
91
92
  }
92
93
  export declare function buildRouterPromptParts(opts: RouterPromptOpts): RouterPromptParts;
@@ -29,11 +29,13 @@ function baseRouterRules(playtest) {
29
29
 
30
30
  What a deck is: a normal web project served by vite -- index.html plus plain JS/JSX modules, with real npm dependencies (more can be installed), the castle-web-sdk package, and usually a kit framework whose engine, behaviors, scenes, editors, and drawings are ordinary files in this directory. The web platform is fully available (DOM, canvas, npm libraries like react, three, etc.). The deck's Quick reference and file list below describe its setup; the full CLAUDE.md / AGENTS.md has deeper detail. NEVER claim something is impossible or unsupported on the platform without checking that context (or, for specifics it doesn't cover, the deck's files) first.
31
31
 
32
+ What the user sees beside this chat: Castle's own panels -- Play, Files, Parameters, Terminal, and this chat -- plus a tab for each file they open. Those panels belong to Castle, and nothing in the deck can change them. A file's tab is different: unless it is the plain code view, it is an EDITOR, an ordinary module that comes from the deck or its kit (this deck's are listed under == editor tabs ==). Users name one by its label ("the <label> tab") or just say "this tab", and they mean that editor, not Castle. When they ask whether a tab can do something it doesn't do yet, or whether it can be changed at all, the answer is yes: a task forks the kit's editor into the deck and changes that copy (see the imports rule below), or gives a new file type an editor of its own. Never tell the user a file's tab is part of Castle.
33
+
32
34
  Hard rules:
33
35
  - You NEVER edit files or run state-changing commands. All building and fixing happens through background task agents -- always hand the longer work to them.
34
36
  - IMPORTS ARE YOURS, and they are the one exception to the rule above. Run \`castle-web list-decks --kind kits\` (also \`mine\` and \`saved\`) to see what this deck can import, and \`castle-web add-import <deckIdOrUrl>\` to add one -- both directly, not through a task. Do NOT claim you can list or import anything until you have actually run these; do not describe imports you have not looked at. \`list-decks\` prints one deck per line starting with the id \`add-import\` takes, and marks the ones this deck already has. A pasted castle.xyz deck link works in place of an id. Everything else about a deck's files still goes to task agents.
35
- - Imported files are READ-ONLY, which is what to say when the user asks whether they can change something a kit or another import gave them, or why an edit to one did not stick: the deck takes its own version of that one file -- a fork, stored beside the import and used in its place -- and that version is what runs. Forking is how their own data and code changes override an import's, and a task agent does it; the tradeoff, worth saying plainly, is that a file done this way stops picking up changes when the import itself is updated, so it stays to the few files the change actually needs. Often it does not come to a fork at all, which is the better thing to say first: a kit picks up the deck's own behaviors and systems, so new logic is usually just a new file in the deck.
36
- - You are the fast lane: get to your final reply as quickly as possible. When the user reports something broken, do NOT dig into the code to diagnose it first -- spawn a task whose job is to investigate AND fix it. Only read deck files when your reply itself needs them (answering a question about the deck, grounding a claim -- never make things up); never read as pre-work before spawning a task, and never read files just to learn conventions already covered by the Quick reference.${playtest ? `\n${PLAYTEST_ROUTER_RULE}` : ""}
37
+ - Imported files are READ-ONLY, which is what to say when the user asks whether they can change something a kit or another import gave them (an editor tab included), or why an edit to one did not stick: the deck takes its own version of that one file -- a fork, stored beside the import and used in its place -- and that version is what runs. Forking is how their own data and code changes override an import's, and a task agent does it; the tradeoff, worth saying plainly, is that a file done this way stops picking up changes when the import itself is updated, so it stays to the few files the change actually needs. Often it does not come to a fork at all, which is the better thing to say first: a kit picks up the deck's own behaviors and systems, so new logic is usually just a new file in the deck.
38
+ - You are the fast lane: get to your final reply as quickly as possible. When the user reports something broken, do NOT dig into the code to diagnose it first -- spawn a task whose job is to investigate AND fix it. A QUESTION is not a fix request: "why is X happening?" gets a task told explicitly to diagnose and CHANGE NOTHING, and your reply says that it will only look and report back. Only read deck files when your reply itself needs them (answering a question about the deck, grounding a claim -- never make things up); never read as pre-work before spawning a task, and never read files just to learn conventions already covered by the Quick reference.${playtest ? `\n${PLAYTEST_ROUTER_RULE}` : ""}
37
39
  - When you point the user at a file, a line, or a tunable value, write it as a link they can tap: \`[label](game.js)\` for a file, \`[label](game.js#L108)\` for a line, \`[label](game.js#params)\` for a file's tunable values and \`[label](game.js#params:enemySpeed)\` for ONE of them (the key exactly as it is written in that file's \`PARAMS\` object -- \`player.speed\` for a nested one). The label is your own words for the thing; the path must be exact and must be a file this deck actually has, or it renders as plain text. A bare \`game.js#108\` in a sentence links too. Cite a line number ONLY when you have read that file with numbered lines -- any deck contents in this prompt carry none, so never count them yourself; link the file or its params instead when you are unsure.
38
40
  - Launch a SET of small steps the user tests one by one -- a pipeline, never one big task they wait on, never untestable fragments. One interacting mechanic = one task (paddle + ball + bricks = one playable core, not three). First step = the smallest genuinely playable thing; later steps build it out. Match breadth to ambition ("basic" = a few steps; "go wild" = many). You're optimizing the user's taste and feedback -- more small testable steps = more points where they steer it into something theirs.
39
41
  - The whole goal: every piece of work TESTABLE in actual gameplay ASAP. Start every task as early as possible and run them in PARALLEL. Do NOT break tasks down by which files they touch, and never add \`after:\` just to avoid two tasks editing the same file -- tasks make surgical edits and overlap fine. The only real dependency between tasks is INFORMATION: a task is blocked only when it needs a fact it does not yet have.
@@ -70,7 +72,7 @@ comma-separated active-task titles or ids, or \`all\`
70
72
  - Never claim the board is cleared without actually emitting the fence.
71
73
  - Tasks are one-and-done -- when the user gives feedback on a finished task, spawn a new fix task (and \`castle-done\` the old row) rather than reopening it.
72
74
  - Task agents are capable coding agents working in this same deck directory, but they know nothing about this conversation beyond your prompt.
73
- - The deck keeps its own version history, and you may READ it: \`castle-web list-versions\` shows the versions newest first, and \`castle-web show-version <id>\` shows what one changed, as diffs of just those files. Use them to answer "what changed" or to ground a claim about recent work. You NEVER run \`save-version\` -- you did not make the changes, so a version of yours would not correspond to a unit of work -- and you NEVER run \`restore-version\`: going back is the user's own decision, not something you do on their behalf.
75
+ - The deck keeps its own version history, and you may READ it: \`castle-web list-versions\` shows the versions newest first, and \`castle-web show-version <id>\` shows what one changed, as diffs of just those files. Use them to answer "what changed" or to ground a claim about recent work. You NEVER run \`save-version\` -- you did not make the changes, so a version of yours would not correspond to a unit of work -- and you NEVER run \`restore-version\`: going back is the user's own decision, not something you do on their behalf. For the same reason, no task you spawn may ever revert, replace, or re-scaffold the deck's scenes, scripts, or behaviors back to kit or starter content -- a fix is always a targeted edit, and every task prompt you write has to be readable that way.
74
76
 
75
77
  Asking with options (the \`\`\`ask block). When you need the user to settle a few choices at once, emit ONE fenced block tagged \`ask\` containing JSON -- it renders inline in the chat as grouped options they tap and submit together (far better than stacking questions they can only half-answer). Reach for it to pin a direction fast when their ask is vague ("make me a game" -> ask what kind), NOT to interrogate.
76
78
 
@@ -87,6 +89,7 @@ Conversation style:
87
89
  - As short and focused as possible -- a few tight sentences. Concrete, energetic.
88
90
  - Plain, everyday language for a CREATOR who may not be a programmer. No dev or game-industry jargon -- not "greybox", "scaffold", "refactor", "wire up", "placeholder art", "core loop", etc. -- in ANYTHING the user sees, including task TITLES. Say what's happening simply ("a rough playable version first, then the real art"; "Player movement", "Enemies you can fight", "Real artwork"). Task titles read like plain to-do items a non-coder understands.
89
91
  - After spawning tasks, less is more -- but NEVER reply with only task directives: always include at least one short line of plain text saying what is being spun up. One tight sentence is plenty; the board shows the rest. Do NOT tack a follow-up question onto your replies by default; ask a question (at most one) only when you genuinely need the answer to proceed.
92
+ - When the user asks HOW to do something or to see an example, answer it yourself -- a couple of sentences, plus a short standalone snippet if it helps -- and do not spawn a task that drops a demo behavior or actor into their scene. Build it only when they want it in their game; if a task did add files, name each one and what it attached to so they can find and remove them.
90
93
  - Do not narrate before tool calls ("Checking the deck...") -- that reads as noise in the chat. Read silently, then give one reply after your final tool call.
91
94
  - The user sees a live task board above the chat -- never re-announce task status yourself.
92
95
  - Spawning a task does NOT apply the change -- tasks run for minutes and finish on the board. Talk about spawned work in future tense ("this will dial the shake back"), and NEVER ask how a change feels right after spawning it -- the user cannot have tried it yet. Save "how is it?" for things whose task already finished.
@@ -833,6 +836,9 @@ export function buildRouterPromptParts(opts) {
833
836
  const quickReference = opts.quickReference?.trim()
834
837
  ? `\n\n== how this deck works ==\n${opts.quickReference.trim()}`
835
838
  : `\n\n== how this deck works ==\n${NO_DECK_DOCS}`;
839
+ const editorTabs = opts.editorTabs?.length
840
+ ? `\n\n== editor tabs ==\n${opts.editorTabs.map((tab) => `- ${tab}`).join("\n")}`
841
+ : "";
836
842
  const deckFiles = opts.deckTree?.trim()
837
843
  ? `\n\n== deck files ==\n${opts.deckTree.trim()}`
838
844
  : "";
@@ -852,7 +858,7 @@ export function buildRouterPromptParts(opts) {
852
858
  system: `${routerRules(opts.plan !== undefined, opts.playtest === true)}
853
859
 
854
860
  == deck ==
855
- ${opts.deckLabel}${quickReference}${deckFiles}`,
861
+ ${opts.deckLabel}${quickReference}${editorTabs}${deckFiles}`,
856
862
  user: `== conversation so far ==
857
863
  ${renderTranscript(opts.messages)}${plan}
858
864
 
@@ -958,7 +964,8 @@ Operating rules:
958
964
  - Speed is of the essence -- go for the quickest viable, testable change, unless this prompt explicitly tells you to take longer and dive deep. It must still amount to at least one meaningful step up (one or a few features, pieces of art, etc.), never a token gesture.
959
965
  - The USER is the verifier -- the whole tasks system exists so the user playtests every change themselves. Your first priority is to finish as soon as possible with the change genuinely in place and reachable in the running deck, so the user can test it right away. Do NOT run verification (screenshots especially) unless ${opts.playtest ? "this task's brief asks for it or " : ""}you are really sure it will catch something a re-read of your own change cannot -- and even then at most one cheap check, never a retry loop. Time spent verifying is time the user is left waiting.
960
966
  - The moment implementation is complete and you switch to verifying, write 90 to the progress file -- verification time must not read as stalled progress.
961
- - Do this one task completely, then stop. Do not expand scope.${planRules}
967
+ - Do this one task completely, then stop. Do not expand scope.
968
+ - If the task is to SHOW HOW something is done or to give an example, answer it -- in your streamed output and notes, with a standalone snippet if that helps -- and do NOT insert a demo behavior, blueprint, or actor into their scene; that only happens when the user asked for it in their game. Anything you did add to a scene must be named in your notes by file path and by the actor or blueprint it attached to, so they can find it and take it out.${planRules}
962
969
  - SAVE A VERSION when your change is done, so the user can see and undo it: \`castle-web save-version -m "<short description of what you changed>" <each path you touched>\`. Name those paths explicitly -- a bare \`save-version\` with no paths records the WHOLE deck, including files a sibling agent is still working on. One version for the whole task, at the end; not one per file.
963
970
  - Overlap with the other agents working in this deck is fine and expected -- do not try to avoid it or wait for them. Saving only your own paths is all that is asked of you; nothing anyone has written is lost by your save.
964
971
  - NEVER run \`restore-version\`. Going back to an earlier version is the user's decision alone -- not yours, not even to undo your own work. If your change is wrong, fix it forward.
@@ -977,6 +984,8 @@ Operating rules:
977
984
  - When a fork IS the way, prefer forking to open a SEAM: put a hook, registration, or override point in the forked file and keep the logic it calls in an ordinary deck file. Later changes then land in the deck instead of forcing more forks. Size that to the change though -- a one- or two-line tweak is just a direct edit to the fork; do not build an override system for it.
978
985
  - A forked file exists on disk TWICE, and reading or grepping finds both copies. \`forks/<alias>/<path>\` is the live one -- edit that one. \`imports/<alias>/<path>\` is the version the fork was taken from; it is what the deck used to run, not what it runs now, and writing to it just fails.
979
986
  - Other task agents may be editing this same deck IN PARALLEL. When you change an existing file, READ it first and make a targeted edit to just the part you need -- never overwrite a whole file you have not read. A blind full-file rewrite clobbers other agents' in-flight changes. Being a bit slower and careful here is the right tradeoff.
987
+ - NEVER revert, replace, or re-scaffold the deck's scenes, scripts, or behaviors back to kit, starter, or imported content, and never delete or rewrite a whole scene as a way to diagnose a problem -- that file IS the person's game, and a rewrite destroys work no one asked you to touch. A brief that asks you to investigate, diagnose, or explain is READ-ONLY: report what you found and change nothing unless the user asked for a fix.
988
+ - Before any change that overwrites or deletes MORE THAN ONE existing file of theirs, save a version first so they can restore: \`castle-web save-version -m "<what is about to change>" <those paths>\`. That is on top of the end-of-task version below, not instead of it.
980
989
  - How the code should read: decks get opened by strangers copying the pattern, so write for a first-time reader. Name things in words -- \`connection\`, not \`conn\`; \`runtime\`, not \`rt\`. A name that needs a comment to decode is the wrong name.
981
990
  - Order a file: data shapes first, then classes, then the functions over that data, so the reader meets the shape before the code that moves it.
982
991
  - Comments say what a thing IS and how the system works, declaratively. Not the case for a choice, not what the next line does -- and nothing at all when the code already says it.
package/dist/agent.js CHANGED
@@ -15,6 +15,7 @@
15
15
  // runAgentCli.
16
16
  import { execFileSync, spawn } from 'child_process';
17
17
  import { claudeContextEnv, quickReferenceFor } from './platformDoc.js';
18
+ import { resolveFileTypes } from './editorConfig.js';
18
19
  import { IMPORTS_DIR } from './imports.js';
19
20
  import { isSameOriginUpgrade } from './wsOrigin.js';
20
21
  import { resolveDeckPath } from './ide.js';
@@ -1857,10 +1858,55 @@ function writeTaskIndex(tasksDir, tasks) {
1857
1858
  // persisted "blocked" task is left as-is: it is not "waiting", so maybeStart
1858
1859
  // never reconsiders it and it can't wedge or auto-start; it just sits on the
1859
1860
  // board (blockedBy intact) until the router stops it, same as before restart.
1861
+ const TASK_STATUSES = ['waiting', 'running', 'blocked', 'done', 'failed', 'interrupted'];
1862
+ const TASK_OPTIONAL_STRINGS = [
1863
+ 'item', 'startedAt', 'finishedAt', 'originMessageId', 'resultSummary', 'errorCopy',
1864
+ 'errorDetail', 'avatar', 'phase', 'durable', 'what',
1865
+ ];
1866
+ const TASK_OPTIONAL_BOOLEANS = ['acknowledged', 'rejected', 'durablePending'];
1867
+ const TASK_OPTIONAL_STRING_LISTS = ['playtestFrames', 'files', 'knobs', 'blockedBy'];
1868
+ const isStringList = (v) => Array.isArray(v) && v.every((s) => typeof s === 'string');
1869
+ // tasks/ sits in the deck, where the agent (or anything else) can write, and a
1870
+ // record the store can't handle used to throw inside createTaskStore and take
1871
+ // the whole serve down -- the deck then couldn't be opened at all. A record
1872
+ // without its identity (id matching its directory, title, createdAt, a known
1873
+ // status) is skipped; anything else that is missing or the wrong type falls
1874
+ // back to its default or is dropped, which also keeps older minimal records.
1875
+ function normalizeLoadedTask(entry, raw) {
1876
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
1877
+ return null;
1878
+ const r = raw;
1879
+ if (r.id !== entry ||
1880
+ typeof r.title !== 'string' ||
1881
+ typeof r.createdAt !== 'string' ||
1882
+ !TASK_STATUSES.includes(r.status)) {
1883
+ return null;
1884
+ }
1885
+ const task = {
1886
+ ...r,
1887
+ prompt: typeof r.prompt === 'string' ? r.prompt : '',
1888
+ after: isStringList(r.after) ? r.after : [],
1889
+ progress: typeof r.progress === 'number' && Number.isFinite(r.progress) ? r.progress : 0,
1890
+ notes: typeof r.notes === 'string' ? r.notes : '',
1891
+ updatedAt: typeof r.updatedAt === 'string' ? r.updatedAt : r.createdAt,
1892
+ };
1893
+ if (typeof r.pid !== 'number')
1894
+ delete task.pid;
1895
+ for (const k of TASK_OPTIONAL_STRINGS)
1896
+ if (typeof r[k] !== 'string')
1897
+ delete task[k];
1898
+ for (const k of TASK_OPTIONAL_BOOLEANS)
1899
+ if (typeof r[k] !== 'boolean')
1900
+ delete task[k];
1901
+ for (const k of TASK_OPTIONAL_STRING_LISTS)
1902
+ if (!isStringList(r[k]))
1903
+ delete task[k];
1904
+ return task;
1905
+ }
1860
1906
  function loadTasks(tasksDir) {
1861
1907
  const tasks = new Map();
1862
1908
  for (const entry of fs.existsSync(tasksDir) ? fs.readdirSync(tasksDir) : []) {
1863
- const rec = readJsonFile(path.join(tasksDir, entry, 'task.json'));
1909
+ const rec = normalizeLoadedTask(entry, readJsonFile(path.join(tasksDir, entry, 'task.json')));
1864
1910
  if (!rec)
1865
1911
  continue;
1866
1912
  if (rec.status === 'running' || rec.status === 'waiting') {
@@ -2890,6 +2936,18 @@ function resolveFailure(result) {
2890
2936
  : 'exit';
2891
2937
  return { kind, detail: error ?? 'unknown failure' };
2892
2938
  }
2939
+ // Only a type with an editor opens in a tab of its own (editorClassInfo in the
2940
+ // shell), so that is the filter; types sharing a label share the tab.
2941
+ function editorTabsFor(deckDir) {
2942
+ const extsByLabel = new Map();
2943
+ for (const type of resolveFileTypes(deckDir) ?? []) {
2944
+ if (!type.editor || type.unsupported)
2945
+ continue;
2946
+ const label = type.label?.trim() || type.ext;
2947
+ extsByLabel.set(label, [...(extsByLabel.get(label) ?? []), type.ext]);
2948
+ }
2949
+ return [...extsByLabel].map(([label, exts]) => `${label} (${exts.join(', ')})`);
2950
+ }
2893
2951
  // Assemble the full stateless prompt for one router turn: rules + deck
2894
2952
  // context + transcript replay (minus log lines and the in-flight reply) +
2895
2953
  // the live board + this turn's instruction.
@@ -2897,6 +2955,7 @@ function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
2897
2955
  return buildRouterPromptParts({
2898
2956
  deckLabel: ctx.deckLabel,
2899
2957
  quickReference: quickReferenceFor(ctx.deckDir, ctx.quickReference, 'router'),
2958
+ editorTabs: editorTabsFor(ctx.deckDir),
2900
2959
  deckTree: buildDeckTree(ctx.deckDir),
2901
2960
  playtest: playtestSteering(),
2902
2961
  messages: ctx.log.messages
@@ -46,5 +46,3 @@ export declare const DEFAULT_MAIN = "main.jsx";
46
46
  export declare function deckMainFile(dir: string): string;
47
47
  export declare function readCastleJson(dir: string): CastleJson | null;
48
48
  export declare function readCastleJsonOrThrow(dir: string): CastleJson | null;
49
- export declare function ensureVisiblePath(deckDir: string, rel: string): boolean;
50
- export declare function ensureVisibleGlob(deckDir: string, glob: string, probe: string): boolean;
@@ -1,6 +1,5 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
- import picomatch from 'picomatch';
4
3
  // Where a deck's dependencies live, relative to its root. Defined here, in a
5
4
  // module with no imports of its own, because both the import machinery and the
6
5
  // fork overlay need it and importing it from either of those would close a
@@ -99,41 +98,3 @@ export function readCastleJsonOrThrow(dir) {
99
98
  throw new Error(`Could not read ${file}: ${e instanceof Error ? e.message : String(e)}`);
100
99
  });
101
100
  }
102
- // Add `<rel>/**` to the deck's editor.visiblePaths so files created in a
103
- // newly-made folder show in the curated Files tree.
104
- export function ensureVisiblePath(deckDir, rel) {
105
- return ensureVisibleGlob(deckDir, `${rel}/**`, `${rel}/__probe__`);
106
- }
107
- // Add `glob` to the deck's editor.visiblePaths. Only touches a deck that is
108
- // ALREADY curated (non-empty visiblePaths) -- when visiblePaths is empty
109
- // everything is visible, and adding a glob would wrongly start hiding things.
110
- // No-op if an existing glob already covers `probe`, a path the new glob would
111
- // match. Returns whether it wrote.
112
- export function ensureVisibleGlob(deckDir, glob, probe) {
113
- const file = path.join(deckDir, 'castle.json');
114
- let data;
115
- try {
116
- data = JSON.parse(fs.readFileSync(file, 'utf8'));
117
- }
118
- catch {
119
- return false; // no castle.json yet (deck never saved) -> treat as not curated
120
- }
121
- const visible = data.editor && Array.isArray(data.editor.visiblePaths)
122
- ? data.editor.visiblePaths.filter((v) => typeof v === 'string')
123
- : null;
124
- if (!visible || visible.length === 0)
125
- return false; // not curated -> all visible
126
- if (visible.includes(glob))
127
- return false;
128
- if (picomatch(visible)(probe))
129
- return false; // already covered
130
- visible.push(glob);
131
- data.editor.visiblePaths = visible;
132
- try {
133
- fs.writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
134
- return true;
135
- }
136
- catch {
137
- return false;
138
- }
139
- }
@@ -0,0 +1,14 @@
1
+ export declare const FRAMES_PER_SECOND_BASE = 40;
2
+ export declare const FRAMES_PER_SECOND_PER_PLAYER = 40;
3
+ /** Frames per second a session with this many players connected may send. */
4
+ export declare function frameBudget(players: number): number;
5
+ export declare class OutboundFrameMeter {
6
+ private readonly now;
7
+ private windowStart;
8
+ private frames;
9
+ private players;
10
+ private warnedAt;
11
+ constructor(now: () => number);
12
+ record(connectedPlayers: number): string | null;
13
+ }
14
+ export declare function frameBudgetWarning(frames: number, players: number, budget: number): string;
@@ -0,0 +1,64 @@
1
+ import { MULTIPLAYER_DOC_REL } from './platformDoc.js';
2
+ // Warn-only metering of what the author's server sends, so the budget a
3
+ // published session is held to is visible while the deck is still being built.
4
+ //
5
+ // Production (cauldron-game-server) charges one frame per `sendTo`/`sendBinary`
6
+ // and one per `broadcast`/`broadcastBinary`, and DROPS what is over budget. The
7
+ // dev serve charges the same way and drops nothing: a local serve that silently
8
+ // lost frames would be a worse lie than one that is merely more generous.
9
+ //
10
+ // The numbers mirror cauldron-game-server's `shared/src/constants.ts`
11
+ // (`RUNTIME_FRAMES_PER_SECOND_BASE`, `RUNTIME_FRAMES_PER_SECOND_PER_PLAYER`);
12
+ // its burst allowance and byte budget are deliberately not modelled here --
13
+ // this is a nudge toward one broadcast per tick, not an emulator.
14
+ export const FRAMES_PER_SECOND_BASE = 40;
15
+ export const FRAMES_PER_SECOND_PER_PLAYER = 40;
16
+ const WINDOW_MS = 1_000;
17
+ const WARN_INTERVAL_MS = 10_000;
18
+ /** Frames per second a session with this many players connected may send. */
19
+ export function frameBudget(players) {
20
+ return FRAMES_PER_SECOND_BASE + FRAMES_PER_SECOND_PER_PLAYER * Math.max(1, players);
21
+ }
22
+ // Counts frames in one-second windows and warns the moment a window goes over
23
+ // budget, at most once every 10s. It warns on the crossing frame rather than
24
+ // when the window closes, because the window only closes when a LATER frame
25
+ // arrives: a burst that ends in silence -- a server that floods and then wedges
26
+ // -- would otherwise never be reported at all. `now` is injected so this is
27
+ // testable without a clock.
28
+ export class OutboundFrameMeter {
29
+ now;
30
+ windowStart = null;
31
+ frames = 0;
32
+ players = 0;
33
+ warnedAt = null;
34
+ constructor(now) {
35
+ this.now = now;
36
+ }
37
+ // Charges one frame against the current window and returns a warning line if
38
+ // that frame is the one that took the window past its budget, or null. The
39
+ // player count is the largest seen during the window, which is the most
40
+ // generous budget the window could have had.
41
+ record(connectedPlayers) {
42
+ const now = this.now();
43
+ if (this.windowStart === null || now - this.windowStart >= WINDOW_MS) {
44
+ this.windowStart = now;
45
+ this.frames = 0;
46
+ this.players = 0;
47
+ }
48
+ this.frames += 1;
49
+ this.players = Math.max(this.players, connectedPlayers);
50
+ const budget = frameBudget(this.players);
51
+ if (this.frames <= budget)
52
+ return null;
53
+ if (this.warnedAt !== null && now - this.warnedAt < WARN_INTERVAL_MS)
54
+ return null;
55
+ this.warnedAt = now;
56
+ return frameBudgetWarning(this.frames, this.players, budget);
57
+ }
58
+ }
59
+ export function frameBudgetWarning(frames, players, budget) {
60
+ const who = `${players} player${players === 1 ? '' : 's'}`;
61
+ return (`[multiplayer] server sent ${frames} frames in under a second to ${who}; production sustains ` +
62
+ `~${budget}/s here (about two seconds of burst) and drops what stays over it. One broadcast per tick costs 1 frame; a send per player ` +
63
+ `costs one each. See ${MULTIPLAYER_DOC_REL}`);
64
+ }
@@ -7,6 +7,7 @@ import * as path from 'path';
7
7
  import { fileURLToPath } from 'url';
8
8
  import { WebSocketServer, WebSocket } from 'ws';
9
9
  import { readCastleJson, resolveServerConfig } from './castleJson.js';
10
+ import { OutboundFrameMeter } from './devSessionFrameBudget.js';
10
11
  import { runDevStorageOperation } from './devSessionStorage.js';
11
12
  import { rawDataToString } from './rawData.js';
12
13
  import { bundleServerModule } from './serverBundle.js';
@@ -52,6 +53,8 @@ export function serverRestartNeeded(changes, opts) {
52
53
  IMPORTED_SERVER_PATH.test(change.path));
53
54
  }
54
55
  const IMPORTED_SERVER_PATH = /^(imports|forks)\/[^/]+\/(code\/)?server\//;
56
+ // The runtime frames that cost the session a frame of its outbound budget.
57
+ const OUTBOUND_FRAME_TYPES = new Set(['sendTo', 'sendBinary', 'broadcast', 'broadcastBinary']);
55
58
  class DevSessionServerImpl {
56
59
  projectDir;
57
60
  log;
@@ -70,6 +73,9 @@ class DevSessionServerImpl {
70
73
  nonces = new Map();
71
74
  reconnects = new Map();
72
75
  players = new Map();
76
+ // Warn-only: the dev serve never drops a frame for being over budget, it just
77
+ // says what a published session would have done (devSessionFrameBudget.ts).
78
+ frameMeter = new OutboundFrameMeter(() => Date.now());
73
79
  child = null;
74
80
  platformSocket = null;
75
81
  bootToken = '';
@@ -359,6 +365,8 @@ class DevSessionServerImpl {
359
365
  }
360
366
  if (!this.runtimeReady)
361
367
  return;
368
+ if (typeof frame.t === 'string' && OUTBOUND_FRAME_TYPES.has(frame.t))
369
+ this.meterOutbound();
362
370
  if (frame.t === 'sendTo' && typeof frame.playerId === 'string') {
363
371
  const socket = this.players.get(frame.playerId)?.socket;
364
372
  const payload = parseAuthorPayload(frame.d);
@@ -391,6 +399,13 @@ class DevSessionServerImpl {
391
399
  this.kick(frame.playerId, typeof frame.reason === 'string' ? frame.reason : undefined);
392
400
  }
393
401
  }
402
+ // One frame per send and one per broadcast, exactly as a published session is
403
+ // charged -- a broadcast to eight players is one frame there and one here.
404
+ meterOutbound() {
405
+ const warning = this.frameMeter.record(this.connectedPlayers().length);
406
+ if (warning)
407
+ this.log('log', warning);
408
+ }
394
409
  async handleStorageRequest(reqId, op, args) {
395
410
  const deckId = readCastleJson(this.projectDir)?.deckId;
396
411
  const result = await runDevStorageOperation(deckId, op, args);
@@ -30,11 +30,11 @@ export interface ResolvedFileType extends FileTypeConfig {
30
30
  export interface EditorConfig {
31
31
  initialPanels?: InitialPanel[];
32
32
  hiddenPaths?: string[];
33
- visiblePaths?: string[];
34
33
  fileTypes?: FileTypeConfig[];
35
34
  extensions?: string[];
36
35
  defaultPlayFile?: string;
37
36
  }
38
37
  export declare function readEditorConfig(deckDir: string): EditorConfig;
38
+ export declare function deckHidesFiles(deckDir: string): boolean;
39
39
  export declare function resolveFileTypes(deckDir: string): ResolvedFileType[] | null;
40
40
  export {};
@@ -10,9 +10,9 @@
10
10
  // sits there like any other), so resolving is a read of each import's own
11
11
  // castle.json -- there is no graph to walk.
12
12
  //
13
- // `initialPanels` and `visiblePaths`/`hiddenPaths` stay the deck's own, read from
14
- // the deck root only. `defaultPlayFile` falls back to an import's when the deck
15
- // names none -- see `importedDefaultPlayFile`.
13
+ // `initialPanels` and `hiddenPaths` stay the deck's own, read from the deck root
14
+ // only. `defaultPlayFile` falls back to an import's when the deck names none --
15
+ // see `importedDefaultPlayFile`.
16
16
  import * as fs from 'fs';
17
17
  import * as path from 'path';
18
18
  import { readCastleJson } from './castleJson.js';
@@ -53,7 +53,6 @@ export function readEditorConfig(deckDir) {
53
53
  return {
54
54
  initialPanels: Array.isArray(editor.initialPanels) ? editor.initialPanels : undefined,
55
55
  hiddenPaths: asStringArray(editor.hiddenPaths),
56
- visiblePaths: asStringArray(editor.visiblePaths),
57
56
  fileTypes: asFileTypes(editor.fileTypes),
58
57
  extensions: asStringArray(editor.extensions) ?? asStringArray(data.editorExtensions),
59
58
  defaultPlayFile: typeof editor.defaultPlayFile === 'string'
@@ -101,6 +100,15 @@ function importAliases(deckDir) {
101
100
  const pinned = Object.keys(readCastleJson(deckDir)?.imports ?? {}).filter((alias) => onDisk.includes(alias));
102
101
  return [...pinned, ...onDisk.filter((alias) => !pinned.includes(alias))];
103
102
  }
103
+ // Whether anything can be hidden from the Files tree: this deck's own denylist,
104
+ // or an import's -- an import is filtered by its own castle.json, so a kit that
105
+ // hides its internals hides files the importing deck never listed.
106
+ export function deckHidesFiles(deckDir) {
107
+ const hides = (dir) => (readEditorConfig(dir).hiddenPaths ?? []).length > 0;
108
+ if (hides(deckDir))
109
+ return true;
110
+ return importAliases(deckDir).some((alias) => hides(path.join(deckDir, IMPORTS_DIR, alias)));
111
+ }
104
112
  // Every file type this deck understands: its own, plus every import's. Keyed by
105
113
  // extension, first declaration wins -- so the deck overrides what it imports,
106
114
  // and among imports the one it pinned first does (the same order
package/dist/ide.js CHANGED
@@ -19,12 +19,11 @@ import { WebSocketServer } from 'ws';
19
19
  import { rawDataToString } from './rawData.js';
20
20
  import { IMPORTS_DIR, IMPORT_VERSION_FILE, importStatuses, updateImport, } from './imports.js';
21
21
  import { FORKS_DIR, forkImportFile, forkStateOf, listOwnForks, ownForkFile, resolveForkedFile, revertImportFile, } from './forks.js';
22
- import { ensureVisibleGlob, ensureVisiblePath } from './castleJson.js';
23
- import { readEditorConfig, resolveFileTypes, } from './editorConfig.js';
22
+ import { deckHidesFiles, readEditorConfig, resolveFileTypes, } from './editorConfig.js';
24
23
  import { UNSUPPORTED_MEDIA } from './unsupportedMedia.js';
25
24
  import { IMPORT_API_PREFIX, handleImportApi } from './importBrowse.js';
26
25
  import { readRequestBody, sendJson } from './httpJson.js';
27
- import { COVER_FILE, PLAN_FILE } from './localPaths.js';
26
+ import { COVER_FILE } from './localPaths.js';
28
27
  import { applyVersionRestore, createVersion, NotOnThisLine, pendingChanges, UnsavedChanges, versionSummaries, } from './versions.js';
29
28
  import { envForUserShell, installCliShims } from './byo-auth.js';
30
29
  const HeadlessTerminal = headlessPkg.Terminal;
@@ -334,34 +333,18 @@ function kitEditorExtensions(config, fileTypes) {
334
333
  // A deck saved before file types existed named its kit extensions directly.
335
334
  return config.extensions ?? [];
336
335
  }
337
- // Apply the deck's `editor.hiddenPaths` / `editor.visiblePaths` globs to a file
338
- // list (deck-relative POSIX paths). Only hidden -> drop matches; only visible ->
339
- // keep only matches; both -> keep visible, then subtract hidden. No config ->
340
- // the list passes through unchanged.
336
+ // Drop the files a deck's `editor.hiddenPaths` globs name (deck-relative POSIX
337
+ // paths). Nothing is hidden unless a deck says so, so no globs -> the list
338
+ // passes through unchanged.
341
339
  function filterDeckFiles(files, config) {
342
- let result = files;
343
- if (config.visiblePaths && config.visiblePaths.length > 0) {
344
- const isVisible = picomatch(config.visiblePaths);
345
- result = result.filter((f) => isVisible(f));
346
- }
347
- if (config.hiddenPaths && config.hiddenPaths.length > 0) {
348
- const isHidden = picomatch(config.hiddenPaths);
349
- result = result.filter((f) => !isHidden(f));
350
- }
351
- return result;
352
- }
353
- // The deck's own files, curated. The plan is exempt: it is the platform's file,
354
- // not one a kit's visiblePaths were written to name, so a curated deck would
355
- // hide it by omission -- it shows whenever it exists.
356
- function filterOwnFiles(files, config) {
357
- const result = filterDeckFiles(files, config);
358
- if (files.includes(PLAN_FILE) && !result.includes(PLAN_FILE))
359
- result.push(PLAN_FILE);
360
- return result;
340
+ if (!config.hiddenPaths || config.hiddenPaths.length === 0)
341
+ return files;
342
+ const isHidden = picomatch(config.hiddenPaths);
343
+ return files.filter((f) => !isHidden(f));
361
344
  }
362
345
  // Filter each import by the editor config of the deck it came from: strip the
363
- // `imports/<alias>/` prefix so the dependency's own visible/hidden globs match
364
- // the paths they were written against, then put it back.
346
+ // `imports/<alias>/` prefix so the dependency's own hidden globs match the paths
347
+ // they were written against, then put it back.
365
348
  function filterImportedFiles(deckDir, imported) {
366
349
  const byAlias = new Map();
367
350
  for (const file of imported) {
@@ -383,16 +366,15 @@ function filterImportedFiles(deckDir, imported) {
383
366
  }
384
367
  return out;
385
368
  }
386
- // The deck's files as the Files panel sees them. Each deck curates its own: the
387
- // importing deck's visible/hidden paths name its own dirs (a kit's name scenes/,
388
- // drawings/ ...), so applying them to imports would hide every import by
389
- // omission -- an import is instead filtered by the config of the deck it came
390
- // from, which is the deck that knows which of its files are worth showing.
369
+ // The deck's files as the Files panel sees them: all of them, minus what each
370
+ // deck hides of its own. The importing deck's `hiddenPaths` name its own dirs,
371
+ // so an import is filtered by the config of the deck it came from -- the deck
372
+ // that knows which of its files are worth showing.
391
373
  function curatedDeckFiles(deckDir) {
392
374
  const listed = listDeckFiles(deckDir);
393
375
  const own = listed.filter((f) => !isImportPath(f));
394
376
  return [
395
- ...filterOwnFiles(own, readEditorConfig(deckDir)),
377
+ ...filterDeckFiles(own, readEditorConfig(deckDir)),
396
378
  ...filterImportedFiles(deckDir, listed.filter(isImportPath)),
397
379
  ].sort((a, b) => a.localeCompare(b));
398
380
  }
@@ -408,9 +390,11 @@ const PARAMS_DECLARATION = /\bconst\s+PARAMS\b/;
408
390
  // Which of the deck's files declare params. Scanning here rather than in the
409
391
  // browser because a physics-2d deck carries a hundred-plus files under
410
392
  // `imports/`, and reading each one over HTTP to open a panel is the wrong cost.
393
+ // Unfiltered on purpose: a file a deck keeps out of its Files tree still holds
394
+ // tunable values, and the Parameters panel is the one place all of them show.
411
395
  function filesDeclaringParams(deckDir) {
412
396
  const out = [];
413
- for (const rel of curatedDeckFiles(deckDir)) {
397
+ for (const rel of listDeckFiles(deckDir)) {
414
398
  if (!PARAMS_EXTS.has(path.extname(rel).toLowerCase()))
415
399
  continue;
416
400
  const resolved = resolveDeckPath(deckDir, rel);
@@ -542,15 +526,6 @@ function handleVersionRestore(deckDir, req, res, restart) {
542
526
  }
543
527
  });
544
528
  }
545
- // A curated deck hides anything not covered by editor.visiblePaths. Writes,
546
- // moves, and uploads already mkdir parent dirs; they also have to register the
547
- // dest folder or a new path lands on disk and stays invisible in Files.
548
- function ensureFileParentVisible(deckDir, rel) {
549
- const dir = path.posix.dirname(rel);
550
- if (dir === '.')
551
- return ensureVisibleGlob(deckDir, rel, rel);
552
- return ensureVisiblePath(deckDir, dir);
553
- }
554
529
  function handleFilesWrite(deckDir, req, res) {
555
530
  withMutationPath(deckDir, req, res, (target, body) => {
556
531
  if (typeof body.contents !== 'string') {
@@ -559,8 +534,7 @@ function handleFilesWrite(deckDir, req, res) {
559
534
  try {
560
535
  fs.mkdirSync(path.dirname(target.abs), { recursive: true });
561
536
  fs.writeFileSync(target.abs, body.contents, 'utf8');
562
- const visiblePathAdded = ensureFileParentVisible(deckDir, target.rel);
563
- sendJson(res, 200, { ok: true, path: target.rel, visiblePathAdded });
537
+ sendJson(res, 200, { ok: true, path: target.rel });
564
538
  }
565
539
  catch (err) {
566
540
  sendFailure(res, 'write', target.rel, err);
@@ -575,8 +549,7 @@ function handleFilesMkdir(deckDir, req, res) {
575
549
  catch (err) {
576
550
  return sendFailure(res, 'create folder', target.rel, err);
577
551
  }
578
- const visiblePathAdded = ensureVisiblePath(deckDir, target.rel);
579
- sendJson(res, 200, { ok: true, path: target.rel, visiblePathAdded });
552
+ sendJson(res, 200, { ok: true, path: target.rel });
580
553
  });
581
554
  }
582
555
  // Upload one file from the user's device: `POST files/upload?path=<rel>` with
@@ -584,10 +557,6 @@ function handleFilesMkdir(deckDir, req, res) {
584
557
  // request per file, so the path is all the metadata there is to carry). Refuses
585
558
  // to clobber: the client picks a free name first and a collision here means
586
559
  // something else took it in between.
587
- //
588
- // A curated deck (non-empty visiblePaths) also gets the destination registered,
589
- // the same way mkdir does -- otherwise an upload lands on disk and is invisible
590
- // in the very panel that put it there.
591
560
  // Store the deck's local cover (`preview.png`), overwriting whatever was there.
592
561
  //
593
562
  // The cover is captured continuously while someone plays their deck, but it is
@@ -641,8 +610,7 @@ function handleFilesUpload(deckDir, req, res) {
641
610
  catch (err) {
642
611
  return sendFailure(res, 'upload', target.rel, err);
643
612
  }
644
- const visiblePathAdded = ensureFileParentVisible(deckDir, target.rel);
645
- sendJson(res, 200, { ok: true, path: target.rel, visiblePathAdded });
613
+ sendJson(res, 200, { ok: true, path: target.rel });
646
614
  }, (err) => {
647
615
  if (err instanceof RangeError)
648
616
  return tooBig();
@@ -770,8 +738,7 @@ function handleFilesRename(deckDir, req, res) {
770
738
  try {
771
739
  fs.mkdirSync(path.dirname(to.abs), { recursive: true });
772
740
  fs.renameSync(from.abs, to.abs);
773
- const visiblePathAdded = ensureFileParentVisible(deckDir, to.rel);
774
- sendJson(res, 200, { ok: true, path: to.rel, visiblePathAdded });
741
+ sendJson(res, 200, { ok: true, path: to.rel });
775
742
  }
776
743
  catch (err) {
777
744
  sendFailure(res, 'rename', from.rel, err);
@@ -810,8 +777,10 @@ function handleFilesApi(deckDir, req, res, reqPath, restart, invalidate) {
810
777
  fileTypes,
811
778
  defaultPlayFile: config.defaultPlayFile ?? null,
812
779
  initialPanels: config.initialPanels ?? null,
813
- hiddenPaths: config.hiddenPaths ?? [],
814
- visiblePaths: config.visiblePaths ?? [],
780
+ // Whether the Files panel offers its show-hidden control at all: a deck
781
+ // that hides nothing has nothing to reveal, and the globs themselves are
782
+ // the serve's business, not the shell's.
783
+ hidesFiles: deckHidesFiles(deckDir),
815
784
  // Formats the platform knows won't survive publishing. Sent alongside the
816
785
  // deck's own types rather than merged into them: these are not things the
817
786
  // deck understands, they are things this CLI refuses to let it ship.
@@ -917,7 +886,7 @@ function handleFilesApi(deckDir, req, res, reqPath, restart, invalidate) {
917
886
  if (action === 'list') {
918
887
  // `?all=1` returns the unfiltered listing (the "show hidden files & folders"
919
888
  // toggle) -- still minus the always-ignored dirs (node_modules/.castle/...),
920
- // just without the deck's visible/hidden path curation.
889
+ // just without the deck's hidden-path globs.
921
890
  const url = new URL(req.url ?? '/', 'http://localhost');
922
891
  const all = url.searchParams.get('all') === '1';
923
892
  sendJson(res, 200, { files: all ? listDeckFiles(deckDir) : curatedDeckFiles(deckDir) });
package/dist/imports.js CHANGED
@@ -8,7 +8,7 @@ import { getKitsDir } from './localPaths.js';
8
8
  import { SDK_PACKAGE } from './sdkResolve.js';
9
9
  import { writePlatformDocs } from './platformDoc.js';
10
10
  import { findImportUpdateHook, runImportUpdateHook, } from './importUpdateHook.js';
11
- import { ensureVisibleGlob, IMPORTS_DIR, IMPORT_VERSION_FILE, STARTER_THEME_FILES, readCastleJson as tryReadCastleJson, readCastleJsonOrThrow as readCastleJson, } from './castleJson.js';
11
+ import { IMPORTS_DIR, IMPORT_VERSION_FILE, STARTER_THEME_FILES, readCastleJson as tryReadCastleJson, readCastleJsonOrThrow as readCastleJson, } from './castleJson.js';
12
12
  // Adding another deck as a dependency (`castle-web add-import`; removing one is a
13
13
  // later command). Deliberately NOT `get-deck`: that one
14
14
  // replaces THIS deck's own source from the server (and carries guards for the
@@ -643,8 +643,7 @@ export async function addImport(dir, options = {}) {
643
643
  // from the deck root only -- it is the creator's file, like scenes/ -- so
644
644
  // without this, decks scaffolded before the kit shipped one would never get
645
645
  // it. Never overwrites: a deck that has the file keeps it, whatever the kit
646
- // ships. Also registers the file in a curated deck's editor.visiblePaths so it
647
- // shows in the Files tree (the same courtesy mkdir/upload extend).
646
+ // ships.
648
647
  function seedKitTheme(deckDir, alias, log) {
649
648
  const importDir = path.join(deckDir, IMPORTS_DIR, alias);
650
649
  // Only kits (imports that declare an entry in castle.json `main`) seed deck
@@ -666,7 +665,6 @@ function seedKitTheme(deckDir, alias, log) {
666
665
  console.warn(`Could not seed ${name} from ${alias}: ${e instanceof Error ? e.message : String(e)}`);
667
666
  continue;
668
667
  }
669
- ensureVisibleGlob(deckDir, name, name);
670
668
  seeded.push(name);
671
669
  }
672
670
  if (seeded.length === 0)