castle-web-cli 0.4.157 → 0.4.159
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.
- package/dist/agent-failures.d.ts +1 -0
- package/dist/agent-failures.js +6 -4
- package/dist/agent-prompts.js +4 -0
- package/dist/agent.d.ts +11 -0
- package/dist/agent.js +175 -15
- package/dist/bundle.js +8 -2
- package/dist/castle-host/host.js +4 -2
- package/dist/castleJson.js +6 -1
- package/dist/check.d.ts +1 -0
- package/dist/check.js +25 -0
- package/dist/devSessionServer.js +31 -7
- package/dist/imports.js +1 -19
- package/dist/index.js +15 -1
- package/dist/init.d.ts +2 -2
- package/dist/init.js +78 -42
- package/dist/mcpPlaytest.d.ts +1 -0
- package/dist/mcpPlaytest.js +182 -0
- package/dist/metering.d.ts +24 -0
- package/dist/metering.js +87 -0
- package/dist/sdkResolve.d.ts +3 -0
- package/dist/sdkResolve.js +55 -0
- package/dist/serve.js +50 -4
- package/dist/serverBundle.js +8 -3
- package/dist/shell/assets/{index-DsDkYFvP.js → index-DMSoTyXh.js} +64 -64
- package/dist/shell/assets/{index-DwezawBs.css → index-DfZmu3XC.css} +1 -1
- package/dist/shell/index.html +2 -2
- package/dist/vitePlugins.d.ts +1 -0
- package/dist/vitePlugins.js +20 -0
- package/kits/base/CLAUDE.md +196 -0
- package/kits/{blank → base}/castle.json +5 -2
- package/kits/base/editorHost.js +172 -0
- package/kits/{blank → base}/node_modules/.package-lock.json +3 -2
- package/kits/{blank → base}/package-lock.json +7 -4
- package/kits/{blank → base}/package.json +4 -2
- package/kits/base/sdk/README.md +569 -0
- package/kits/base/sdk/castle.d.ts +27 -0
- package/kits/base/sdk/castle.js +16 -0
- package/kits/base/sdk/commands.d.ts +181 -0
- package/kits/base/sdk/commands.js +16 -0
- package/kits/base/sdk/context.d.ts +17 -0
- package/kits/base/sdk/context.js +15 -0
- package/kits/base/sdk/errors.d.ts +22 -0
- package/kits/base/sdk/errors.js +16 -0
- package/kits/base/sdk/files.d.ts +15 -0
- package/kits/base/sdk/files.js +52 -0
- package/kits/base/sdk/haptics.d.ts +6 -0
- package/kits/base/sdk/haptics.js +36 -0
- package/kits/base/sdk/leaderboard.d.ts +26 -0
- package/kits/base/sdk/leaderboard.js +296 -0
- package/kits/base/sdk/lifecycle.d.ts +4 -0
- package/kits/base/sdk/lifecycle.js +13 -0
- package/kits/base/sdk/multiplayer.d.ts +43 -0
- package/kits/base/sdk/multiplayer.js +464 -0
- package/kits/base/sdk/multiplayerProtocol.d.ts +51 -0
- package/kits/base/sdk/multiplayerProtocol.js +5 -0
- package/kits/base/sdk/passes.d.ts +7 -0
- package/kits/base/sdk/passes.js +84 -0
- package/kits/base/sdk/portal.d.ts +7 -0
- package/kits/base/sdk/portal.js +35 -0
- package/kits/base/sdk/runtime.d.ts +62 -0
- package/kits/base/sdk/runtime.js +970 -0
- package/kits/base/sdk/saveQueue.d.ts +27 -0
- package/kits/base/sdk/saveQueue.js +205 -0
- package/kits/base/sdk/server/platformHandle.d.ts +25 -0
- package/kits/base/sdk/server/platformHandle.js +1 -0
- package/kits/base/sdk/server/wrapper.d.ts +28 -0
- package/kits/base/sdk/server/wrapper.js +109 -0
- package/kits/base/sdk/storage.d.ts +16 -0
- package/kits/base/sdk/storage.js +323 -0
- package/kits/base/sdk/time.d.ts +17 -0
- package/kits/base/sdk/time.js +120 -0
- package/kits/base/sdk/transport.d.ts +17 -0
- package/kits/base/sdk/transport.js +141 -0
- package/kits/base/sdk/types.d.ts +3 -0
- package/kits/base/sdk/types.js +1 -0
- package/kits/base/sdk/user.d.ts +10 -0
- package/kits/base/sdk/user.js +45 -0
- package/kits/multiplayer-2d/.prettierrc +5 -0
- package/kits/multiplayer-2d/CLAUDE.md +129 -0
- package/kits/multiplayer-2d/behaviors/Box.jsx +92 -0
- package/kits/multiplayer-2d/behaviors/Player.jsx +86 -0
- package/kits/multiplayer-2d/blueprints/crate.scene +13 -0
- package/kits/multiplayer-2d/blueprints/other-player.scene +13 -0
- package/kits/multiplayer-2d/blueprints/player.scene +15 -0
- package/kits/multiplayer-2d/blueprints/wall.scene +12 -0
- package/kits/multiplayer-2d/castle.json +39 -0
- package/kits/multiplayer-2d/code/client/avatars.js +93 -0
- package/kits/multiplayer-2d/code/client/poses.js +168 -0
- package/kits/multiplayer-2d/code/server/index.js +26 -0
- package/kits/multiplayer-2d/code/server/limits.js +99 -0
- package/kits/multiplayer-2d/code/server/ownership.js +177 -0
- package/kits/multiplayer-2d/code/server/players.js +127 -0
- package/kits/multiplayer-2d/code/server/sceneBodies.js +98 -0
- package/kits/multiplayer-2d/code/server/world.js +337 -0
- package/kits/multiplayer-2d/code/systems/multiplayer.js +424 -0
- package/kits/multiplayer-2d/eslint.config.js +21 -0
- package/kits/multiplayer-2d/fonts.generated.js +9 -0
- package/kits/multiplayer-2d/index.html +25 -0
- package/kits/multiplayer-2d/main.jsx +10 -0
- package/kits/multiplayer-2d/package-lock.json +351 -0
- package/kits/multiplayer-2d/package.json +30 -0
- package/kits/multiplayer-2d/scenes/main.scene +20 -0
- package/kits/multiplayer-2d/test/two-client-test.mjs +341 -0
- package/kits/multiplayer-2d/theme.style +4 -0
- package/kits/multiplayer-3d/.prettierrc +5 -0
- package/kits/multiplayer-3d/CLAUDE.md +215 -0
- package/kits/multiplayer-3d/blueprints/ball.scene +21 -0
- package/kits/multiplayer-3d/blueprints/other-player.scene +21 -0
- package/kits/multiplayer-3d/castle.json +43 -0
- package/kits/multiplayer-3d/code/client/avatars.js +136 -0
- package/kits/multiplayer-3d/code/client/nameTags.js +101 -0
- package/kits/multiplayer-3d/code/client/poses.js +220 -0
- package/kits/multiplayer-3d/code/server/index.js +23 -0
- package/kits/multiplayer-3d/code/server/limits.js +107 -0
- package/kits/multiplayer-3d/code/server/ownership.js +157 -0
- package/kits/multiplayer-3d/code/server/players.js +114 -0
- package/kits/multiplayer-3d/code/server/sceneBodies.js +88 -0
- package/kits/multiplayer-3d/code/server/world.js +306 -0
- package/kits/multiplayer-3d/code/systems/multiplayer.js +427 -0
- package/kits/multiplayer-3d/eslint.config.js +20 -0
- package/kits/multiplayer-3d/fonts.generated.js +9 -0
- package/kits/multiplayer-3d/index.html +22 -0
- package/kits/multiplayer-3d/main.jsx +9 -0
- package/kits/multiplayer-3d/package-lock.json +368 -0
- package/kits/multiplayer-3d/package.json +32 -0
- package/kits/multiplayer-3d/scenes/main.scene +409 -0
- package/kits/multiplayer-3d/theme.style +3 -0
- package/kits/physics-2d/CLAUDE.md +6 -0
- package/kits/physics-2d/castle.json +7 -1
- package/kits/physics-2d/editors/behaviorRegistry.js +5 -0
- package/kits/physics-2d/editors/editorRegistry.jsx +3 -1
- package/kits/physics-2d/engine/files.js +9 -5
- package/kits/physics-2d/engine/systemRegistry.js +2 -0
- package/kits/physics-2d/engine/ui.module.css +11 -0
- package/kits/physics-2d/package-lock.json +8 -2
- package/kits/physics-2d/package.json +2 -2
- package/kits/physics-3d/CLAUDE.md +4 -4
- package/kits/physics-3d/behaviors/Shape.jsx +1 -1
- package/kits/physics-3d/blueprints/crate.scene +1 -1
- package/kits/physics-3d/blueprints/door.scene +4 -4
- package/kits/physics-3d/blueprints/pillar.scene +1 -1
- package/kits/physics-3d/blueprints/platform.scene +1 -1
- package/kits/physics-3d/blueprints/statue.scene +1 -1
- package/kits/physics-3d/blueprints/wall.scene +1 -1
- package/kits/physics-3d/castle.json +8 -11
- package/kits/physics-3d/docs/pxmodel-format.md +1 -1
- package/kits/physics-3d/engine3d/materials.js +3 -3
- package/kits/physics-3d/engine3d/modelFiles.js +4 -2
- package/kits/physics-3d/engine3d/world3d.js +1 -1
- package/kits/physics-3d/fonts.generated.js +9 -0
- package/kits/physics-3d/main.jsx +1 -1
- package/kits/physics-3d/package-lock.json +85 -2
- package/kits/physics-3d/package.json +6 -2
- package/kits/physics-3d/scenes/main.scene +1 -1
- package/kits/physics-3d/scenes/model-lab.scene +1 -1
- package/kits/real-time/.prettierrc +5 -0
- package/kits/real-time/CLAUDE.md +60 -0
- package/kits/real-time/castle.json +19 -0
- package/kits/real-time/code/client/clock.js +68 -0
- package/kits/real-time/code/client/connection.js +134 -0
- package/kits/real-time/code/client/gameHooks.js +50 -0
- package/kits/real-time/code/client/interpolate.js +82 -0
- package/kits/real-time/code/client/messages.js +55 -0
- package/kits/real-time/code/client/ownership.js +94 -0
- package/kits/real-time/code/client/smooth.js +54 -0
- package/kits/real-time/code/server/blockDelta.js +48 -0
- package/kits/real-time/code/server/gameHooks.js +47 -0
- package/kits/real-time/code/server/limits.js +35 -0
- package/kits/real-time/code/server/session.js +251 -0
- package/kits/real-time/eslint.config.js +22 -0
- package/kits/real-time/index.html +45 -0
- package/kits/real-time/package.json +14 -0
- package/kits/{tabletop → turn-based}/CLAUDE.md +42 -49
- package/kits/turn-based/blueprints/board.scene +15 -0
- package/kits/turn-based/blueprints/square.scene +25 -0
- package/kits/turn-based/castle.json +37 -0
- package/kits/turn-based/code/behaviors/Board.jsx +169 -0
- package/kits/turn-based/code/behaviors/Square.jsx +26 -0
- package/kits/turn-based/code/server/index.js +152 -0
- package/kits/turn-based/drawings/square.sprite +25 -0
- package/kits/turn-based/eslint.config.js +12 -0
- package/kits/turn-based/fonts.generated.js +9 -0
- package/kits/{tabletop → turn-based}/index.html +5 -3
- package/kits/{tabletop → turn-based}/main.jsx +2 -2
- package/kits/{tabletop → turn-based}/package-lock.json +17 -4
- package/kits/{tabletop → turn-based}/package.json +5 -2
- package/kits/turn-based/room.js +289 -0
- package/kits/turn-based/scenes/main.scene +227 -0
- package/kits/{tabletop → turn-based}/testing.js +131 -99
- package/kits/turn-based/theme.style +3 -0
- package/package.json +1 -1
- package/kits/blank/CLAUDE.md +0 -198
- package/kits/tabletop/castle.json +0 -34
- package/kits/tabletop/room.js +0 -269
- /package/kits/{blank → base}/index.html +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/README.md +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/catalog.d.ts +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/catalog.js +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/face.d.ts +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/face.js +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Bore.d.ts +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Bore.js +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/CourierPrime.d.ts +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/CourierPrime.js +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/DMSans.d.ts +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/DMSans.js +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Glacier.d.ts +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Glacier.js +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.d.ts +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.js +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Piazzolla.d.ts +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Piazzolla.js +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Synco.d.ts +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Synco.js +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Tektur.d.ts +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Tektur.js +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/YatraOne.d.ts +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/YatraOne.js +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/index.d.ts +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/index.js +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/CC-BY-ND-4.0.txt +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/FONTS.md +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/OFL-1.1.txt +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/package.json +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Bore.woff2 +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/CourierPrime.woff2 +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/DMSans.woff2 +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Glacier.woff2 +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/HelicoCentrica.woff2 +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Piazzolla.woff2 +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/SOURCE.txt +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Synco.woff2 +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Tektur.woff2 +0 -0
- /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/YatraOne.woff2 +0 -0
- /package/kits/physics-3d/drawings/{crate.pxart → crate.sprite} +0 -0
- /package/kits/physics-3d/drawings/{door-edge.pxart → door-edge.sprite} +0 -0
- /package/kits/physics-3d/drawings/{door.pxart → door.sprite} +0 -0
- /package/kits/physics-3d/drawings/{face.pxart → face.sprite} +0 -0
- /package/kits/physics-3d/drawings/{floor.pxart → floor.sprite} +0 -0
- /package/kits/physics-3d/drawings/{platform.pxart → platform.sprite} +0 -0
- /package/kits/physics-3d/drawings/{statue.pxart → statue.sprite} +0 -0
- /package/kits/physics-3d/drawings/{wall.pxart → wall.sprite} +0 -0
- /package/kits/{tabletop → turn-based}/.prettierrc +0 -0
package/dist/agent-failures.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ export interface AgentFailure {
|
|
|
8
8
|
model?: string;
|
|
9
9
|
suggestion?: string;
|
|
10
10
|
resetAtMs?: number;
|
|
11
|
+
castleCreditsExhausted?: boolean;
|
|
11
12
|
}
|
|
12
13
|
export declare function failureForStatus(status: number, body: string, model?: string): AgentFailure | undefined;
|
|
13
14
|
export declare function classifyProviderError(text: string | undefined, model?: string): AgentFailure | undefined;
|
package/dist/agent-failures.js
CHANGED
|
@@ -8,10 +8,9 @@
|
|
|
8
8
|
// config - deterministic and won't fix itself (bad slug, bad key, no
|
|
9
9
|
// credits). Never retried: retrying is pure latency. Copy names
|
|
10
10
|
// what's wrong and points at settings / Castle.
|
|
11
|
-
// limit - Castle's daily AI allowance
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
// around it (own credential).
|
|
11
|
+
// limit - Castle's daily AI allowance or prepaid balance is spent. The
|
|
12
|
+
// copy points at the applicable recovery: reset/own credential,
|
|
13
|
+
// or purchasing more credits.
|
|
15
14
|
// transient - the provider was busy or broke. NOT auto-retried either (see
|
|
16
15
|
// below), but the copy invites the user to send again.
|
|
17
16
|
// no-work - the model answered instead of working. Config is fine; the
|
|
@@ -179,6 +178,9 @@ export function failureCopy(opts) {
|
|
|
179
178
|
case "config":
|
|
180
179
|
return `${configCopy(opts.failure)}${tasksNote}`;
|
|
181
180
|
case "limit":
|
|
181
|
+
if (opts.failure.castleCreditsExhausted) {
|
|
182
|
+
return `Out of Castle AI credits — get more at castle.xyz/credits${tasksNote}`;
|
|
183
|
+
}
|
|
182
184
|
return `Daily Castle AI limit reached${resetsClause(opts.failure.resetAtMs)}. Runs on your own API key or login aren't limited.${tasksNote}`;
|
|
183
185
|
case "transient":
|
|
184
186
|
return `OpenRouter is busy right now and I couldn't get through. Send that again in a moment.${tasksNote}`;
|
package/dist/agent-prompts.js
CHANGED
|
@@ -938,6 +938,10 @@ Operating rules:
|
|
|
938
938
|
- 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.
|
|
939
939
|
- 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.
|
|
940
940
|
- 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.
|
|
941
|
+
- 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.
|
|
942
|
+
- 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.
|
|
943
|
+
- 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.
|
|
944
|
+
- No new abstraction layers, config systems or generic engines. Prefer one more actor in the scene over one more subsystem.
|
|
941
945
|
- Favor real, editable assets: for game objects, characters, and scenery, make pixel-art drawings and place them as real actors in the scene rather than code-drawn shapes -- it keeps the deck editable in the editor and remixable. (Data-driven UI like health bars, score/text, and HUD gauges, plus dynamic things like bullets/particles/effects, stay procedural -- don't force those into drawings.)
|
|
942
946
|
- Respect art ownership: if YOUR task is to create art, make it as real, editable drawing files (NOT hand-written pixel grids or code-drawn shapes), following the deck's CLAUDE.md / AGENTS.md for the drawing format and exact command. But if your prompt only REFERENCES drawing names (a sibling task is creating them in parallel), point the scene at those names and do NOT create the drawing files yourself -- two agents drawing the same sprites clobber each other. The deck's CLAUDE.md / AGENTS.md is the source of truth for how to make art. Reference the intended drawing name from the scene right away (the actor renders a plain-block fallback until the file exists); a newly written drawing file shows up for the person on their next reload, which is theirs to trigger.
|
|
943
947
|
- Castle decks are played on phones -- any control you build MUST be touch-friendly by default: respond to touch and drag on the canvas (and tap where natural), never keyboard-only. Keep keyboard working too as a bonus, but a control that only works with a keyboard is broken for most players. (Use the kit's pointer/touch input -- see its CLAUDE.md.)
|
package/dist/agent.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as http from 'http';
|
|
2
2
|
import { Duplex } from 'stream';
|
|
3
3
|
import type { ORReasoningEffort, ORRoutingMode } from './native/openrouter.js';
|
|
4
|
+
import { type PlaytestToolResult } from './native/playtest.js';
|
|
4
5
|
export declare const AGENT_WS_PATH = "/__castle/agent";
|
|
5
6
|
export declare const AGENT_ATTACHMENT_PREFIX = "/__castle/agent/attachments/";
|
|
6
7
|
export declare const AGENT_PLAYTEST_PREFIX = "/__castle/agent/playtest/";
|
|
@@ -71,6 +72,16 @@ export interface AgentServer {
|
|
|
71
72
|
handleUpgrade(req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean;
|
|
72
73
|
/** Serve attachment images. Returns true if it handled the request. */
|
|
73
74
|
handleHttpRequest(req: http.IncomingMessage, res: http.ServerResponse, reqPath: string): boolean;
|
|
75
|
+
/**
|
|
76
|
+
* Run one playtest on the serve's warm Chromium. Backs the `playtest_request`
|
|
77
|
+
* control-WS message (serve.ts), which is how a claude task agent reaches
|
|
78
|
+
* this through its MCP server -- smith calls runPlaytest directly instead.
|
|
79
|
+
*/
|
|
80
|
+
runPlaytestFor(req: {
|
|
81
|
+
taskId?: string;
|
|
82
|
+
args: Record<string, unknown>;
|
|
83
|
+
onProgress?: (label: string) => void;
|
|
84
|
+
}): Promise<PlaytestToolResult>;
|
|
74
85
|
shutdown(): void;
|
|
75
86
|
}
|
|
76
87
|
export declare function createAgentServer(opts: {
|
package/dist/agent.js
CHANGED
|
@@ -29,7 +29,7 @@ import { applyPlanOps, buildRouterPrompt, buildTaskPrompt, parsePlanOps, planOpe
|
|
|
29
29
|
import { readCastleJson } from './castleJson.js';
|
|
30
30
|
import { checkOpenrouterKey, checkOpenrouterModel, openrouterCatalogEntry, primeOpenrouterCatalog, } from './openrouter-catalog.js';
|
|
31
31
|
import { classifyProviderError, failureCopy, setReaderTimeZone, } from './agent-failures.js';
|
|
32
|
-
import { fetchBudget, meteringHeaders, newAgentSessionId, reportCursorRun, withCustomHeaders, } from './metering.js';
|
|
32
|
+
import { castleCreditsExhausted, fetchAiCredits, fetchBudget, meteringHeaders, newAgentSessionId, reportCursorRun, spendableMicros, withCustomHeaders, } from './metering.js';
|
|
33
33
|
import { anthropicKeyHelperCommand, claudeHasSavedLogin, cursorAuthPath, cursorHasUserLogin, resolveAnthropicAuth, userKey, ANTHROPIC_CREDENTIAL_ENV, ANTHROPIC_PROXY_ENV, CASTLE_USER_KEYS_PATH, } from './byo-auth.js';
|
|
34
34
|
import { accountsSnapshot, loginProviderFor, watchCredentials, writeCredential, } from './byo-accounts.js';
|
|
35
35
|
import { cancelLogin, logout, startLogin, submitLoginCode } from './byo-login.js';
|
|
@@ -37,6 +37,7 @@ import { runAgentNative } from './native/loop.js';
|
|
|
37
37
|
import { createPlaytestBrowserManager, } from './native/playtest-browser.js';
|
|
38
38
|
import { createPlaywrightPlaytestExecutor } from './native/playtest-executor.js';
|
|
39
39
|
import { createRemotePlaytestExecutor } from './native/playtest-remote.js';
|
|
40
|
+
import { runPlaytest, } from './native/playtest.js';
|
|
40
41
|
export const AGENT_WS_PATH = '/__castle/agent';
|
|
41
42
|
export const AGENT_ATTACHMENT_PREFIX = '/__castle/agent/attachments/';
|
|
42
43
|
// Playtest frame PNGs (tasks/<id>/playtest/<file>.png), served for the
|
|
@@ -407,9 +408,45 @@ function handleModelCaps(req, res) {
|
|
|
407
408
|
// (acceptEdits was rejected: it survives the downgrade but still denies
|
|
408
409
|
// network Bash like curl, which plain auto allows). Deliberately NOT passed
|
|
409
410
|
// to plain-claude spawns, where auto still resolves correctly.
|
|
411
|
+
const OPENROUTER_ALLOWED_TOOLS = ['Edit', 'Write', 'NotebookEdit', 'Bash'];
|
|
412
|
+
// The tool id claude assigns our MCP server's `playtest` tool: mcp__<server>__<tool>,
|
|
413
|
+
// where <server> is the key under mcpServers in --mcp-config (see mcpConfigArg).
|
|
414
|
+
// Task-only, matching smith (native/tools.ts) -- a router turn has no deck to
|
|
415
|
+
// play and no frames dir to write into.
|
|
416
|
+
const CLAUDE_PLAYTEST_TOOL = 'mcp__castle__playtest';
|
|
410
417
|
// Single `=` token because --allowedTools is variadic and would otherwise
|
|
411
418
|
// swallow the trailing prompt positional.
|
|
412
|
-
|
|
419
|
+
function openrouterAllowedToolsArg(role) {
|
|
420
|
+
const tools = role === 'task' ? [...OPENROUTER_ALLOWED_TOOLS, CLAUDE_PLAYTEST_TOOL] : OPENROUTER_ALLOWED_TOOLS;
|
|
421
|
+
return `--allowedTools=${tools.join(',')}`;
|
|
422
|
+
}
|
|
423
|
+
// The one MCP server a task spawn sees. `--strict-mcp-config` is already passed,
|
|
424
|
+
// so this REPLACES any user-level MCP config rather than adding to it.
|
|
425
|
+
//
|
|
426
|
+
// process.execPath + this CLI's own entry, never `castle-web` on PATH: a local
|
|
427
|
+
// deck runs the CLI as `node /…/cli/dist/index.js` and may have nothing named
|
|
428
|
+
// castle-web installed at all. In the sandbox both resolve to the global install.
|
|
429
|
+
//
|
|
430
|
+
// Single `=` token for the same reason as OPENROUTER_ALLOWED_TOOLS above:
|
|
431
|
+
// --mcp-config is variadic (`<configs...>`), so the separate-argument form eats
|
|
432
|
+
// the trailing prompt positional and the run dies with "MCP config file not
|
|
433
|
+
// found: <the whole prompt>" (verified against claude 2.1.247).
|
|
434
|
+
function mcpConfigArg(deckDir, taskId) {
|
|
435
|
+
const config = JSON.stringify({
|
|
436
|
+
mcpServers: {
|
|
437
|
+
castle: {
|
|
438
|
+
command: process.execPath,
|
|
439
|
+
args: [
|
|
440
|
+
path.resolve(process.argv[1]),
|
|
441
|
+
'mcp-playtest',
|
|
442
|
+
deckDir,
|
|
443
|
+
...(taskId ? ['--task-id', taskId] : []),
|
|
444
|
+
],
|
|
445
|
+
},
|
|
446
|
+
},
|
|
447
|
+
});
|
|
448
|
+
return `--mcp-config=${config}`;
|
|
449
|
+
}
|
|
413
450
|
// Cursor's proprietary model. Also the slug reported to the metering ledger, so
|
|
414
451
|
// the two can never drift into disagreeing about what a cursor row ran on.
|
|
415
452
|
const CURSOR_MODEL = 'composer-2.5-fast';
|
|
@@ -430,7 +467,11 @@ openrouterModel,
|
|
|
430
467
|
// This run's ledger identity, and the deck dir its castle.json is read from.
|
|
431
468
|
// Only the claude branch can carry it: cursor-agent runs on its own key and
|
|
432
469
|
// never traverses the llm-proxy.
|
|
433
|
-
metering
|
|
470
|
+
metering,
|
|
471
|
+
// The task this spawn belongs to, so its playtest frames land under
|
|
472
|
+
// tasks/<id>/playtest/ and count against that task's call budget. Absent for
|
|
473
|
+
// router turns, which get no playtest tool at all.
|
|
474
|
+
taskId) {
|
|
434
475
|
if (backend === 'claude') {
|
|
435
476
|
const viaOpenrouter = claudeModel === 'openrouter';
|
|
436
477
|
const orAuth = viaOpenrouter ? resolveOpenrouterAuth() : null;
|
|
@@ -449,7 +490,7 @@ metering) {
|
|
|
449
490
|
'--include-partial-messages',
|
|
450
491
|
'--permission-mode',
|
|
451
492
|
'auto',
|
|
452
|
-
...(viaOpenrouter ? [
|
|
493
|
+
...(viaOpenrouter ? [openrouterAllowedToolsArg(role)] : []),
|
|
453
494
|
'--model',
|
|
454
495
|
viaOpenrouter ? openrouterModel : claudeModel,
|
|
455
496
|
'--effort',
|
|
@@ -464,6 +505,7 @@ metering) {
|
|
|
464
505
|
'--settings',
|
|
465
506
|
claudeSettingsArg(anAuth),
|
|
466
507
|
'--strict-mcp-config',
|
|
508
|
+
...(role === 'task' ? [mcpConfigArg(metering.deckDir, taskId)] : []),
|
|
467
509
|
...(role === 'task' ? ['--append-system-prompt', CLAUDE_TASK_SYSTEM_REMINDER] : []),
|
|
468
510
|
prompt,
|
|
469
511
|
],
|
|
@@ -519,6 +561,12 @@ const TASK_RETRY_BACKOFF_BASE_MS = Number(process.env.CASTLE_TASK_RETRY_BACKOFF_
|
|
|
519
561
|
// Router turns are unaffected: only one ever runs at a time. Override for
|
|
520
562
|
// tests / impatient devs.
|
|
521
563
|
const TASK_SPAWN_STAGGER_MS = Number(process.env.CASTLE_TASK_SPAWN_STAGGER_MS) || 400;
|
|
564
|
+
// The router is the only thing that creates tasks in the product, and it does
|
|
565
|
+
// so mid-turn -- there is no way to spawn ONE task with a chosen `after` list
|
|
566
|
+
// and learn its id. An eval driving a fixed dependency chain needs exactly
|
|
567
|
+
// that, so `spawn-task` on the agent socket is gated behind this and a real
|
|
568
|
+
// serve never accepts task creation from a socket message.
|
|
569
|
+
const SPAWN_TASK_MESSAGE_ENABLED = process.env.CASTLE_AGENT_SPAWN_TASK === '1';
|
|
522
570
|
const TASK_POLL_MS = 1_000;
|
|
523
571
|
const FENCE_HOLDBACK = '```castle-';
|
|
524
572
|
const RESULT_SUMMARY_CHARS = 600;
|
|
@@ -932,6 +980,8 @@ const PROGRESS_FILE_RE = /\.castle\/agent\/tasks\/[^/]+\/progress$/;
|
|
|
932
980
|
// Returns null to hide the action (progress-file writes + anything non-edit/read).
|
|
933
981
|
function claudeToolFeedLabel(name, input) {
|
|
934
982
|
const kind = name.toLowerCase();
|
|
983
|
+
if (kind === CLAUDE_PLAYTEST_TOOL)
|
|
984
|
+
return 'Playtesting';
|
|
935
985
|
if (['edit', 'write', 'notebookedit', 'multiedit'].some((p) => kind.startsWith(p))) {
|
|
936
986
|
const file = firstString(input.file_path, input.path, input.notebook_path);
|
|
937
987
|
if (!file || PROGRESS_FILE_RE.test(file))
|
|
@@ -951,6 +1001,8 @@ function claudeToolFeedLabel(name, input) {
|
|
|
951
1001
|
// Mirrors the cursor toolActivityLabel verbs so the two backends read alike.
|
|
952
1002
|
function genericClaudeToolLabel(name) {
|
|
953
1003
|
const kind = name.toLowerCase();
|
|
1004
|
+
if (kind === CLAUDE_PLAYTEST_TOOL)
|
|
1005
|
+
return 'Playtesting';
|
|
954
1006
|
if (kind.startsWith('read') || kind.startsWith('notebookread'))
|
|
955
1007
|
return 'Reading the deck';
|
|
956
1008
|
if (['edit', 'write', 'notebook', 'multiedit'].some((p) => kind.startsWith(p)))
|
|
@@ -1908,6 +1960,14 @@ async function castleSpendRefusal(backend, claudeModel, orAuth) {
|
|
|
1908
1960
|
}
|
|
1909
1961
|
if (!budget.blocked)
|
|
1910
1962
|
return null;
|
|
1963
|
+
const credits = await fetchAiCredits();
|
|
1964
|
+
if (castleCreditsExhausted(budget, credits)) {
|
|
1965
|
+
return {
|
|
1966
|
+
kind: 'limit',
|
|
1967
|
+
detail: 'Out of Castle AI credits — get more at castle.xyz/credits',
|
|
1968
|
+
castleCreditsExhausted: true,
|
|
1969
|
+
};
|
|
1970
|
+
}
|
|
1911
1971
|
return {
|
|
1912
1972
|
kind: 'limit',
|
|
1913
1973
|
detail: 'daily Castle AI limit reached',
|
|
@@ -1934,25 +1994,28 @@ function blockedClaudeModels(budget) {
|
|
|
1934
1994
|
return [];
|
|
1935
1995
|
return PICKER_CLAUDE_MODELS.filter((m) => claudeModelBlocked(m, budget));
|
|
1936
1996
|
}
|
|
1937
|
-
function usageFrame(budget) {
|
|
1997
|
+
function usageFrame(budget, credits) {
|
|
1938
1998
|
if (!budget)
|
|
1939
1999
|
return null;
|
|
1940
2000
|
return {
|
|
1941
2001
|
usedMicros: budget.usedMicros,
|
|
1942
2002
|
limitMicros: budget.limitMicros,
|
|
2003
|
+
spendableMicros: spendableMicros(budget),
|
|
1943
2004
|
resetAtMs: budget.resetAtMs,
|
|
1944
2005
|
blocked: budget.blocked,
|
|
2006
|
+
credits,
|
|
2007
|
+
creditsExhausted: castleCreditsExhausted(budget, credits),
|
|
1945
2008
|
blockedClaudeModels: blockedClaudeModels(budget),
|
|
1946
2009
|
};
|
|
1947
2010
|
}
|
|
1948
2011
|
/**
|
|
1949
|
-
* The editor's
|
|
2012
|
+
* The editor's Castle-usage feed, pushed over the agent socket exactly the way
|
|
1950
2013
|
* settings are: the current value rides `hello`, and a change is broadcast.
|
|
1951
2014
|
* Outside a sandbox fetchBudget answers null forever, so nothing is ever sent
|
|
1952
2015
|
* and the shell simply has no bar to show.
|
|
1953
2016
|
*
|
|
1954
2017
|
* Null is a value here, not just "no answer yet": a user running on their own
|
|
1955
|
-
* credential is told nothing about Castle's
|
|
2018
|
+
* credential is told nothing about Castle's budget, because none of their
|
|
1956
2019
|
* runs spend it and none of them are gated on it -- showing the bar (worse, a
|
|
1957
2020
|
* spent-out red one) would describe a limit that doesn't apply to them. It has
|
|
1958
2021
|
* to be broadcast rather than merely withheld, so the bar clears when a
|
|
@@ -1960,20 +2023,38 @@ function usageFrame(budget) {
|
|
|
1960
2023
|
*/
|
|
1961
2024
|
function createUsageFeed(opts) {
|
|
1962
2025
|
let latest = null;
|
|
1963
|
-
|
|
1964
|
-
|
|
2026
|
+
let credits = null;
|
|
2027
|
+
let budgetPolls = 0;
|
|
2028
|
+
async function refreshAsync(refreshCredits = false) {
|
|
2029
|
+
if (!opts.castlePaid()) {
|
|
2030
|
+
credits = null;
|
|
2031
|
+
publishUsage(null);
|
|
2032
|
+
return;
|
|
2033
|
+
}
|
|
2034
|
+
const [budget, nextCredits] = await Promise.all([
|
|
2035
|
+
fetchBudget(),
|
|
2036
|
+
refreshCredits ? fetchAiCredits() : Promise.resolve(credits),
|
|
2037
|
+
]);
|
|
2038
|
+
if (refreshCredits)
|
|
2039
|
+
credits = nextCredits;
|
|
2040
|
+
publishUsage(usageFrame(budget, credits));
|
|
2041
|
+
}
|
|
2042
|
+
function publishUsage(next) {
|
|
1965
2043
|
if (JSON.stringify(next ?? null) === JSON.stringify(latest ?? null))
|
|
1966
2044
|
return;
|
|
1967
2045
|
latest = next;
|
|
1968
2046
|
opts.broadcast({ type: 'usage', usage: next });
|
|
1969
2047
|
}
|
|
1970
|
-
const refresh = () => void refreshAsync();
|
|
2048
|
+
const refresh = () => void refreshAsync(true);
|
|
1971
2049
|
const stopRunWatch = onAgentRunFinished(refresh);
|
|
1972
2050
|
const timer = setInterval(() => {
|
|
1973
|
-
if (opts.hasClients())
|
|
1974
|
-
|
|
2051
|
+
if (!opts.hasClients())
|
|
2052
|
+
return;
|
|
2053
|
+
budgetPolls += 1;
|
|
2054
|
+
void refreshAsync(budgetPolls % 5 === 0);
|
|
1975
2055
|
}, USAGE_POLL_MS);
|
|
1976
2056
|
timer.unref?.();
|
|
2057
|
+
refresh();
|
|
1977
2058
|
return {
|
|
1978
2059
|
latest: () => latest,
|
|
1979
2060
|
refresh,
|
|
@@ -2050,7 +2131,7 @@ async function runAgentTurn(opts) {
|
|
|
2050
2131
|
onSpawn: opts.onSpawn,
|
|
2051
2132
|
}));
|
|
2052
2133
|
}
|
|
2053
|
-
const invocation = buildAgentInvocation(opts.backend, opts.role, opts.prompt, opts.claudeModel, opts.openrouterModel, { sessionId, deckDir: opts.cwd });
|
|
2134
|
+
const invocation = buildAgentInvocation(opts.backend, opts.role, opts.prompt, opts.claudeModel, opts.openrouterModel, { sessionId, deckDir: opts.cwd }, opts.taskId);
|
|
2054
2135
|
const startedMs = Date.now();
|
|
2055
2136
|
const run = runAgentCli({
|
|
2056
2137
|
cwd: opts.cwd,
|
|
@@ -2453,6 +2534,7 @@ async function runTaskAgentIn(ctx, task) {
|
|
|
2453
2534
|
framesDir: path.join(dir, 'playtest'),
|
|
2454
2535
|
}
|
|
2455
2536
|
: undefined,
|
|
2537
|
+
taskId: task.id,
|
|
2456
2538
|
restart: ctx.restart,
|
|
2457
2539
|
children: ctx.children,
|
|
2458
2540
|
onSpawn: (pid) => {
|
|
@@ -2557,7 +2639,12 @@ function startTask(ctx, task) {
|
|
|
2557
2639
|
task.acknowledged = true;
|
|
2558
2640
|
if (result.ok && !wasStopped)
|
|
2559
2641
|
task.progress = 100;
|
|
2560
|
-
|
|
2642
|
+
// Smith reports its frames on the run result; a claude agent's reach
|
|
2643
|
+
// the record through runPlaytestFor as each call lands. Overwriting
|
|
2644
|
+
// with `?? []` would erase the latter, since a CLI backend's result
|
|
2645
|
+
// never carries them.
|
|
2646
|
+
if (result.playtestFrames)
|
|
2647
|
+
task.playtestFrames = result.playtestFrames;
|
|
2561
2648
|
task.finishedAt = nowIso();
|
|
2562
2649
|
task.resultSummary = wasStopped
|
|
2563
2650
|
? 'stopped by the router'
|
|
@@ -2829,6 +2916,7 @@ function createTaskStore(opts) {
|
|
|
2829
2916
|
return {
|
|
2830
2917
|
sorted,
|
|
2831
2918
|
get: (id) => tasks.get(id),
|
|
2919
|
+
touch,
|
|
2832
2920
|
spawnFromDirective,
|
|
2833
2921
|
acknowledge,
|
|
2834
2922
|
checkOff,
|
|
@@ -3969,6 +4057,50 @@ function createRouterQueue(deps) {
|
|
|
3969
4057
|
queuedSnippets: () => computeQueuedSnippets(ctx.state.pendingSends),
|
|
3970
4058
|
};
|
|
3971
4059
|
}
|
|
4060
|
+
// The serve-side half of the claude backend's playtest tool: resolve which
|
|
4061
|
+
// task's frames dir and call budget a request belongs to, run it on the shared
|
|
4062
|
+
// warm Chromium, and record the frames on the task so its card shows them.
|
|
4063
|
+
// Smith never comes through here -- native/loop.ts builds its own ctx.
|
|
4064
|
+
function makePlaytestRunner(deps) {
|
|
4065
|
+
// Per-TASK playtest budget, so PLAYTEST_MAX_CALLS_PER_RUN means the same
|
|
4066
|
+
// thing to a claude agent as to smith. Stricter than smith's, which resets
|
|
4067
|
+
// per attempt (one runAgentNative invocation): a retried claude task keeps
|
|
4068
|
+
// spending the same four calls.
|
|
4069
|
+
const callCounts = new Map();
|
|
4070
|
+
return async function runPlaytestFor(req) {
|
|
4071
|
+
const task = req.taskId ? deps.taskStore.get(req.taskId) : undefined;
|
|
4072
|
+
if (req.taskId && !task) {
|
|
4073
|
+
return { ok: false, output: `Error: no task ${req.taskId} on this serve.` };
|
|
4074
|
+
}
|
|
4075
|
+
let callCount = task ? callCounts.get(task.id) : undefined;
|
|
4076
|
+
if (task && !callCount) {
|
|
4077
|
+
callCount = { value: 0 };
|
|
4078
|
+
callCounts.set(task.id, callCount);
|
|
4079
|
+
}
|
|
4080
|
+
const result = await runPlaytest(req.args, deps.deckDir, deps.playtest
|
|
4081
|
+
? {
|
|
4082
|
+
executor: deps.playtest.executor,
|
|
4083
|
+
serveUrl: deps.playtest.serveUrl,
|
|
4084
|
+
framesDir: task
|
|
4085
|
+
? path.join(deps.tasksDir, task.id, 'playtest')
|
|
4086
|
+
: // No task to attribute the frames to (a human at a terminal, or
|
|
4087
|
+
// a future `castle-web playtest`). Under .castle/ deliberately:
|
|
4088
|
+
// castle-www lists a user's cloud decks by globbing the deck's
|
|
4089
|
+
// parent, so a stray dir beside the deck reads as a deck.
|
|
4090
|
+
path.join(deps.deckDir, '.castle', 'playtests', nowIso().replace(/[:.]/g, '-')),
|
|
4091
|
+
// An ad-hoc call has no agent run to protect, so it gets a fresh
|
|
4092
|
+
// budget rather than sharing one across unrelated invocations.
|
|
4093
|
+
callCount: callCount ?? { value: 0 },
|
|
4094
|
+
onProgress: req.onProgress,
|
|
4095
|
+
}
|
|
4096
|
+
: undefined, undefined);
|
|
4097
|
+
if (task && result.playtestFrames?.length) {
|
|
4098
|
+
task.playtestFrames = [...(task.playtestFrames ?? []), ...result.playtestFrames];
|
|
4099
|
+
deps.taskStore.touch(task);
|
|
4100
|
+
}
|
|
4101
|
+
return result;
|
|
4102
|
+
};
|
|
4103
|
+
}
|
|
3972
4104
|
export function createAgentServer(opts) {
|
|
3973
4105
|
const { deckDir, deckLabel } = opts;
|
|
3974
4106
|
const quickReference = readQuickReference(deckDir);
|
|
@@ -4108,6 +4240,27 @@ export function createAgentServer(opts) {
|
|
|
4108
4240
|
function handleTaskAck(id, rejected) {
|
|
4109
4241
|
taskStore.acknowledge(id, rejected);
|
|
4110
4242
|
}
|
|
4243
|
+
// `after` goes through the same resolveDeps the router's fences use, so a
|
|
4244
|
+
// caller may name an upstream by id or by title and gets the real dependency
|
|
4245
|
+
// path -- waiting, blocked, and the upstream summaries in the task prompt.
|
|
4246
|
+
function handleSpawnTask(socket, msg) {
|
|
4247
|
+
const requestId = typeof msg.requestId === 'string' ? msg.requestId : undefined;
|
|
4248
|
+
const reply = (payload) => {
|
|
4249
|
+
if (socket.readyState === socket.OPEN) {
|
|
4250
|
+
socket.send(JSON.stringify({ type: 'spawn-task-result', requestId, ...payload }));
|
|
4251
|
+
}
|
|
4252
|
+
};
|
|
4253
|
+
const title = typeof msg.title === 'string' ? msg.title.trim() : '';
|
|
4254
|
+
const prompt = typeof msg.prompt === 'string' ? msg.prompt.trim() : '';
|
|
4255
|
+
if (!title || !prompt) {
|
|
4256
|
+
reply({ error: 'spawn-task needs a non-empty title and prompt' });
|
|
4257
|
+
return;
|
|
4258
|
+
}
|
|
4259
|
+
const after = Array.isArray(msg.after) ? msg.after.filter((t) => typeof t === 'string') : [];
|
|
4260
|
+
const item = typeof msg.item === 'string' && msg.item.trim() ? msg.item.trim() : undefined;
|
|
4261
|
+
const id = taskStore.spawnFromDirective({ title, prompt, after, item }, `spawn-task:${requestId ?? 'anon'}`);
|
|
4262
|
+
reply({ id });
|
|
4263
|
+
}
|
|
4111
4264
|
const wss = new WebSocketServer({ noServer: true });
|
|
4112
4265
|
// Ids of user messages already accepted, so a client's resend after a lost
|
|
4113
4266
|
// ack is dropped rather than asked twice. Bounded and insertion-ordered: a
|
|
@@ -4188,9 +4341,15 @@ export function createAgentServer(opts) {
|
|
|
4188
4341
|
else if (msg.type === 'task-ack' && typeof msg.id === 'string') {
|
|
4189
4342
|
handleTaskAck(msg.id, msg.rejected === true);
|
|
4190
4343
|
}
|
|
4344
|
+
else if (msg.type === 'spawn-task' && SPAWN_TASK_MESSAGE_ENABLED) {
|
|
4345
|
+
handleSpawnTask(socket, msg);
|
|
4346
|
+
}
|
|
4191
4347
|
else if (msg.type === 'set-settings') {
|
|
4192
4348
|
applySettings(msg);
|
|
4193
4349
|
}
|
|
4350
|
+
else if (msg.type === 'refresh-usage') {
|
|
4351
|
+
usageFeed.refresh();
|
|
4352
|
+
}
|
|
4194
4353
|
else if (msg.type === 'set-credential' || msg.type === 'clear-credential') {
|
|
4195
4354
|
applyCredentialChange(msg, { pushAccounts: accountsFeed.push });
|
|
4196
4355
|
}
|
|
@@ -4233,6 +4392,7 @@ export function createAgentServer(opts) {
|
|
|
4233
4392
|
wss.handleUpgrade(req, socket, head, (ws) => attachClient(ws));
|
|
4234
4393
|
return true;
|
|
4235
4394
|
}
|
|
4395
|
+
const runPlaytestFor = makePlaytestRunner({ deckDir, tasksDir, taskStore, playtest });
|
|
4236
4396
|
const handleAttachment = makeAttachmentHandler(attachmentsDir);
|
|
4237
4397
|
const handlePlaytestFrame = makePlaytestFrameHandler(tasksDir);
|
|
4238
4398
|
function handleHttpRequest(req, res, reqPath) {
|
|
@@ -4256,5 +4416,5 @@ export function createAgentServer(opts) {
|
|
|
4256
4416
|
wss.close();
|
|
4257
4417
|
void playtestBrowserManager?.shutdown();
|
|
4258
4418
|
}
|
|
4259
|
-
return { handleUpgrade, handleHttpRequest, shutdown };
|
|
4419
|
+
return { handleUpgrade, handleHttpRequest, runPlaytestFor, shutdown };
|
|
4260
4420
|
}
|
package/dist/bundle.js
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import * as path from 'path';
|
|
2
2
|
import { build } from 'vite';
|
|
3
3
|
import { viteSingleFile } from 'vite-plugin-singlefile';
|
|
4
|
-
import { sceneFilesPlugin, importsAliasPlugin, forksOverlayPlugin } from './vitePlugins.js';
|
|
4
|
+
import { sceneFilesPlugin, importsAliasPlugin, forksOverlayPlugin, sdkAliasPlugin, } from './vitePlugins.js';
|
|
5
5
|
export async function bundleProject(dir) {
|
|
6
6
|
const result = await build({
|
|
7
7
|
root: dir,
|
|
8
|
-
plugins: [
|
|
8
|
+
plugins: [
|
|
9
|
+
forksOverlayPlugin(),
|
|
10
|
+
importsAliasPlugin(),
|
|
11
|
+
sdkAliasPlugin(),
|
|
12
|
+
viteSingleFile(),
|
|
13
|
+
sceneFilesPlugin(),
|
|
14
|
+
],
|
|
9
15
|
build: {
|
|
10
16
|
write: false,
|
|
11
17
|
rollupOptions: {
|
package/dist/castle-host/host.js
CHANGED
|
@@ -320,7 +320,7 @@ async function sharedDeckStorageLoad(ctx, params, gql) {
|
|
|
320
320
|
// ---------------------------------------------------------------------------
|
|
321
321
|
// Staged writes.
|
|
322
322
|
//
|
|
323
|
-
// The deck coalesces
|
|
323
|
+
// The deck coalesces writes by key and hands them over every 200ms; from here on
|
|
324
324
|
// they are the host's. That matters because the host runs in the PAGE: when a
|
|
325
325
|
// deck frame is torn down, or the page itself starts to unload, this code is
|
|
326
326
|
// still alive to finish the request, and the deck's own attempt would not be --
|
|
@@ -591,7 +591,9 @@ function leaderboardParties(parties) {
|
|
|
591
591
|
function userGetCurrent(ctx) {
|
|
592
592
|
if (!ctx.userId || !ctx.username)
|
|
593
593
|
return { user: null };
|
|
594
|
-
return {
|
|
594
|
+
return {
|
|
595
|
+
user: { userId: ctx.userId, username: ctx.username, isAnonymous: ctx.isAnonymous === true },
|
|
596
|
+
};
|
|
595
597
|
}
|
|
596
598
|
async function timeGetServerTime(gql) {
|
|
597
599
|
const data = await graphql(gql, SERVER_TIME_QUERY, {}, "time.getServerTime");
|
package/dist/castleJson.js
CHANGED
|
@@ -25,15 +25,20 @@ export const DEFAULT_SERVER_TICK_RATE = 20;
|
|
|
25
25
|
export const DEFAULT_SERVER_MAX_PLAYERS = 8;
|
|
26
26
|
export const SERVER_TICK_RATE_CAP = 30;
|
|
27
27
|
export const SERVER_MAX_PLAYERS_CAP = 24;
|
|
28
|
+
// A deck may keep its source under `code/`, so both roots are candidates.
|
|
28
29
|
const DEFAULT_SERVER_ENTRIES = [
|
|
29
30
|
'server/index.js',
|
|
30
31
|
'server/index.ts',
|
|
31
32
|
'server/index.mjs',
|
|
33
|
+
'code/server/index.js',
|
|
34
|
+
'code/server/index.ts',
|
|
35
|
+
'code/server/index.mjs',
|
|
32
36
|
];
|
|
33
37
|
export function resolveServerConfig(dir) {
|
|
34
38
|
const server = readCastleJson(dir)?.server;
|
|
35
39
|
const declared = typeof server?.main === 'string' ? server.main.trim() : '';
|
|
36
|
-
const entry = declared ||
|
|
40
|
+
const entry = declared ||
|
|
41
|
+
DEFAULT_SERVER_ENTRIES.find((candidate) => fs.existsSync(path.join(dir, candidate)));
|
|
37
42
|
if (!entry || !isSafeServerEntry(dir, entry))
|
|
38
43
|
return null;
|
|
39
44
|
return {
|
package/dist/check.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function check(dir: string): Promise<void>;
|
package/dist/check.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import { bundleProject } from './bundle.js';
|
|
4
|
+
// `castle-web check` -- does this deck still build?
|
|
5
|
+
//
|
|
6
|
+
// The bundle is the gate that matters wherever a deck came from: it is the same
|
|
7
|
+
// build `save-deck` runs, so anything it refuses is a deck that would publish
|
|
8
|
+
// broken. A kit adds its own lint and duplicate gates on top through its own
|
|
9
|
+
// `check` script; a deck built on nothing has no lint config to run, and used
|
|
10
|
+
// to have no way to answer the question at all.
|
|
11
|
+
export async function check(dir) {
|
|
12
|
+
const deckDir = path.resolve(dir);
|
|
13
|
+
if (!fs.existsSync(path.join(deckDir, 'index.html'))) {
|
|
14
|
+
console.error(`No index.html in ${deckDir} -- is this a deck?`);
|
|
15
|
+
process.exit(1);
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
await bundleProject(deckDir);
|
|
19
|
+
}
|
|
20
|
+
catch (e) {
|
|
21
|
+
console.error(e instanceof Error ? e.message : String(e));
|
|
22
|
+
process.exit(1);
|
|
23
|
+
}
|
|
24
|
+
console.log('Bundle OK.');
|
|
25
|
+
}
|
package/dist/devSessionServer.js
CHANGED
|
@@ -6,7 +6,7 @@ import * as os from 'os';
|
|
|
6
6
|
import * as path from 'path';
|
|
7
7
|
import { fileURLToPath } from 'url';
|
|
8
8
|
import { WebSocketServer, WebSocket } from 'ws';
|
|
9
|
-
import { readCastleJson, resolveServerConfig
|
|
9
|
+
import { readCastleJson, resolveServerConfig } from './castleJson.js';
|
|
10
10
|
import { bundleServerModule } from './serverBundle.js';
|
|
11
11
|
const PROTOCOL_VERSION = 1;
|
|
12
12
|
const MAX_CLIENT_FRAME_BYTES = 16 * 1024;
|
|
@@ -24,13 +24,20 @@ export async function startDevSessionServer(opts) {
|
|
|
24
24
|
throw error;
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
|
+
function serverDirOf(entry) {
|
|
28
|
+
const slash = entry.lastIndexOf('/');
|
|
29
|
+
return slash < 0 ? '' : entry.slice(0, slash + 1);
|
|
30
|
+
}
|
|
27
31
|
class DevSessionServerImpl {
|
|
28
32
|
projectDir;
|
|
29
33
|
log;
|
|
30
34
|
sessionId = 'dev';
|
|
31
35
|
port = 0;
|
|
32
36
|
server = http.createServer((_req, res) => res.writeHead(404).end());
|
|
33
|
-
clientWss = new WebSocketServer({
|
|
37
|
+
clientWss = new WebSocketServer({
|
|
38
|
+
noServer: true,
|
|
39
|
+
maxPayload: MAX_CLIENT_FRAME_BYTES,
|
|
40
|
+
});
|
|
34
41
|
platformWss = new WebSocketServer({ noServer: true, maxPayload: 80 * 1024 });
|
|
35
42
|
nonces = new Map();
|
|
36
43
|
reconnects = new Map();
|
|
@@ -48,11 +55,14 @@ class DevSessionServerImpl {
|
|
|
48
55
|
readyResolve = null;
|
|
49
56
|
readyReject = null;
|
|
50
57
|
serverEntry;
|
|
58
|
+
// Everything beside the entry restarts the server too, wherever it lives.
|
|
59
|
+
serverDir;
|
|
51
60
|
serverSettings;
|
|
52
61
|
constructor(projectDir, log) {
|
|
53
62
|
this.projectDir = projectDir;
|
|
54
63
|
this.log = log;
|
|
55
64
|
this.serverEntry = resolveServerConfig(projectDir)?.entry ?? 'server/index.js';
|
|
65
|
+
this.serverDir = serverDirOf(this.serverEntry);
|
|
56
66
|
this.serverSettings = JSON.stringify(readCastleJson(projectDir)?.server ?? null);
|
|
57
67
|
this.server.on('upgrade', (request, socket, head) => this.handleUpgrade(request, socket, head));
|
|
58
68
|
}
|
|
@@ -84,13 +94,15 @@ class DevSessionServerImpl {
|
|
|
84
94
|
nextSettings !== this.serverSettings;
|
|
85
95
|
this.serverSettings = nextSettings;
|
|
86
96
|
if (!serverSettingsChanged &&
|
|
87
|
-
!message.changes.some((change) => change.path === this.serverEntry || change.path.startsWith(
|
|
97
|
+
!message.changes.some((change) => change.path === this.serverEntry || change.path.startsWith(this.serverDir)))
|
|
88
98
|
return;
|
|
89
99
|
if (this.restartTimer)
|
|
90
100
|
clearTimeout(this.restartTimer);
|
|
91
101
|
this.restartTimer = setTimeout(() => {
|
|
92
102
|
this.restartTimer = null;
|
|
93
|
-
this.restartQueue = this.restartQueue
|
|
103
|
+
this.restartQueue = this.restartQueue
|
|
104
|
+
.then(() => this.restartChild())
|
|
105
|
+
.catch((error) => {
|
|
94
106
|
this.log('error', `restart failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
95
107
|
});
|
|
96
108
|
}, 100);
|
|
@@ -147,7 +159,9 @@ class DevSessionServerImpl {
|
|
|
147
159
|
this.clientWss.handleUpgrade(request, socket, head, (ws) => this.attachClient(ws, auth));
|
|
148
160
|
}
|
|
149
161
|
upgradePlatform(request, socket, head, url) {
|
|
150
|
-
if (!this.bootToken ||
|
|
162
|
+
if (!this.bootToken ||
|
|
163
|
+
url.searchParams.get('bootToken') !== this.bootToken ||
|
|
164
|
+
this.platformSocket) {
|
|
151
165
|
rejectUpgrade(socket, 401);
|
|
152
166
|
return;
|
|
153
167
|
}
|
|
@@ -230,7 +244,12 @@ class DevSessionServerImpl {
|
|
|
230
244
|
this.sendClient(socket, { t: 'pong' });
|
|
231
245
|
}
|
|
232
246
|
else if (frame.t === 'm' && Object.prototype.hasOwnProperty.call(frame, 'd')) {
|
|
233
|
-
this.sendPlatform({
|
|
247
|
+
this.sendPlatform({
|
|
248
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
249
|
+
t: 'clientMessage',
|
|
250
|
+
playerId,
|
|
251
|
+
d: frame.d,
|
|
252
|
+
});
|
|
234
253
|
}
|
|
235
254
|
else {
|
|
236
255
|
socket.close(1008, 'invalid client frame');
|
|
@@ -328,6 +347,7 @@ class DevSessionServerImpl {
|
|
|
328
347
|
if (!config)
|
|
329
348
|
throw new Error('multiplayer server entry is unavailable');
|
|
330
349
|
this.serverEntry = config.entry;
|
|
350
|
+
this.serverDir = serverDirOf(config.entry);
|
|
331
351
|
const code = await bundleServerModule(this.projectDir, config, false);
|
|
332
352
|
this.removeTempDir();
|
|
333
353
|
this.tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'castle-dev-session-'));
|
|
@@ -386,7 +406,11 @@ class DevSessionServerImpl {
|
|
|
386
406
|
}
|
|
387
407
|
}
|
|
388
408
|
currentConfig() {
|
|
389
|
-
return resolveServerConfig(this.projectDir) ?? {
|
|
409
|
+
return (resolveServerConfig(this.projectDir) ?? {
|
|
410
|
+
entry: 'server/index.js',
|
|
411
|
+
tickRate: 20,
|
|
412
|
+
maxPlayers: 8,
|
|
413
|
+
});
|
|
390
414
|
}
|
|
391
415
|
sendPlatform(frame) {
|
|
392
416
|
if (this.platformSocket?.readyState === WebSocket.OPEN)
|