castle-web-cli 0.4.245 → 0.4.247

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.
@@ -74,6 +74,8 @@ const COMMAND_NAMES = [
74
74
  "hub.reportChat",
75
75
  "hub.commit",
76
76
  "hub.cancel",
77
+ "deck.invite",
78
+ "deck.inviteArrival",
77
79
  "haptics.play",
78
80
  "multiplayer.getSession",
79
81
  "multiplayer.getJoinHint",
@@ -183,12 +185,17 @@ export async function executeCommand(ctx, command, params, capabilities, options
183
185
  const acquisition = isSessionAcquisition(command)
184
186
  ? capabilities.hub?.sessionAcquisitionStarted?.(ctx)
185
187
  : undefined;
188
+ const deckInviteAcquisition = isSessionAcquisition(command)
189
+ ? capabilities.deckInvite?.sessionAcquisitionStarted(ctx)
190
+ : undefined;
186
191
  try {
187
192
  const data = await dispatchCommand(ctx, command, (params ?? {}), capabilities, options);
188
193
  capabilities.hub?.assertActive?.();
189
194
  // A join the deck gave up on is not the connection it holds.
190
195
  if (!options.signal?.aborted)
191
196
  noteAcquiredSession(ctx, command, data, capabilities, acquisition);
197
+ if (!options.signal?.aborted && deckInviteAcquisition !== undefined)
198
+ noteDeckInviteSession(ctx, data, capabilities, deckInviteAcquisition);
192
199
  return { ok: true, data };
193
200
  }
194
201
  catch (error) {
@@ -219,6 +226,17 @@ function noteAcquiredSession(ctx, command, data, caps, acquisition) {
219
226
  caps.hub.sessionAcquired(result.sessionId, ctx, acquisition);
220
227
  }
221
228
  }
229
+ // Deck invites mint from the public session the deck joined last; any other
230
+ // acquisition (a named room, a party, a destination) leaves none to mint from.
231
+ function noteDeckInviteSession(ctx, data, caps, acquisition) {
232
+ const result = data;
233
+ if (result?.status !== "ok" || typeof result.sessionId !== "string" || !result.sessionId)
234
+ return;
235
+ const join = SESSION_JOINS.get(result) ?? { isPublic: false, env: null };
236
+ caps.deckInvite?.sessionAcquired(result.sessionId, join, ctx, acquisition);
237
+ }
238
+ // How multiplayerGetSession acquired each result it returned.
239
+ const SESSION_JOINS = new WeakMap();
222
240
  const HUB_VISIT_COMMANDS = new Set([
223
241
  "hub.go",
224
242
  "hub.back",
@@ -274,6 +292,8 @@ function runCommand(ctx, command, params, caps, options) {
274
292
  }
275
293
  if (isHubVisitCommand(command))
276
294
  return runHubCommand(ctx, command, params, caps, options.signal);
295
+ if (isDeckInviteCommand(command))
296
+ return runDeckInviteCommand(ctx, command, caps, options.signal);
277
297
  const gql = caps.graphqlFetch;
278
298
  switch (command) {
279
299
  case "agent.chat":
@@ -442,6 +462,16 @@ async function multiplayerGetSession(ctx, params, caps) {
442
462
  if (request.mode === "public")
443
463
  await caps.hub?.prepareInvite?.(ctx);
444
464
  const inviteHint = request.mode === "public" ? caps.hub?.inviteJoinHint?.(ctx) : null;
465
+ // A document opened from a deck invite link joins in the link's env, every
466
+ // join. Its token rides on each public join that is not a party play (a hub
467
+ // invite wins; a party's join wins) until the arrival completes or Ghost
468
+ // refuses it. Ghost's join-time check spends nothing, so overlapping joins
469
+ // may all carry it.
470
+ const deckLink = inviteHint ? null : caps.deckInvite?.linkJoin(ctx) ?? null;
471
+ const steerable = !!deckLink && request.mode === "public" && !ctx.partyId;
472
+ if (steerable)
473
+ await caps.deckInvite?.prepare(ctx);
474
+ const deckToken = steerable ? caps.deckInvite?.linkJoin(ctx)?.token ?? null : null;
445
475
  // Which shared session a play belongs to is the host's call, not the deck's,
446
476
  // the way `shared.cpp` reads the party off the engine rather than the scene.
447
477
  // A play that arrived through a party stays inside it unless trusted host
@@ -450,14 +480,17 @@ async function multiplayerGetSession(ctx, params, caps) {
450
480
  ? "party"
451
481
  : request.mode;
452
482
  let data;
483
+ const deckSecret = deckToken;
453
484
  try {
454
- data = await graphql(caps.graphqlFetch, inviteHint ? CAULDRON_INVITE_SESSION_QUERY : CAULDRON_MULTIPLAYER_SESSION_QUERY, {
485
+ data = await graphql(caps.graphqlFetch, inviteHint ? CAULDRON_INVITE_SESSION_QUERY
486
+ : deckLink ? CAULDRON_DECK_INVITE_SESSION_QUERY : CAULDRON_MULTIPLAYER_SESSION_QUERY, {
455
487
  deckId,
456
488
  mode,
457
489
  key: request.key ?? null,
458
490
  sessionId: request.mode === "public" ? hintedSessionId : null,
459
- partyId: inviteHint ? null : ctx.partyId ?? null,
491
+ partyId: inviteHint || deckToken ? null : ctx.partyId ?? null,
460
492
  ...(inviteHint ? { hubInviteToken: inviteHint.token, env: inviteHint.env } : {}),
493
+ ...(deckLink ? { deckInviteToken: deckToken, env: deckLink.env } : {}),
461
494
  }, "multiplayer.getSession");
462
495
  }
463
496
  catch (error) {
@@ -467,9 +500,15 @@ async function multiplayerGetSession(ctx, params, caps) {
467
500
  if (error instanceof HostCommandError && error.code === "LOGIN_REQUIRED") {
468
501
  return signedOutSoloSession();
469
502
  }
470
- throw error;
503
+ // A join that carried a deck invite token answers with Ghost's code alone.
504
+ throw deckSecret ? deckInviteSafeError(error, "multiplayer.getSession", deckSecret) : error;
471
505
  }
472
- return multiplayerSessionResult(data.getCauldronMultiplayerSession);
506
+ const result = multiplayerSessionResult(data.getCauldronMultiplayerSession);
507
+ SESSION_JOINS.set(result, {
508
+ isPublic: mode === "public",
509
+ env: inviteHint ? inviteHint.env : deckLink ? deckLink.env : null,
510
+ });
511
+ return result;
473
512
  }
474
513
  function signedOutSoloSession() {
475
514
  return { status: "solo", url: null, nonce: null, sessionId: null, soloReason: "unavailable" };
@@ -2921,6 +2960,10 @@ const CAULDRON_MULTIPLAYER_SESSION_QUERY = `
2921
2960
  const CAULDRON_INVITE_SESSION_QUERY = CAULDRON_MULTIPLAYER_SESSION_QUERY
2922
2961
  .replace("$partyId: ID", "$partyId: ID\n $hubInviteToken: String\n $env: String")
2923
2962
  .replace("partyId: $partyId", "partyId: $partyId\n hubInviteToken: $hubInviteToken\n env: $env");
2963
+ // Likewise for hosts without a deck invite token.
2964
+ const CAULDRON_DECK_INVITE_SESSION_QUERY = CAULDRON_MULTIPLAYER_SESSION_QUERY
2965
+ .replace("$partyId: ID", "$partyId: ID\n $deckInviteToken: String\n $env: String")
2966
+ .replace("partyId: $partyId", "partyId: $partyId\n deckInviteToken: $deckInviteToken\n env: $env");
2924
2967
  const CAULDRON_MULTIPLAYER_DESTINATION_DESCRIPTION_QUERY = `
2925
2968
  query CastleCauldronMultiplayerDestinationDescription($deckId: ID!, $routeId: String!) {
2926
2969
  describeCauldronMultiplayerDestination(deckId: $deckId, routeId: $routeId) {
@@ -4588,3 +4631,318 @@ function runHubCommand(ctx, command, params, caps, signal) {
4588
4631
  : Promise.resolve({ status: "unavailable" });
4589
4632
  }
4590
4633
  }
4634
+ // Ghost mints 32 random bytes as base64url: exactly 43 characters.
4635
+ const DECK_INVITE_TOKEN = /^[A-Za-z0-9_-]{43}$/;
4636
+ const DECK_INVITE_USER_ID = /^[1-9]\d{0,9}$/;
4637
+ const DECK_INVITE_DECK_ID = /^[A-Za-z0-9_-]{1,64}$/;
4638
+ // Ghost's roster check can lag a join; the deck's command times out at 15 s.
4639
+ const DECK_INVITE_ROSTER_LAG_MS = 12_000;
4640
+ const DECK_INVITE_RETRY_MS = 1_000;
4641
+ const DECK_INVITE_RESOLVE_ATTEMPTS = 5;
4642
+ const DECK_INVITE_FRIENDS_MAX = 5;
4643
+ // The only codes a call carrying the token passes to the frame; everything else,
4644
+ // a cancellation included, is CASTLE_HOST_ERROR.
4645
+ const DECK_INVITE_GHOST_CODE = /^CAULDRON_DECK_INVITE_[A-Z0-9_]{1,40}$/;
4646
+ const DECK_INVITE_ACCOUNT_CODES = new Set(["FEATURE_NOT_ENABLED", "LOGIN_REQUIRED", "ACCOUNT_REQUIRED"]);
4647
+ /** The link of a castle.xyz deck URL; "invalid" for a malformed `deckInvite`. */
4648
+ export function deckInviteFromUri(uri) {
4649
+ if (!uri)
4650
+ return null;
4651
+ try {
4652
+ const url = new URL(uri);
4653
+ if (url.protocol !== "https:" || !["castle.xyz", "www.castle.xyz"].includes(url.hostname) || !url.pathname.startsWith("/d/"))
4654
+ return null;
4655
+ const token = url.searchParams.get("deckInvite");
4656
+ if (token === null)
4657
+ return null;
4658
+ const deckId = decodeURIComponent(url.pathname.slice(3).split("/")[0] ?? "");
4659
+ return DECK_INVITE_TOKEN.test(token) && url.searchParams.getAll("deckInvite").length === 1 && DECK_INVITE_DECK_ID.test(deckId)
4660
+ ? { deckId, token } : "invalid";
4661
+ }
4662
+ catch {
4663
+ return null;
4664
+ }
4665
+ }
4666
+ const DECK_INVITE_CREATE = `mutation CastleDeckInvite($deckId: ID!, $sessionId: ID!, $env: String) {
4667
+ createCauldronDeckInvite(deckId: $deckId, sessionId: $sessionId, env: $env)
4668
+ }`;
4669
+ // Ghost refuses a token for another deck before it spends a use.
4670
+ const DECK_INVITE_RESOLVE = `mutation CastleDeckInviteResolve($token: String!, $deckId: ID, $env: String) {
4671
+ resolveCauldronDeckInvite(token: $token, deckId: $deckId, env: $env)
4672
+ }`;
4673
+ const DECK_INVITE_COMPLETE = `mutation CastleDeckInviteArrival($token: String!, $sessionId: ID!, $env: String) {
4674
+ completeCauldronDeckInvite(token: $token, sessionId: $sessionId, env: $env)
4675
+ }`;
4676
+ // Ghost's own answer about this link, deck or account; anything else (a lost
4677
+ // response, a server error) may pass, so it is not.
4678
+ function deckInviteRefusal(error) {
4679
+ if (!(error instanceof HostCommandError))
4680
+ return null;
4681
+ const code = error.code;
4682
+ return (code.startsWith("CAULDRON_DECK_INVITE_") && code !== "CAULDRON_DECK_INVITE_NOT_IN_SESSION") ||
4683
+ code === "FEATURE_NOT_ENABLED" || code === "ACCOUNT_REQUIRED" || code === "LOGIN_REQUIRED" ? code : null;
4684
+ }
4685
+ // A call that carried a deck invite token answers the frame with Ghost's code
4686
+ // alone: never its message, its extensions, or a transport error's text, any of
4687
+ // which could echo the token back.
4688
+ function deckInviteSafeError(error, command, token) {
4689
+ const raw = error instanceof HostCommandError ? error.code : "";
4690
+ const ghost = DECK_INVITE_GHOST_CODE.test(raw) || DECK_INVITE_ACCOUNT_CODES.has(raw);
4691
+ const code = ghost && !(token && raw.includes(token)) ? raw : "CASTLE_HOST_ERROR";
4692
+ return new HostCommandError(code, "Castle could not complete this invite request.", command);
4693
+ }
4694
+ async function deckInviteGraphql(gql, query, variables, command, token) {
4695
+ try {
4696
+ return await graphql(gql, query, variables, command);
4697
+ }
4698
+ catch (error) {
4699
+ throw deckInviteSafeError(error, command, token);
4700
+ }
4701
+ }
4702
+ function redactToken(text, token) {
4703
+ return token ? text.split(token).join("") : text;
4704
+ }
4705
+ function deckInviteUser(value, token) {
4706
+ const raw = value;
4707
+ return typeof raw?.userId === "string" && DECK_INVITE_USER_ID.test(raw.userId) && typeof raw.username === "string"
4708
+ ? { userId: raw.userId, username: redactToken(raw.username, token).slice(0, 64) } : null;
4709
+ }
4710
+ export function createGhostDeckInvite(options) {
4711
+ const impl = new GhostDeckInviteImpl(options);
4712
+ return {
4713
+ dispose: () => impl.dispose(),
4714
+ sessionAcquisitionStarted: () => impl.sessionAcquisitionStarted(),
4715
+ sessionAcquired: (sessionId, join, ctx, acquisition) => impl.sessionAcquired(sessionId, join, ctx, acquisition),
4716
+ prepare: (ctx) => impl.prepare(ctx),
4717
+ linkJoin: (ctx) => impl.linkJoin(ctx),
4718
+ invite: (ctx, signal) => impl.invite(ctx, signal),
4719
+ inviteArrival: (ctx, signal) => impl.inviteArrival(ctx, signal),
4720
+ };
4721
+ }
4722
+ class GhostDeckInviteImpl {
4723
+ options;
4724
+ disposed = false;
4725
+ token;
4726
+ resolved = false;
4727
+ // Public joins carry the token after a resolve for this deck, until the
4728
+ // arrival completes or Ghost says the link is unusable.
4729
+ hintActive = false;
4730
+ inviter = null;
4731
+ preparation = null;
4732
+ resolveFailures = 0;
4733
+ resolveRetryAt = 0;
4734
+ session = null;
4735
+ acquisitions = 0;
4736
+ acceptedAcquisition = 0;
4737
+ arrival = null;
4738
+ gql;
4739
+ env;
4740
+ now;
4741
+ sleep;
4742
+ constructor(options) {
4743
+ this.options = options;
4744
+ const link = options.link;
4745
+ // A link to another deck is never resolved here: resolving spends one of its uses.
4746
+ this.token = link && link.deckId === options.deckId && DECK_INVITE_TOKEN.test(link.token) ? link.token : null;
4747
+ this.env = options.env ?? null;
4748
+ this.now = options.now ?? (() => Date.now());
4749
+ this.sleep = options.sleep ?? defaultHubSleep;
4750
+ this.gql = async (query, variables) => {
4751
+ this.assertActive();
4752
+ const result = await options.graphqlFetch(query, variables);
4753
+ this.assertActive();
4754
+ return result;
4755
+ };
4756
+ }
4757
+ assertActive(signal) {
4758
+ if (this.disposed || signal?.aborted)
4759
+ throw new HostCommandError("CANCELLED", "This play ended.", "deck.invite");
4760
+ }
4761
+ dispose() {
4762
+ this.disposed = true;
4763
+ }
4764
+ ours(ctx) {
4765
+ return !this.disposed && ctx.deckId === this.options.deckId &&
4766
+ typeof ctx.documentId === "string" && ctx.documentId === this.options.documentId;
4767
+ }
4768
+ // The deck keeps the connection of the join it started last that succeeded,
4769
+ // so an earlier join answering late must not replace it.
4770
+ sessionAcquisitionStarted() {
4771
+ return ++this.acquisitions;
4772
+ }
4773
+ sessionAcquired(sessionId, join, ctx, acquisition) {
4774
+ if (!this.ours(ctx) || !ctx.deckId)
4775
+ return;
4776
+ if (acquisition < this.acceptedAcquisition)
4777
+ return;
4778
+ this.acceptedAcquisition = acquisition;
4779
+ this.session = { sessionId, deckId: ctx.deckId, isPublic: join.isPublic, env: join.env };
4780
+ }
4781
+ publicSession(ctx) {
4782
+ const session = this.session;
4783
+ return this.ours(ctx) && session && session.isPublic && session.deckId === ctx.deckId ? session : null;
4784
+ }
4785
+ prepare(ctx) {
4786
+ if (!this.ours(ctx) || !this.token || this.resolved)
4787
+ return Promise.resolve();
4788
+ // Ghost resolves for an account; a signed-out play keeps the token for after sign-in.
4789
+ if (!ctx.userId)
4790
+ return Promise.resolve();
4791
+ const token = this.token;
4792
+ return this.preparation ??= (async () => {
4793
+ const wait = this.resolveRetryAt - this.now();
4794
+ if (wait > 0) {
4795
+ await this.sleep(wait);
4796
+ this.assertActive();
4797
+ }
4798
+ const data = await deckInviteGraphql(this.gql, DECK_INVITE_RESOLVE, { token, deckId: ctx.deckId, env: this.env }, "multiplayer.getSession", token);
4799
+ const raw = data.resolveCauldronDeckInvite;
4800
+ // Ghost names the link's deck when it says; it must be this one.
4801
+ if (raw?.status !== "ok" || (raw.deckId !== undefined && raw.deckId !== this.options.deckId) || !this.ours(ctx)) {
4802
+ this.giveUp();
4803
+ return;
4804
+ }
4805
+ this.inviter = deckInviteUser(raw.inviter, token);
4806
+ this.resolved = true;
4807
+ this.hintActive = true;
4808
+ })().catch((error) => {
4809
+ this.preparation = null;
4810
+ if (error instanceof HostCommandError && error.code === "CANCELLED")
4811
+ throw error;
4812
+ if (deckInviteRefusal(error) || ++this.resolveFailures >= DECK_INVITE_RESOLVE_ATTEMPTS) {
4813
+ this.giveUp();
4814
+ return;
4815
+ }
4816
+ this.resolveRetryAt = this.now() + DECK_INVITE_RETRY_MS * 2 ** (this.resolveFailures - 1);
4817
+ throw error;
4818
+ });
4819
+ }
4820
+ // The link is unusable: no steer, no arrival. A settled preparation keeps
4821
+ // later joins from resolving it again.
4822
+ giveUp() {
4823
+ this.resolved = false;
4824
+ this.hintActive = false;
4825
+ this.inviter = null;
4826
+ this.preparation = Promise.resolve();
4827
+ }
4828
+ linkJoin(ctx) {
4829
+ if (!this.ours(ctx) || !this.token)
4830
+ return null;
4831
+ return { token: this.resolved && this.hintActive ? this.token : null, env: this.env };
4832
+ }
4833
+ // Ghost may not see a fresh join in the session's roster yet; only its
4834
+ // explicit no-write answer for that is retried, and briefly. Null when the
4835
+ // session the call was for is no longer the deck's, before or after a try.
4836
+ async rosterRetry(signal, current, run) {
4837
+ const started = this.now();
4838
+ for (;;) {
4839
+ this.assertActive(signal);
4840
+ if (!current())
4841
+ return null;
4842
+ try {
4843
+ const result = await run();
4844
+ return current() ? result : null;
4845
+ }
4846
+ catch (error) {
4847
+ if (!(error instanceof HostCommandError) || error.code !== "CAULDRON_DECK_INVITE_NOT_IN_SESSION")
4848
+ throw error;
4849
+ if (!current())
4850
+ return null;
4851
+ if (this.now() - started >= DECK_INVITE_ROSTER_LAG_MS)
4852
+ throw error;
4853
+ await this.sleep(DECK_INVITE_RETRY_MS, signal);
4854
+ }
4855
+ }
4856
+ }
4857
+ async invite(ctx, signal) {
4858
+ this.assertActive(signal);
4859
+ const source = this.publicSession(ctx);
4860
+ if (!source || !ctx.userId)
4861
+ return { status: "unavailable" };
4862
+ const current = () => this.session === source && this.ours(ctx);
4863
+ let raw;
4864
+ try {
4865
+ const data = await this.rosterRetry(signal, current, () => deckInviteGraphql(this.gql, DECK_INVITE_CREATE, { deckId: this.options.deckId, sessionId: source.sessionId, env: source.env }, "deck.invite", this.token));
4866
+ if (!data)
4867
+ return { status: "unavailable" };
4868
+ raw = data.createCauldronDeckInvite;
4869
+ }
4870
+ catch (error) {
4871
+ const reason = deckInviteRefusal(error);
4872
+ if (reason)
4873
+ return { status: "unavailable", reason };
4874
+ throw error;
4875
+ }
4876
+ this.assertActive(signal);
4877
+ if (!current() || raw?.status !== "ok" || typeof raw.url !== "string" || !raw.url.startsWith(`https://castle.xyz/d/`) ||
4878
+ typeof raw.expiresAt !== "string")
4879
+ return { status: "unavailable" };
4880
+ const url = raw.url;
4881
+ const share = this.options.onInviteLink;
4882
+ // The deck's answer does not wait on the share sheet, which can outlast its timeout.
4883
+ if (share)
4884
+ void Promise.resolve().then(() => share(url)).catch(() => { });
4885
+ return { status: "ok", url, expiresAt: raw.expiresAt };
4886
+ }
4887
+ // Idempotent per session: a deck asking again gets the same answer without
4888
+ // another write, and two asks at once share one.
4889
+ inviteArrival(ctx, signal) {
4890
+ this.assertActive(signal);
4891
+ const source = this.publicSession(ctx);
4892
+ const token = this.token;
4893
+ if (!source || !token || !this.resolved)
4894
+ return Promise.resolve({ status: "unavailable" });
4895
+ if (this.arrival?.session === source)
4896
+ return this.arrival.promise;
4897
+ const promise = this.completeArrival(ctx, token, source, signal);
4898
+ const entry = { session: source, promise };
4899
+ this.arrival = entry;
4900
+ // A failure that may pass, or a session given up mid-call, is asked again next time.
4901
+ promise.then((result) => {
4902
+ if (result.status !== "ok" && !result.reason && this.arrival === entry)
4903
+ this.arrival = null;
4904
+ }, () => { if (this.arrival === entry)
4905
+ this.arrival = null; });
4906
+ return promise;
4907
+ }
4908
+ async completeArrival(ctx, token, source, signal) {
4909
+ const current = () => this.session === source && this.ours(ctx);
4910
+ let raw;
4911
+ try {
4912
+ const data = await this.rosterRetry(signal, current, () => deckInviteGraphql(this.gql, DECK_INVITE_COMPLETE, { token, sessionId: source.sessionId, env: source.env }, "deck.inviteArrival", token));
4913
+ if (!data)
4914
+ return { status: "unavailable" };
4915
+ raw = data.completeCauldronDeckInvite;
4916
+ }
4917
+ catch (error) {
4918
+ const reason = deckInviteRefusal(error);
4919
+ if (!reason)
4920
+ throw error;
4921
+ this.hintActive = false;
4922
+ return { status: "unavailable", reason };
4923
+ }
4924
+ if (raw?.status !== "ok")
4925
+ return { status: "unavailable" };
4926
+ const friends = Array.isArray(raw.friends)
4927
+ ? raw.friends.slice(0, DECK_INVITE_FRIENDS_MAX).flatMap((friend) => {
4928
+ const user = deckInviteUser(friend, token);
4929
+ return user ? [user] : [];
4930
+ })
4931
+ : [];
4932
+ // Arrived: later joins go where the player chooses, in the link's env.
4933
+ this.hintActive = false;
4934
+ return { status: "ok", inviter: this.inviter, friends };
4935
+ }
4936
+ }
4937
+ function isDeckInviteCommand(command) {
4938
+ return command === "deck.invite" || command === "deck.inviteArrival";
4939
+ }
4940
+ function runDeckInviteCommand(ctx, command, caps, signal) {
4941
+ const invites = caps.deckInvite;
4942
+ switch (command) {
4943
+ case "deck.invite":
4944
+ return invites ? invites.invite(ctx, signal) : Promise.resolve({ status: "unavailable" });
4945
+ case "deck.inviteArrival":
4946
+ return invites ? invites.inviteArrival(ctx, signal) : Promise.resolve({ status: "unavailable" });
4947
+ }
4948
+ }
@@ -0,0 +1 @@
1
+ export declare const CHARACTER_DOC = "# Characters, in practice\n\nRead this before writing or changing a deck's `characterBundle`, its\n`Characters` client code, or the server's story calls. Written fresh by the\nCastle CLI at every serve start, only because this deck's `castle.json` has a\n`characterBundle`. Characters are experimental and not open to players yet:\npublishing works, but conversations only run for accounts Castle has let in.\n\n## The three parts\n\n- **`characterBundle` in `castle.json`**: `version` (the bundle's label),\n `characters` (each `{ id, version, name, instructions }`), `eventTypes`\n (each `{ id, claims: [{ id, text, witnessCharacterIds }] }`) and `beats`.\n All four are required; `eventTypes` and `beats` may be empty. Ghost\n rejects unknown keys. Limits: 48 characters, 32 event types, 8 claims per\n event type, 12 witnesses per claim, 64 beats, `instructions` 8000\n characters, claim text 500, the whole bundle 192 KiB.\n- **Client**: `import { Characters } from \"castle-web-sdk\"`, then\n `Characters.open(id)`, and `send`, `status`, `history` and `reset` on the handle.\n- **Server**: `session.storage.playthrough(player.userId)` in the deck's\n server, with `recordEvent`, `deliverKnowledge`, `completeBeat`, `status`\n and `history` under `.characters`, plus `get`/`set`/`remove` for\n playthrough game state.\n\nEach player has their own copy of every character (a **playthrough**). Castle\npicks the characters' model; a deck cannot choose it or give a character tools.\nThis guide covers the basic bundle and playthrough API above; other bundle\nfields (gameplay, information rules, schedulers, runtime characters, actions,\nrepeatable events) are gated pilots that creator decks cannot use.\n\n## Publish before you test\n\nCharacters only run in a published deck, including in the local preview,\nwhich talks to the real character service under the deck's id. After any\nchange to `characterBundle`, run `save-deck` before trying a conversation.\nKeep the key in `castle.json`: every save publishes the bundle with that\nversion of the deck. `\"characterBundle\": null` removes it. Deleting the key\nsends nothing, so the last bundle stays tied to an older version of the deck\nand characters stop opening after the next save. A playthrough keeps the bundle\nit started with until the player resets.\n\n## Bundle rules\n\n- `instructions` is the character's private brief: personality, wants, voice,\n what it would never say. Keep story facts out of it; facts reach a character\n through events, so it learns them when they happen.\n- In the basic bundle an event type happens at most once per playthrough. Recording it tells no\n one; the server then delivers claims. `source: { type: \"creator_event\" }`\n reaches only a claim's declared witnesses; `source: { type: \"character\",\n characterId }` relays it from a character that already knows the same claims\n of the same occurrence. Nothing spreads on its own, and what a character says\n never becomes world fact.\n- A beat (`opportunity: \"opening\"`, `repeat: \"once_per_event\"`, the only\n values) opens the character's next reply with `openingText` once it knows\n the beat's `requiredClaimIds`. The reply carries `result.selectedBeat`. The\n beat is finished only when the server calls `completeBeat` with one of its\n `completionOutcomeIds`; apply game effects after that, not before.\n\n## Client rules\n\n- `Characters.open(id)` returns `{ generation, definitionVersion, character,\n previewAllowance }` and admits the player. It runs no model and spends\n nothing. Open every character before the server records events for that\n player, and again after a reset.\n- `send({ operationId, input })` returns before the reply: poll\n `status(operationId)` until `completed`, `failed` or `interrupted`. A\n finished status can arrive with `result: null`, so fetch status once more.\n `progress?.response` is a disposable draft while running; replace it with\n `result.response`.\n- Input is 1-2000 characters; operation ids are at most 120. One new\n `crypto.randomUUID()` per message, kept until the reply arrives. After a lost\n response, ask `status` or `history` with the same id. Never resend under a\n new id (that is a second, billed message), and never replay a message into a\n new generation for the player.\n- `history({ limit, cursor })` is newest first, `limit` 1-50, `cursor` null\n on the last page. Show completed operations with a `response`, oldest first.\n- `reset(operationId)` resets the whole deck playthrough for every character\n and returns a handle in the new generation. On a lost response, reopen: a\n higher generation means it happened; otherwise retry on the old handle with\n the same id. Clear every cached message, draft and story flag after.\n- Tag pending replies with character id and generation so a late reply never\n lands in another conversation or a fresh playthrough. Bind the send button and\n Enter key yourself (a `<form>` may not submit in the player frame) and keep\n movement keys from firing while typing.\n- Errors are `CastleError` codes: `CAULDRON_CHARACTER_UNAVAILABLE` (not open\n for this deck or player, service off, or the deck's daily limit reached),\n `CAULDRON_CHARACTER_BACKLOG_LIMIT` (the player's daily allowance is used up,\n or too many replies are waiting), `CAULDRON_CHARACTER_NOT_FOUND`,\n `CAULDRON_CHARACTER_INVALID_ARGUMENT`, `CAULDRON_CHARACTER_CONFLICT` (an\n operation id reused with different text) and\n `CAULDRON_STORAGE_STALE_GENERATION` (an old handle after a reset; reopen).\n In creator decks, players under 13 or of unknown age get no character talk,\n so the deck must still make sense without it.\n\n## Server rules\n\n- The story calls need a running server, even for one player: a `server`\n entry (`maxPlayers: 1`, `tickRate: 0` is fine) and a named room per player,\n keyed by a hash of the user id. The key only picks the room; identity comes\n from the callback's `player`. A private deck gets no server (`conn.isSolo`),\n so test on an unlisted deck.\n- Always `session.storage.playthrough(player.userId)`, never a user id from a\n message. Have the client send its `generation` with each story action and\n ignore actions from an earlier one.\n- Every story call takes an `operationId` and returns an operation that may be\n `queued` or `running`: poll `characters.status` until it finishes before\n using `result` (`recordEvent` gives `result.eventOccurrenceId`). Build\n operation ids from a client request id so a retried action cannot apply\n twice. History holds story operations too, so a restarted server can rebuild\n its state from it.\n- Keep story flags in `playthrough.get/set/remove`, which reset with the\n characters, not in `session.storage.user`.\n\n## Shared characters\n\nA destination in `server.destinations` with `characters: \"shared\"`,\n`selection: \"exact\"` and `persistence: \"world\"` makes the bundle's\ncharacters shared by everyone in that world: one memory per world, while each\nplayer sees only their own conversations. The bundle needs\n`\"conversation\": { \"version\": 1, \"authority\": \"server\", \"maxListeners\": 0 }`\n(up to 3 listeners) or every turn is refused. Clients join with\n`Multiplayer.joinDestination({ routeId, slot })` (each slot is its own world),\ncheck `connection.sharedCharacters`, send with `connection.requestCharacterTurn({\nrequestId, operationId, characterId, input, audience? })`, poll\n`getCharacterTurnStatus(operationId)` until it leaves `queued`/`running`\n(the reply is `response`), and load replies with `readCharacters({ requestId,\nquery: { type: \"history\", characterId, limit, cursor } })`, whose operations\ncarry `response` but not the player's words. `audience` is `{ characterIds\n}` for characters who overhear, `playerIds` (up to 7 connected players) and\n`disclosure` (`participants` by default, or `world`). After\n`CAULDRON_CHARACTER_TIMEOUT` or a closed connection, ask status with the same\noperation id; never resend under a new one.\n\nThe deck server must let each request through: `onWorldCharacterTurn(session,\nturn)` calls `turn.send()` or `turn.reject(code)`, and\n`onWorldCharacterCommand` (`apply`/`reject`) and `onWorldCharacterRead`\n(`read`/`reject`) do the same; returning without settling rejects. The\nserver cannot change the speaker, input or audience. A character runs one turn\nat a time with two more waiting (`CAULDRON_SHARED_CHARACTER_BUSY` past that).\nShared worlds have no playthroughs or resets, and `session.storage.playthrough`\nis not available in them.\n";
@@ -0,0 +1,149 @@
1
+ // The on-demand characters guide, written beside platform.md at serve start
2
+ // only for a deck whose castle.json declares a characterBundle (platformDoc.ts
3
+ // owns the path and the writing). Characters are experimental and not open to
4
+ // creators yet, so nothing about them reaches a deck that has not opted in:
5
+ // no bullet in platform.md, no line in any prompt. A deck with a bundle gets one
6
+ // pointer bullet in its platform.md and this file. The creator-facing pages are
7
+ // castle-docs docs/cauldron/characters; keep the two in step.
8
+ export const CHARACTER_DOC = `# Characters, in practice
9
+
10
+ Read this before writing or changing a deck's \`characterBundle\`, its
11
+ \`Characters\` client code, or the server's story calls. Written fresh by the
12
+ Castle CLI at every serve start, only because this deck's \`castle.json\` has a
13
+ \`characterBundle\`. Characters are experimental and not open to players yet:
14
+ publishing works, but conversations only run for accounts Castle has let in.
15
+
16
+ ## The three parts
17
+
18
+ - **\`characterBundle\` in \`castle.json\`**: \`version\` (the bundle's label),
19
+ \`characters\` (each \`{ id, version, name, instructions }\`), \`eventTypes\`
20
+ (each \`{ id, claims: [{ id, text, witnessCharacterIds }] }\`) and \`beats\`.
21
+ All four are required; \`eventTypes\` and \`beats\` may be empty. Ghost
22
+ rejects unknown keys. Limits: 48 characters, 32 event types, 8 claims per
23
+ event type, 12 witnesses per claim, 64 beats, \`instructions\` 8000
24
+ characters, claim text 500, the whole bundle 192 KiB.
25
+ - **Client**: \`import { Characters } from "castle-web-sdk"\`, then
26
+ \`Characters.open(id)\`, and \`send\`, \`status\`, \`history\` and \`reset\` on the handle.
27
+ - **Server**: \`session.storage.playthrough(player.userId)\` in the deck's
28
+ server, with \`recordEvent\`, \`deliverKnowledge\`, \`completeBeat\`, \`status\`
29
+ and \`history\` under \`.characters\`, plus \`get\`/\`set\`/\`remove\` for
30
+ playthrough game state.
31
+
32
+ Each player has their own copy of every character (a **playthrough**). Castle
33
+ picks the characters' model; a deck cannot choose it or give a character tools.
34
+ This guide covers the basic bundle and playthrough API above; other bundle
35
+ fields (gameplay, information rules, schedulers, runtime characters, actions,
36
+ repeatable events) are gated pilots that creator decks cannot use.
37
+
38
+ ## Publish before you test
39
+
40
+ Characters only run in a published deck, including in the local preview,
41
+ which talks to the real character service under the deck's id. After any
42
+ change to \`characterBundle\`, run \`save-deck\` before trying a conversation.
43
+ Keep the key in \`castle.json\`: every save publishes the bundle with that
44
+ version of the deck. \`"characterBundle": null\` removes it. Deleting the key
45
+ sends nothing, so the last bundle stays tied to an older version of the deck
46
+ and characters stop opening after the next save. A playthrough keeps the bundle
47
+ it started with until the player resets.
48
+
49
+ ## Bundle rules
50
+
51
+ - \`instructions\` is the character's private brief: personality, wants, voice,
52
+ what it would never say. Keep story facts out of it; facts reach a character
53
+ through events, so it learns them when they happen.
54
+ - In the basic bundle an event type happens at most once per playthrough. Recording it tells no
55
+ one; the server then delivers claims. \`source: { type: "creator_event" }\`
56
+ reaches only a claim's declared witnesses; \`source: { type: "character",
57
+ characterId }\` relays it from a character that already knows the same claims
58
+ of the same occurrence. Nothing spreads on its own, and what a character says
59
+ never becomes world fact.
60
+ - A beat (\`opportunity: "opening"\`, \`repeat: "once_per_event"\`, the only
61
+ values) opens the character's next reply with \`openingText\` once it knows
62
+ the beat's \`requiredClaimIds\`. The reply carries \`result.selectedBeat\`. The
63
+ beat is finished only when the server calls \`completeBeat\` with one of its
64
+ \`completionOutcomeIds\`; apply game effects after that, not before.
65
+
66
+ ## Client rules
67
+
68
+ - \`Characters.open(id)\` returns \`{ generation, definitionVersion, character,
69
+ previewAllowance }\` and admits the player. It runs no model and spends
70
+ nothing. Open every character before the server records events for that
71
+ player, and again after a reset.
72
+ - \`send({ operationId, input })\` returns before the reply: poll
73
+ \`status(operationId)\` until \`completed\`, \`failed\` or \`interrupted\`. A
74
+ finished status can arrive with \`result: null\`, so fetch status once more.
75
+ \`progress?.response\` is a disposable draft while running; replace it with
76
+ \`result.response\`.
77
+ - Input is 1-2000 characters; operation ids are at most 120. One new
78
+ \`crypto.randomUUID()\` per message, kept until the reply arrives. After a lost
79
+ response, ask \`status\` or \`history\` with the same id. Never resend under a
80
+ new id (that is a second, billed message), and never replay a message into a
81
+ new generation for the player.
82
+ - \`history({ limit, cursor })\` is newest first, \`limit\` 1-50, \`cursor\` null
83
+ on the last page. Show completed operations with a \`response\`, oldest first.
84
+ - \`reset(operationId)\` resets the whole deck playthrough for every character
85
+ and returns a handle in the new generation. On a lost response, reopen: a
86
+ higher generation means it happened; otherwise retry on the old handle with
87
+ the same id. Clear every cached message, draft and story flag after.
88
+ - Tag pending replies with character id and generation so a late reply never
89
+ lands in another conversation or a fresh playthrough. Bind the send button and
90
+ Enter key yourself (a \`<form>\` may not submit in the player frame) and keep
91
+ movement keys from firing while typing.
92
+ - Errors are \`CastleError\` codes: \`CAULDRON_CHARACTER_UNAVAILABLE\` (not open
93
+ for this deck or player, service off, or the deck's daily limit reached),
94
+ \`CAULDRON_CHARACTER_BACKLOG_LIMIT\` (the player's daily allowance is used up,
95
+ or too many replies are waiting), \`CAULDRON_CHARACTER_NOT_FOUND\`,
96
+ \`CAULDRON_CHARACTER_INVALID_ARGUMENT\`, \`CAULDRON_CHARACTER_CONFLICT\` (an
97
+ operation id reused with different text) and
98
+ \`CAULDRON_STORAGE_STALE_GENERATION\` (an old handle after a reset; reopen).
99
+ In creator decks, players under 13 or of unknown age get no character talk,
100
+ so the deck must still make sense without it.
101
+
102
+ ## Server rules
103
+
104
+ - The story calls need a running server, even for one player: a \`server\`
105
+ entry (\`maxPlayers: 1\`, \`tickRate: 0\` is fine) and a named room per player,
106
+ keyed by a hash of the user id. The key only picks the room; identity comes
107
+ from the callback's \`player\`. A private deck gets no server (\`conn.isSolo\`),
108
+ so test on an unlisted deck.
109
+ - Always \`session.storage.playthrough(player.userId)\`, never a user id from a
110
+ message. Have the client send its \`generation\` with each story action and
111
+ ignore actions from an earlier one.
112
+ - Every story call takes an \`operationId\` and returns an operation that may be
113
+ \`queued\` or \`running\`: poll \`characters.status\` until it finishes before
114
+ using \`result\` (\`recordEvent\` gives \`result.eventOccurrenceId\`). Build
115
+ operation ids from a client request id so a retried action cannot apply
116
+ twice. History holds story operations too, so a restarted server can rebuild
117
+ its state from it.
118
+ - Keep story flags in \`playthrough.get/set/remove\`, which reset with the
119
+ characters, not in \`session.storage.user\`.
120
+
121
+ ## Shared characters
122
+
123
+ A destination in \`server.destinations\` with \`characters: "shared"\`,
124
+ \`selection: "exact"\` and \`persistence: "world"\` makes the bundle's
125
+ characters shared by everyone in that world: one memory per world, while each
126
+ player sees only their own conversations. The bundle needs
127
+ \`"conversation": { "version": 1, "authority": "server", "maxListeners": 0 }\`
128
+ (up to 3 listeners) or every turn is refused. Clients join with
129
+ \`Multiplayer.joinDestination({ routeId, slot })\` (each slot is its own world),
130
+ check \`connection.sharedCharacters\`, send with \`connection.requestCharacterTurn({
131
+ requestId, operationId, characterId, input, audience? })\`, poll
132
+ \`getCharacterTurnStatus(operationId)\` until it leaves \`queued\`/\`running\`
133
+ (the reply is \`response\`), and load replies with \`readCharacters({ requestId,
134
+ query: { type: "history", characterId, limit, cursor } })\`, whose operations
135
+ carry \`response\` but not the player's words. \`audience\` is \`{ characterIds
136
+ }\` for characters who overhear, \`playerIds\` (up to 7 connected players) and
137
+ \`disclosure\` (\`participants\` by default, or \`world\`). After
138
+ \`CAULDRON_CHARACTER_TIMEOUT\` or a closed connection, ask status with the same
139
+ operation id; never resend under a new one.
140
+
141
+ The deck server must let each request through: \`onWorldCharacterTurn(session,
142
+ turn)\` calls \`turn.send()\` or \`turn.reject(code)\`, and
143
+ \`onWorldCharacterCommand\` (\`apply\`/\`reject\`) and \`onWorldCharacterRead\`
144
+ (\`read\`/\`reject\`) do the same; returning without settling rejects. The
145
+ server cannot change the speaker, input or audience. A character runs one turn
146
+ at a time with two more waiting (\`CAULDRON_SHARED_CHARACTER_BUSY\` past that).
147
+ Shared worlds have no playthroughs or resets, and \`session.storage.playthrough\`
148
+ is not available in them.
149
+ `;
@@ -44,6 +44,15 @@ export declare const HISTORY_LOST_MARKER_FILE: string;
44
44
  * (webSourceSync.ts). Not a git marker: the serve consumes it with git off too.
45
45
  */
46
46
  export declare const WEB_SOURCE_NEWER_MARKER_FILE: string;
47
+ /** Written the first time the Castle remote refuses a push as too large (see pushMain). */
48
+ export declare const PUSH_TOO_LARGE_MARKER_FILE: string;
49
+ /**
50
+ * The last push the remote refused as too large, in .git: `{ sha, tree, at, blobs }`. While it is
51
+ * fresh, a push of the same history waits instead of uploading the same refused pack again.
52
+ */
53
+ export declare const PUSH_TOO_LARGE_STATE_FILE = "castle-push-too-large.json";
54
+ /** How long a refused-as-too-large history waits before a push tries it again. */
55
+ export declare const PUSH_TOO_LARGE_BACKOFF_MS: number;
47
56
  /** Every marker the serve turns into an agent turn. */
48
57
  export declare const AGENT_MARKER_FILES: readonly string[];
49
58
  /** The markers the serve consumes whether or not git is on (CASTLE_GIT). */
@@ -313,6 +322,7 @@ export interface SyncOutcome {
313
322
  merge: 'none' | 'fast-forward' | 'merged' | 'conflict' | 'seeded' | 'deferred';
314
323
  pushed: boolean;
315
324
  }
325
+ export declare const PUSH_CAP_ENV = "CASTLE_GIT_PUSH_CAP_BYTES";
316
326
  /**
317
327
  * The remote's main as local main last took it in: what a recovery may start the deck again
318
328
  * from. castle/main can be ahead of it -- fetched, but its merge deferred while tasks were busy,