castle-web-cli 0.4.214 → 0.4.216

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.
package/dist/agent.js CHANGED
@@ -29,7 +29,8 @@ import * as path from 'path';
29
29
  import { nanoid } from 'nanoid';
30
30
  import { WebSocketServer } from 'ws';
31
31
  import { rawDataToString } from './rawData.js';
32
- import { extractDirectives, meansAll, parseTaskFenceBody, resolveTargets, taskFenceRegex, } from './routerFences.js';
32
+ import { extractDirectives, meansAll, closedPrefLines, parsePrefLines, parseTaskFenceBody, resolveTargets, taskFenceRegex, } from './routerFences.js';
33
+ import { carriesStopNotes, recentStops, stopNotes, } from './routerStops.js';
33
34
  import { accountForRun, closingMessageOf } from './taskAccount.js';
34
35
  import { atomicWriteFileSync } from './atomicFile.js';
35
36
  import { AGENT_ATTACHMENT_PREFIX, AGENT_PLAYTEST_PREFIX, PLAN_FILE } from './localPaths.js';
@@ -45,7 +46,7 @@ import { createPlaytestBrowserManager, } from './native/playtest-browser.js';
45
46
  import { createPlaywrightPlaytestExecutor } from './native/playtest-executor.js';
46
47
  import { createRemotePlaytestExecutor } from './native/playtest-remote.js';
47
48
  import { runPlaytest, } from './native/playtest.js';
48
- import { cloudGitMode } from './cloudGit.js';
49
+ import { AGENT_ROLE_ENV, cloudGitMode } from './cloudGit.js';
49
50
  import { createServeGitHooks } from './cloudGitServe.js';
50
51
  export const AGENT_WS_PATH = '/__castle/agent';
51
52
  const DEFAULT_SETTINGS = {
@@ -342,8 +343,8 @@ const OPENROUTER_ALLOWED_TOOLS = ['Edit', 'Write', 'NotebookEdit', 'Bash'];
342
343
  const CLAUDE_PLAYTEST_TOOL = 'mcp__castle__playtest';
343
344
  // Single `=` token because --allowedTools is variadic and would otherwise
344
345
  // swallow the trailing prompt positional.
345
- function openrouterAllowedToolsArg(role) {
346
- const tools = role === 'task' ? [...OPENROUTER_ALLOWED_TOOLS, CLAUDE_PLAYTEST_TOOL] : OPENROUTER_ALLOWED_TOOLS;
346
+ function openrouterAllowedToolsArg(playtestTool) {
347
+ const tools = playtestTool ? [...OPENROUTER_ALLOWED_TOOLS, CLAUDE_PLAYTEST_TOOL] : OPENROUTER_ALLOWED_TOOLS;
347
348
  return `--allowedTools=${tools.join(',')}`;
348
349
  }
349
350
  // The one MCP server a task spawn sees. `--strict-mcp-config` is already passed,
@@ -373,6 +374,17 @@ function mcpConfigArg(deckDir, taskId) {
373
374
  });
374
375
  return `--mcp-config=${config}`;
375
376
  }
377
+ // One castle.json read per task, taken when its fence is read and shared by
378
+ // its prompt and every spawn attempt, so a preference flipped later can never
379
+ // pair a prompt with the wrong tool set. The tool follows the deck's own answer only: CASTLE_AGENT_PLAYTEST=off
380
+ // has only ever dropped the steering, never the tool.
381
+ export function taskPlaytestFor(deckDir) {
382
+ const declined = readCastleJson(deckDir)?.agent?.playtest === 'off';
383
+ return { steering: !declined && process.env.CASTLE_AGENT_PLAYTEST !== 'off', tool: !declined };
384
+ }
385
+ export function playtestToolArgs(tool, deckDir, taskId) {
386
+ return tool ? [mcpConfigArg(deckDir, taskId)] : [];
387
+ }
376
388
  // Keep runs independent of the machine's user config: no user plugins (LSP
377
389
  // servers etc.), no user MCP servers. CLAUDE.md auto-discovery and OAuth still
378
390
  // work. On a user's own Anthropic KEY this also carries the apiKeyHelper that
@@ -405,7 +417,7 @@ metering,
405
417
  // The task this spawn belongs to, so its playtest frames land under
406
418
  // tasks/<id>/playtest/ and count against that task's call budget. Absent for
407
419
  // router turns, which get no playtest tool at all.
408
- taskId,
420
+ taskId, playtestTool,
409
421
  // The stable part of a router prompt, passed as appended system text so the
410
422
  // CLI's own cache breakpoints cover it.
411
423
  systemPrompt) {
@@ -416,6 +428,7 @@ systemPrompt) {
416
428
  .filter((text) => Boolean(text))
417
429
  .join('\n\n');
418
430
  const hosted = Boolean(process.env.CASTLE_SANDBOX_ID);
431
+ const playtestArgs = role === 'task' ? playtestToolArgs(playtestTool, metering.deckDir, taskId) : [];
419
432
  const orAuth = viaOpenrouter ? resolveOpenrouterAuth() : null;
420
433
  const anAuth = viaOpenrouter ? null : resolveAnthropicAuth();
421
434
  // Direct = the user's own credential/login is in play, so this run bypasses
@@ -435,7 +448,7 @@ systemPrompt) {
435
448
  '--include-partial-messages',
436
449
  '--permission-mode',
437
450
  hosted ? 'bypassPermissions' : 'auto',
438
- ...(!hosted && viaOpenrouter ? [openrouterAllowedToolsArg(role)] : []),
451
+ ...(!hosted && viaOpenrouter ? [openrouterAllowedToolsArg(playtestArgs.length > 0)] : []),
439
452
  '--model',
440
453
  spawnModel,
441
454
  '--effort',
@@ -450,7 +463,7 @@ systemPrompt) {
450
463
  '--settings',
451
464
  claudeSettingsArg(anAuth),
452
465
  '--strict-mcp-config',
453
- ...(role === 'task' ? [mcpConfigArg(metering.deckDir, taskId)] : []),
466
+ ...playtestArgs,
454
467
  ...(systemText ? ['--append-system-prompt', systemText] : []),
455
468
  prompt,
456
469
  ],
@@ -462,6 +475,7 @@ systemPrompt) {
462
475
  direct,
463
476
  })),
464
477
  ...claudeContextEnv(role),
478
+ [AGENT_ROLE_ENV]: role,
465
479
  // Claude Code 2.1.258 refuses bypassPermissions as root unless the
466
480
  // child explicitly identifies itself as running in a sandbox.
467
481
  ...(hosted ? { IS_SANDBOX: '1' } : {}),
@@ -528,7 +542,7 @@ function readJsonFile(filePath) {
528
542
  }
529
543
  }
530
544
  // How much of a router reply is safe to show while it is still streaming:
531
- // everything before the first castle-task fence, holding back a partial fence
545
+ // everything before the first castle directive fence, holding back a partial fence
532
546
  // marker at the tail so "```cast..." never flashes up before we know what it
533
547
  // is. The full cleaned text replaces the streamed text when the reply ends.
534
548
  function visibleLength(raw) {
@@ -548,12 +562,57 @@ const planSessions = new Map();
548
562
  function planDefault() {
549
563
  return process.env.CASTLE_AGENT_PLAN !== 'off';
550
564
  }
551
- // The playtest steering: one router rule plus the task prompt's carve-out
552
- // (PLAYTEST_ROUTER_RULE in agent-prompts.ts). On unless the serve was told
553
- // `CASTLE_AGENT_PLAYTEST=off` (the only env value that does anything; no
554
- // per-deck switch).
555
- function playtestSteering() {
556
- return process.env.CASTLE_AGENT_PLAYTEST !== 'off';
565
+ // Read on every router turn and task spawn so a deck preference change takes
566
+ // effect immediately; the rare user-initiated change may split the prompt cache.
567
+ export function playtestEnabled(deckDir) {
568
+ if (process.env.CASTLE_AGENT_PLAYTEST === 'off')
569
+ return false;
570
+ return readCastleJson(deckDir)?.agent?.playtest !== 'off';
571
+ }
572
+ // Undefined also when there is no castle.json to hold the answer: offering the
573
+ // switch there would confirm a preference setPlaytestPref cannot persist.
574
+ export function playtestPrefFor(deckDir) {
575
+ if (process.env.CASTLE_AGENT_PLAYTEST === 'off')
576
+ return undefined;
577
+ const config = readCastleJson(deckDir);
578
+ if (!config)
579
+ return undefined;
580
+ return config.agent?.playtest === 'off' ? 'off' : 'on';
581
+ }
582
+ export function setPlaytestPref(deckDir, value) {
583
+ const file = path.join(deckDir, 'castle.json');
584
+ if (!fs.existsSync(file))
585
+ return false;
586
+ const current = readCastleJson(deckDir);
587
+ if (!current || typeof current !== 'object' || Array.isArray(current))
588
+ return false;
589
+ const currentAgent = current.agent && typeof current.agent === 'object' && !Array.isArray(current.agent)
590
+ ? current.agent
591
+ : undefined;
592
+ if (value === 'off') {
593
+ if (currentAgent?.playtest === 'off')
594
+ return false;
595
+ const next = { ...current, agent: { ...(currentAgent ?? {}), playtest: 'off' } };
596
+ fs.writeFileSync(file, JSON.stringify(next, null, 2) + '\n', 'utf8');
597
+ return true;
598
+ }
599
+ if (!currentAgent || !Object.prototype.hasOwnProperty.call(currentAgent, 'playtest'))
600
+ return false;
601
+ const agent = { ...currentAgent };
602
+ delete agent.playtest;
603
+ const next = { ...current };
604
+ if (Object.keys(agent).length === 0)
605
+ delete next.agent;
606
+ else
607
+ next.agent = agent;
608
+ fs.writeFileSync(file, JSON.stringify(next, null, 2) + '\n', 'utf8');
609
+ return true;
610
+ }
611
+ function deckPrefsFrame(deckDir) {
612
+ return {
613
+ type: 'deck-prefs',
614
+ prefs: { playtest: playtestPrefFor(deckDir) ?? null },
615
+ };
557
616
  }
558
617
  function planSession(deckDir) {
559
618
  const existing = planSessions.get(deckDir);
@@ -737,7 +796,7 @@ function scanNewTaskFences(raw, fromIndex) {
737
796
  while ((match = re.exec(raw))) {
738
797
  const directive = parseTaskFenceBody(match[1]);
739
798
  if (directive)
740
- directives.push(directive);
799
+ directives.push({ directive, at: match.index });
741
800
  nextIndex = re.lastIndex;
742
801
  }
743
802
  return { directives, nextIndex };
@@ -1785,12 +1844,14 @@ async function runAgentTurn(opts) {
1785
1844
  crashed: false,
1786
1845
  };
1787
1846
  }
1847
+ if (opts.cancelled?.())
1848
+ return { ok: false, finalText: '', error: 'not run', crashed: false };
1788
1849
  // One id per call: a router turn, or a single task attempt (the retry loop
1789
1850
  // in runTaskAgentIn calls this once per attempt, and each attempt is its own
1790
1851
  // conversation -- nothing is resumed).
1791
1852
  const sessionId = newAgentSessionId(opts.role);
1792
1853
  const settled = (run) => run.finally(() => notifyAgentRunFinished());
1793
- const invocation = buildAgentInvocation(opts.role, opts.prompt, opts.claudeModel, opts.openrouterModel, opts.effort, { sessionId, deckDir: opts.cwd }, opts.taskId, opts.systemPrompt);
1854
+ const invocation = buildAgentInvocation(opts.role, opts.prompt, opts.claudeModel, opts.openrouterModel, opts.effort, { sessionId, deckDir: opts.cwd }, opts.taskId, opts.playtestTool, opts.systemPrompt);
1794
1855
  const run = runAgentCli({
1795
1856
  cwd: opts.cwd,
1796
1857
  command: invocation.command,
@@ -2132,6 +2193,7 @@ async function runTaskAgentIn(ctx, task) {
2132
2193
  // Read at task start, like the router's per turn: a task the router spawns
2133
2194
  // right after adopting a kit must be briefed with the kit's guide.
2134
2195
  const deckGuide = readQuickReference(ctx.deckDir);
2196
+ const playtest = task.playtest ?? taskPlaytestFor(ctx.deckDir);
2135
2197
  const taskPrompt = buildTaskPrompt({
2136
2198
  deckLabel: ctx.deckLabel,
2137
2199
  taskId: task.id,
@@ -2141,7 +2203,7 @@ async function runTaskAgentIn(ctx, task) {
2141
2203
  notesPath: path.join(relDir, 'notes.md'),
2142
2204
  handoffPath: path.join(relDir, 'handoff'),
2143
2205
  depsSummary: ctx.depsSummary,
2144
- playtest: playtestSteering(),
2206
+ playtest: playtest.steering,
2145
2207
  deckTree: buildDeckTree(ctx.deckDir),
2146
2208
  quickReference: quickReferenceFor(ctx.deckDir, deckGuide, 'task'),
2147
2209
  plan: taskPlanOpts(ctx.deckDir, task.item, ctx.finishedWork),
@@ -2202,7 +2264,9 @@ async function runTaskAgentIn(ctx, task) {
2202
2264
  timeoutMs: TASK_TIMEOUT_MS,
2203
2265
  logPath: path.join(dir, 'log.jsonl'),
2204
2266
  taskId: task.id,
2267
+ playtestTool: playtest.tool,
2205
2268
  children: ctx.children,
2269
+ cancelled: () => ctx.stopRequested.has(task.id),
2206
2270
  onSpawn: (pid) => {
2207
2271
  task.pid = pid;
2208
2272
  },
@@ -2509,6 +2573,7 @@ function createTaskStore(opts) {
2509
2573
  prompt: directive.prompt,
2510
2574
  after: resolveTargets(tasks, directive.after),
2511
2575
  item: directive.item,
2576
+ playtest: taskPlaytestFor(deckDir),
2512
2577
  status: 'waiting',
2513
2578
  progress: 0,
2514
2579
  notes: '',
@@ -2588,11 +2653,15 @@ function createTaskStore(opts) {
2588
2653
  .filter((t) => t.status === 'running' || t.status === 'waiting' || t.status === 'blocked')
2589
2654
  .map((t) => t.id)
2590
2655
  : resolveTargets(tasks, tokens);
2656
+ const targets = [];
2591
2657
  for (const id of ids) {
2592
2658
  const task = tasks.get(id);
2593
- if (task)
2594
- haltTask(task, children, stopRequested, touch);
2659
+ if (!task)
2660
+ continue;
2661
+ targets.push({ id: task.id, title: task.title, status: task.status, progress: task.progress });
2662
+ haltTask(task, children, stopRequested, touch);
2595
2663
  }
2664
+ return targets;
2596
2665
  }
2597
2666
  return {
2598
2667
  sorted,
@@ -2813,12 +2882,12 @@ function clientUrl(reqPath, signPath) {
2813
2882
  // A sent message renders its pasted images as `<img src>`, which cannot carry
2814
2883
  // the serve token any more than a playtest frame can -- see ServeSecurity.signPath.
2815
2884
  function asClientMessage(message, signPath) {
2816
- if (!message.attachments?.length)
2817
- return message;
2818
- return {
2819
- ...message,
2820
- attachments: message.attachments.map((name) => clientUrl(`${AGENT_ATTACHMENT_PREFIX}${name}`, signPath)),
2821
- };
2885
+ const clientMessage = { ...message };
2886
+ delete clientMessage.stopped;
2887
+ if (!clientMessage.attachments?.length)
2888
+ return clientMessage;
2889
+ clientMessage.attachments = clientMessage.attachments.map((name) => clientUrl(`${AGENT_ATTACHMENT_PREFIX}${name}`, signPath));
2890
+ return clientMessage;
2822
2891
  }
2823
2892
  function loadTaskFeeds(tasksDir) {
2824
2893
  const map = new Map();
@@ -2878,8 +2947,13 @@ function createMessageThinking(broadcast) {
2878
2947
  function createMessageLog(messagesPath, broadcast, welcomeMessage, forClient) {
2879
2948
  const loaded = readJsonFile(messagesPath) ?? [];
2880
2949
  const messages = loaded
2881
- .filter((m) => m.text.trim() !== '' || m.role === 'user')
2882
- .map((m) => (m.status === 'streaming' ? { ...m, status: 'done' } : m));
2950
+ .filter((m) => m.text.trim() !== '' || m.role === 'user' || carriesStopNotes(m))
2951
+ .map((m) => {
2952
+ const settled = m.status === 'streaming' ? { ...m, status: 'done' } : m;
2953
+ return settled.text.trim() === '' && carriesStopNotes(settled)
2954
+ ? { ...settled, hideFromUi: true }
2955
+ : settled;
2956
+ });
2883
2957
  function persist() {
2884
2958
  atomicWriteFileSync(messagesPath, JSON.stringify(messages, null, 2) + '\n');
2885
2959
  }
@@ -3023,23 +3097,29 @@ function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
3023
3097
  // Read per turn, not once per serve: adopting a kit mid-conversation
3024
3098
  // rewrites CLAUDE.md, and the next turn has to see the kit's guide.
3025
3099
  const deckGuide = readQuickReference(ctx.deckDir);
3100
+ const messages = ctx.log.messages.filter((message) => message.role !== 'log' && message.id !== selfMessageId && message.status !== 'streaming');
3026
3101
  return buildRouterPromptParts({
3027
3102
  deckLabel: ctx.deckLabel,
3028
3103
  quickReference: quickReferenceFor(ctx.deckDir, deckGuide, 'router'),
3029
3104
  editorTabs: editorTabsFor(ctx.deckDir),
3030
3105
  kits: kitCatalogLines(ctx.deckDir),
3031
3106
  deckTree: buildDeckTree(ctx.deckDir),
3032
- playtest: playtestSteering(),
3107
+ playtest: playtestEnabled(ctx.deckDir),
3108
+ playtestPref: playtestPrefFor(ctx.deckDir),
3033
3109
  askCalls: askCallsEnabled(ctx.deckDir),
3034
- messages: ctx.log.messages
3035
- .filter((m) => m.role !== 'log' && m.id !== selfMessageId && m.status !== 'streaming')
3036
- .map((m) => ({
3110
+ messages: messages.map((m) => ({
3037
3111
  role: m.role,
3038
3112
  // Replace a prior turn's raw ```ask JSON with a readable question list
3039
3113
  // so the model doesn't re-echo the block verbatim.
3040
3114
  text: m.role === 'assistant' ? humanizeAskBlocks(m.text) : m.text,
3041
3115
  interrupted: m.interrupted,
3042
3116
  })),
3117
+ stopped: recentStops(messages).map((note) => ({
3118
+ title: note.title,
3119
+ id: note.taskId,
3120
+ progress: note.progress,
3121
+ repliesAgo: note.repliesAgo,
3122
+ })),
3043
3123
  // Only the live board -- match what the user sees. Hide tasks that are
3044
3124
  // BOTH acknowledged AND finished; an active (running/waiting) task always
3045
3125
  // shows even if somehow acked, so nothing can ever go invisible mid-work.
@@ -3098,6 +3178,15 @@ function settleInterruptedTurn(ctx, message) {
3098
3178
  // same `after:` resolution against the live task board -- which by now
3099
3179
  // already includes any tasks spawned earlier in this same reply, so an
3100
3180
  // `after:` referencing an earlier fence's title resolves correctly.
3181
+ // Applied as soon as the fence closes, not only at settle, so a task fence
3182
+ // later in the same reply spawns under the new preference. A task decides its
3183
+ // playtest tool the moment it spawns, so each task fence sees only the
3184
+ // preference fences that close before it in the reply.
3185
+ function applyStreamedPrefs(ctx, raw) {
3186
+ const pref = parsePrefLines(closedPrefLines(raw)).playtest;
3187
+ if (pref && setPlaytestPref(ctx.deckDir, pref))
3188
+ ctx.broadcast(deckPrefsFrame(ctx.deckDir));
3189
+ }
3101
3190
  function spawnCompletedTaskFences(ctx, message, midStream, raw) {
3102
3191
  const { directives, nextIndex } = scanNewTaskFences(raw, midStream.scannedUpTo);
3103
3192
  midStream.scannedUpTo = nextIndex;
@@ -3108,10 +3197,11 @@ function spawnCompletedTaskFences(ctx, message, midStream, raw) {
3108
3197
  .filter((t) => t.status === 'running' || t.status === 'waiting')
3109
3198
  .map((t) => t.title.toLowerCase()));
3110
3199
  const newIds = [];
3111
- for (const directive of directives) {
3200
+ for (const { directive, at } of directives) {
3112
3201
  const key = directive.title.toLowerCase();
3113
3202
  if (inFlight.has(key) || midStream.spawnedTitles.has(key))
3114
3203
  continue;
3204
+ applyStreamedPrefs(ctx, raw.slice(0, at));
3115
3205
  newIds.push(ctx.taskStore.spawnFromDirective(directive, message.id));
3116
3206
  midStream.spawnedTitles.add(key);
3117
3207
  }
@@ -3155,6 +3245,7 @@ function runRouterTurnIn(ctx, instruction) {
3155
3245
  const prompt = routerTurnPrompt(ctx, instruction, message.id, readPlanSnapshot(ctx.deckDir));
3156
3246
  void runAgentTurn({
3157
3247
  role: 'router',
3248
+ playtestTool: false,
3158
3249
  prompt: prompt.user,
3159
3250
  systemPrompt: prompt.system,
3160
3251
  claudeModel: ctx.claudeModel(),
@@ -3177,6 +3268,7 @@ function runRouterTurnIn(ctx, instruction) {
3177
3268
  // Spawning changes WHEN a fence is acted on, not what is displayed --
3178
3269
  // the holdback above still hides fenced text until the reply ends.
3179
3270
  spawnCompletedTaskFences(ctx, message, midStream, raw);
3271
+ applyStreamedPrefs(ctx, raw);
3180
3272
  },
3181
3273
  onActivity: (activity) => {
3182
3274
  if (activity === lastActivity)
@@ -3206,11 +3298,20 @@ function runRouterTurnIn(ctx, instruction) {
3206
3298
  settleInterruptedTurn(ctx, message);
3207
3299
  return;
3208
3300
  }
3209
- const { cleaned, directives, checkoffs, stops, plan } = extractDirectives(result.finalText);
3301
+ const { cleaned, directives, checkoffs, stops, prefs, plan } = extractDirectives(result.finalText);
3210
3302
  if (result.ok && checkoffs.length > 0)
3211
3303
  ctx.taskStore.checkOff(checkoffs);
3212
- if (result.ok && stops.length > 0)
3213
- ctx.taskStore.stop(stops);
3304
+ if (result.ok && stops.length > 0) {
3305
+ const notes = stopNotes(ctx.taskStore.stop(stops));
3306
+ if (notes.length > 0)
3307
+ message.stopped = notes;
3308
+ }
3309
+ if (result.ok) {
3310
+ const pref = parsePrefLines(prefs).playtest;
3311
+ if (pref && setPlaytestPref(ctx.deckDir, pref)) {
3312
+ ctx.broadcast(deckPrefsFrame(ctx.deckDir));
3313
+ }
3314
+ }
3214
3315
  // Settle-time only, unlike task fences: nothing is waiting on the file,
3215
3316
  // and a half-streamed op line is a line that says something else.
3216
3317
  if (result.ok && plan) {
@@ -4156,6 +4257,7 @@ export function createAgentServer(opts) {
4156
4257
  .map((message) => asClientMessage(message, opts.signPath)),
4157
4258
  tasks: taskStore.sorted().map((task) => asClientTask(task, opts.signPath)),
4158
4259
  settings,
4260
+ prefs: deckPrefsFrame(deckDir).prefs,
4159
4261
  feeds: Object.fromEntries(taskFeeds.map),
4160
4262
  thinking: messageThinking.snapshot(),
4161
4263
  running: routerQueue.isRunning(),
@@ -4219,6 +4321,12 @@ export function createAgentServer(opts) {
4219
4321
  else if (msg.type === 'set-settings') {
4220
4322
  applySettings(msg);
4221
4323
  }
4324
+ else if (msg.type === 'set-deck-pref' &&
4325
+ msg.key === 'playtest' &&
4326
+ (msg.value === 'on' || msg.value === 'off')) {
4327
+ if (setPlaytestPref(deckDir, msg.value))
4328
+ broadcast(deckPrefsFrame(deckDir));
4329
+ }
4222
4330
  else if (msg.type === 'refresh-usage') {
4223
4331
  usageFeed.refresh();
4224
4332
  }
package/dist/api.d.ts CHANGED
@@ -147,6 +147,14 @@ export interface CauldronServerConfig {
147
147
  voice: {
148
148
  enabled: boolean;
149
149
  };
150
+ destinations?: Array<{
151
+ routeId: string;
152
+ access: 'player' | 'party' | 'public';
153
+ selection: 'exact' | 'find';
154
+ persistence: 'transient' | 'world';
155
+ characters?: 'shared';
156
+ maxPlayers: number;
157
+ }>;
150
158
  }
151
159
  export interface CauldronServerBundleResult {
152
160
  deckId: string;
@@ -180,4 +188,18 @@ export type GitEnvironment = 'staging' | 'production';
180
188
  export declare function ensureGitRepo(deckId: string, environment: GitEnvironment): Promise<{
181
189
  remoteUrl: string;
182
190
  }>;
191
+ export interface GitMirrorBundle {
192
+ url: string;
193
+ /** Null for a bundle an older mirror run listed without it: then not checked. */
194
+ bytes: number | null;
195
+ sha256: string | null;
196
+ }
197
+ export interface GitMirrorState {
198
+ /** main as the deck's S3 mirror last recorded it; null before the first mirror. */
199
+ mainSha: string | null;
200
+ mirroredAt: string | null;
201
+ /** The mirror chain in apply order, as presigned GETs; only asked for with includeBundles. */
202
+ bundles: GitMirrorBundle[];
203
+ }
204
+ export declare function gitMirrorState(deckId: string, includeBundles: boolean, timeoutMs: number): Promise<GitMirrorState | null>;
183
205
  export {};
package/dist/api.js CHANGED
@@ -332,3 +332,34 @@ export async function ensureGitRepo(deckId, environment) {
332
332
  }
333
333
  return { remoteUrl: result.remoteUrl };
334
334
  }
335
+ // What the deck's S3 git mirror holds (castle-sandboxes docs/git-remotes-snapshot-without-history.md
336
+ // §4). Sandbox-scoped: the cloud CLI asks it to advance its snapshot floor and, on a cold
337
+ // resume, for the chain of bundles to rebuild history from when code.storage is unreachable.
338
+ // No `environment` argument: from a sandbox, ghost uses the sandbox's own. A deck with no git
339
+ // repo answers with a GIT_REPO_NOT_FOUND error; one not mirrored yet, with nulls and [].
340
+ export async function gitMirrorState(deckId, includeBundles, timeoutMs) {
341
+ const data = await graphql(`query($deckId: ID!, $includeBundles: Boolean) {
342
+ gitMirrorState(deckId: $deckId, includeBundles: $includeBundles) {
343
+ mainSha
344
+ mirroredAt
345
+ bundles { url bytes sha256 }
346
+ }
347
+ }`, { deckId, includeBundles }, { timeoutMs });
348
+ handleAPIError(data);
349
+ const result = pickData(data, 'gitMirrorState');
350
+ if (!result)
351
+ return null;
352
+ const bundles = Array.isArray(result.bundles) ? result.bundles : [];
353
+ return {
354
+ mainSha: typeof result.mainSha === 'string' ? result.mainSha : null,
355
+ mirroredAt: typeof result.mirroredAt === 'string' ? result.mirroredAt : null,
356
+ // In apply order (the full base first); an entry without a URL could not be applied at all.
357
+ bundles: bundles
358
+ .filter((b) => !!b && typeof b.url === 'string')
359
+ .map((b) => ({
360
+ url: b.url,
361
+ bytes: typeof b.bytes === 'number' ? b.bytes : null,
362
+ sha256: typeof b.sha256 === 'string' ? b.sha256 : null,
363
+ })),
364
+ };
365
+ }
@@ -51,6 +51,11 @@ export interface HostCapabilities {
51
51
  params: MultiplayerGetSessionParams,
52
52
  ctx: HostContext,
53
53
  ) => Promise<MultiplayerGetSessionResult>;
54
+ joinMultiplayerDestination?: (
55
+ params: MultiplayerJoinDestinationParams,
56
+ ctx: HostContext,
57
+ signal?: AbortSignal,
58
+ ) => Promise<MultiplayerJoinDestinationResult>;
54
59
  }
55
60
 
56
61
  export type OracleStream = (url: string, body: string, sink: OracleStreamSink) => () => void;
@@ -82,6 +87,46 @@ export interface MultiplayerGetSessionResult {
82
87
  soloReason: 'private_deck' | 'no_server_bundle' | 'unavailable' | null;
83
88
  }
84
89
 
90
+ export interface MultiplayerJoinDestinationParams {
91
+ routeId: string;
92
+ slot: string;
93
+ }
94
+
95
+ export type MultiplayerDestinationAudience = 'player' | 'party' | 'public';
96
+
97
+ export interface MultiplayerJoinDestinationResult {
98
+ status:
99
+ | 'ok'
100
+ | 'cancelled'
101
+ | 'full'
102
+ | 'unavailable'
103
+ | 'not_found'
104
+ | 'forbidden'
105
+ | 'party_required';
106
+ url: string | null;
107
+ nonce: string | null;
108
+ sessionId: string | null;
109
+ audience: MultiplayerDestinationAudience | null;
110
+ }
111
+
112
+ export interface CauldronMultiplayerDestinationDescription {
113
+ access: MultiplayerDestinationAudience;
114
+ configRevision: string;
115
+ }
116
+
117
+ export function describeCauldronMultiplayerDestination(
118
+ gql: GraphqlFetch,
119
+ ctx: HostContext,
120
+ routeId: string,
121
+ ): Promise<CauldronMultiplayerDestinationDescription>;
122
+
123
+ export function acquireCauldronMultiplayerDestination(
124
+ gql: GraphqlFetch,
125
+ ctx: HostContext,
126
+ params: MultiplayerJoinDestinationParams,
127
+ expectedConfigRevision: string,
128
+ ): Promise<MultiplayerJoinDestinationResult>;
129
+
85
130
  export interface LeaderboardStreakCredit {
86
131
  deckId: string | null;
87
132
  kind: string;
@@ -40,6 +40,7 @@ const COMMAND_NAMES = [
40
40
  "portal.info",
41
41
  "haptics.play",
42
42
  "multiplayer.getSession",
43
+ "multiplayer.joinDestination",
43
44
  "voice.getState",
44
45
  "voice.requestJoin",
45
46
  "voice.leave",
@@ -142,6 +143,13 @@ function runCommand(ctx, command, params, caps, options) {
142
143
  if (command === "multiplayer.getSession" && caps.getMultiplayerSession) {
143
144
  return caps.getMultiplayerSession(multiplayerSessionRequest(params), ctx);
144
145
  }
146
+ if (command === "multiplayer.joinDestination") {
147
+ const request = multiplayerDestinationRequest(params);
148
+ if (!caps.joinMultiplayerDestination) {
149
+ return Promise.resolve(unavailableDestinationResult());
150
+ }
151
+ return caps.joinMultiplayerDestination(request, ctx, options.signal);
152
+ }
145
153
  if (isPlatformCommand(command)) {
146
154
  return runPlatformCommand(ctx, command, params, caps);
147
155
  }
@@ -263,6 +271,76 @@ function multiplayerSessionResult(value) {
263
271
  }
264
272
  return { status: "ok", url, nonce, sessionId, soloReason: null };
265
273
  }
274
+ function multiplayerDestinationRequest(params) {
275
+ const routeId = asDestinationRouteId(params.routeId);
276
+ const slot = asBoundedText(params.slot, "slot", "multiplayer.joinDestination", 128, 128);
277
+ try {
278
+ encodeURIComponent(slot);
279
+ }
280
+ catch {
281
+ throw new HostCommandError("INVALID_ARGUMENT", "Castle command multiplayer.joinDestination requires slot to be valid text.", "multiplayer.joinDestination");
282
+ }
283
+ return {
284
+ routeId,
285
+ slot,
286
+ };
287
+ }
288
+ function asDestinationRouteId(value) {
289
+ const routeId = asString(value, "routeId", "multiplayer.joinDestination");
290
+ if (/^[A-Za-z0-9_-]{1,64}$/.test(routeId))
291
+ return routeId;
292
+ throw new HostCommandError("INVALID_ARGUMENT", "Castle command multiplayer.joinDestination requires a valid routeId.", "multiplayer.joinDestination");
293
+ }
294
+ function unavailableDestinationResult() {
295
+ return {
296
+ status: "unavailable",
297
+ url: null,
298
+ nonce: null,
299
+ sessionId: null,
300
+ audience: null,
301
+ };
302
+ }
303
+ export async function describeCauldronMultiplayerDestination(gql, ctx, routeId) {
304
+ const validatedRouteId = asDestinationRouteId(routeId);
305
+ const deckId = requireDeckId(ctx, "multiplayer.joinDestination");
306
+ const data = await graphql(gql, CAULDRON_MULTIPLAYER_DESTINATION_DESCRIPTION_QUERY, { deckId, routeId: validatedRouteId }, "multiplayer.joinDestination");
307
+ const description = data.describeCauldronMultiplayerDestination;
308
+ const access = asDestinationAudience(description?.access);
309
+ const configRevision = asOptionalString(description?.configRevision);
310
+ if (!configRevision) {
311
+ throw new HostCommandError("CAULDRON_DESTINATION_UNAVAILABLE", "Castle returned an invalid destination description.", "multiplayer.joinDestination");
312
+ }
313
+ return { access, configRevision };
314
+ }
315
+ export async function acquireCauldronMultiplayerDestination(gql, ctx, params, expectedConfigRevision) {
316
+ const request = multiplayerDestinationRequest({ ...params });
317
+ const deckId = requireDeckId(ctx, "multiplayer.joinDestination");
318
+ const data = await graphql(gql, CAULDRON_MULTIPLAYER_DESTINATION_SESSION_QUERY, {
319
+ deckId,
320
+ routeId: request.routeId,
321
+ slot: request.slot,
322
+ expectedConfigRevision: asString(expectedConfigRevision, "expectedConfigRevision", "multiplayer.joinDestination"),
323
+ partyId: ctx.partyId ?? null,
324
+ }, "multiplayer.joinDestination");
325
+ const session = data.getCauldronMultiplayerDestinationSession;
326
+ const sessionId = asOptionalString(session?.sessionId);
327
+ const url = asOptionalString(session?.url);
328
+ const nonce = asOptionalString(session?.nonce);
329
+ if (!sessionId || !url || !nonce)
330
+ return unavailableDestinationResult();
331
+ return {
332
+ status: "ok",
333
+ sessionId,
334
+ url,
335
+ nonce,
336
+ audience: asDestinationAudience(session?.audience),
337
+ };
338
+ }
339
+ function asDestinationAudience(value) {
340
+ if (value === "player" || value === "party" || value === "public")
341
+ return value;
342
+ throw new HostCommandError("CAULDRON_DESTINATION_UNAVAILABLE", "Castle returned an invalid destination audience.", "multiplayer.joinDestination");
343
+ }
266
344
  // A reason this SDK does not know reads as the catch-all: the deck still
267
345
  // learns it is solo, just not why. This does not cover a ghost older than the
268
346
  // field: that rejects the whole query as invalid, so ghost deploys before any
@@ -2293,6 +2371,36 @@ const CAULDRON_MULTIPLAYER_SESSION_QUERY = `
2293
2371
  }
2294
2372
  }
2295
2373
  `;
2374
+ const CAULDRON_MULTIPLAYER_DESTINATION_DESCRIPTION_QUERY = `
2375
+ query CastleCauldronMultiplayerDestinationDescription($deckId: ID!, $routeId: String!) {
2376
+ describeCauldronMultiplayerDestination(deckId: $deckId, routeId: $routeId) {
2377
+ access
2378
+ configRevision
2379
+ }
2380
+ }
2381
+ `;
2382
+ const CAULDRON_MULTIPLAYER_DESTINATION_SESSION_QUERY = `
2383
+ query CastleCauldronMultiplayerDestinationSession(
2384
+ $deckId: ID!
2385
+ $routeId: String!
2386
+ $slot: String!
2387
+ $expectedConfigRevision: String!
2388
+ $partyId: ID
2389
+ ) {
2390
+ getCauldronMultiplayerDestinationSession(
2391
+ deckId: $deckId
2392
+ routeId: $routeId
2393
+ slot: $slot
2394
+ expectedConfigRevision: $expectedConfigRevision
2395
+ partyId: $partyId
2396
+ ) {
2397
+ sessionId
2398
+ url
2399
+ nonce
2400
+ audience
2401
+ }
2402
+ }
2403
+ `;
2296
2404
  const CAULDRON_STORAGE_GET_QUERY = `
2297
2405
  query CastleCauldronStorageGet(
2298
2406
  $deckId: ID!