castle-web-cli 0.4.227 → 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.
Files changed (42) hide show
  1. package/dist/agent-prompts.d.ts +9 -3
  2. package/dist/agent-prompts.js +140 -48
  3. package/dist/agent.js +127 -14
  4. package/dist/api.d.ts +37 -0
  5. package/dist/api.js +29 -0
  6. package/dist/castle-host/host.d.ts +6 -0
  7. package/dist/castle-host/host.js +42 -3
  8. package/dist/castleJson.d.ts +15 -0
  9. package/dist/castleJson.js +136 -3
  10. package/dist/cloudGit.d.ts +27 -1
  11. package/dist/cloudGit.js +359 -24
  12. package/dist/cloudGitServe.js +9 -5
  13. package/dist/gitCollaborators.d.ts +16 -0
  14. package/dist/gitCollaborators.js +42 -0
  15. package/dist/gitIncoming.d.ts +17 -0
  16. package/dist/gitIncoming.js +113 -0
  17. package/dist/gitRemote.js +2 -2
  18. package/dist/imports.js +4 -2
  19. package/dist/index.js +5 -0
  20. package/dist/init.js +1 -1
  21. package/dist/native/playtest-browser.js +13 -1
  22. package/dist/platformDoc.js +1 -1
  23. package/dist/save-deck.js +3 -0
  24. package/dist/serve.js +17 -0
  25. package/dist/shell/assets/index-Cf61cNfT.css +1 -0
  26. package/dist/shell/assets/{index-D006JHww.js → index-D2tWM896.js} +71 -71
  27. package/dist/shell/index.html +2 -2
  28. package/dist/sourceLineage.d.ts +42 -0
  29. package/dist/sourceLineage.js +380 -0
  30. package/dist/webSourceSync.d.ts +9 -0
  31. package/dist/webSourceSync.js +24 -9
  32. package/kits/base/castle.json +1 -1
  33. package/kits/base/sdk/README.md +81 -0
  34. package/kits/base/sdk/castle.d.ts +1 -1
  35. package/kits/base/sdk/commands.d.ts +6 -0
  36. package/kits/base/sdk/multiplayer.d.ts +44 -6
  37. package/kits/base/sdk/multiplayer.js +62 -1
  38. package/kits/base/sdk/server/platformHandle.d.ts +9 -1
  39. package/kits/base/sdk/server/wrapper.d.ts +111 -4
  40. package/kits/base/sdk/server/wrapper.js +650 -24
  41. package/package.json +10 -2
  42. package/dist/shell/assets/index-BxDYy_-C.css +0 -1
@@ -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
@@ -37,7 +37,8 @@ import { badTaskEndingsSince, platformInterruptionReason, ROUTER_STOPPED_RESULT,
37
37
  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
- import { applyPlanOps, buildRouterPromptParts, buildTaskPrompt, parsePlanOps, truncateToBytes, userTurnInstruction, CLAUDE_TASK_SYSTEM_REMINDER, modelTaskAddendum, isMuseModel, } from './agent-prompts.js';
40
+ import { readGitIncomingNote, removeGitIncoming } from './gitIncoming.js';
41
+ import { applyPlanOps, buildRouterPromptParts, buildTaskPrompt, parsePlanOps, userTurnInstruction, CLAUDE_TASK_SYSTEM_REMINDER, modelTaskAddendum, isMuseModel, } from './agent-prompts.js';
41
42
  import { readCastleJson } from './castleJson.js';
42
43
  import { checkOpenrouterKey, checkOpenrouterModel, primeOpenrouterCatalog, } from './openrouter-catalog.js';
43
44
  import { classifyProviderError, failureCopy, failureLabel, routerTaskError, setReaderTimeZone, } from './agent-failures.js';
@@ -51,7 +52,9 @@ import { createRemotePlaytestExecutor } from './native/playtest-remote.js';
51
52
  import { runPlaytest, } from './native/playtest.js';
52
53
  import { AGENT_ROLE_ENV, cloudGitMode } from './cloudGit.js';
53
54
  import { createServeGitHooks, createServeMarkerPoll } from './cloudGitServe.js';
55
+ import { deckCollaborators, reportDeckEditorPresence, } from './api.js';
54
56
  export const AGENT_WS_PATH = '/__castle/agent';
57
+ const PRESENCE_INTERVAL_MS = 15_000;
55
58
  const DEFAULT_SETTINGS = {
56
59
  // Both roles run the claude CLI routed through OpenRouter at the slug below.
57
60
  // Note this takes the Anthropic credential out of play entirely: a role on
@@ -541,11 +544,6 @@ const MAX_TASK_RESUMES = 3;
541
544
  const TASK_POLL_MS = 1_000;
542
545
  const FENCE_HOLDBACK = '```castle-';
543
546
  const RESULT_SUMMARY_CHARS = 600;
544
- // Byte ceiling on the plan.md injected into router turns and task prompts.
545
- // Nothing bounds the file itself -- ops touch one line each and the user pastes
546
- // what they like -- meanwhile the whole prompt rides inside one argv entry (see
547
- // TRANSCRIPT_BYTE_BUDGET in agent-prompts.ts), so this term needs its own bound.
548
- const PLAN_BYTE_BUDGET = 8 * 1024;
549
547
  const MAX_ATTACHMENTS = 6;
550
548
  // @-mentioned places are references, so the only cost is instruction bytes --
551
549
  // but a client is not the one to decide how many the router is told about.
@@ -661,12 +659,7 @@ function readPlanSnapshot(deckDir) {
661
659
  }
662
660
  if (!raw.trim())
663
661
  return { raw };
664
- if (Buffer.byteLength(raw, 'utf8') <= PLAN_BYTE_BUDGET)
665
- return { raw, text: raw.trim() };
666
- return {
667
- raw,
668
- 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.)`,
669
- };
662
+ return { raw, text: raw.trim() };
670
663
  }
671
664
  // How many op notices ride into the next router turn. More than a handful is a
672
665
  // fence that went wrong wholesale, and the first few say so.
@@ -752,6 +745,7 @@ function routerPlanOpts(deckDir, snapshot, nominations, tasks) {
752
745
  text: t.durable ?? '',
753
746
  })),
754
747
  finishedWork: planFinishedWork(tasks),
748
+ settledItems: planSettledItems(tasks),
755
749
  notices,
756
750
  };
757
751
  }
@@ -2190,6 +2184,25 @@ function refreshHandoff(dir, task) {
2190
2184
  }
2191
2185
  return changed;
2192
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
+ }
2193
2206
  // What the plan's derived `## Built` is made of: the work of tasks that
2194
2207
  // actually finished, addressed by the plan item they advanced. A task that
2195
2208
  // belongs to no item, failed, or never wrote a `what:` line has nothing to
@@ -4535,16 +4548,20 @@ function maybeStartRouterQueueTurn(ctx) {
4535
4548
  persistPendingSends(ctx);
4536
4549
  const draft = state.pendingInterruptedDraft;
4537
4550
  state.pendingInterruptedDraft = '';
4551
+ state.turnInterrupted = false;
4538
4552
  state.routerRunning = true;
4539
4553
  broadcastQueueState(ctx);
4540
- startRouterTurn(ctx, userTurnInstruction({
4554
+ const instruction = userTurnInstruction({
4541
4555
  messages: texts,
4542
4556
  interruptedDraft: draft || undefined,
4543
4557
  attachments: attachmentPaths,
4544
4558
  marked: markedPaths,
4545
4559
  flattened,
4546
4560
  refs,
4547
- }));
4561
+ });
4562
+ const incoming = readGitIncomingNote(ctx.deckDir);
4563
+ state.incomingNoteShas = incoming.shas;
4564
+ startRouterTurn(ctx, incoming.note ? `${incoming.note}\n\n${instruction}` : instruction);
4548
4565
  }
4549
4566
  // The turn settled: clear the busy flag, broadcast it, then flush anything
4550
4567
  // that queued mid-turn (a clean end and an interrupt take the same path). A
@@ -4553,6 +4570,7 @@ function maybeStartRouterQueueTurn(ctx) {
4553
4570
  // which case flushing it supersedes the retry (its turn re-covers things).
4554
4571
  function onRouterQueueSettled(ctx, retryable) {
4555
4572
  const { state } = ctx;
4573
+ const interrupted = state.turnInterrupted;
4556
4574
  state.routerRunning = false;
4557
4575
  if (retryable &&
4558
4576
  !state.autoRetryUsed &&
@@ -4564,6 +4582,11 @@ function onRouterQueueSettled(ctx, retryable) {
4564
4582
  startRouterTurn(ctx, state.lastInstruction);
4565
4583
  return;
4566
4584
  }
4585
+ const incomingNoteShas = state.incomingNoteShas;
4586
+ state.incomingNoteShas = [];
4587
+ state.turnInterrupted = false;
4588
+ if (!retryable && !interrupted)
4589
+ removeGitIncoming(ctx.deckDir, incomingNoteShas);
4567
4590
  broadcastQueueState(ctx);
4568
4591
  maybeStartRouterQueueTurn(ctx);
4569
4592
  if (!state.routerRunning) {
@@ -4585,6 +4608,7 @@ function onRouterQueueSettled(ctx, retryable) {
4585
4608
  // combined instruction.
4586
4609
  function foldRouterQueueTurn(ctx) {
4587
4610
  const { state } = ctx;
4611
+ state.turnInterrupted = true;
4588
4612
  state.userEpoch += 1;
4589
4613
  killRouterChildren(ctx);
4590
4614
  reclaimInFlightSends(state.pendingSends, state.inFlightSends);
@@ -4660,6 +4684,7 @@ function interruptRouterQueue(ctx) {
4660
4684
  // the turn outright. Captured before reclaim, which would otherwise fill
4661
4685
  // the queue and make every Stop look like a Send now.
4662
4686
  const hasFollowUp = state.pendingSends.length > 0;
4687
+ state.turnInterrupted = true;
4663
4688
  state.userEpoch += 1;
4664
4689
  const draft = killRouterChildren(ctx);
4665
4690
  // Only a continued turn ("Send now") reclaims its in-flight sends so they
@@ -4711,6 +4736,8 @@ function createRouterQueue(deps) {
4711
4736
  autoRetryUsed: false,
4712
4737
  autoFoldUsed: false,
4713
4738
  lastInstruction: '',
4739
+ incomingNoteShas: [],
4740
+ turnInterrupted: false,
4714
4741
  },
4715
4742
  };
4716
4743
  // Restart recovery: re-enqueue sends that never reached the message log,
@@ -4837,6 +4864,85 @@ export function createAgentServer(opts) {
4837
4864
  socket.send(payload);
4838
4865
  }
4839
4866
  }
4867
+ const presenceDeckId = cloudGitMode(deckDir) ? readCastleJson(deckDir)?.deckId : undefined;
4868
+ let presenceOthers = [];
4869
+ let collaboratorRoster = [];
4870
+ let presenceTimer = null;
4871
+ let presenceTick = 0;
4872
+ let presenceRunning = false;
4873
+ let collaboratorsRunning = false;
4874
+ let presenceFailureLogged = false;
4875
+ let collaboratorsFailureLogged = false;
4876
+ const presenceEntry = (entry) => ({
4877
+ userId: String(entry.userId),
4878
+ username: String(entry.username),
4879
+ photoUrl: typeof entry.photo?.url === 'string' ? entry.photo.url : null,
4880
+ lastSeenAt: String(entry.lastSeenAt),
4881
+ });
4882
+ const collaboratorEntry = (entry) => ({
4883
+ userId: String(entry.userId),
4884
+ username: String(entry.username),
4885
+ photoUrl: typeof entry.photo?.url === 'string' ? entry.photo.url : null,
4886
+ addedAt: String(entry.addedAt),
4887
+ });
4888
+ async function refreshPresence() {
4889
+ if (!presenceDeckId || clients.size === 0 || presenceRunning)
4890
+ return;
4891
+ presenceRunning = true;
4892
+ try {
4893
+ presenceOthers = (await reportDeckEditorPresence(presenceDeckId)).map(presenceEntry);
4894
+ presenceFailureLogged = false;
4895
+ broadcast({ type: 'presence', others: presenceOthers });
4896
+ }
4897
+ catch (err) {
4898
+ if (!presenceFailureLogged) {
4899
+ console.error(`[presence] could not report deck editor presence: ${err instanceof Error ? err.message : String(err)}`);
4900
+ presenceFailureLogged = true;
4901
+ }
4902
+ }
4903
+ finally {
4904
+ presenceRunning = false;
4905
+ }
4906
+ }
4907
+ async function refreshCollaborators() {
4908
+ if (!presenceDeckId || clients.size === 0 || collaboratorsRunning)
4909
+ return;
4910
+ collaboratorsRunning = true;
4911
+ try {
4912
+ collaboratorRoster = (await deckCollaborators(presenceDeckId)).map(collaboratorEntry);
4913
+ collaboratorsFailureLogged = false;
4914
+ broadcast({ type: 'collaborators', collaborators: collaboratorRoster });
4915
+ }
4916
+ catch (err) {
4917
+ if (!collaboratorsFailureLogged) {
4918
+ console.error(`[presence] could not list deck collaborators: ${err instanceof Error ? err.message : String(err)}`);
4919
+ collaboratorsFailureLogged = true;
4920
+ }
4921
+ }
4922
+ finally {
4923
+ collaboratorsRunning = false;
4924
+ }
4925
+ }
4926
+ function tickPresence() {
4927
+ presenceTick += 1;
4928
+ void refreshPresence();
4929
+ if (presenceTick === 1 || (presenceTick - 1) % 4 === 0)
4930
+ void refreshCollaborators();
4931
+ }
4932
+ function startPresence() {
4933
+ if (!presenceDeckId || presenceTimer)
4934
+ return;
4935
+ tickPresence();
4936
+ presenceTimer = setInterval(tickPresence, PRESENCE_INTERVAL_MS);
4937
+ presenceTimer.unref();
4938
+ }
4939
+ function stopPresence() {
4940
+ if (presenceTimer)
4941
+ clearInterval(presenceTimer);
4942
+ presenceTimer = null;
4943
+ presenceTick = 0;
4944
+ presenceOthers = [];
4945
+ }
4840
4946
  const log = createMessageLog(messagesPath, broadcast, welcomeMessage, (message) => asClientMessage(message, opts.signPath));
4841
4947
  const messages = log.messages;
4842
4948
  const addLog = (text) => log.addLog(text);
@@ -5005,8 +5111,12 @@ export function createAgentServer(opts) {
5005
5111
  queued: routerQueue.queuedSnippets(),
5006
5112
  usage: usageFeed.latest(),
5007
5113
  accounts: accountsFeed.snapshot(),
5114
+ presence: presenceOthers,
5115
+ collaborators: collaboratorRoster,
5008
5116
  };
5009
5117
  socket.send(JSON.stringify(hello));
5118
+ if (clients.size === 1)
5119
+ startPresence();
5010
5120
  // A newly attached client is the one moment the cached value may be stale
5011
5121
  // by a whole poll interval (nothing refreshes while nobody is watching).
5012
5122
  usageFeed.refresh();
@@ -5100,6 +5210,8 @@ export function createAgentServer(opts) {
5100
5210
  });
5101
5211
  socket.on('close', () => {
5102
5212
  clients.delete(socket);
5213
+ if (clients.size === 0)
5214
+ stopPresence();
5103
5215
  });
5104
5216
  }
5105
5217
  function handleUpgrade(req, socket, head) {
@@ -5124,6 +5236,7 @@ export function createAgentServer(opts) {
5124
5236
  return handleAttachment(req, res, reqPath) || handlePlaytestFrame(req, res, reqPath);
5125
5237
  }
5126
5238
  function shutdown() {
5239
+ stopPresence();
5127
5240
  gitHooks?.stop();
5128
5241
  markerPoll?.stop();
5129
5242
  taskStore.shutdown();
package/dist/api.d.ts CHANGED
@@ -72,6 +72,24 @@ export interface MeProfile {
72
72
  }
73
73
  export declare function me(): Promise<MeProfile | null>;
74
74
  export declare function whoAmI(): Promise<Pick<MeProfile, 'userId' | 'username'> | null>;
75
+ export interface DeckEditorPresenceEntry {
76
+ userId: string;
77
+ username: string;
78
+ photo?: {
79
+ url?: string;
80
+ } | null;
81
+ lastSeenAt: string;
82
+ }
83
+ export interface DeckCollaborator {
84
+ userId: string;
85
+ username: string;
86
+ photo?: {
87
+ url?: string;
88
+ } | null;
89
+ addedAt: string;
90
+ }
91
+ export declare function reportDeckEditorPresence(deckId: string): Promise<DeckEditorPresenceEntry[]>;
92
+ export declare function deckCollaborators(deckId: string): Promise<DeckCollaborator[]>;
75
93
  export interface DeckRow {
76
94
  deckId: string;
77
95
  title: string | null;
@@ -153,8 +171,20 @@ export interface CauldronServerConfig {
153
171
  selection: 'exact' | 'find';
154
172
  persistence: 'transient' | 'world';
155
173
  characters?: 'shared';
174
+ worldTime?: {
175
+ advance: 'wallClock';
176
+ };
156
177
  maxPlayers: number;
157
178
  }>;
179
+ worldNotifications?: {
180
+ version: 1;
181
+ templates: Array<{
182
+ id: string;
183
+ text: string;
184
+ slots: string[];
185
+ timeSensitive?: boolean;
186
+ }>;
187
+ };
158
188
  }
159
189
  export interface CauldronServerBundleResult {
160
190
  deckId: string;
@@ -182,6 +212,13 @@ export interface DeckMeta {
182
212
  }
183
213
  export declare function deckMeta(deckId: string): Promise<DeckMeta | null>;
184
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[]>;
185
222
  export declare function clearDeckLeaderboards(deckId: string): Promise<void>;
186
223
  export declare function saveWebDeckSource(deckId: string, uploadId: string, expectedS3Key?: string | null): Promise<WebDeckSource>;
187
224
  export type CloudDeckKit = 'PHYSICS_2D' | 'PHYSICS_3D' | 'MULTIPLAYER_2D' | 'MULTIPLAYER_3D' | 'TURN_BASED' | 'NONE';