castle-web-cli 0.4.197 → 0.4.199

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 (62) hide show
  1. package/dist/agent-prompts.d.ts +1 -0
  2. package/dist/agent-prompts.js +9 -3
  3. package/dist/agent.js +25 -1
  4. package/dist/api.d.ts +1 -1
  5. package/dist/api.js +14 -3
  6. package/dist/byo-auth.js +4 -5
  7. package/dist/castle-host/host.js +215 -0
  8. package/dist/devSessionServer.js +40 -3
  9. package/dist/devSessionStorage.js +155 -0
  10. package/dist/filesChanged.d.ts +23 -0
  11. package/dist/filesChanged.js +15 -9
  12. package/dist/ide.d.ts +3 -0
  13. package/dist/ide.js +37 -25
  14. package/dist/init.js +1 -1
  15. package/dist/paramsFile.d.ts +80 -0
  16. package/dist/paramsFile.js +516 -0
  17. package/dist/paramsRegisterPlugin.d.ts +3 -0
  18. package/dist/paramsRegisterPlugin.js +81 -0
  19. package/dist/paramsTunes.d.ts +44 -0
  20. package/dist/paramsTunes.js +200 -0
  21. package/dist/paramsWrites.d.ts +30 -0
  22. package/dist/paramsWrites.js +138 -0
  23. package/dist/platformDoc.d.ts +1 -1
  24. package/dist/platformDoc.js +6 -20
  25. package/dist/save-deck.js +9 -1
  26. package/dist/serve.js +23 -15
  27. package/dist/shell/assets/index-DJSLmPmw.js +449 -0
  28. package/dist/shell/assets/index-uXcYGwQC.css +1 -0
  29. package/dist/shell/index.html +2 -2
  30. package/dist/textHash.d.ts +2 -0
  31. package/dist/textHash.js +28 -0
  32. package/kits/base/castle.json +1 -1
  33. package/kits/base/package-lock.json +1 -1
  34. package/kits/base/sdk/README.md +4 -0
  35. package/kits/base/sdk/castle.d.ts +4 -0
  36. package/kits/base/sdk/castle.js +2 -0
  37. package/kits/base/sdk/characters.d.ts +26 -0
  38. package/kits/base/sdk/characters.js +108 -0
  39. package/kits/base/sdk/commands.d.ts +70 -0
  40. package/kits/base/sdk/multiplayer.js +68 -0
  41. package/kits/base/sdk/paramsRegistry.d.ts +32 -0
  42. package/kits/base/sdk/paramsRegistry.js +100 -0
  43. package/kits/base/sdk/runtime.d.ts +7 -0
  44. package/kits/base/sdk/runtime.js +34 -0
  45. package/kits/base/sdk/server/storage.d.ts +77 -0
  46. package/kits/base/sdk/server/storage.js +272 -18
  47. package/kits/base/sdk/server/wrapper.d.ts +1 -1
  48. package/kits/physics-2d/behaviors/Collider.jsx +3 -3
  49. package/kits/physics-2d/behaviors/Joints.jsx +2 -2
  50. package/kits/physics-2d/castle.json +2 -2
  51. package/kits/physics-2d/editors/SceneEditor.jsx +5 -5
  52. package/kits/physics-2d/editors/pxArtTimeline.jsx +1 -1
  53. package/kits/physics-2d/editors/pxArtTimeline.module.css +73 -73
  54. package/kits/physics-2d/editors/themeEditor.module.css +17 -17
  55. package/kits/physics-2d/engine/castle-tokens.css +64 -0
  56. package/kits/physics-2d/engine/fields/fields.module.css +43 -37
  57. package/kits/physics-2d/engine/ui.jsx +1 -0
  58. package/kits/physics-2d/engine/ui.module.css +262 -288
  59. package/kits/physics-2d/package-lock.json +6 -1
  60. package/package.json +1 -1
  61. package/dist/shell/assets/index-MSHtKPXt.css +0 -1
  62. package/dist/shell/assets/index-yHGXRGlX.js +0 -449
@@ -88,6 +88,7 @@ export interface RouterPromptOpts {
88
88
  plan?: RouterPlanOpts;
89
89
  playtest?: boolean;
90
90
  editorTabs?: string[];
91
+ paramsWrites?: string[];
91
92
  instruction: string;
92
93
  }
93
94
  export declare function buildRouterPromptParts(opts: RouterPromptOpts): RouterPromptParts;
@@ -35,7 +35,7 @@ Hard rules:
35
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.
36
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.
37
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
- - 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.
38
+ - 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. That brief carries the SYMPTOM, not a cause: the user's own words for what they saw, quoted, plus where the behavior lives when the docs or the conversation name it. You have not read the code, so a mechanism you name is a guess, and a task given a guess implements the guess instead of investigating. 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.
39
39
  - 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}` : ""}
40
40
  - 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.
41
41
  - 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.
@@ -143,7 +143,7 @@ now- food-hauling
143
143
  - Finishing an item is \`now- <label>\`; whatever should outlive it goes to Decisions / Tried in the SAME fence, and the rest is meant to be forgotten. An item that leaves \`## Now\` with nothing promoted takes everything the two of you settled while building it with it. You never write what EXISTS: \`## Built\` is derived from the tasks for you, and board rows are not plan lines.
144
144
  - Ops are for inflection points -- a decision crystallizes, an experiment concludes, the user reflects, an item starts or finishes. A turn that changed nothing about the plan carries no fence at all.
145
145
  - THE USER SHAPING THE GAME IS AN INFLECTION POINT. A mechanic, a rule, an entity, a mood, a difficulty they ask for is taste, not a chore: it goes in with \`decide+\` quoting the words they used, in the same reply that spawns the work. Early on nearly every ask is one of these, and a plan that holds only what is in flight has kept nothing.
146
- - A bare number, a knob setting, or a bug they want gone is not taste -- just do the tweak. The REASON they give for one is: "make the islands bigger, it's already pretty hard" is a \`decide+\` about the difficulty they want, not about island size.
146
+ - A bare number, a knob setting, or a bug they want gone is not taste -- just do the tweak. The REASON they give for one is: "make the islands bigger, it's already pretty hard" is a \`decide+\` about the difficulty they want, not about island size. A line about a value someone tuned names the intent and the knob, never the number: \`decide+ gentle-start: the first wave should feel easy -- spawnRate ("go easy at the start" -- user)\`, not \`... spawnRate at 0.4\`. A number inside the quote stays, since the quote is their words verbatim; your own sentence never carries one. The number lives in one place, the \`PARAMS\` object of the file that uses it, and a plan line repeating it becomes a second answer the moment anyone moves the slider.
147
147
  - Put the fence AFTER your task fences: tasks spawn the moment their fence closes.
148
148
  - NOTHING in \`## Open questions\` may be answered by anything else in the same reply, fence or task: asking and deciding are different acts. A probe IS the top open question, asked in its own words.
149
149
  - An open question you have asked outright twice, and the user passed over both times, is TABLED: \`open- <label>\` it in that reply's fence and stop asking it. Passing over it twice is their answer about the question. It comes back only if they bring it up.
@@ -849,6 +849,12 @@ export function buildRouterPromptParts(opts) {
849
849
  const plan = opts.plan
850
850
  ? `\n\n== plan ==\n${renderPlanDigest(opts.plan, opts.tasks)}`
851
851
  : "";
852
+ // Omitted entirely when nothing was tuned: a quiet turn has to cost 0 bytes,
853
+ // and every prompt built before this section existed has to stay
854
+ // byte-identical.
855
+ const paramsWrites = opts.paramsWrites?.length
856
+ ? `\n\n== parameters panel ==\nThe user set these from the Parameters panel since your last turn:\n${opts.paramsWrites.map((slot) => `- ${slot}`).join("\n")}`
857
+ : "";
852
858
  // Two parts, split for prompt caching. `system` holds what is the same from
853
859
  // one turn to the next within a serve -- the rules, the deck identity and
854
860
  // the file tree -- and is sent as system text, which is the prefix the
@@ -864,7 +870,7 @@ ${opts.deckLabel}${quickReference}${editorTabs}${deckFiles}`,
864
870
  ${renderTranscript(opts.messages)}${plan}
865
871
 
866
872
  == background tasks ==
867
- ${renderTasks(opts.tasks, opts.plan !== undefined)}
873
+ ${renderTasks(opts.tasks, opts.plan !== undefined)}${paramsWrites}
868
874
 
869
875
  == now ==
870
876
  ${opts.instruction}
package/dist/agent.js CHANGED
@@ -16,6 +16,7 @@
16
16
  import { execFileSync, spawn } from 'child_process';
17
17
  import { claudeContextEnv, quickReferenceFor } from './platformDoc.js';
18
18
  import { resolveFileTypes } from './editorConfig.js';
19
+ import { panelWritesSince } from './paramsWrites.js';
19
20
  import { IMPORTS_DIR } from './imports.js';
20
21
  import { isSameOriginUpgrade } from './wsOrigin.js';
21
22
  import { resolveDeckPath } from './ide.js';
@@ -2733,7 +2734,7 @@ function lineCountOf(abs) {
2733
2734
  function isPositiveInteger(value) {
2734
2735
  return typeof value === 'number' && Number.isInteger(value) && value > 0;
2735
2736
  }
2736
- // A `ParamSlot.id` (shell/paramsFile.ts): `speed`, or `player.speed` in a group.
2737
+ // A `ParamSlot.id` (paramsFile.ts): `speed`, or `player.speed` in a group.
2737
2738
  const PARAM_FIELD_RE = /^[\w$]+(?:\.[\w$]+)*$/;
2738
2739
  const MAX_FRAGMENT_CHARS = 200;
2739
2740
  // One place a client @-mentioned, or null when it names no file this deck has.
@@ -3055,6 +3056,28 @@ function editorTabsFor(deckDir) {
3055
3056
  }
3056
3057
  return [...extsByLabel].map(([label, exts]) => `${label} (${exts.join(', ')})`);
3057
3058
  }
3059
+ // "Since your last turn" is this router's last REPLY, not the message it is
3060
+ // about to answer: a panel tune lands while the user is looking at the deck,
3061
+ // before they type, so a watermark taken from the incoming message would never
3062
+ // show one. An errored reply is not a turn: a retryable failure leaves it in
3063
+ // the log and re-runs the same instruction, so counting it would make the
3064
+ // retry's watermark the failed turn's own start and drop every tune the user
3065
+ // made before they typed. A log always opens with the seeded welcome message,
3066
+ // so the no-reply floor of 0 -- the whole journal, capped by the render -- is
3067
+ // only reachable on a log someone emptied by hand.
3068
+ function panelWriteWatermark(messages, selfMessageId) {
3069
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
3070
+ const message = messages[i];
3071
+ if (message.role !== 'assistant' || message.id === selfMessageId)
3072
+ continue;
3073
+ if (message.status === 'error')
3074
+ continue;
3075
+ const at = Date.parse(message.at);
3076
+ if (Number.isFinite(at))
3077
+ return at;
3078
+ }
3079
+ return 0;
3080
+ }
3058
3081
  // Assemble the full stateless prompt for one router turn: rules + deck
3059
3082
  // context + transcript replay (minus log lines and the in-flight reply) +
3060
3083
  // the live board + this turn's instruction.
@@ -3082,6 +3105,7 @@ function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
3082
3105
  .filter((t) => !(t.acknowledged && isTerminal(t.status)))
3083
3106
  .map(asPromptTask),
3084
3107
  plan: routerPlanOpts(ctx.deckDir, plan, ctx.taskStore.pendingDurables(), ctx.taskStore.sorted()),
3108
+ paramsWrites: panelWritesSince(ctx.deckDir, panelWriteWatermark(ctx.log.messages, selfMessageId)),
3085
3109
  instruction,
3086
3110
  });
3087
3111
  }
package/dist/api.d.ts CHANGED
@@ -97,7 +97,7 @@ export declare function myPlaylists(userId: string, limit: number): Promise<Play
97
97
  export declare function isDeckIdShaped(value: string): boolean;
98
98
  export declare function webDeckSourceVersions(deckIds: string[]): Promise<Map<string, string>>;
99
99
  export declare function deckRows(deckIds: string[]): Promise<DeckRow[]>;
100
- export declare function updateCardAndDeckV2(deck: Record<string, unknown>, card: Record<string, unknown>): Promise<{
100
+ export declare function updateCardAndDeckV2(deck: Record<string, unknown>, card: Record<string, unknown>, characterBundle?: unknown): Promise<{
101
101
  deckId: string;
102
102
  cardId: string;
103
103
  }>;
package/dist/api.js CHANGED
@@ -179,13 +179,24 @@ export async function webDeckSourceVersions(deckIds) {
179
179
  export async function deckRows(deckIds) {
180
180
  return aliasedDeckQuery(deckIds, (id) => `deck(deckId: "${id}") { ${DECK_ROW_FIELDS} }`);
181
181
  }
182
- export async function updateCardAndDeckV2(deck, card) {
183
- const data = await graphql(`mutation($deck: DeckInput!, $card: CardInput!) {
182
+ export async function updateCardAndDeckV2(deck, card, characterBundle) {
183
+ // Old Ghost versions do not know the characterBundle argument. Keep the exact
184
+ // pre-feature mutation for ordinary decks; only a deck that explicitly owns the
185
+ // property opts into the gated schema. An explicit null clears prior definitions.
186
+ const publishesCharacters = characterBundle !== undefined;
187
+ const data = await graphql(publishesCharacters
188
+ ? `mutation($deck: DeckInput!, $card: CardInput!, $characterBundle: Json) {
189
+ updateCardAndDeckV2(deck: $deck, card: $card, characterBundle: $characterBundle) {
190
+ deck { deckId }
191
+ card { cardId }
192
+ }
193
+ }`
194
+ : `mutation($deck: DeckInput!, $card: CardInput!) {
184
195
  updateCardAndDeckV2(deck: $deck, card: $card) {
185
196
  deck { deckId }
186
197
  card { cardId }
187
198
  }
188
- }`, { deck, card });
199
+ }`, publishesCharacters ? { deck, card, characterBundle } : { deck, card });
189
200
  handleAPIError(data);
190
201
  const result = data.data?.updateCardAndDeckV2;
191
202
  return { deckId: result.deck.deckId, cardId: result.card.cardId };
package/dist/byo-auth.js CHANGED
@@ -16,11 +16,10 @@ import * as path from "path";
16
16
  import { fileURLToPath } from "url";
17
17
  import { inCastleSandbox } from "./metering.js";
18
18
  const DIST_DIR = path.dirname(fileURLToPath(import.meta.url));
19
- // A user's OWN provider credentials, kept SEPARATE from Castle's keys.json so
20
- // castle-www's per-serve re-sync of keys.json (cloudSandbox.ts syncCastleKeys)
21
- // can't clobber them. Same shape as keys.json (env-var-name keys). When a key is
22
- // present the run goes DIRECT to that provider on the user's own credential and
23
- // is NOT metered -- deleting the key reverts to Castle's proxy on the next run.
19
+ // A user's OWN provider credentials, kept SEPARATE from Castle's keys.json.
20
+ // Same shape as keys.json (env-var-name keys). When a key is present the run
21
+ // goes DIRECT to that provider on the user's own credential and is NOT metered
22
+ // -- deleting the key reverts to Castle's proxy on the next run.
24
23
  // The path override mirrors CASTLE_KEYS_PATH so the QA battery stays isolated
25
24
  // from a developer's real ~/.castle. No env fallback on read: the file is the
26
25
  // only source, so a delete fully reverts.
@@ -32,6 +32,11 @@ const COMMAND_NAMES = [
32
32
  "portal.prefetch",
33
33
  "haptics.play",
34
34
  "multiplayer.getSession",
35
+ "characters.open",
36
+ "characters.send",
37
+ "characters.status",
38
+ "characters.history",
39
+ "characters.reset",
35
40
  "cauldronStorage.get",
36
41
  "cauldronStorage.set",
37
42
  "cauldronStorage.delete",
@@ -129,6 +134,16 @@ function runCommand(ctx, command, params, caps) {
129
134
  return passHas(ctx, params, caps);
130
135
  case "multiplayer.getSession":
131
136
  return multiplayerGetSession(ctx, params, caps);
137
+ case "characters.open":
138
+ return charactersOpen(ctx, params, gql);
139
+ case "characters.send":
140
+ return charactersSend(ctx, params, gql);
141
+ case "characters.status":
142
+ return charactersStatus(ctx, params, gql);
143
+ case "characters.history":
144
+ return charactersHistory(ctx, params, gql);
145
+ case "characters.reset":
146
+ return charactersReset(ctx, params, gql);
132
147
  case "cauldronStorage.get":
133
148
  return cauldronStorageGet(ctx, params, gql);
134
149
  case "cauldronStorage.set":
@@ -816,6 +831,38 @@ function asMultiplayerMode(value) {
816
831
  return value;
817
832
  throw new HostCommandError("INVALID_ARGUMENT", "Castle command multiplayer.getSession requires mode.", "multiplayer.getSession");
818
833
  }
834
+ function asGeneration(value, command) {
835
+ if (Number.isSafeInteger(value) && value > 0)
836
+ return value;
837
+ throw new HostCommandError("INVALID_ARGUMENT", `Castle command ${command} requires a positive generation.`, command);
838
+ }
839
+ function asHistoryLimit(value) {
840
+ if (value === undefined || value === null)
841
+ return null;
842
+ if (Number.isSafeInteger(value) && value >= 1 && value <= 50) {
843
+ return value;
844
+ }
845
+ throw new HostCommandError("INVALID_ARGUMENT", "Castle command characters.history requires a limit from 1 through 50.", "characters.history");
846
+ }
847
+ function asBoundedText(value, field, command, maxCharacters, maxBytes) {
848
+ if (typeof value === "string" &&
849
+ value.length > 0 &&
850
+ value.length <= maxCharacters &&
851
+ !value.includes("\0") &&
852
+ new TextEncoder().encode(value).length <= maxBytes) {
853
+ return value;
854
+ }
855
+ throw new HostCommandError("INVALID_ARGUMENT", `Castle command ${command} requires ${field} of at most ${maxCharacters} characters and ${maxBytes} bytes.`, command);
856
+ }
857
+ function asCharacterId(value, command) {
858
+ return asBoundedText(value, "characterId", command, 100, 128);
859
+ }
860
+ function asCharacterOperationId(value, command) {
861
+ return asBoundedText(value, "operationId", command, 120, 128);
862
+ }
863
+ function asCharacterInput(value, command) {
864
+ return asBoundedText(value, "input", command, 2_000, 8_000);
865
+ }
819
866
  // GraphQL hands numeric fields back as numbers or as strings depending on the
820
867
  // scalar, so leaderboard payload shaping accepts both.
821
868
  function asNumberish(value) {
@@ -827,6 +874,86 @@ function asNumberish(value) {
827
874
  return Number.isFinite(parsed) ? parsed : null;
828
875
  }
829
876
  // ---------------------------------------------------------------------------
877
+ // Managed characters.
878
+ //
879
+ // Every command derives the deck and player from HostContext. The untrusted deck
880
+ // sends no subject, definition, instructions or allowance choice. Opening first
881
+ // resolves the current playthrough generation, then pins Ghost's trusted published
882
+ // definition to that generation. Reset carries the old generation so a stale handle
883
+ // cannot advance a newer playthrough.
884
+ async function charactersOpen(ctx, params, gql) {
885
+ const command = "characters.open";
886
+ const deckId = requireDeckId(ctx, command);
887
+ requireUserId(ctx, command);
888
+ const characterId = asCharacterId(params.characterId, command);
889
+ const opened = await graphql(gql, CAULDRON_PLAYTHROUGH_OPEN_MUTATION, { deckId }, command);
890
+ const generation = asGeneration(opened.cauldronPlaythroughOpen?.generation, command);
891
+ const admission = await characterAdmission(gql, deckId, generation, command);
892
+ requirePublishedCharacter(admission, characterId, command);
893
+ return admission;
894
+ }
895
+ async function charactersSend(ctx, params, gql) {
896
+ const command = "characters.send";
897
+ const deckId = requireDeckId(ctx, command);
898
+ requireUserId(ctx, command);
899
+ const data = await graphql(gql, CAULDRON_CHARACTER_SEND_MUTATION, {
900
+ deckId,
901
+ generation: asGeneration(params.generation, command),
902
+ characterId: asCharacterId(params.characterId, command),
903
+ operationId: asCharacterOperationId(params.operationId, command),
904
+ input: asCharacterInput(params.input, command),
905
+ }, command);
906
+ return data.cauldronCharacterSend;
907
+ }
908
+ async function charactersStatus(ctx, params, gql) {
909
+ const command = "characters.status";
910
+ const deckId = requireDeckId(ctx, command);
911
+ requireUserId(ctx, command);
912
+ const data = await graphql(gql, CAULDRON_CHARACTER_STATUS_QUERY, {
913
+ deckId,
914
+ generation: asGeneration(params.generation, command),
915
+ operationId: asCharacterOperationId(params.operationId, command),
916
+ }, command);
917
+ return data.cauldronCharacterStatus;
918
+ }
919
+ async function charactersHistory(ctx, params, gql) {
920
+ const command = "characters.history";
921
+ const deckId = requireDeckId(ctx, command);
922
+ requireUserId(ctx, command);
923
+ const data = await graphql(gql, CAULDRON_CHARACTER_HISTORY_QUERY, {
924
+ deckId,
925
+ generation: asGeneration(params.generation, command),
926
+ characterId: asCharacterId(params.characterId, command),
927
+ limit: asHistoryLimit(params.limit),
928
+ cursor: asOptionalString(params.cursor),
929
+ }, command);
930
+ return data.cauldronCharacterHistory;
931
+ }
932
+ async function charactersReset(ctx, params, gql) {
933
+ const command = "characters.reset";
934
+ const deckId = requireDeckId(ctx, command);
935
+ requireUserId(ctx, command);
936
+ const characterId = asCharacterId(params.characterId, command);
937
+ const reset = await graphql(gql, CAULDRON_PLAYTHROUGH_RESET_MUTATION, {
938
+ deckId,
939
+ generation: asGeneration(params.generation, command),
940
+ operationId: asCharacterOperationId(params.operationId, command),
941
+ }, command);
942
+ const generation = asGeneration(reset.cauldronPlaythroughReset?.generation, command);
943
+ const admission = await characterAdmission(gql, deckId, generation, command);
944
+ requirePublishedCharacter(admission, characterId, command);
945
+ return admission;
946
+ }
947
+ async function characterAdmission(gql, deckId, generation, command) {
948
+ const data = await graphql(gql, CAULDRON_CHARACTER_OPEN_MUTATION, { deckId, generation }, command);
949
+ return data.cauldronCharacterOpen;
950
+ }
951
+ function requirePublishedCharacter(admission, characterId, command) {
952
+ if (admission?.characters?.some((character) => character.id === characterId))
953
+ return;
954
+ throw new HostCommandError("CAULDRON_CHARACTER_NOT_FOUND", `This deck has no published character ${JSON.stringify(characterId)}.`, command);
955
+ }
956
+ // ---------------------------------------------------------------------------
830
957
  // Cauldron deck storage.
831
958
  //
832
959
  // Each of these maps to exactly one bounded server-side operation. The deck
@@ -942,6 +1069,94 @@ async function cauldronStorageBoardGet(ctx, params, gql) {
942
1069
  }, "cauldronStorage.boardGet");
943
1070
  return { entry: data.cauldronStorageBoardGet ?? null };
944
1071
  }
1072
+ const CHARACTER_OPERATION_FIELDS = `
1073
+ operationId
1074
+ characterId
1075
+ status
1076
+ progress
1077
+ result
1078
+ `;
1079
+ const CHARACTER_ADMISSION_FIELDS = `
1080
+ generation
1081
+ definitionVersion
1082
+ characters { id version name }
1083
+ previewAllowance { utcDay allowanceUnits usedUnits remainingUnits }
1084
+ `;
1085
+ const CAULDRON_PLAYTHROUGH_OPEN_MUTATION = `
1086
+ mutation CastleCharacterPlaythroughOpen($deckId: ID!) {
1087
+ cauldronPlaythroughOpen(deckId: $deckId) { generation }
1088
+ }
1089
+ `;
1090
+ const CAULDRON_PLAYTHROUGH_RESET_MUTATION = `
1091
+ mutation CastleCharacterPlaythroughReset(
1092
+ $deckId: ID!
1093
+ $generation: Int!
1094
+ $operationId: String!
1095
+ ) {
1096
+ cauldronPlaythroughReset(
1097
+ deckId: $deckId
1098
+ generation: $generation
1099
+ operationId: $operationId
1100
+ ) { generation }
1101
+ }
1102
+ `;
1103
+ const CAULDRON_CHARACTER_OPEN_MUTATION = `
1104
+ mutation CastleCharacterOpen($deckId: ID!, $generation: Int!) {
1105
+ cauldronCharacterOpen(deckId: $deckId, generation: $generation) {
1106
+ ${CHARACTER_ADMISSION_FIELDS}
1107
+ }
1108
+ }
1109
+ `;
1110
+ const CAULDRON_CHARACTER_SEND_MUTATION = `
1111
+ mutation CastleCharacterSend(
1112
+ $deckId: ID!
1113
+ $generation: Int!
1114
+ $characterId: ID!
1115
+ $operationId: String!
1116
+ $input: String!
1117
+ ) {
1118
+ cauldronCharacterSend(
1119
+ deckId: $deckId
1120
+ generation: $generation
1121
+ characterId: $characterId
1122
+ operationId: $operationId
1123
+ input: $input
1124
+ ) { ${CHARACTER_OPERATION_FIELDS} }
1125
+ }
1126
+ `;
1127
+ const CAULDRON_CHARACTER_STATUS_QUERY = `
1128
+ query CastleCharacterStatus(
1129
+ $deckId: ID!
1130
+ $generation: Int!
1131
+ $operationId: String!
1132
+ ) {
1133
+ cauldronCharacterStatus(
1134
+ deckId: $deckId
1135
+ generation: $generation
1136
+ operationId: $operationId
1137
+ ) { ${CHARACTER_OPERATION_FIELDS} }
1138
+ }
1139
+ `;
1140
+ const CAULDRON_CHARACTER_HISTORY_QUERY = `
1141
+ query CastleCharacterHistory(
1142
+ $deckId: ID!
1143
+ $generation: Int!
1144
+ $characterId: ID!
1145
+ $limit: Int
1146
+ $cursor: ID
1147
+ ) {
1148
+ cauldronCharacterHistory(
1149
+ deckId: $deckId
1150
+ generation: $generation
1151
+ characterId: $characterId
1152
+ limit: $limit
1153
+ cursor: $cursor
1154
+ ) {
1155
+ operations { ${CHARACTER_OPERATION_FIELDS} }
1156
+ cursor
1157
+ }
1158
+ }
1159
+ `;
945
1160
  const DECK_STORAGE_QUERY = `
946
1161
  query CastleDeckStorage($deckId: ID!, $sessionId: ID) {
947
1162
  deckStorage(deckId: $deckId, sessionId: $sessionId)
@@ -17,6 +17,9 @@ const MAX_CLIENT_FRAME_BYTES = 16 * 1024;
17
17
  const MAX_SERVER_FRAME_BYTES = 64 * 1024;
18
18
  const BINARY_MESSAGE_TAG = 0x01;
19
19
  const NONCE_TTL_MS = 60_000;
20
+ // The SDK falls back to a fresh nonce only when a saved token is definitely
21
+ // invalid. HTTP upgrade failures surface as 1006 in browser WebSockets.
22
+ const INVALID_RECONNECT_CLOSE_CODE = 4003;
20
23
  const CHILD_READY_TIMEOUT_MS = 15_000;
21
24
  const CHILD_STOP_GRACE_MS = 2_000;
22
25
  export async function startDevSessionServer(opts) {
@@ -186,9 +189,26 @@ class DevSessionServerImpl {
186
189
  rejectUpgrade(socket, 404);
187
190
  return;
188
191
  }
192
+ if (!this.runtimeReady) {
193
+ rejectUpgrade(socket, 503);
194
+ return;
195
+ }
189
196
  const auth = this.authenticateClient(url);
190
- if (!auth || !this.runtimeReady) {
191
- rejectUpgrade(socket, auth ? 503 : 401);
197
+ if (!auth) {
198
+ // The content proxy has already checked the browser Origin. Its
199
+ // forwarded Host differs from Origin, so this listener cannot repeat
200
+ // that comparison here.
201
+ if (url.searchParams.has('reconnect') && !url.searchParams.has('nonce')) {
202
+ this.clientWss.handleUpgrade(request, socket, head, (ws) => {
203
+ // Even during the close handshake, a bad frame can make ws emit an
204
+ // error. An unhandled error would terminate the entire dev serve.
205
+ ws.on('error', () => undefined);
206
+ ws.close(INVALID_RECONNECT_CLOSE_CODE, 'invalid reconnect token');
207
+ });
208
+ }
209
+ else {
210
+ rejectUpgrade(socket, 401);
211
+ }
192
212
  return;
193
213
  }
194
214
  if (auth.type === 'nonce')
@@ -220,7 +240,7 @@ class DevSessionServerImpl {
220
240
  }
221
241
  const playerId = this.reconnects.get(reconnect);
222
242
  const player = playerId ? this.players.get(playerId) : undefined;
223
- if (!player || player.reconnectToken !== reconnect || player.socket)
243
+ if (!player || player.reconnectToken !== reconnect)
224
244
  return null;
225
245
  return { type: 'reconnect', token: reconnect, playerId: playerId };
226
246
  }
@@ -243,9 +263,23 @@ class DevSessionServerImpl {
243
263
  else {
244
264
  playerId = auth.playerId;
245
265
  player = this.players.get(playerId);
266
+ // A second upgrade can pass authentication before the first rotates the
267
+ // token. Only the first attachment may consume it.
268
+ if (!player || player.reconnectToken !== auth.token) {
269
+ socket.close(INVALID_RECONNECT_CLOSE_CODE, 'stale reconnect token');
270
+ return;
271
+ }
246
272
  this.reconnects.delete(auth.token);
273
+ const previousSocket = player.socket;
247
274
  player.reconnectToken = this.rotateReconnect(playerId);
248
275
  player.socket = socket;
276
+ if (previousSocket) {
277
+ // A page reload can attach before the old document's socket closes.
278
+ // Tell the runtime to remove that actor before joining the replacement.
279
+ this.sendPlatform({ protocolVersion: PROTOCOL_VERSION, t: 'playerLeft', playerId });
280
+ this.sendClient(previousSocket, { t: 'replaced' });
281
+ previousSocket.close(4001, 'replaced');
282
+ }
249
283
  }
250
284
  socket.on('message', (data, isBinary) => this.handleClientMessage(playerId, socket, data, isBinary));
251
285
  socket.on('close', (code) => this.detachClient(playerId, socket, code));
@@ -265,6 +299,9 @@ class DevSessionServerImpl {
265
299
  this.broadcastRoster();
266
300
  }
267
301
  handleClientMessage(playerId, socket, data, isBinary) {
302
+ // Frames queued on the superseded socket must not act as the new player.
303
+ if (this.players.get(playerId)?.socket !== socket)
304
+ return;
268
305
  if (isBinary) {
269
306
  const buffer = Buffer.isBuffer(data)
270
307
  ? data
@@ -5,6 +5,161 @@ const SCOPE_ARGS = `
5
5
  $subject: ID
6
6
  `;
7
7
  const OPERATIONS = {
8
+ characterStatus: {
9
+ field: 'cauldronCharacterStatus',
10
+ query: `query CastleDevCharacterStatus($deckId: ID!, $subject: ID!, $generation: Int!, $operationId: String!) {
11
+ cauldronCharacterStatus(
12
+ deckId: $deckId
13
+ subject: $subject
14
+ generation: $generation
15
+ operationId: $operationId
16
+ asServer: true
17
+ ) { operationId characterId status result archived }
18
+ }`,
19
+ },
20
+ characterHistory: {
21
+ field: 'cauldronCharacterHistory',
22
+ query: `query CastleDevCharacterHistory($deckId: ID!, $subject: ID!, $generation: Int!, $limit: Int, $cursor: ID) {
23
+ cauldronCharacterHistory(
24
+ deckId: $deckId
25
+ subject: $subject
26
+ generation: $generation
27
+ limit: $limit
28
+ cursor: $cursor
29
+ asServer: true
30
+ ) {
31
+ operations { operationId characterId status result archived }
32
+ cursor
33
+ }
34
+ }`,
35
+ },
36
+ characterRecordEvent: {
37
+ field: 'cauldronCharacterRecordEvent',
38
+ query: `mutation CastleDevCharacterRecordEvent($deckId: ID!, $subject: ID!, $generation: Int!, $operationId: String!, $eventTypeId: ID!, $data: Json) {
39
+ cauldronCharacterRecordEvent(
40
+ deckId: $deckId
41
+ subject: $subject
42
+ generation: $generation
43
+ operationId: $operationId
44
+ eventTypeId: $eventTypeId
45
+ data: $data
46
+ asServer: true
47
+ ) { operationId characterId status result archived }
48
+ }`,
49
+ },
50
+ characterSetGameState: {
51
+ field: 'cauldronCharacterSetGameState',
52
+ query: `mutation CastleDevCharacterSetGameState($deckId: ID!, $subject: ID!, $generation: Int!, $operationId: String!, $expectedRevision: Int!, $changes: [CauldronCharacterStateChangeInput!]!) {
53
+ cauldronCharacterSetGameState(deckId: $deckId, subject: $subject, generation: $generation, operationId: $operationId, expectedRevision: $expectedRevision, changes: $changes, asServer: true) {
54
+ operationId characterId status result archived
55
+ }
56
+ }`,
57
+ },
58
+ characterShareClaim: {
59
+ field: 'cauldronCharacterShareClaim',
60
+ query: `mutation CastleDevCharacterShareClaim($deckId: ID!, $subject: ID!, $generation: Int!, $operationId: String!, $recipientCharacterId: ID!, $claimId: ID!, $source: CauldronCharacterKnowledgeSourceInput!) {
61
+ cauldronCharacterShareClaim(deckId: $deckId, subject: $subject, generation: $generation, operationId: $operationId, recipientCharacterId: $recipientCharacterId, claimId: $claimId, source: $source, asServer: true) {
62
+ operationId characterId status result archived
63
+ }
64
+ }`,
65
+ },
66
+ characterInspect: {
67
+ field: 'cauldronCharacterInspect',
68
+ query: `query CastleDevCharacterInspect($deckId: ID!, $subject: ID!, $generation: Int!) {
69
+ cauldronCharacterInspect(deckId: $deckId, subject: $subject, generation: $generation, asServer: true)
70
+ }`,
71
+ },
72
+ characterDeliverKnowledge: {
73
+ field: 'cauldronCharacterDeliverKnowledge',
74
+ query: `mutation CastleDevCharacterDeliverKnowledge(
75
+ $deckId: ID!
76
+ $subject: ID!
77
+ $generation: Int!
78
+ $operationId: String!
79
+ $recipientCharacterId: ID!
80
+ $eventOccurrenceId: ID!
81
+ $claimIds: [ID!]!
82
+ $source: CauldronCharacterKnowledgeSourceInput!
83
+ ) {
84
+ cauldronCharacterDeliverKnowledge(
85
+ deckId: $deckId
86
+ subject: $subject
87
+ generation: $generation
88
+ operationId: $operationId
89
+ recipientCharacterId: $recipientCharacterId
90
+ eventOccurrenceId: $eventOccurrenceId
91
+ claimIds: $claimIds
92
+ source: $source
93
+ asServer: true
94
+ ) { operationId characterId status result }
95
+ }`,
96
+ },
97
+ characterCompleteBeat: {
98
+ field: 'cauldronCharacterCompleteBeat',
99
+ query: `mutation CastleDevCharacterCompleteBeat(
100
+ $deckId: ID!
101
+ $subject: ID!
102
+ $generation: Int!
103
+ $operationId: String!
104
+ $characterId: ID!
105
+ $beatId: ID!
106
+ $eventOccurrenceId: ID!
107
+ $outcomeId: ID!
108
+ ) {
109
+ cauldronCharacterCompleteBeat(
110
+ deckId: $deckId
111
+ subject: $subject
112
+ generation: $generation
113
+ operationId: $operationId
114
+ characterId: $characterId
115
+ beatId: $beatId
116
+ eventOccurrenceId: $eventOccurrenceId
117
+ outcomeId: $outcomeId
118
+ asServer: true
119
+ ) { operationId characterId status result }
120
+ }`,
121
+ },
122
+ playthroughOpen: {
123
+ field: 'cauldronPlaythroughOpen',
124
+ query: `mutation CastleDevPlaythroughOpen($deckId: ID!, $subject: ID!) {
125
+ cauldronPlaythroughOpen(deckId: $deckId, subject: $subject, asServer: true) { generation }
126
+ }`,
127
+ },
128
+ playthroughGet: {
129
+ field: 'cauldronPlaythroughGet',
130
+ query: `query CastleDevPlaythroughGet($deckId: ID!, $subject: ID!, $generation: Int!, $keys: [String!]!) {
131
+ cauldronPlaythroughGet(deckId: $deckId, subject: $subject, generation: $generation, keys: $keys, asServer: true) {
132
+ key
133
+ value
134
+ }
135
+ }`,
136
+ },
137
+ playthroughSet: {
138
+ field: 'cauldronPlaythroughSet',
139
+ query: `mutation CastleDevPlaythroughSet($deckId: ID!, $subject: ID!, $generation: Int!, $entries: [CauldronPlaythroughEntryInput!]!) {
140
+ cauldronPlaythroughSet(deckId: $deckId, subject: $subject, generation: $generation, entries: $entries, asServer: true) {
141
+ rowCount
142
+ byteCount
143
+ }
144
+ }`,
145
+ },
146
+ playthroughDelete: {
147
+ field: 'cauldronPlaythroughDelete',
148
+ query: `mutation CastleDevPlaythroughDelete($deckId: ID!, $subject: ID!, $generation: Int!, $keys: [String!]!) {
149
+ cauldronPlaythroughDelete(deckId: $deckId, subject: $subject, generation: $generation, keys: $keys, asServer: true) {
150
+ rowCount
151
+ byteCount
152
+ }
153
+ }`,
154
+ },
155
+ playthroughReset: {
156
+ field: 'cauldronPlaythroughReset',
157
+ query: `mutation CastleDevPlaythroughReset($deckId: ID!, $subject: ID!, $generation: Int!, $operationId: String!) {
158
+ cauldronPlaythroughReset(deckId: $deckId, subject: $subject, generation: $generation, operationId: $operationId, asServer: true) {
159
+ generation
160
+ }
161
+ }`,
162
+ },
8
163
  get: {
9
164
  field: 'cauldronStorageGet',
10
165
  query: `query CastleDevStorageGet(${SCOPE_ARGS} $keys: [String!]!) {