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
@@ -5,6 +5,7 @@ const KEEPALIVE_INTERVAL_MS = 25_000;
5
5
  const HELLO_TIMEOUT_MS = 10_000;
6
6
  const RECONNECT_BUDGET_MS = 30_000;
7
7
  const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
8
+ const INVALID_DEV_RECONNECT_CLOSE_CODE = 4003;
8
9
  let activeConnection = null;
9
10
  export const Multiplayer = { join };
10
11
  async function join(options) {
@@ -28,6 +29,7 @@ class MultiplayerConnectionImpl {
28
29
  currentSoloReason = null;
29
30
  baseUrl = "";
30
31
  reconnectToken = "";
32
+ devReconnectStorageKey = null;
31
33
  socket = null;
32
34
  socketAttempt = 0;
33
35
  keepalive = null;
@@ -120,9 +122,42 @@ class MultiplayerConnectionImpl {
120
122
  this.solo = false;
121
123
  this.currentSoloReason = null;
122
124
  this.baseUrl = result.url;
125
+ this.devReconnectStorageKey = result.devReconnectScope
126
+ ? `castle-dev-mp-reconnect:${result.url}:${result.sessionId}:${result.devReconnectScope}`
127
+ : null;
123
128
  this.transition("connecting");
129
+ const savedToken = this.devReconnectStorageKey
130
+ ? readDevReconnectToken(this.devReconnectStorageKey)
131
+ : null;
132
+ if (savedToken && await this.restoreDevReconnect(savedToken))
133
+ return;
134
+ this.assertOpen();
124
135
  await this.openSocket("nonce", result.nonce);
125
136
  }
137
+ async restoreDevReconnect(token) {
138
+ const startedAt = Date.now();
139
+ let attempt = 0;
140
+ while (true) {
141
+ this.assertOpen();
142
+ try {
143
+ await this.openSocket("reconnect", token);
144
+ return true;
145
+ }
146
+ catch (error) {
147
+ if (error instanceof SocketClosedError &&
148
+ error.code === INVALID_DEV_RECONNECT_CLOSE_CODE) {
149
+ clearDevReconnectToken(this.devReconnectStorageKey, token);
150
+ return false;
151
+ }
152
+ // A 503 during a server rebuild, network failure, or hello timeout
153
+ // does not prove the credential expired. Retain it if retries run out.
154
+ if (Date.now() - startedAt >= RECONNECT_BUDGET_MS)
155
+ throw error;
156
+ const delay = RECONNECT_DELAYS_MS[Math.min(attempt++, RECONNECT_DELAYS_MS.length - 1)];
157
+ await pause(delay);
158
+ }
159
+ }
160
+ }
126
161
  connectSolo(result) {
127
162
  this.solo = true;
128
163
  this.currentSoloReason = result.soloReason ?? "unavailable";
@@ -210,6 +245,8 @@ class MultiplayerConnectionImpl {
210
245
  this.currentPlayerId = frame.playerId;
211
246
  this.currentSessionId = frame.sessionId;
212
247
  this.reconnectToken = frame.reconnectToken;
248
+ if (this.devReconnectStorageKey)
249
+ writeDevReconnectToken(this.devReconnectStorageKey, frame.reconnectToken);
213
250
  // Re-acquisition is limited to one per outage, not one per session. A phone
214
251
  // is backgrounded many times in a play, and each of those is its own outage;
215
252
  // without this the second one finds the budget spent and closes for good.
@@ -342,6 +379,12 @@ class MultiplayerConnectionImpl {
342
379
  finish(metadata) {
343
380
  if (this.currentState === "closed")
344
381
  return;
382
+ // A failed recovery can leave the server's reconnect token valid. Keep it
383
+ // for a later page reload; only a deliberate/authoritative end retires it.
384
+ if (this.devReconnectStorageKey &&
385
+ this.reconnectToken &&
386
+ (metadata.type === "left" || metadata.type === "bye" || metadata.type === "replaced"))
387
+ clearDevReconnectToken(this.devReconnectStorageKey, this.reconnectToken);
345
388
  this.stopKeepalive();
346
389
  const socket = this.socket;
347
390
  this.socket = null;
@@ -419,6 +462,31 @@ function authenticatedUrl(baseUrl, credential, value) {
419
462
  url.searchParams.set(credential, value);
420
463
  return url.toString();
421
464
  }
465
+ function readDevReconnectToken(key) {
466
+ try {
467
+ return sessionStorage.getItem(key);
468
+ }
469
+ catch {
470
+ return null;
471
+ }
472
+ }
473
+ function writeDevReconnectToken(key, token) {
474
+ try {
475
+ sessionStorage.setItem(key, token);
476
+ }
477
+ catch {
478
+ // Private browsing or disabled storage still has ordinary in-page recovery.
479
+ }
480
+ }
481
+ function clearDevReconnectToken(key, token) {
482
+ try {
483
+ if (sessionStorage.getItem(key) === token)
484
+ sessionStorage.removeItem(key);
485
+ }
486
+ catch {
487
+ // Storage may disappear while the page is closing.
488
+ }
489
+ }
422
490
  function parsePlatformFrame(value) {
423
491
  if (typeof value !== "string")
424
492
  return null;
@@ -0,0 +1,32 @@
1
+ export type TunedParamValue = number | string | boolean;
2
+ export interface TunedParam {
3
+ id: string;
4
+ before: TunedParamValue;
5
+ after: TunedParamValue;
6
+ }
7
+ export declare function registerParams(path: string, params: unknown): void;
8
+ export interface AppliedNotice {
9
+ type: "castle-params-applied";
10
+ path: string;
11
+ /** The broadcast this answers, so a late reply cannot settle a later wait. */
12
+ seq: number | null;
13
+ ok: boolean;
14
+ }
15
+ /**
16
+ * What the deck tells the editor about a tuned change it was sent.
17
+ *
18
+ * A separate function because the SHAPE is the contract: the editor holds a
19
+ * run's worth of state on it, and a serve that starts numbering broadcasts
20
+ * while a deck still answers without a number has to read as "not this one"
21
+ * rather than as a match.
22
+ */
23
+ export declare function appliedNotice(path: string, seq: unknown, ok: boolean): AppliedNotice;
24
+ /**
25
+ * Write tuned values into every live `PARAMS` registered under the path. False
26
+ * unless every slot landed on every object -- an unregistered path, a key one
27
+ * object does not have, a frozen object -- and the rest are still written,
28
+ * because a slot that cannot be applied is no reason to withhold the ones that
29
+ * can. An older instance missing a key a later code edit added reports false
30
+ * too: the run may be reading it, so the editor offers a restart.
31
+ */
32
+ export declare function applyTunedParams(path: string, slots: TunedParam[]): boolean;
@@ -0,0 +1,100 @@
1
+ // The live `PARAMS` objects of the deck's modules, so a value tuned in the
2
+ // editor's Parameters panel reaches the run already in progress.
3
+ //
4
+ // Nothing in a deck calls `registerParams`. The dev serve appends the call to
5
+ // every module that declares a `PARAMS` object (cli/src/paramsRegisterPlugin.ts)
6
+ // and a published deck never gets it at all -- there is no editor out there to
7
+ // tune anything. That is the whole reason the registry keys on the deck-relative
8
+ // path rather than on anything the module says about itself: the path is what
9
+ // the serve's broadcast names, and the module never had to agree to anything.
10
+ //
11
+ // A path holds EVERY object ever registered under it, not the latest. The serve
12
+ // appends the call to every transform of the module, including a kit's
13
+ // cache-busting `?t=` re-import, which evaluates a fresh module instance with a
14
+ // fresh `PARAMS` under the same path. An older instance can still be the one
15
+ // running -- physics-2d's play frame keeps the classes it started with and never
16
+ // adopts swapped ones -- and the registry cannot tell which instance a run reads,
17
+ // so the only honest answer is to write the tune into all of them.
18
+ //
19
+ // Each object is mutated IN PLACE, never replaced. Deck code holds the same
20
+ // reference (`PARAMS.jumpHeight` at the use site is the documented way to read
21
+ // one), so handing back a new object would leave every reader on the old one.
22
+ const registered = new Map();
23
+ export function registerParams(path, params) {
24
+ if (typeof path !== "string" || !path)
25
+ return;
26
+ if (typeof params !== "object" || params === null)
27
+ return;
28
+ let instances = registered.get(path);
29
+ if (!instances) {
30
+ instances = new Set();
31
+ registered.set(path, instances);
32
+ }
33
+ instances.add(params);
34
+ }
35
+ // Own properties only, at every level. A `ParamSlot.id` comes from a key the
36
+ // file wrote in an object literal, so an inherited name (`constructor`,
37
+ // `toString`) is never one of them -- and writing through one would add a
38
+ // property to an object that never had it.
39
+ function owns(holder, key) {
40
+ return Object.prototype.hasOwnProperty.call(holder, key);
41
+ }
42
+ function assign(root, id, value) {
43
+ const keys = id.split(".");
44
+ let holder = root;
45
+ for (let i = 0; i < keys.length - 1; i += 1) {
46
+ const next = owns(holder, keys[i]) ? holder[keys[i]] : undefined;
47
+ if (typeof next !== "object" || next === null)
48
+ return false;
49
+ holder = next;
50
+ }
51
+ const leaf = keys[keys.length - 1];
52
+ if (!owns(holder, leaf))
53
+ return false;
54
+ try {
55
+ holder[leaf] = value;
56
+ }
57
+ catch {
58
+ // A frozen PARAMS object. Module code is strict, so the assignment throws
59
+ // rather than failing quietly, and the editor can say the tune did not land.
60
+ return false;
61
+ }
62
+ return true;
63
+ }
64
+ /**
65
+ * What the deck tells the editor about a tuned change it was sent.
66
+ *
67
+ * A separate function because the SHAPE is the contract: the editor holds a
68
+ * run's worth of state on it, and a serve that starts numbering broadcasts
69
+ * while a deck still answers without a number has to read as "not this one"
70
+ * rather than as a match.
71
+ */
72
+ export function appliedNotice(path, seq, ok) {
73
+ return {
74
+ type: "castle-params-applied",
75
+ path,
76
+ seq: typeof seq === "number" && Number.isFinite(seq) ? seq : null,
77
+ ok,
78
+ };
79
+ }
80
+ /**
81
+ * Write tuned values into every live `PARAMS` registered under the path. False
82
+ * unless every slot landed on every object -- an unregistered path, a key one
83
+ * object does not have, a frozen object -- and the rest are still written,
84
+ * because a slot that cannot be applied is no reason to withhold the ones that
85
+ * can. An older instance missing a key a later code edit added reports false
86
+ * too: the run may be reading it, so the editor offers a restart.
87
+ */
88
+ export function applyTunedParams(path, slots) {
89
+ const instances = registered.get(path);
90
+ if (!instances || instances.size === 0)
91
+ return false;
92
+ let applied = true;
93
+ for (const target of instances) {
94
+ for (const slot of slots) {
95
+ if (!assign(target, slot.id, slot.after))
96
+ applied = false;
97
+ }
98
+ }
99
+ return applied;
100
+ }
@@ -1,4 +1,5 @@
1
1
  import { type CommandName, type CommandParams, type CommandResponseEnvelope } from "./commands";
2
+ import { type TunedParam } from "./paramsRegistry";
2
3
  export declare const CARD_RATIO: number;
3
4
  interface LocalResponse {
4
5
  type: string;
@@ -11,6 +12,12 @@ export interface FileChange {
11
12
  /** Deck-relative POSIX path. */
12
13
  path: string;
13
14
  event: "add" | "change" | "delete";
15
+ /**
16
+ * Present when the serve verified that nothing but `PARAMS` values changed.
17
+ * Applied to the module's registered object before listeners are told, so a
18
+ * consumer deciding whether to reload sees a deck that is already current.
19
+ */
20
+ tuned?: TunedParam[];
14
21
  /**
15
22
  * Deck-relative paths affected via the Vite import graph: the changed file
16
23
  * itself (when imported by anything) plus every transitive importer. Empty
@@ -1,5 +1,6 @@
1
1
  import { CASTLE_SDK_PROTOCOL, } from "./commands";
2
2
  import { getCastleEmbed, isEdit } from "./context";
3
+ import { appliedNotice, applyTunedParams, } from "./paramsRegistry";
3
4
  export const CARD_RATIO = 5 / 7;
4
5
  // Host -> deck capture request, and the deck's answer. Kept in sync with the
5
6
  // editor shell (cli/src/shell/coverApi.ts).
@@ -929,6 +930,30 @@ export function onFilesChanged(listener) {
929
930
  filesChangedListeners.add(listener);
930
931
  return () => filesChangedListeners.delete(listener);
931
932
  }
933
+ const isTunedValue = (v) => typeof v === "number" || typeof v === "string" || typeof v === "boolean";
934
+ function tunedSlots(raw) {
935
+ if (!Array.isArray(raw))
936
+ return undefined;
937
+ const slots = [];
938
+ for (const slot of raw) {
939
+ if (typeof slot?.id !== "string")
940
+ return undefined;
941
+ if (!isTunedValue(slot.before) || !isTunedValue(slot.after))
942
+ return undefined;
943
+ slots.push({ id: slot.id, before: slot.before, after: slot.after });
944
+ }
945
+ return slots.length > 0 ? slots : undefined;
946
+ }
947
+ // Answer whether the tune landed, even when nothing was registered under the
948
+ // path. The editor's Play panel waits on this before deciding whether it is
949
+ // showing current files, and a silence it has to time out reads as a stall.
950
+ function reportApplied(path, seq, ok) {
951
+ if (typeof window === "undefined" || window.parent === window)
952
+ return;
953
+ const origin = window
954
+ .__castleShellOrigin;
955
+ window.parent.postMessage(appliedNotice(path, seq, ok), origin || "*");
956
+ }
932
957
  function dispatchFilesChanged(msg) {
933
958
  const rawChanges = Array.isArray(msg.changes) ? msg.changes : [];
934
959
  const changes = [];
@@ -938,9 +963,11 @@ function dispatchFilesChanged(msg) {
938
963
  const event = raw.event;
939
964
  if (event !== "add" && event !== "change" && event !== "delete")
940
965
  continue;
966
+ const tuned = tunedSlots(raw.tuned);
941
967
  changes.push({
942
968
  path: raw.path,
943
969
  event,
970
+ ...(tuned ? { tuned } : {}),
944
971
  affected: Array.isArray(raw.affected)
945
972
  ? raw.affected.filter((p) => typeof p === "string")
946
973
  : [],
@@ -948,6 +975,13 @@ function dispatchFilesChanged(msg) {
948
975
  }
949
976
  if (changes.length === 0)
950
977
  return;
978
+ // Before the listeners: a consumer asking whether to reload should be looking
979
+ // at a deck the tune has already reached.
980
+ for (const change of changes) {
981
+ if (!change.tuned)
982
+ continue;
983
+ reportApplied(change.path, msg.seq, applyTunedParams(change.path, change.tuned));
984
+ }
951
985
  const affected = Array.isArray(msg.affected)
952
986
  ? msg.affected.filter((p) => typeof p === "string")
953
987
  : [];
@@ -1,4 +1,5 @@
1
1
  import type { Json } from "../types";
2
+ import type { CharacterHistory, CharacterOperation } from "../commands";
2
3
  import type { PlatformHandle } from "./platformHandle";
3
4
  export interface ServerStorageListOptions {
4
5
  prefix?: string;
@@ -36,11 +37,87 @@ export interface ServerStorageBoard {
36
37
  top(limit?: number): Promise<ServerStorageBoardScore[]>;
37
38
  get(userId: string): Promise<ServerStorageBoardScore | null>;
38
39
  }
40
+ /**
41
+ * Experimental generation-bound game state for one player. A handle never changes
42
+ * generation: reset returns a new handle so work holding the old one stays fenced by
43
+ * the platform instead of silently writing into the new playthrough.
44
+ */
45
+ export interface ServerPlaythrough {
46
+ readonly generation: number;
47
+ /** Explicit narrative changes for this same player and generation. */
48
+ readonly characters: ServerPlaythroughCharacters;
49
+ get<T extends Json = Json>(keys: string[]): Promise<Record<string, T>>;
50
+ set(values: Record<string, Json>): Promise<void>;
51
+ remove(keys: string[]): Promise<void>;
52
+ reset(operationId: string): Promise<ServerPlaythrough>;
53
+ }
54
+ export interface RecordCharacterEventInput {
55
+ operationId: string;
56
+ eventTypeId: string;
57
+ data?: Record<string, string | number | boolean>;
58
+ }
59
+ export interface SetCharacterGameStateInput {
60
+ operationId: string;
61
+ expectedRevision: number;
62
+ changes: Array<{
63
+ key: string;
64
+ value: string | number | boolean;
65
+ }>;
66
+ }
67
+ export interface ShareCharacterClaimInput {
68
+ operationId: string;
69
+ recipientCharacterId: string;
70
+ claimId: string;
71
+ source: {
72
+ type: "character";
73
+ characterId: string;
74
+ };
75
+ }
76
+ export type CharacterKnowledgeSource = {
77
+ type: "creator_event";
78
+ } | {
79
+ type: "character";
80
+ characterId: string;
81
+ };
82
+ export interface DeliverCharacterKnowledgeInput {
83
+ operationId: string;
84
+ recipientCharacterId: string;
85
+ eventOccurrenceId: string;
86
+ claimIds: string[];
87
+ source: CharacterKnowledgeSource;
88
+ }
89
+ export interface CompleteCharacterBeatInput {
90
+ operationId: string;
91
+ characterId: string;
92
+ beatId: string;
93
+ eventOccurrenceId: string;
94
+ outcomeId: string;
95
+ }
96
+ /**
97
+ * Narrative commands do not run a model. They record creator-validated events,
98
+ * knowledge delivery and beat completion inside this immutable playthrough.
99
+ */
100
+ export interface ServerPlaythroughCharacters {
101
+ recordEvent(input: RecordCharacterEventInput): Promise<CharacterOperation>;
102
+ setGameState(input: SetCharacterGameStateInput): Promise<CharacterOperation>;
103
+ shareClaim(input: ShareCharacterClaimInput): Promise<CharacterOperation>;
104
+ inspect(): Promise<Json>;
105
+ deliverKnowledge(input: DeliverCharacterKnowledgeInput): Promise<CharacterOperation>;
106
+ completeBeat(input: CompleteCharacterBeatInput): Promise<CharacterOperation>;
107
+ status(operationId: string): Promise<CharacterOperation>;
108
+ history(options?: ServerCharacterHistoryOptions): Promise<CharacterHistory>;
109
+ }
110
+ export interface ServerCharacterHistoryOptions {
111
+ limit?: number;
112
+ cursor?: string | null;
113
+ }
39
114
  export interface ServerStorage {
40
115
  /** Shared by everyone playing the deck, and owned by this server. */
41
116
  readonly deck: ServerStorageScope;
42
117
  /** One player's public data. Readable by anyone; writable by them or by this server. */
43
118
  user(userId: string): ServerStorageScope;
44
119
  board(name: string): ServerStorageBoard;
120
+ /** Opens one player's experimental, generation-bound game namespace. */
121
+ playthrough(userId: string): Promise<ServerPlaythrough>;
45
122
  }
46
123
  export declare function createServerStorage(platformHandle: PlatformHandle): ServerStorage;