castle-web-cli 0.4.226 → 0.4.228

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 (50) hide show
  1. package/dist/agent-prompts.d.ts +5 -0
  2. package/dist/agent-prompts.js +7 -7
  3. package/dist/agent.d.ts +1 -0
  4. package/dist/agent.js +159 -48
  5. package/dist/api.d.ts +21 -0
  6. package/dist/api.js +21 -3
  7. package/dist/castle-host/host.d.ts +6 -0
  8. package/dist/castle-host/host.js +42 -3
  9. package/dist/cloudGit.d.ts +7 -0
  10. package/dist/cloudGit.js +92 -14
  11. package/dist/cloudGitServe.js +9 -5
  12. package/dist/get-deck.js +5 -2
  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/importBrowse.js +7 -6
  19. package/dist/imports.d.ts +2 -1
  20. package/dist/imports.js +82 -13
  21. package/dist/init.js +17 -4
  22. package/dist/native/playtest-browser.js +13 -1
  23. package/dist/platformDoc.d.ts +1 -0
  24. package/dist/platformDoc.js +31 -9
  25. package/dist/playPagePolicy.js +35 -1
  26. package/dist/remix.js +1 -1
  27. package/dist/save-deck.d.ts +1 -7
  28. package/dist/save-deck.js +18 -26
  29. package/dist/saveFailure.d.ts +26 -0
  30. package/dist/saveFailure.js +102 -0
  31. package/dist/serve.js +17 -0
  32. package/dist/shell/assets/index-Cf61cNfT.css +1 -0
  33. package/dist/shell/assets/{index-C7ksEq3_.js → index-D2tWM896.js} +94 -94
  34. package/dist/shell/index.html +2 -2
  35. package/kits/base/CLAUDE.md +2 -1
  36. package/kits/base/castle.json +1 -1
  37. package/kits/base/sdk/README.md +87 -0
  38. package/kits/base/sdk/castle.d.ts +3 -1
  39. package/kits/base/sdk/castle.js +1 -0
  40. package/kits/base/sdk/commands.d.ts +6 -0
  41. package/kits/base/sdk/display.d.ts +36 -0
  42. package/kits/base/sdk/display.js +96 -0
  43. package/kits/base/sdk/multiplayer.d.ts +3 -1
  44. package/kits/base/sdk/multiplayer.js +11 -1
  45. package/kits/base/sdk/runtime.js +35 -17
  46. package/kits/base/sdk/server/platformHandle.d.ts +2 -0
  47. package/kits/base/sdk/server/wrapper.d.ts +58 -0
  48. package/kits/base/sdk/server/wrapper.js +350 -8
  49. package/package.json +11 -3
  50. package/dist/shell/assets/index-4G5NKIQ8.css +0 -1
@@ -141,11 +141,16 @@ export interface PromptRef {
141
141
  field?: string;
142
142
  fragment?: string;
143
143
  }
144
+ export interface FlattenedAttachment {
145
+ view: string;
146
+ original: string;
147
+ }
144
148
  export declare function userTurnInstruction(opts: {
145
149
  messages: string[];
146
150
  interruptedDraft?: string;
147
151
  attachments?: string[];
148
152
  marked?: string[];
153
+ flattened?: FlattenedAttachment[];
149
154
  refs?: PromptRef[];
150
155
  }): string;
151
156
  export declare function buildTaskPrompt(opts: {
@@ -59,7 +59,7 @@ function baseRouterRules(playtest, playtestPref, steer = false) {
59
59
  : playtest
60
60
  ? `\n${PLAYTEST_ROUTER_RULE}`
61
61
  : '';
62
- const modelsRule = `\n- You cannot change which models run. Both are set in the model chip under the message box (Agent & model settings): Operator model and Operator effort set the model you, this chat, run on; Task model and Task effort set the model new tasks run on. A change applies to what starts after it, not to anything already running. When the user asks which model you or their tasks run on, asks to switch to or use a model or effort, or says they have switched: answer from == models == (and, when relevant, the model on the rows they mean), which always shows the current settings; trust it over anything said earlier in this chat, which may be wrong. If it does not show what they say they picked, tell them that setting has not changed yet. Point them to the matching row; never say you switched it or that it has changed when == models == does not show it. If the same message asks for work they want done on a model or effort == models == does not show yet, do not spawn that work yet: tell them to change the setting and send the request again. When == models == already shows it, spawn the work as usual${steer ? STEER_MODEL_CLAUSE : '.'} Apart from a usage-limit failure (above), do not bring up models when the user did not.`;
62
+ const modelsRule = `\n- You cannot change which models run. Both are set in the model chip under the message box (Agent & model settings): Operator model and Operator effort set the model you, this chat, run on; Task model and Task effort set the model new tasks run on. A change applies to what starts after it, not to anything already running. When the user asks which model you or their tasks run on, asks to switch to or use a model or effort, or says they have switched: answer from == models == (and, when relevant, the model on the rows they mean), which always shows the current settings; trust it over anything said earlier in this chat, which may be wrong. The tool you run inside calls itself Claude Code; that names the tool, not you. Your model is the one == models == names for this chat: answer whether you are Claude, or any model, from it. When it names a model that is not Claude (${CLAUDE_FAMILY} are Claude), you are not Claude: say so plainly. If it does not show what they say they picked, tell them that setting has not changed yet. Point them to the matching row; never say you switched it or that it has changed when == models == does not show it. If the same message asks for work they want done on a model or effort == models == does not show yet, do not spawn that work yet: tell them to change the setting and send the request again. When == models == already shows it, spawn the work as usual${steer ? STEER_MODEL_CLAUSE : '.'} Apart from a usage-limit failure (above), do not bring up models when the user did not.`;
63
63
  return `You are Castle's create assistant: the fast conversational router for a game-making session. The deck (game project) lives in the current directory and runs live in a pane right next to this chat.
64
64
 
65
65
  What a deck is: a normal web project served by vite -- index.html plus plain JS/JSX modules, with real npm dependencies (more can be installed), the castle-web-sdk package, and usually a kit framework whose engine, behaviors, scenes, editors, and drawings are ordinary files in this directory. The web platform is fully available (DOM, canvas, npm libraries like react, three, etc.). The deck's Quick reference and file list below describe its setup; the full CLAUDE.md / AGENTS.md has deeper detail. NEVER claim something is impossible or unsupported on the platform without checking that context (or, for specifics it doesn't cover, the deck's files) first.
@@ -189,7 +189,7 @@ now- food-hauling
189
189
  - THE USER SHAPING THE GAME IS AN INFLECTION POINT. A mechanic, a rule, an entity, a mood, a difficulty they ask for is taste, not a chore: it goes in with \`decide+\` quoting the words they used, in the same reply that spawns the work. Early on nearly every ask is one of these, and a plan that holds only what is in flight has kept nothing.
190
190
  - A bare number, a knob setting, or a bug they want gone is not taste -- just do the tweak. The REASON they give for one is: "make the islands bigger, it's already pretty hard" is a \`decide+\` about the difficulty they want, not about island size. A line about a value someone tuned names the intent and the knob, never the number: \`decide+ gentle-start: the first wave should feel easy -- spawnRate ("go easy at the start" -- user)\`, not \`... spawnRate at 0.4\`. A number inside the quote stays, since the quote is their words verbatim; your own sentence never carries one. The number lives in one place, the \`PARAMS\` object of the file that uses it, and a plan line repeating it becomes a second answer the moment anyone moves the slider.
191
191
  - Put the fence AFTER your task fences: tasks spawn the moment their fence closes.
192
- - NOTHING in \`## Open questions\` may be answered by anything else in the same reply, fence or task: asking and deciding are different acts. A probe IS the top open question, asked in its own words.
192
+ - NOTHING in \`## Open questions\` may be answered by anything else in the same reply, fence or task: asking and deciding are different acts.
193
193
  - An open question you have asked outright twice, and the user passed over both times, is TABLED: \`open- <label>\` it in that reply's fence and stop asking it. Passing over it twice is their answer about the question. It comes back only if they bring it up.
194
194
  - An ask that goes against a \`## Decisions\` line: say what was decided and why in one sentence BEFORE you build it. They may well have changed their mind -- that is theirs to say, and the line is yours to raise.
195
195
  - No plan.md yet and the deck is getting work? Open one here with the ops the moment supports: an \`identity:\` line, the \`## Now\` items you are spawning, an \`open+\` for what you are guessing at. SPARSE AND TRUE, and never in place of their actual ask.
@@ -830,10 +830,6 @@ export function renderPlanDigest(plan, tasks) {
830
830
  }
831
831
  return parts.join("\n\n");
832
832
  }
833
- // The non-empty lines of `## Open questions`, for the runtime's agenda nudge
834
- // (agent.ts): a standing question the router keeps not asking gets named in a
835
- // notice, since five wordings of a prompt rule for the same behavior all
836
- // measured 0 (26-08-18) while the notice-shaped close rule measured real.
837
833
  export function planOpenQuestionLines(fileText) {
838
834
  const section = parsePlanSections(fileText).find((s) => s.key === "open questions");
839
835
  return (section?.lines ?? []).map((l) => l.trim()).filter(Boolean);
@@ -887,6 +883,7 @@ export function renderTaskPlanSlice(fileText, item, finishedWork) {
887
883
  // settings rather than a provider slug. "Muse" is the chip's name for a model
888
884
  // Castle pays for, which only the budget's free prefixes decide.
889
885
  const CLAUDE_MODEL_LABELS = { sonnet: "Sonnet", opus: "Opus", fable: "Fable" };
886
+ const CLAUDE_FAMILY = Object.values(CLAUDE_MODEL_LABELS).join(", ").replace(/, ([^,]*)$/, " and $1");
890
887
  const noFreeModels = () => false;
891
888
  export function modelLabel(model, isFreeModel) {
892
889
  const trimmed = model.trim();
@@ -1058,7 +1055,10 @@ export function userTurnInstruction(opts) {
1058
1055
  const markNote = marked.length > 0
1059
1056
  ? ` ${marked.join(", ")} ${marked.length === 1 ? "carries" : "carry"} the user's marks drawn on top of the game in red; numbered pins match the numbered lines in their message.`
1060
1057
  : "";
1061
- parts.push(`The user attached image file(s), saved in the deck at: ${opts.attachments.join(", ")}. Open them with your read tool. Take them into account; pass the paths along to task agents that need them.${markNote}`);
1058
+ const flatNote = (opts.flattened ?? [])
1059
+ .map(({ view, original }) => ` ${view} is ${original} flattened onto white, because its transparent areas would show to you as black; ${original} keeps the transparency, so pass that one to a task that puts the image in the game.`)
1060
+ .join("");
1061
+ parts.push(`The user attached image file(s), saved in the deck at: ${opts.attachments.join(", ")}. Open them with your read tool. Take them into account; pass the paths along to task agents that need them.${markNote}${flatNote}`);
1062
1062
  }
1063
1063
  if (opts.refs && opts.refs.length > 0) {
1064
1064
  parts.push(`The user pointed at: ${opts.refs.map(refPhrase).join(", ")}. Read them with your read tool if you need them to reply. When you spawn a task one of these concerns, name it the same way in that task's prompt -- the path and the lines, or the path and the param -- so the agent reads that place; do not mention it to tasks it does not concern.`);
package/dist/agent.d.ts CHANGED
@@ -143,6 +143,7 @@ export declare function createTaskStore(opts: {
143
143
  onRetry: (task: TaskRecord, attempt: number) => void;
144
144
  onFeed: (task: TaskRecord, entry: string) => void;
145
145
  }): TaskStore;
146
+ export declare function attachmentViewName(fileName: string): string;
146
147
  export declare function computeSettingsWarnings(settings: AgentSettings): Promise<SettingsWarnings>;
147
148
  export interface AgentServer {
148
149
  /** Start tasks recovered from a restart; call once the serve is listening. */
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, planOpenQuestionLines, 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, truncateToBytes, 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
@@ -647,8 +650,6 @@ function planSession(deckDir) {
647
650
  const session = {
648
651
  enabled: declared === 'on' ? true : declared === 'off' ? false : planDefault(),
649
652
  notices: [],
650
- asyncNotices: [],
651
- quietBuildTurns: 0,
652
653
  };
653
654
  planSessions.set(deckDir, session);
654
655
  return session;
@@ -744,9 +745,8 @@ function routerPlanOpts(deckDir, snapshot, nominations, tasks) {
744
745
  const session = planSession(deckDir);
745
746
  if (!session.enabled)
746
747
  return undefined;
747
- const notices = [...session.notices, ...session.asyncNotices].slice(0, PLAN_NOTICE_LIMIT);
748
+ const notices = session.notices.slice(0, PLAN_NOTICE_LIMIT);
748
749
  session.notices = [];
749
- session.asyncNotices = [];
750
750
  return {
751
751
  fileText: snapshot.text,
752
752
  pendingDurables: nominations.map((t) => ({
@@ -758,32 +758,6 @@ function routerPlanOpts(deckDir, snapshot, nominations, tasks) {
758
758
  notices,
759
759
  };
760
760
  }
761
- // The agenda nudge. A reply that spawned work, asked nothing (no probe chips,
762
- // no question mark), while `## Open questions` holds a standing line, is a
763
- // quiet build turn; the second in a row queues a notice naming the top line.
764
- // Counting quiet turns and naming the line is exactly what five wordings of a
765
- // prompt rule could not get the router to do for itself (0 across 14 samples,
766
- // 26-08-18) and what the notice-shaped close rule showed it does do when told.
767
- function trackStandingQuestions(ctx, cleaned, spawnedWork) {
768
- const session = planSession(ctx.deckDir);
769
- if (!session.enabled)
770
- return;
771
- const askedSomething = /\[\[[^\]\n]+\]\]/.test(cleaned) || cleaned.includes('?');
772
- if (askedSomething || !spawnedWork) {
773
- session.quietBuildTurns = 0;
774
- return;
775
- }
776
- const standing = planOpenQuestionLines(readPlanSnapshot(ctx.deckDir).raw ?? '');
777
- if (standing.length === 0) {
778
- session.quietBuildTurns = 0;
779
- return;
780
- }
781
- session.quietBuildTurns += 1;
782
- if (session.quietBuildTurns < 2)
783
- return;
784
- session.quietBuildTurns = 0;
785
- session.asyncNotices.push(`the plan's top open question has now sat through two build turns with nothing asked -- this is the turn to ask it, in its own words, while work spawns anyway: ${standing[0]}`);
786
- }
787
761
  function taskPlanOpts(deckDir, item, finishedWork) {
788
762
  if (!planSession(deckDir).enabled)
789
763
  return undefined;
@@ -3285,13 +3259,21 @@ const ATTACHMENT_MIME = {
3285
3259
  gif: 'image/gif',
3286
3260
  webp: 'image/webp',
3287
3261
  };
3262
+ // The copy of an attachment the model is shown: the composer's `view`, the
3263
+ // picture flattened onto white because the model sees transparency as black.
3264
+ export function attachmentViewName(fileName) {
3265
+ return fileName.replace(/\.[^.]+$/, '') + '-view.jpg';
3266
+ }
3267
+ const VIEW_DATA_URL = /^data:image\/jpeg;base64,([A-Za-z0-9+/=]+)$/;
3288
3268
  // Decode pasted/attached images (data URLs) into .castle/agent/attachments/.
3289
- // Returns the saved file names, and which of them carry the user's marks.
3269
+ // Returns the saved file names, which of them carry the user's marks, and
3270
+ // which have a flattened view saved beside them (attachmentViewName).
3290
3271
  function saveAttachments(attachmentsDir, messageId, images) {
3291
3272
  const saved = [];
3292
3273
  const marked = [];
3274
+ const viewed = [];
3293
3275
  if (!Array.isArray(images))
3294
- return { saved, marked };
3276
+ return { saved, marked, viewed };
3295
3277
  for (const [index, image] of images.slice(0, MAX_ATTACHMENTS).entries()) {
3296
3278
  const dataUrl = image?.dataUrl;
3297
3279
  if (typeof dataUrl !== 'string' || dataUrl.length > MAX_ATTACHMENT_BYTES * 1.4)
@@ -3310,9 +3292,23 @@ function saveAttachments(attachmentsDir, messageId, images) {
3310
3292
  }
3311
3293
  catch {
3312
3294
  /* disk trouble -- skip this image */
3295
+ continue;
3296
+ }
3297
+ const view = image.view;
3298
+ const viewMatch = typeof view === 'string' && view.length <= MAX_ATTACHMENT_BYTES * 1.4
3299
+ ? VIEW_DATA_URL.exec(view)
3300
+ : null;
3301
+ if (!viewMatch)
3302
+ continue;
3303
+ try {
3304
+ atomicWriteFileSync(path.join(attachmentsDir, attachmentViewName(fileName)), Buffer.from(viewMatch[1], 'base64'));
3305
+ viewed.push(fileName);
3306
+ }
3307
+ catch {
3308
+ /* the model reads the faithful file instead */
3313
3309
  }
3314
3310
  }
3315
- return { saved, marked };
3311
+ return { saved, marked, viewed };
3316
3312
  }
3317
3313
  function isExistingFile(abs) {
3318
3314
  try {
@@ -3993,7 +3989,6 @@ function runRouterTurnIn(ctx, instruction) {
3993
3989
  if (result.ok) {
3994
3990
  message.text = cleaned;
3995
3991
  message.status = 'done';
3996
- trackStandingQuestions(ctx, cleaned, taskIds.length > 0);
3997
3992
  }
3998
3993
  else {
3999
3994
  const failure = resolveFailure(result);
@@ -4346,12 +4341,19 @@ function handleStopTask(taskStore, socket, msg) {
4346
4341
  }
4347
4342
  }
4348
4343
  // A mirror on disk is not evidence: only names that are also this send's
4349
- // attachments count as marked.
4344
+ // attachments count as marked or viewed.
4345
+ function attachmentSubset(item, names) {
4346
+ if (!Array.isArray(names))
4347
+ return [];
4348
+ return names.filter((name) => typeof name === 'string' && item.attachments.includes(name));
4349
+ }
4350
4350
  function markedOf(item) {
4351
- if (!Array.isArray(item.marked))
4352
- return {};
4353
- const marked = item.marked.filter((name) => typeof name === 'string' && item.attachments.includes(name));
4354
- return marked.length > 0 ? { marked } : {};
4351
+ const marked = attachmentSubset(item, item.marked);
4352
+ const viewed = attachmentSubset(item, item.viewed);
4353
+ return {
4354
+ ...(marked.length > 0 ? { marked } : {}),
4355
+ ...(viewed.length > 0 ? { viewed } : {}),
4356
+ };
4355
4357
  }
4356
4358
  // Restart recovery: load the durable queue mirror, keeping only well-formed
4357
4359
  // sends that never reached the message log. A send whose id is already in
@@ -4474,6 +4476,7 @@ function commitDrainedSends(drained, log) {
4474
4476
  const texts = [];
4475
4477
  const attachmentPaths = [];
4476
4478
  const markedPaths = [];
4479
+ const flattened = [];
4477
4480
  const refs = [];
4478
4481
  for (const item of drained) {
4479
4482
  if (!item.logged) {
@@ -4495,14 +4498,20 @@ function commitDrainedSends(drained, log) {
4495
4498
  if (item.text.trim())
4496
4499
  texts.push(item.text);
4497
4500
  for (const name of item.attachments) {
4498
- const attachmentPath = path.join('.castle', 'agent', 'attachments', name);
4499
- attachmentPaths.push(attachmentPath);
4501
+ const original = path.join('.castle', 'agent', 'attachments', name);
4502
+ const view = item.viewed?.includes(name)
4503
+ ? path.join('.castle', 'agent', 'attachments', attachmentViewName(name))
4504
+ : null;
4505
+ const listed = view ?? original;
4506
+ attachmentPaths.push(listed);
4507
+ if (view)
4508
+ flattened.push({ view, original });
4500
4509
  if (item.marked?.includes(name))
4501
- markedPaths.push(attachmentPath);
4510
+ markedPaths.push(listed);
4502
4511
  }
4503
4512
  refs.push(...item.refs);
4504
4513
  }
4505
- return { texts, attachmentPaths, markedPaths, refs: uniqueLocators(refs) };
4514
+ return { texts, attachmentPaths, markedPaths, flattened, refs: uniqueLocators(refs) };
4506
4515
  }
4507
4516
  // Drain the queue into the log as real user messages and start one follow-up
4508
4517
  // turn addressing them all (a burst batches into a single turn). A pending
@@ -4524,20 +4533,25 @@ function maybeStartRouterQueueTurn(ctx) {
4524
4533
  for (const send of drained)
4525
4534
  if (!send.hideFromUi)
4526
4535
  ctx.taskStore.releaseHeld(send.text);
4527
- const { texts, attachmentPaths, markedPaths, refs } = commitDrainedSends(drained, ctx.log);
4536
+ const { texts, attachmentPaths, markedPaths, flattened, refs } = commitDrainedSends(drained, ctx.log);
4528
4537
  // The queue is now committed to messages.json; clear its durable mirror.
4529
4538
  persistPendingSends(ctx);
4530
4539
  const draft = state.pendingInterruptedDraft;
4531
4540
  state.pendingInterruptedDraft = '';
4541
+ state.turnInterrupted = false;
4532
4542
  state.routerRunning = true;
4533
4543
  broadcastQueueState(ctx);
4534
- startRouterTurn(ctx, userTurnInstruction({
4544
+ const instruction = userTurnInstruction({
4535
4545
  messages: texts,
4536
4546
  interruptedDraft: draft || undefined,
4537
4547
  attachments: attachmentPaths,
4538
4548
  marked: markedPaths,
4549
+ flattened,
4539
4550
  refs,
4540
- }));
4551
+ });
4552
+ const incoming = readGitIncomingNote(ctx.deckDir);
4553
+ state.incomingNoteShas = incoming.shas;
4554
+ startRouterTurn(ctx, incoming.note ? `${incoming.note}\n\n${instruction}` : instruction);
4541
4555
  }
4542
4556
  // The turn settled: clear the busy flag, broadcast it, then flush anything
4543
4557
  // that queued mid-turn (a clean end and an interrupt take the same path). A
@@ -4546,6 +4560,7 @@ function maybeStartRouterQueueTurn(ctx) {
4546
4560
  // which case flushing it supersedes the retry (its turn re-covers things).
4547
4561
  function onRouterQueueSettled(ctx, retryable) {
4548
4562
  const { state } = ctx;
4563
+ const interrupted = state.turnInterrupted;
4549
4564
  state.routerRunning = false;
4550
4565
  if (retryable &&
4551
4566
  !state.autoRetryUsed &&
@@ -4557,6 +4572,11 @@ function onRouterQueueSettled(ctx, retryable) {
4557
4572
  startRouterTurn(ctx, state.lastInstruction);
4558
4573
  return;
4559
4574
  }
4575
+ const incomingNoteShas = state.incomingNoteShas;
4576
+ state.incomingNoteShas = [];
4577
+ state.turnInterrupted = false;
4578
+ if (!retryable && !interrupted)
4579
+ removeGitIncoming(ctx.deckDir, incomingNoteShas);
4560
4580
  broadcastQueueState(ctx);
4561
4581
  maybeStartRouterQueueTurn(ctx);
4562
4582
  if (!state.routerRunning) {
@@ -4578,6 +4598,7 @@ function onRouterQueueSettled(ctx, retryable) {
4578
4598
  // combined instruction.
4579
4599
  function foldRouterQueueTurn(ctx) {
4580
4600
  const { state } = ctx;
4601
+ state.turnInterrupted = true;
4581
4602
  state.userEpoch += 1;
4582
4603
  killRouterChildren(ctx);
4583
4604
  reclaimInFlightSends(state.pendingSends, state.inFlightSends);
@@ -4615,12 +4636,13 @@ function handleQueueUserMessage(ctx, text, images, refs, clientId, hideFromUi) {
4615
4636
  return;
4616
4637
  }
4617
4638
  const id = sentId ?? nanoid(8);
4618
- const { saved: attachments, marked } = saveAttachments(ctx.attachmentsDir, id, images);
4639
+ const { saved: attachments, marked, viewed } = saveAttachments(ctx.attachmentsDir, id, images);
4619
4640
  state.pendingSends.push({
4620
4641
  id,
4621
4642
  text,
4622
4643
  attachments,
4623
4644
  ...(marked.length > 0 ? { marked } : {}),
4645
+ ...(viewed.length > 0 ? { viewed } : {}),
4624
4646
  refs: validMessageRefs(ctx.deckDir, refs),
4625
4647
  ...(hideFromUi ? { hideFromUi: true } : {}),
4626
4648
  });
@@ -4652,6 +4674,7 @@ function interruptRouterQueue(ctx) {
4652
4674
  // the turn outright. Captured before reclaim, which would otherwise fill
4653
4675
  // the queue and make every Stop look like a Send now.
4654
4676
  const hasFollowUp = state.pendingSends.length > 0;
4677
+ state.turnInterrupted = true;
4655
4678
  state.userEpoch += 1;
4656
4679
  const draft = killRouterChildren(ctx);
4657
4680
  // Only a continued turn ("Send now") reclaims its in-flight sends so they
@@ -4703,6 +4726,8 @@ function createRouterQueue(deps) {
4703
4726
  autoRetryUsed: false,
4704
4727
  autoFoldUsed: false,
4705
4728
  lastInstruction: '',
4729
+ incomingNoteShas: [],
4730
+ turnInterrupted: false,
4706
4731
  },
4707
4732
  };
4708
4733
  // Restart recovery: re-enqueue sends that never reached the message log,
@@ -4829,6 +4854,85 @@ export function createAgentServer(opts) {
4829
4854
  socket.send(payload);
4830
4855
  }
4831
4856
  }
4857
+ const presenceDeckId = cloudGitMode(deckDir) ? readCastleJson(deckDir)?.deckId : undefined;
4858
+ let presenceOthers = [];
4859
+ let collaboratorRoster = [];
4860
+ let presenceTimer = null;
4861
+ let presenceTick = 0;
4862
+ let presenceRunning = false;
4863
+ let collaboratorsRunning = false;
4864
+ let presenceFailureLogged = false;
4865
+ let collaboratorsFailureLogged = false;
4866
+ const presenceEntry = (entry) => ({
4867
+ userId: String(entry.userId),
4868
+ username: String(entry.username),
4869
+ photoUrl: typeof entry.photo?.url === 'string' ? entry.photo.url : null,
4870
+ lastSeenAt: String(entry.lastSeenAt),
4871
+ });
4872
+ const collaboratorEntry = (entry) => ({
4873
+ userId: String(entry.userId),
4874
+ username: String(entry.username),
4875
+ photoUrl: typeof entry.photo?.url === 'string' ? entry.photo.url : null,
4876
+ addedAt: String(entry.addedAt),
4877
+ });
4878
+ async function refreshPresence() {
4879
+ if (!presenceDeckId || clients.size === 0 || presenceRunning)
4880
+ return;
4881
+ presenceRunning = true;
4882
+ try {
4883
+ presenceOthers = (await reportDeckEditorPresence(presenceDeckId)).map(presenceEntry);
4884
+ presenceFailureLogged = false;
4885
+ broadcast({ type: 'presence', others: presenceOthers });
4886
+ }
4887
+ catch (err) {
4888
+ if (!presenceFailureLogged) {
4889
+ console.error(`[presence] could not report deck editor presence: ${err instanceof Error ? err.message : String(err)}`);
4890
+ presenceFailureLogged = true;
4891
+ }
4892
+ }
4893
+ finally {
4894
+ presenceRunning = false;
4895
+ }
4896
+ }
4897
+ async function refreshCollaborators() {
4898
+ if (!presenceDeckId || clients.size === 0 || collaboratorsRunning)
4899
+ return;
4900
+ collaboratorsRunning = true;
4901
+ try {
4902
+ collaboratorRoster = (await deckCollaborators(presenceDeckId)).map(collaboratorEntry);
4903
+ collaboratorsFailureLogged = false;
4904
+ broadcast({ type: 'collaborators', collaborators: collaboratorRoster });
4905
+ }
4906
+ catch (err) {
4907
+ if (!collaboratorsFailureLogged) {
4908
+ console.error(`[presence] could not list deck collaborators: ${err instanceof Error ? err.message : String(err)}`);
4909
+ collaboratorsFailureLogged = true;
4910
+ }
4911
+ }
4912
+ finally {
4913
+ collaboratorsRunning = false;
4914
+ }
4915
+ }
4916
+ function tickPresence() {
4917
+ presenceTick += 1;
4918
+ void refreshPresence();
4919
+ if (presenceTick === 1 || (presenceTick - 1) % 4 === 0)
4920
+ void refreshCollaborators();
4921
+ }
4922
+ function startPresence() {
4923
+ if (!presenceDeckId || presenceTimer)
4924
+ return;
4925
+ tickPresence();
4926
+ presenceTimer = setInterval(tickPresence, PRESENCE_INTERVAL_MS);
4927
+ presenceTimer.unref();
4928
+ }
4929
+ function stopPresence() {
4930
+ if (presenceTimer)
4931
+ clearInterval(presenceTimer);
4932
+ presenceTimer = null;
4933
+ presenceTick = 0;
4934
+ presenceOthers = [];
4935
+ }
4832
4936
  const log = createMessageLog(messagesPath, broadcast, welcomeMessage, (message) => asClientMessage(message, opts.signPath));
4833
4937
  const messages = log.messages;
4834
4938
  const addLog = (text) => log.addLog(text);
@@ -4997,8 +5101,12 @@ export function createAgentServer(opts) {
4997
5101
  queued: routerQueue.queuedSnippets(),
4998
5102
  usage: usageFeed.latest(),
4999
5103
  accounts: accountsFeed.snapshot(),
5104
+ presence: presenceOthers,
5105
+ collaborators: collaboratorRoster,
5000
5106
  };
5001
5107
  socket.send(JSON.stringify(hello));
5108
+ if (clients.size === 1)
5109
+ startPresence();
5002
5110
  // A newly attached client is the one moment the cached value may be stale
5003
5111
  // by a whole poll interval (nothing refreshes while nobody is watching).
5004
5112
  usageFeed.refresh();
@@ -5092,6 +5200,8 @@ export function createAgentServer(opts) {
5092
5200
  });
5093
5201
  socket.on('close', () => {
5094
5202
  clients.delete(socket);
5203
+ if (clients.size === 0)
5204
+ stopPresence();
5095
5205
  });
5096
5206
  }
5097
5207
  function handleUpgrade(req, socket, head) {
@@ -5116,6 +5226,7 @@ export function createAgentServer(opts) {
5116
5226
  return handleAttachment(req, res, reqPath) || handlePlaytestFrame(req, res, reqPath);
5117
5227
  }
5118
5228
  function shutdown() {
5229
+ stopPresence();
5119
5230
  gitHooks?.stop();
5120
5231
  markerPoll?.stop();
5121
5232
  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;
@@ -176,6 +194,9 @@ export interface DeckMeta {
176
194
  creator: {
177
195
  username: string;
178
196
  } | null;
197
+ initialCard: {
198
+ type: string | null;
199
+ } | null;
179
200
  }
180
201
  export declare function deckMeta(deckId: string): Promise<DeckMeta | null>;
181
202
  export declare function webDeckSource(deckId: string): Promise<WebDeckSource | null>;
package/dist/api.js CHANGED
@@ -103,6 +103,24 @@ export async function whoAmI() {
103
103
  handleAPIError(data);
104
104
  return pickData(data, 'me');
105
105
  }
106
+ export async function reportDeckEditorPresence(deckId) {
107
+ const data = await graphql(`mutation($deckId: ID!) {
108
+ reportDeckEditorPresence(deckId: $deckId) {
109
+ userId username photo { url } lastSeenAt
110
+ }
111
+ }`, { deckId });
112
+ handleAPIError(data);
113
+ return pickData(data, 'reportDeckEditorPresence') ?? [];
114
+ }
115
+ export async function deckCollaborators(deckId) {
116
+ const data = await graphql(`query($deckId: ID!) {
117
+ deckCollaborators(deckId: $deckId) {
118
+ userId username photo { url } addedAt
119
+ }
120
+ }`, { deckId });
121
+ handleAPIError(data);
122
+ return pickData(data, 'deckCollaborators') ?? [];
123
+ }
106
124
  // Everything an import-picker row shows for one deck: what it is, whose it is,
107
125
  // what it looks like, and who it was remixed from. One fragment, so the three
108
126
  // list queries below can't drift apart.
@@ -273,12 +291,12 @@ export async function saveCauldronServerBundle(deckId, uploadId, serverConfig) {
273
291
  handleAPIError(data);
274
292
  return pickData(data, 'saveCauldronServerBundle');
275
293
  }
276
- // Title + author, for naming an import. Readable without auth for the same decks
277
- // webDeckSource is (unlisted ones), so this works in a sandbox with no login.
294
+ // Metadata for naming an import and distinguishing classic decks. Readable
295
+ // without auth for the same decks webDeckSource is, including unlisted ones.
278
296
  export async function deckMeta(deckId) {
279
297
  const data = await graphql(`query($deckId: ID!) {
280
298
  deck(deckId: $deckId) {
281
- deckId title creator { username }
299
+ deckId title creator { username } initialCard { type }
282
300
  }
283
301
  }`, { deckId });
284
302
  return data?.data?.deck ?? null;
@@ -14,6 +14,12 @@ export interface HostContext {
14
14
  isAnonymous?: boolean;
15
15
  deepLinkUri?: string | null;
16
16
  partyId?: string | null;
17
+ joinHint?: {
18
+ deckId: string;
19
+ sessionId?: string | null;
20
+ routeId?: string | null;
21
+ slot?: string | null;
22
+ } | null;
17
23
  }
18
24
 
19
25
  export interface GraphqlError {
@@ -40,6 +40,7 @@ const COMMAND_NAMES = [
40
40
  "portal.info",
41
41
  "haptics.play",
42
42
  "multiplayer.getSession",
43
+ "multiplayer.getJoinHint",
43
44
  "multiplayer.joinDestination",
44
45
  "voice.getState",
45
46
  "voice.requestJoin",
@@ -188,6 +189,8 @@ function runCommand(ctx, command, params, caps, options) {
188
189
  return passHas(ctx, params, caps);
189
190
  case "multiplayer.getSession":
190
191
  return multiplayerGetSession(ctx, params, caps);
192
+ case "multiplayer.getJoinHint":
193
+ return Promise.resolve(multiplayerGetJoinHint(ctx));
191
194
  case "voice.getState":
192
195
  return voiceGetState(ctx, params, caps);
193
196
  case "voice.requestJoin":
@@ -240,13 +243,47 @@ function runCommand(ctx, command, params, caps, options) {
240
243
  async function multiplayerGetSession(ctx, params, caps) {
241
244
  const request = multiplayerSessionRequest(params);
242
245
  const deckId = requireDeckId(ctx, "multiplayer.getSession");
246
+ const hintedSessionId = multiplayerHintedSessionId(ctx, deckId);
243
247
  // Which shared session a play belongs to is the host's call, not the deck's,
244
248
  // the way `shared.cpp` reads the party off the engine rather than the scene.
245
- // A play that arrived through a party stays inside it; otherwise public.
246
- const mode = request.mode === "public" && ctx.partyId ? "party" : request.mode;
247
- const data = await graphql(caps.graphqlFetch, CAULDRON_MULTIPLAYER_SESSION_QUERY, { deckId, mode, key: request.key ?? null, partyId: ctx.partyId ?? null }, "multiplayer.getSession");
249
+ // A play that arrived through a party stays inside it unless trusted host
250
+ // chrome is sending this public join to the room where a friend is playing.
251
+ const mode = request.mode === "public" && ctx.partyId && !hintedSessionId
252
+ ? "party"
253
+ : request.mode;
254
+ const data = await graphql(caps.graphqlFetch, CAULDRON_MULTIPLAYER_SESSION_QUERY, {
255
+ deckId,
256
+ mode,
257
+ key: request.key ?? null,
258
+ sessionId: request.mode === "public" ? hintedSessionId : null,
259
+ partyId: ctx.partyId ?? null,
260
+ }, "multiplayer.getSession");
248
261
  return multiplayerSessionResult(data.getCauldronMultiplayerSession);
249
262
  }
263
+ const MULTIPLAYER_SESSION_ID_MAX_LENGTH = 256;
264
+ function multiplayerHintedSessionId(ctx, deckId) {
265
+ const hint = ctx.joinHint;
266
+ if (!hint || hint.deckId !== deckId)
267
+ return null;
268
+ return typeof hint.sessionId === "string" &&
269
+ hint.sessionId.length > 0 &&
270
+ hint.sessionId.length <= MULTIPLAYER_SESSION_ID_MAX_LENGTH
271
+ ? hint.sessionId
272
+ : null;
273
+ }
274
+ function multiplayerGetJoinHint(ctx) {
275
+ const hint = ctx.joinHint;
276
+ if (!ctx.deckId ||
277
+ !hint ||
278
+ hint.deckId !== ctx.deckId ||
279
+ typeof hint.routeId !== "string" ||
280
+ hint.routeId.length === 0 ||
281
+ typeof hint.slot !== "string" ||
282
+ hint.slot.length === 0) {
283
+ return null;
284
+ }
285
+ return { routeId: hint.routeId, slot: hint.slot };
286
+ }
250
287
  function multiplayerSessionRequest(params) {
251
288
  const mode = asMultiplayerMode(params.mode);
252
289
  return {
@@ -2421,12 +2458,14 @@ const CAULDRON_MULTIPLAYER_SESSION_QUERY = `
2421
2458
  $deckId: ID!
2422
2459
  $mode: String!
2423
2460
  $key: String
2461
+ $sessionId: ID
2424
2462
  $partyId: ID
2425
2463
  ) {
2426
2464
  getCauldronMultiplayerSession(
2427
2465
  deckId: $deckId
2428
2466
  mode: $mode
2429
2467
  key: $key
2468
+ sessionId: $sessionId
2430
2469
  partyId: $partyId
2431
2470
  ) {
2432
2471
  sessionId