castle-web-cli 0.4.228 → 0.4.229

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.
@@ -31,6 +31,7 @@ export interface PromptSibling {
31
31
  }
32
32
  export interface RouterPlanOpts {
33
33
  fileText?: string;
34
+ settledItems?: string[];
34
35
  pendingDurables?: PlanNomination[];
35
36
  finishedWork?: PlanFinishedWork[];
36
37
  notices?: string[];
@@ -62,6 +63,12 @@ export declare const STEER_MODEL_CLAUSE = ", as a new task even when it changes
62
63
  export declare const SEND_FENCE_RULES = "\n\nTo hand a message to a task that is running or waiting to run:\n\n```castle-send\nthe task's title or id, alone on the first line\nthe user's message for it -- their own words, quoted, plus only what from this conversation the task needs to act on them\n```\n\n- `castle-send` reaches a RUNNING or WAITING task: it reads the message at its next step and folds it into the work it is doing, without starting over. One fence per task. It is the ONLY thing that reaches a running task -- a reply that says a task will pick something up, without this fence, sends nothing. The board row shows each message you sent and whether the task has read it.\n- It cannot reach a finished task. For those, spawn a new task (see the one-and-done rule below).";
63
64
  export declare const PROBE_CLAUSE_STEER = "But NEVER spawn work a pending probe could invalidate outright: castle-send can pass the answer to a running task, but it cannot undo work the answer throws away.";
64
65
  export declare function truncateToBytes(line: string, budget: number): string;
66
+ export declare const PLAN_SECTION_CAPS: Record<string, number>;
67
+ export declare const PLAN_DIGEST_BYTE_BUDGET: number;
68
+ export declare const BUILT_MAX_LINES = 15;
69
+ export declare const TASK_PLAN_SLICE_BYTE_BUDGET: number;
70
+ export declare const DECISIONS_PINNED = 10;
71
+ export declare const DECISIONS_RETRIEVED = 6;
65
72
  export type PlanOpVerb = "decide" | "open" | "tried" | "now" | "identity";
66
73
  export interface PlanOpSource {
67
74
  kind: "user" | "task";
@@ -91,9 +98,8 @@ export interface PlanOpsApplied {
91
98
  notices: string[];
92
99
  }
93
100
  export declare function applyPlanOps(fileText: string, ops: PlanOp[], sources?: PlanOpSources): PlanOpsApplied;
94
- export declare function renderPlanDigest(plan: RouterPlanOpts, tasks: PromptTask[]): string;
95
- export declare function planOpenQuestionLines(fileText: string): string[];
96
- export declare function renderTaskPlanSlice(fileText: string, item: string | undefined, finishedWork?: PlanFinishedWork[]): string;
101
+ export declare function renderPlanDigest(plan: RouterPlanOpts, tasks: PromptTask[], query?: string): string;
102
+ export declare function renderTaskPlanSlice(fileText: string, item: string | undefined, finishedWork?: PlanFinishedWork[], query?: string): string;
97
103
  export type FreeModelCheck = (model: string) => boolean;
98
104
  export declare function modelLabel(model: string, isFreeModel: FreeModelCheck): string;
99
105
  export declare const NO_DECK_DOCS = "This deck has no CLAUDE.md / AGENTS.md quick reference. There is no documentation to read -- do not search for one (CLAUDE.md, README, **/*.md, etc.).";
@@ -257,17 +257,20 @@ function renderTranscript(messages) {
257
257
  // runaway section is trimmed here instead, and can never crowd the rest of the
258
258
  // plan out of the digest. Key is the lowercased heading; "" is the title +
259
259
  // pitch ahead of the first heading, which only the user writes.
260
- const PLAN_SECTION_CAPS = {
260
+ export const PLAN_SECTION_CAPS = {
261
261
  "": 2,
262
262
  "what this game is": 6,
263
- decisions: 12,
264
- "open questions": 7,
263
+ decisions: 16,
264
+ "open questions": 3,
265
265
  now: 10,
266
266
  tried: 8,
267
267
  };
268
268
  const PLAN_SECTION_DEFAULT_CAP = 8;
269
- const PLAN_DIGEST_BYTE_BUDGET = 3 * 1024;
270
- const BUILT_MAX_LINES = 15;
269
+ export const PLAN_DIGEST_BYTE_BUDGET = 3 * 1024;
270
+ export const BUILT_MAX_LINES = 15;
271
+ export const TASK_PLAN_SLICE_BYTE_BUDGET = 6 * 1024;
272
+ export const DECISIONS_PINNED = 10;
273
+ export const DECISIONS_RETRIEVED = 6;
271
274
  // plan.md's sections in the order they are written and rendered, with the
272
275
  // heading each is created as. `built` is listed for its POSITION only: it is
273
276
  // derived into the digest from finished tasks (see deriveBuiltLines) and is
@@ -683,6 +686,54 @@ function trimSection(section) {
683
686
  function planItemLabel(line) {
684
687
  return /^[-*]\s*([^\s:]+)\s*:/.exec(line)?.[1];
685
688
  }
689
+ const DECISION_STOP_WORDS = new Set("the a an and or but if then than that this these those there here with without into onto from for to of in on at by as is are was were be been being it its it's i you we they he she them him her my your our their me us do does did done have has had having not no yes so just like get got make made makes making want wants wanted need needs should would could can cant can't will wont won't dont don't doesnt doesn't didnt didn't isnt isn't arent aren't im i'm ive i've lets let's ok okay yeah yep nah also too very really still now when where what which who how why all any some more most much many few each every other another same different new old first last next back up down out over under again once only ever never always also thing things something anything nothing everything way ways kind sort bit lot little big small good bad great nice fine right wrong sure maybe actually probably think thought feel feels felt look looks looked looking see seen show shows keep keeps kept go goes going went come comes came put take takes took use used using work works worked working try tries tried trying add adds added adding change changes changed changing fix fixes fixed fixing remove removed set sets user task game play player players screen currently current one two three".split(" "));
690
+ function planContentTokens(text) {
691
+ const unattributed = text.toLowerCase()
692
+ .replace(/\(".*?"\s*--\s*(?:user|task\s+\S+)\)/g, "")
693
+ .replace(/--\s*(?:user|task\s+\S+)/g, "");
694
+ const tokens = new Set();
695
+ for (const raw of unattributed.match(/[a-z][a-z']+/g) ?? []) {
696
+ let word = raw.replace(/^'+|'+$/g, "");
697
+ if (word.length < 4 || DECISION_STOP_WORDS.has(word))
698
+ continue;
699
+ for (const suffix of ["ing", "ers", "er", "es", "ed", "s", "ly"]) {
700
+ if (word.endsWith(suffix) && word.length - suffix.length >= 4) {
701
+ word = word.slice(0, -suffix.length);
702
+ break;
703
+ }
704
+ }
705
+ tokens.add(word);
706
+ }
707
+ return tokens;
708
+ }
709
+ function selectDecisionLines(section, built, query) {
710
+ const lines = section.lines.map((line) => line.trim()).filter(Boolean);
711
+ if (lines.length <= PLAN_SECTION_CAPS.decisions)
712
+ return { lines, trimmed: false };
713
+ const pinned = lines.slice(0, DECISIONS_PINNED);
714
+ const shownBuilt = new Set(built.map(planItemLabel).filter(Boolean));
715
+ const queryTokens = planContentTokens(query);
716
+ const candidates = lines.slice(DECISIONS_PINNED).map((line, index) => {
717
+ const shared = [...planContentTokens(line)].filter((token) => queryTokens.has(token)).length;
718
+ const labelTokens = planContentTokens((planItemLabel(line) ?? "").replace(/-/g, " "));
719
+ const labelMatch = labelTokens.size > 0 && [...labelTokens].every((token) => queryTokens.has(token));
720
+ return { line, index, score: shared + (labelMatch ? 1 : 0), qualifies: shared >= 2 || labelMatch };
721
+ }).filter((candidate) => !shownBuilt.has(planItemLabel(candidate.line)));
722
+ const ranked = candidates.filter((candidate) => candidate.qualifies)
723
+ .sort((a, b) => b.score - a.score || b.index - a.index);
724
+ const selected = ranked.slice(0, DECISIONS_RETRIEVED);
725
+ const selectedIndexes = new Set(selected.map((candidate) => candidate.index));
726
+ for (const candidate of [...candidates].reverse()) {
727
+ if (selected.length >= DECISIONS_RETRIEVED)
728
+ break;
729
+ if (selectedIndexes.has(candidate.index))
730
+ continue;
731
+ selected.push(candidate);
732
+ selectedIndexes.add(candidate.index);
733
+ }
734
+ const retrieved = selected.sort((a, b) => a.index - b.index).map((candidate) => candidate.line);
735
+ return { lines: [...pinned, ...retrieved], trimmed: pinned.length + retrieved.length < lines.length };
736
+ }
686
737
  // The machine half of the digest: which board rows belong to this plan item.
687
738
  // It is joined in here, never written into plan.md -- the file stays prose with
688
739
  // two human writers, and everything the runtime knows rides in the render.
@@ -754,11 +805,36 @@ function deriveBuiltLines(finished) {
754
805
  lines.push(`(${dropped} more in the archive)`);
755
806
  return lines;
756
807
  }
757
- function fitPlanSections(plan, tasks) {
808
+ function fitPlanSections(plan, tasks, query) {
758
809
  const sections = [];
759
- for (const section of parsePlanSections(plan.fileText ?? "")) {
760
- const { lines, trimmed } = trimSection(section);
761
- if (lines.length === 0 && !section.heading)
810
+ const built = deriveBuiltLines(plan.finishedWork ?? []);
811
+ const settled = new Set(plan.settledItems ?? []);
812
+ const source = parsePlanSections(plan.fileText ?? "");
813
+ const decided = new Set(source
814
+ .filter((section) => section.key === "decisions" || section.key === "tried")
815
+ .flatMap((section) => section.lines.map((line) => planItemLabel(line.trim())))
816
+ .filter((label) => Boolean(label)));
817
+ for (const section of source) {
818
+ const visible = section.key === "now"
819
+ ? {
820
+ ...section,
821
+ lines: section.lines
822
+ .filter((line) => !settled.has(planItemLabel(line.trim()) ?? ""))
823
+ .reverse(),
824
+ }
825
+ : section.key === "open questions"
826
+ ? {
827
+ ...section,
828
+ lines: section.lines
829
+ .filter((line) => line.includes("(proposed -- confirm?)") ||
830
+ !decided.has(planItemLabel(line.trim()) ?? ""))
831
+ .reverse(),
832
+ }
833
+ : section;
834
+ const { lines, trimmed } = section.key === "decisions"
835
+ ? selectDecisionLines(section, built, query)
836
+ : trimSection(visible);
837
+ if (lines.length === 0)
762
838
  continue;
763
839
  sections.push({
764
840
  heading: section.heading,
@@ -769,7 +845,6 @@ function fitPlanSections(plan, tasks) {
769
845
  trimmed,
770
846
  });
771
847
  }
772
- const built = deriveBuiltLines(plan.finishedWork ?? []);
773
848
  if (built.length > 0) {
774
849
  insertByOrder(sections, {
775
850
  heading: "## Built",
@@ -778,25 +853,49 @@ function fitPlanSections(plan, tasks) {
778
853
  trimmed: false,
779
854
  });
780
855
  }
856
+ return fitSectionsToBytes(sections, PLAN_DIGEST_BYTE_BUDGET);
857
+ }
858
+ function fitSectionsToBytes(sections, budget) {
781
859
  const render = () => sections
782
860
  .map((s) => [s.heading, ...s.lines, s.trimmed ? "(trimmed)" : ""]
783
861
  .filter(Boolean)
784
862
  .join("\n"))
785
863
  .join("\n\n");
786
- while (Buffer.byteLength(render(), "utf8") > PLAN_DIGEST_BYTE_BUDGET) {
864
+ while (Buffer.byteLength(render(), "utf8") > budget) {
787
865
  const victim = trimVictim(sections);
788
866
  if (!victim)
789
867
  break;
790
868
  victim.lines.pop();
791
869
  victim.trimmed = true;
792
870
  }
793
- // Backstop for a plan whose remaining one-line-per-section still overruns
794
- // (pathological line lengths); the 8KB file cap upstream keeps it rare.
795
- const rendered = render();
796
- if (Buffer.byteLength(rendered, "utf8") <= PLAN_DIGEST_BYTE_BUDGET) {
797
- return rendered;
871
+ // Every section is down to a line and the render still overruns: one line
872
+ // is pathologically long. Shorten THAT line rather than cutting the render's
873
+ // tail, which is where Built and a task's own item line sit.
874
+ const ellipsis = " ...";
875
+ const ellipsisBytes = Buffer.byteLength(ellipsis, "utf8");
876
+ const lineFloor = 16;
877
+ const bodyOf = (line) => line.endsWith(ellipsis) ? line.slice(0, -ellipsis.length) : line;
878
+ for (;;) {
879
+ const over = Buffer.byteLength(render(), "utf8") - budget;
880
+ if (over <= 0)
881
+ return render();
882
+ let longest;
883
+ for (const section of sections) {
884
+ section.lines.forEach((line, at) => {
885
+ const bytes = Buffer.byteLength(bodyOf(line), "utf8");
886
+ if (bytes > lineFloor && (!longest || bytes > longest.bytes))
887
+ longest = { section, at, bytes };
888
+ });
889
+ }
890
+ if (!longest)
891
+ break;
892
+ const keep = Math.max(lineFloor, longest.bytes - over - ellipsisBytes);
893
+ const body = bodyOf(longest.section.lines[longest.at]);
894
+ longest.section.lines[longest.at] = `${truncateToBytes(body, keep).trimEnd()}${ellipsis}`;
895
+ longest.section.trimmed = true;
798
896
  }
799
- return `${truncateToBytes(rendered, PLAN_DIGEST_BYTE_BUDGET).trimEnd()}\n(trimmed)`;
897
+ const marker = "\n(trimmed)";
898
+ return `${truncateToBytes(render(), budget - Buffer.byteLength(marker, "utf8")).trimEnd()}${marker}`;
800
899
  }
801
900
  // The plan as the router sees it: the file (capped, with board status joined
802
901
  // onto its items and `## Built` derived in) plus the nominations waiting on its
@@ -806,8 +905,8 @@ function fitPlanSections(plan, tasks) {
806
905
  // it. They are small and bounded, and they are the input to promotion -- a
807
906
  // long plan crowding them out would silently stop promotion working at exactly
808
907
  // the point a deck most needs it.
809
- export function renderPlanDigest(plan, tasks) {
810
- const fitted = fitPlanSections(plan, tasks);
908
+ export function renderPlanDigest(plan, tasks, query = "") {
909
+ const fitted = fitPlanSections(plan, tasks, query);
811
910
  // A deck can have finished work before it has a plan.md -- what exists is
812
911
  // still worth showing, and saying the file is missing is what gets one
813
912
  // drafted.
@@ -830,47 +929,36 @@ export function renderPlanDigest(plan, tasks) {
830
929
  }
831
930
  return parts.join("\n\n");
832
931
  }
833
- export function planOpenQuestionLines(fileText) {
834
- const section = parsePlanSections(fileText).find((s) => s.key === "open questions");
835
- return (section?.lines ?? []).map((l) => l.trim()).filter(Boolean);
836
- }
837
932
  // The slice one task agent gets: the constraints and the don't-rebuilds, plus
838
933
  // the single item line its own work belongs to. See TASK_PLAN_SECTIONS for what
839
934
  // is deliberately left out.
840
- export function renderTaskPlanSlice(fileText, item, finishedWork) {
841
- const sections = parsePlanSections(fileText);
842
- const parts = [];
843
- // Only this item's own Built line: what already exists where this task is
844
- // about to work, so it extends rather than rebuilds. Other items' work is
845
- // not its business.
935
+ export function renderTaskPlanSlice(fileText, item, finishedWork, query = "") {
936
+ const source = parsePlanSections(fileText);
937
+ const sections = [];
846
938
  const built = deriveBuiltLines((finishedWork ?? []).filter((w) => item && w.item === item));
847
- let builtDone = built.length === 0;
848
- const pushBuilt = () => {
849
- if (builtDone)
850
- return;
851
- parts.push(["## Built", ...built].join("\n"));
852
- builtDone = true;
853
- };
854
- for (const section of sections) {
939
+ for (const section of source) {
855
940
  if (section.key !== "" && !TASK_PLAN_SECTIONS.has(section.key))
856
941
  continue;
857
- const { lines } = trimSection(section);
942
+ const { lines, trimmed } = section.key === "decisions"
943
+ ? selectDecisionLines(section, built, query)
944
+ : trimSection(section);
858
945
  if (lines.length === 0)
859
946
  continue;
860
- if (sectionRank(section.key) > sectionRank("built"))
861
- pushBuilt();
862
- parts.push([section.heading, ...lines].filter(Boolean).join("\n"));
947
+ sections.push({ heading: section.heading, key: section.key, lines, trimmed });
948
+ }
949
+ if (built.length > 0) {
950
+ insertByOrder(sections, { heading: "## Built", key: "built", lines: built, trimmed: false });
863
951
  }
864
- pushBuilt();
865
952
  const itemLine = item
866
- ? sections
953
+ ? source
867
954
  .find((s) => s.key === "now")
868
955
  ?.lines.map((l) => l.trim())
869
956
  .find((l) => planItemLabel(l) === item)
870
957
  : undefined;
871
- if (itemLine)
872
- parts.push(`The plan item your task belongs to:\n${itemLine}`);
873
- return parts.join("\n\n");
958
+ if (itemLine) {
959
+ sections.push({ heading: "The plan item your task belongs to:", key: "now", lines: [itemLine], trimmed: false });
960
+ }
961
+ return fitSectionsToBytes(sections, TASK_PLAN_SLICE_BYTE_BUDGET);
874
962
  }
875
963
  // `showItems` is the plan opt's presence, not the row's. A deck that ran with
876
964
  // the plan doc on and then switched it off still has item labels on its old
@@ -955,7 +1043,11 @@ export function buildRouterPromptParts(opts) {
955
1043
  // roughly the turns the board does, so co-locating them means it invalidates
956
1044
  // nothing the board wasn't already invalidating.
957
1045
  const plan = opts.plan
958
- ? `\n\n== plan ==\n${renderPlanDigest(opts.plan, opts.tasks)}`
1046
+ ? `\n\n== plan ==\n${renderPlanDigest(opts.plan, opts.tasks, opts.messages
1047
+ .filter((message) => message.role === "user")
1048
+ .slice(-4)
1049
+ .map((message) => message.text)
1050
+ .join("\n"))}`
959
1051
  : "";
960
1052
  // Omitted entirely when nothing was tuned: a quiet turn has to cost 0 bytes,
961
1053
  // and every prompt built before this section existed has to stay
@@ -1086,7 +1178,7 @@ export function buildTaskPrompt(opts) {
1086
1178
  ? `\n\nDeck files (snapshot at task start; parallel sibling tasks may create files named in your prompt that are absent here):\n\n${opts.deckTree.trim()}\n`
1087
1179
  : "";
1088
1180
  const planSliceText = opts.plan
1089
- ? renderTaskPlanSlice(opts.plan.fileText ?? "", opts.plan.item, opts.plan.finishedWork)
1181
+ ? renderTaskPlanSlice(opts.plan.fileText ?? "", opts.plan.item, opts.plan.finishedWork, `${opts.title}\n${opts.prompt}`)
1090
1182
  : "";
1091
1183
  const planSlice = planSliceText.trim()
1092
1184
  ? `\n\nThe deck's plan (from plan.md):\n\n${planSliceText}\n`
package/dist/agent.js CHANGED
@@ -38,7 +38,7 @@ import { accountForRun, closingMessageOf } from './taskAccount.js';
38
38
  import { atomicWriteFileSync } from './atomicFile.js';
39
39
  import { AGENT_ATTACHMENT_PREFIX, AGENT_PLAYTEST_PREFIX, PLAN_FILE } from './localPaths.js';
40
40
  import { readGitIncomingNote, removeGitIncoming } from './gitIncoming.js';
41
- import { applyPlanOps, buildRouterPromptParts, buildTaskPrompt, parsePlanOps, truncateToBytes, userTurnInstruction, CLAUDE_TASK_SYSTEM_REMINDER, modelTaskAddendum, isMuseModel, } from './agent-prompts.js';
41
+ import { applyPlanOps, buildRouterPromptParts, buildTaskPrompt, parsePlanOps, userTurnInstruction, CLAUDE_TASK_SYSTEM_REMINDER, modelTaskAddendum, isMuseModel, } from './agent-prompts.js';
42
42
  import { readCastleJson } from './castleJson.js';
43
43
  import { checkOpenrouterKey, checkOpenrouterModel, primeOpenrouterCatalog, } from './openrouter-catalog.js';
44
44
  import { classifyProviderError, failureCopy, failureLabel, routerTaskError, setReaderTimeZone, } from './agent-failures.js';
@@ -544,11 +544,6 @@ const MAX_TASK_RESUMES = 3;
544
544
  const TASK_POLL_MS = 1_000;
545
545
  const FENCE_HOLDBACK = '```castle-';
546
546
  const RESULT_SUMMARY_CHARS = 600;
547
- // Byte ceiling on the plan.md injected into router turns and task prompts.
548
- // Nothing bounds the file itself -- ops touch one line each and the user pastes
549
- // what they like -- meanwhile the whole prompt rides inside one argv entry (see
550
- // TRANSCRIPT_BYTE_BUDGET in agent-prompts.ts), so this term needs its own bound.
551
- const PLAN_BYTE_BUDGET = 8 * 1024;
552
547
  const MAX_ATTACHMENTS = 6;
553
548
  // @-mentioned places are references, so the only cost is instruction bytes --
554
549
  // but a client is not the one to decide how many the router is told about.
@@ -664,12 +659,7 @@ function readPlanSnapshot(deckDir) {
664
659
  }
665
660
  if (!raw.trim())
666
661
  return { raw };
667
- if (Buffer.byteLength(raw, 'utf8') <= PLAN_BYTE_BUDGET)
668
- return { raw, text: raw.trim() };
669
- return {
670
- raw,
671
- text: `${truncateToBytes(raw, PLAN_BYTE_BUDGET).trim()}\n\n(trimmed -- plan.md is longer than this. Tell the user it has grown too long; it should stay a short working plan.)`,
672
- };
662
+ return { raw, text: raw.trim() };
673
663
  }
674
664
  // How many op notices ride into the next router turn. More than a handful is a
675
665
  // fence that went wrong wholesale, and the first few say so.
@@ -755,6 +745,7 @@ function routerPlanOpts(deckDir, snapshot, nominations, tasks) {
755
745
  text: t.durable ?? '',
756
746
  })),
757
747
  finishedWork: planFinishedWork(tasks),
748
+ settledItems: planSettledItems(tasks),
758
749
  notices,
759
750
  };
760
751
  }
@@ -2193,6 +2184,25 @@ function refreshHandoff(dir, task) {
2193
2184
  }
2194
2185
  return changed;
2195
2186
  }
2187
+ // An item is settled when nothing on it is live and the LATEST task spawned for
2188
+ // it finished done: a failed or interrupted follow-up after an earlier success
2189
+ // is work still owed, and hiding the item would hide that.
2190
+ function planSettledItems(tasks) {
2191
+ const latest = new Map();
2192
+ const live = new Set();
2193
+ for (const task of tasks) {
2194
+ if (!task.item || task.item === '-')
2195
+ continue;
2196
+ if (!isTerminal(task.status))
2197
+ live.add(task.item);
2198
+ const prev = latest.get(task.item);
2199
+ if (!prev || task.createdAt >= prev.createdAt)
2200
+ latest.set(task.item, task);
2201
+ }
2202
+ return [...latest.entries()]
2203
+ .filter(([item, task]) => task.status === 'done' && !live.has(item))
2204
+ .map(([item]) => item);
2205
+ }
2196
2206
  // What the plan's derived `## Built` is made of: the work of tasks that
2197
2207
  // actually finished, addressed by the plan item they advanced. A task that
2198
2208
  // belongs to no item, failed, or never wrote a `what:` line has nothing to
package/dist/api.d.ts CHANGED
@@ -171,8 +171,20 @@ export interface CauldronServerConfig {
171
171
  selection: 'exact' | 'find';
172
172
  persistence: 'transient' | 'world';
173
173
  characters?: 'shared';
174
+ worldTime?: {
175
+ advance: 'wallClock';
176
+ };
174
177
  maxPlayers: number;
175
178
  }>;
179
+ worldNotifications?: {
180
+ version: 1;
181
+ templates: Array<{
182
+ id: string;
183
+ text: string;
184
+ slots: string[];
185
+ timeSensitive?: boolean;
186
+ }>;
187
+ };
176
188
  }
177
189
  export interface CauldronServerBundleResult {
178
190
  deckId: string;
@@ -200,6 +212,13 @@ export interface DeckMeta {
200
212
  }
201
213
  export declare function deckMeta(deckId: string): Promise<DeckMeta | null>;
202
214
  export declare function webDeckSource(deckId: string): Promise<WebDeckSource | null>;
215
+ export interface SavedSourceVersion {
216
+ s3Key: string;
217
+ archiveUrl: string;
218
+ savedAt: string;
219
+ bytes: number;
220
+ }
221
+ export declare function savedSourceHistory(deckId: string, timeoutMs?: number): Promise<SavedSourceVersion[]>;
203
222
  export declare function clearDeckLeaderboards(deckId: string): Promise<void>;
204
223
  export declare function saveWebDeckSource(deckId: string, uploadId: string, expectedS3Key?: string | null): Promise<WebDeckSource>;
205
224
  export type CloudDeckKit = 'PHYSICS_2D' | 'PHYSICS_3D' | 'MULTIPLAYER_2D' | 'MULTIPLAYER_3D' | 'TURN_BASED' | 'NONE';
package/dist/api.js CHANGED
@@ -310,6 +310,17 @@ export async function webDeckSource(deckId) {
310
310
  handleAPIError(data);
311
311
  return pickData(data, 'webDeckSource');
312
312
  }
313
+ // Every saved version of the deck's source, newest first (Ghost lists at most 50), for its
314
+ // creator or an edit collaborator. A Ghost without the field fails this, as does anyone else.
315
+ export async function savedSourceHistory(deckId, timeoutMs) {
316
+ const data = await graphql(`query($deckId: ID!) {
317
+ webDeckSourceVersions(deckId: $deckId) {
318
+ s3Key archiveUrl savedAt bytes
319
+ }
320
+ }`, { deckId }, timeoutMs === undefined ? {} : { timeoutMs: Math.max(1, timeoutMs) });
321
+ handleAPIError(data);
322
+ return pickData(data, 'webDeckSourceVersions');
323
+ }
313
324
  // Starts every leaderboard on the deck over from empty. Ghost allows it only for
314
325
  // the deck's creator.
315
326
  export async function clearDeckLeaderboards(deckId) {
@@ -27,6 +27,7 @@ export interface CastleJson {
27
27
  tickRate?: number;
28
28
  maxPlayers?: number;
29
29
  destinations?: ServerDestinationConfig[];
30
+ worldNotifications?: ServerWorldNotificationsConfig;
30
31
  };
31
32
  voice?: {
32
33
  enabled?: boolean;
@@ -47,14 +48,28 @@ export interface ServerDestinationConfig {
47
48
  selection: 'exact' | 'find';
48
49
  persistence: 'transient' | 'world';
49
50
  characters?: 'shared';
51
+ worldTime?: {
52
+ advance: 'wallClock';
53
+ };
50
54
  maxPlayers: number;
51
55
  }
56
+ export interface ServerWorldNotificationTemplateConfig {
57
+ id: string;
58
+ text: string;
59
+ slots: string[];
60
+ timeSensitive?: boolean;
61
+ }
62
+ export interface ServerWorldNotificationsConfig {
63
+ version: 1;
64
+ templates: ServerWorldNotificationTemplateConfig[];
65
+ }
52
66
  export interface ResolvedServerConfig {
53
67
  entry: string;
54
68
  tickRate: number;
55
69
  maxPlayers: number;
56
70
  voiceEnabled: boolean;
57
71
  destinations?: ServerDestinationConfig[];
72
+ worldNotifications?: ServerWorldNotificationsConfig;
58
73
  }
59
74
  export declare function resolveServerConfig(dir: string): ResolvedServerConfig | null;
60
75
  export declare function deckStarterScene(dir: string): string;
@@ -48,14 +48,19 @@ export function resolveServerConfig(dir) {
48
48
  DEFAULT_SERVER_ENTRIES.find((candidate) => fs.existsSync(path.join(dir, candidate)));
49
49
  if (!entry || !isSafeServerEntry(dir, entry))
50
50
  return null;
51
+ const destinations = server?.destinations === undefined
52
+ ? undefined
53
+ : validateServerDestinations(server.destinations);
54
+ const worldNotifications = server?.worldNotifications === undefined
55
+ ? undefined
56
+ : validateServerWorldNotifications(server.worldNotifications, destinations);
51
57
  return {
52
58
  entry,
53
59
  tickRate: clampNumber(server?.tickRate, DEFAULT_SERVER_TICK_RATE, 0, SERVER_TICK_RATE_CAP),
54
60
  maxPlayers: Math.floor(clampNumber(server?.maxPlayers, DEFAULT_SERVER_MAX_PLAYERS, 1, SERVER_MAX_PLAYERS_CAP)),
55
61
  voiceEnabled: castleJson?.voice?.enabled !== false,
56
- ...(server?.destinations === undefined
57
- ? {}
58
- : { destinations: validateServerDestinations(server.destinations) }),
62
+ ...(destinations === undefined ? {} : { destinations }),
63
+ ...(worldNotifications === undefined ? {} : { worldNotifications }),
59
64
  };
60
65
  }
61
66
  function validateServerDestinations(value) {
@@ -68,6 +73,17 @@ function validateServerDestinations(value) {
68
73
  throw invalidDestination(index, 'must be an object');
69
74
  }
70
75
  const route = candidate;
76
+ if (Object.keys(route).some((key) => ![
77
+ 'routeId',
78
+ 'access',
79
+ 'selection',
80
+ 'persistence',
81
+ 'maxPlayers',
82
+ 'characters',
83
+ 'worldTime',
84
+ ].includes(key))) {
85
+ throw invalidDestination(index, 'contains an unknown field');
86
+ }
71
87
  const routeId = route.routeId;
72
88
  if (typeof routeId !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(routeId)) {
73
89
  throw invalidDestination(index, 'routeId must match [A-Za-z0-9_-] and be 1 through 64 characters');
@@ -94,6 +110,20 @@ function validateServerDestinations(value) {
94
110
  (route.persistence !== 'world' || route.selection !== 'exact')) {
95
111
  throw invalidDestination(index, 'shared characters require selection "exact" and persistence "world"');
96
112
  }
113
+ let worldTime;
114
+ if (route.worldTime !== undefined) {
115
+ if (route.persistence !== 'world') {
116
+ throw invalidDestination(index, 'worldTime is only valid on a persistent world route');
117
+ }
118
+ if (!route.worldTime ||
119
+ typeof route.worldTime !== 'object' ||
120
+ Array.isArray(route.worldTime) ||
121
+ Object.keys(route.worldTime).some((key) => key !== 'advance') ||
122
+ route.worldTime.advance !== 'wallClock') {
123
+ throw invalidDestination(index, 'worldTime.advance must be wallClock');
124
+ }
125
+ worldTime = { advance: 'wallClock' };
126
+ }
97
127
  if (!Number.isInteger(route.maxPlayers) ||
98
128
  route.maxPlayers < 1 ||
99
129
  route.maxPlayers > SERVER_MAX_PLAYERS_CAP) {
@@ -105,10 +135,113 @@ function validateServerDestinations(value) {
105
135
  selection: route.selection,
106
136
  persistence: route.persistence,
107
137
  ...(route.characters === 'shared' ? { characters: 'shared' } : {}),
138
+ ...(worldTime === undefined ? {} : { worldTime }),
108
139
  maxPlayers: route.maxPlayers,
109
140
  };
110
141
  });
111
142
  }
143
+ const SERVER_WORLD_NOTIFICATION_TEMPLATES_CAP = 16;
144
+ const SERVER_WORLD_NOTIFICATION_SLOTS_CAP = 4;
145
+ const SAFE_WORLD_NOTIFICATION_KEY = /^[A-Za-z0-9_-]+$/;
146
+ const WORLD_NOTIFICATION_PLACEHOLDER = /\{([A-Za-z0-9_-]+)\}/g;
147
+ const WORLD_NOTIFICATION_URL = /(?:https?:\/\/|www\.|\b[a-z0-9-]+\.(?:app|com|dev|gg|io|net|org|xyz)\b)/i;
148
+ function worldNotificationCharacters(value) {
149
+ return Array.from(value).length;
150
+ }
151
+ function isWorldNotificationSafeKey(value) {
152
+ return typeof value === 'string' &&
153
+ worldNotificationCharacters(value) >= 1 &&
154
+ worldNotificationCharacters(value) <= 64 &&
155
+ SAFE_WORLD_NOTIFICATION_KEY.test(value);
156
+ }
157
+ function validateServerWorldNotifications(value, destinations) {
158
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
159
+ throw invalidWorldNotifications('must be an object');
160
+ }
161
+ const config = value;
162
+ if (Object.keys(config).some((key) => key !== 'version' && key !== 'templates')) {
163
+ throw invalidWorldNotifications('contains an unsupported field');
164
+ }
165
+ if (config.version !== 1)
166
+ throw invalidWorldNotifications('version must be 1');
167
+ if (!Array.isArray(config.templates) ||
168
+ config.templates.length > SERVER_WORLD_NOTIFICATION_TEMPLATES_CAP) {
169
+ throw invalidWorldNotifications(`templates must be an array of at most ${SERVER_WORLD_NOTIFICATION_TEMPLATES_CAP} templates`);
170
+ }
171
+ if (!destinations?.some((route) => route.persistence === 'world')) {
172
+ throw invalidWorldNotifications('requires at least one persistent world destination');
173
+ }
174
+ const templateIds = new Set();
175
+ const templates = config.templates.map((candidate, index) => {
176
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
177
+ throw invalidWorldNotificationTemplate(index, 'must be an object');
178
+ }
179
+ const template = candidate;
180
+ if (Object.keys(template).some((key) => key !== 'id' && key !== 'text' && key !== 'slots' && key !== 'timeSensitive')) {
181
+ throw invalidWorldNotificationTemplate(index, 'contains an unsupported field');
182
+ }
183
+ if (!isWorldNotificationSafeKey(template.id)) {
184
+ throw invalidWorldNotificationTemplate(index, 'id must be a safe key of at most 64 characters');
185
+ }
186
+ if (templateIds.has(template.id)) {
187
+ throw invalidWorldNotificationTemplate(index, `id "${template.id}" is duplicated`);
188
+ }
189
+ templateIds.add(template.id);
190
+ if (typeof template.text !== 'string' ||
191
+ worldNotificationCharacters(template.text) < 1 ||
192
+ worldNotificationCharacters(template.text) > 120 ||
193
+ template.text.includes('\n') ||
194
+ template.text.includes('\r') ||
195
+ WORLD_NOTIFICATION_URL.test(template.text)) {
196
+ throw invalidWorldNotificationTemplate(index, 'text must be 1 through 120 characters on one line and contain no URL');
197
+ }
198
+ if (!Array.isArray(template.slots) || template.slots.length > SERVER_WORLD_NOTIFICATION_SLOTS_CAP) {
199
+ throw invalidWorldNotificationTemplate(index, `slots must be an array of at most ${SERVER_WORLD_NOTIFICATION_SLOTS_CAP} safe keys`);
200
+ }
201
+ const slots = template.slots.map((slot, slotIndex) => {
202
+ if (!isWorldNotificationSafeKey(slot)) {
203
+ throw invalidWorldNotificationTemplate(index, `slots[${slotIndex}] must be a safe key`);
204
+ }
205
+ return slot;
206
+ });
207
+ if (new Set(slots).size !== slots.length) {
208
+ throw invalidWorldNotificationTemplate(index, 'slots must not contain duplicates');
209
+ }
210
+ if (slots.includes('actor')) {
211
+ throw invalidWorldNotificationTemplate(index, 'slots cannot declare the reserved name actor');
212
+ }
213
+ const placeholders = new Set();
214
+ for (const match of template.text.matchAll(WORLD_NOTIFICATION_PLACEHOLDER)) {
215
+ const placeholder = match[1];
216
+ placeholders.add(placeholder);
217
+ }
218
+ const textWithoutPlaceholders = template.text.replace(WORLD_NOTIFICATION_PLACEHOLDER, '');
219
+ if (textWithoutPlaceholders.includes('{') || textWithoutPlaceholders.includes('}')) {
220
+ throw invalidWorldNotificationTemplate(index, 'text contains an invalid placeholder');
221
+ }
222
+ for (const placeholder of placeholders) {
223
+ if (!slots.includes(placeholder)) {
224
+ throw invalidWorldNotificationTemplate(index, `placeholder "${placeholder}" must appear in slots`);
225
+ }
226
+ }
227
+ if (template.timeSensitive !== undefined && typeof template.timeSensitive !== 'boolean') {
228
+ throw invalidWorldNotificationTemplate(index, 'timeSensitive must be a boolean when present');
229
+ }
230
+ return {
231
+ id: template.id,
232
+ text: template.text,
233
+ slots,
234
+ timeSensitive: template.timeSensitive === true,
235
+ };
236
+ });
237
+ return { version: 1, templates };
238
+ }
239
+ function invalidWorldNotifications(message) {
240
+ return new Error(`server.worldNotifications ${message}.`);
241
+ }
242
+ function invalidWorldNotificationTemplate(index, message) {
243
+ return new Error(`server.worldNotifications.templates[${index}] ${message}.`);
244
+ }
112
245
  function invalidDestination(index, message) {
113
246
  return new Error(`server.destinations[${index}] ${message}.`);
114
247
  }