castle-web-cli 0.4.213 → 0.4.215

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,6 +46,8 @@ 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';
49
+ import { AGENT_ROLE_ENV, cloudGitMode } from './cloudGit.js';
50
+ import { createServeGitHooks } from './cloudGitServe.js';
48
51
  export const AGENT_WS_PATH = '/__castle/agent';
49
52
  const DEFAULT_SETTINGS = {
50
53
  // Both roles run the claude CLI routed through OpenRouter at the slug below.
@@ -340,8 +343,8 @@ const OPENROUTER_ALLOWED_TOOLS = ['Edit', 'Write', 'NotebookEdit', 'Bash'];
340
343
  const CLAUDE_PLAYTEST_TOOL = 'mcp__castle__playtest';
341
344
  // Single `=` token because --allowedTools is variadic and would otherwise
342
345
  // swallow the trailing prompt positional.
343
- function openrouterAllowedToolsArg(role) {
344
- 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;
345
348
  return `--allowedTools=${tools.join(',')}`;
346
349
  }
347
350
  // The one MCP server a task spawn sees. `--strict-mcp-config` is already passed,
@@ -371,6 +374,17 @@ function mcpConfigArg(deckDir, taskId) {
371
374
  });
372
375
  return `--mcp-config=${config}`;
373
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
+ }
374
388
  // Keep runs independent of the machine's user config: no user plugins (LSP
375
389
  // servers etc.), no user MCP servers. CLAUDE.md auto-discovery and OAuth still
376
390
  // work. On a user's own Anthropic KEY this also carries the apiKeyHelper that
@@ -403,7 +417,7 @@ metering,
403
417
  // The task this spawn belongs to, so its playtest frames land under
404
418
  // tasks/<id>/playtest/ and count against that task's call budget. Absent for
405
419
  // router turns, which get no playtest tool at all.
406
- taskId,
420
+ taskId, playtestTool,
407
421
  // The stable part of a router prompt, passed as appended system text so the
408
422
  // CLI's own cache breakpoints cover it.
409
423
  systemPrompt) {
@@ -414,6 +428,7 @@ systemPrompt) {
414
428
  .filter((text) => Boolean(text))
415
429
  .join('\n\n');
416
430
  const hosted = Boolean(process.env.CASTLE_SANDBOX_ID);
431
+ const playtestArgs = role === 'task' ? playtestToolArgs(playtestTool, metering.deckDir, taskId) : [];
417
432
  const orAuth = viaOpenrouter ? resolveOpenrouterAuth() : null;
418
433
  const anAuth = viaOpenrouter ? null : resolveAnthropicAuth();
419
434
  // Direct = the user's own credential/login is in play, so this run bypasses
@@ -433,7 +448,7 @@ systemPrompt) {
433
448
  '--include-partial-messages',
434
449
  '--permission-mode',
435
450
  hosted ? 'bypassPermissions' : 'auto',
436
- ...(!hosted && viaOpenrouter ? [openrouterAllowedToolsArg(role)] : []),
451
+ ...(!hosted && viaOpenrouter ? [openrouterAllowedToolsArg(playtestArgs.length > 0)] : []),
437
452
  '--model',
438
453
  spawnModel,
439
454
  '--effort',
@@ -448,7 +463,7 @@ systemPrompt) {
448
463
  '--settings',
449
464
  claudeSettingsArg(anAuth),
450
465
  '--strict-mcp-config',
451
- ...(role === 'task' ? [mcpConfigArg(metering.deckDir, taskId)] : []),
466
+ ...playtestArgs,
452
467
  ...(systemText ? ['--append-system-prompt', systemText] : []),
453
468
  prompt,
454
469
  ],
@@ -460,6 +475,7 @@ systemPrompt) {
460
475
  direct,
461
476
  })),
462
477
  ...claudeContextEnv(role),
478
+ [AGENT_ROLE_ENV]: role,
463
479
  // Claude Code 2.1.258 refuses bypassPermissions as root unless the
464
480
  // child explicitly identifies itself as running in a sandbox.
465
481
  ...(hosted ? { IS_SANDBOX: '1' } : {}),
@@ -526,7 +542,7 @@ function readJsonFile(filePath) {
526
542
  }
527
543
  }
528
544
  // How much of a router reply is safe to show while it is still streaming:
529
- // 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
530
546
  // marker at the tail so "```cast..." never flashes up before we know what it
531
547
  // is. The full cleaned text replaces the streamed text when the reply ends.
532
548
  function visibleLength(raw) {
@@ -546,12 +562,57 @@ const planSessions = new Map();
546
562
  function planDefault() {
547
563
  return process.env.CASTLE_AGENT_PLAN !== 'off';
548
564
  }
549
- // The playtest steering: one router rule plus the task prompt's carve-out
550
- // (PLAYTEST_ROUTER_RULE in agent-prompts.ts). On unless the serve was told
551
- // `CASTLE_AGENT_PLAYTEST=off` (the only env value that does anything; no
552
- // per-deck switch).
553
- function playtestSteering() {
554
- 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
+ };
555
616
  }
556
617
  function planSession(deckDir) {
557
618
  const existing = planSessions.get(deckDir);
@@ -735,7 +796,7 @@ function scanNewTaskFences(raw, fromIndex) {
735
796
  while ((match = re.exec(raw))) {
736
797
  const directive = parseTaskFenceBody(match[1]);
737
798
  if (directive)
738
- directives.push(directive);
799
+ directives.push({ directive, at: match.index });
739
800
  nextIndex = re.lastIndex;
740
801
  }
741
802
  return { directives, nextIndex };
@@ -1783,12 +1844,14 @@ async function runAgentTurn(opts) {
1783
1844
  crashed: false,
1784
1845
  };
1785
1846
  }
1847
+ if (opts.cancelled?.())
1848
+ return { ok: false, finalText: '', error: 'not run', crashed: false };
1786
1849
  // One id per call: a router turn, or a single task attempt (the retry loop
1787
1850
  // in runTaskAgentIn calls this once per attempt, and each attempt is its own
1788
1851
  // conversation -- nothing is resumed).
1789
1852
  const sessionId = newAgentSessionId(opts.role);
1790
1853
  const settled = (run) => run.finally(() => notifyAgentRunFinished());
1791
- 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);
1792
1855
  const run = runAgentCli({
1793
1856
  cwd: opts.cwd,
1794
1857
  command: invocation.command,
@@ -2130,6 +2193,7 @@ async function runTaskAgentIn(ctx, task) {
2130
2193
  // Read at task start, like the router's per turn: a task the router spawns
2131
2194
  // right after adopting a kit must be briefed with the kit's guide.
2132
2195
  const deckGuide = readQuickReference(ctx.deckDir);
2196
+ const playtest = task.playtest ?? taskPlaytestFor(ctx.deckDir);
2133
2197
  const taskPrompt = buildTaskPrompt({
2134
2198
  deckLabel: ctx.deckLabel,
2135
2199
  taskId: task.id,
@@ -2139,11 +2203,12 @@ async function runTaskAgentIn(ctx, task) {
2139
2203
  notesPath: path.join(relDir, 'notes.md'),
2140
2204
  handoffPath: path.join(relDir, 'handoff'),
2141
2205
  depsSummary: ctx.depsSummary,
2142
- playtest: playtestSteering(),
2206
+ playtest: playtest.steering,
2143
2207
  deckTree: buildDeckTree(ctx.deckDir),
2144
2208
  quickReference: quickReferenceFor(ctx.deckDir, deckGuide, 'task'),
2145
2209
  plan: taskPlanOpts(ctx.deckDir, task.item, ctx.finishedWork),
2146
2210
  siblings: ctx.siblings,
2211
+ git: cloudGitMode(ctx.deckDir),
2147
2212
  });
2148
2213
  // No /goal wrapper: it makes a fresh evaluator re-check the WHOLE task
2149
2214
  // prompt (including user-only "done when you reach wave 5"-style play
@@ -2199,7 +2264,9 @@ async function runTaskAgentIn(ctx, task) {
2199
2264
  timeoutMs: TASK_TIMEOUT_MS,
2200
2265
  logPath: path.join(dir, 'log.jsonl'),
2201
2266
  taskId: task.id,
2267
+ playtestTool: playtest.tool,
2202
2268
  children: ctx.children,
2269
+ cancelled: () => ctx.stopRequested.has(task.id),
2203
2270
  onSpawn: (pid) => {
2204
2271
  task.pid = pid;
2205
2272
  },
@@ -2506,6 +2573,7 @@ function createTaskStore(opts) {
2506
2573
  prompt: directive.prompt,
2507
2574
  after: resolveTargets(tasks, directive.after),
2508
2575
  item: directive.item,
2576
+ playtest: taskPlaytestFor(deckDir),
2509
2577
  status: 'waiting',
2510
2578
  progress: 0,
2511
2579
  notes: '',
@@ -2585,11 +2653,15 @@ function createTaskStore(opts) {
2585
2653
  .filter((t) => t.status === 'running' || t.status === 'waiting' || t.status === 'blocked')
2586
2654
  .map((t) => t.id)
2587
2655
  : resolveTargets(tasks, tokens);
2656
+ const targets = [];
2588
2657
  for (const id of ids) {
2589
2658
  const task = tasks.get(id);
2590
- if (task)
2591
- 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);
2592
2663
  }
2664
+ return targets;
2593
2665
  }
2594
2666
  return {
2595
2667
  sorted,
@@ -2810,12 +2882,12 @@ function clientUrl(reqPath, signPath) {
2810
2882
  // A sent message renders its pasted images as `<img src>`, which cannot carry
2811
2883
  // the serve token any more than a playtest frame can -- see ServeSecurity.signPath.
2812
2884
  function asClientMessage(message, signPath) {
2813
- if (!message.attachments?.length)
2814
- return message;
2815
- return {
2816
- ...message,
2817
- attachments: message.attachments.map((name) => clientUrl(`${AGENT_ATTACHMENT_PREFIX}${name}`, signPath)),
2818
- };
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;
2819
2891
  }
2820
2892
  function loadTaskFeeds(tasksDir) {
2821
2893
  const map = new Map();
@@ -2875,8 +2947,13 @@ function createMessageThinking(broadcast) {
2875
2947
  function createMessageLog(messagesPath, broadcast, welcomeMessage, forClient) {
2876
2948
  const loaded = readJsonFile(messagesPath) ?? [];
2877
2949
  const messages = loaded
2878
- .filter((m) => m.text.trim() !== '' || m.role === 'user')
2879
- .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
+ });
2880
2957
  function persist() {
2881
2958
  atomicWriteFileSync(messagesPath, JSON.stringify(messages, null, 2) + '\n');
2882
2959
  }
@@ -3020,23 +3097,29 @@ function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
3020
3097
  // Read per turn, not once per serve: adopting a kit mid-conversation
3021
3098
  // rewrites CLAUDE.md, and the next turn has to see the kit's guide.
3022
3099
  const deckGuide = readQuickReference(ctx.deckDir);
3100
+ const messages = ctx.log.messages.filter((message) => message.role !== 'log' && message.id !== selfMessageId && message.status !== 'streaming');
3023
3101
  return buildRouterPromptParts({
3024
3102
  deckLabel: ctx.deckLabel,
3025
3103
  quickReference: quickReferenceFor(ctx.deckDir, deckGuide, 'router'),
3026
3104
  editorTabs: editorTabsFor(ctx.deckDir),
3027
3105
  kits: kitCatalogLines(ctx.deckDir),
3028
3106
  deckTree: buildDeckTree(ctx.deckDir),
3029
- playtest: playtestSteering(),
3107
+ playtest: playtestEnabled(ctx.deckDir),
3108
+ playtestPref: playtestPrefFor(ctx.deckDir),
3030
3109
  askCalls: askCallsEnabled(ctx.deckDir),
3031
- messages: ctx.log.messages
3032
- .filter((m) => m.role !== 'log' && m.id !== selfMessageId && m.status !== 'streaming')
3033
- .map((m) => ({
3110
+ messages: messages.map((m) => ({
3034
3111
  role: m.role,
3035
3112
  // Replace a prior turn's raw ```ask JSON with a readable question list
3036
3113
  // so the model doesn't re-echo the block verbatim.
3037
3114
  text: m.role === 'assistant' ? humanizeAskBlocks(m.text) : m.text,
3038
3115
  interrupted: m.interrupted,
3039
3116
  })),
3117
+ stopped: recentStops(messages).map((note) => ({
3118
+ title: note.title,
3119
+ id: note.taskId,
3120
+ progress: note.progress,
3121
+ repliesAgo: note.repliesAgo,
3122
+ })),
3040
3123
  // Only the live board -- match what the user sees. Hide tasks that are
3041
3124
  // BOTH acknowledged AND finished; an active (running/waiting) task always
3042
3125
  // shows even if somehow acked, so nothing can ever go invisible mid-work.
@@ -3095,6 +3178,15 @@ function settleInterruptedTurn(ctx, message) {
3095
3178
  // same `after:` resolution against the live task board -- which by now
3096
3179
  // already includes any tasks spawned earlier in this same reply, so an
3097
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
+ }
3098
3190
  function spawnCompletedTaskFences(ctx, message, midStream, raw) {
3099
3191
  const { directives, nextIndex } = scanNewTaskFences(raw, midStream.scannedUpTo);
3100
3192
  midStream.scannedUpTo = nextIndex;
@@ -3105,10 +3197,11 @@ function spawnCompletedTaskFences(ctx, message, midStream, raw) {
3105
3197
  .filter((t) => t.status === 'running' || t.status === 'waiting')
3106
3198
  .map((t) => t.title.toLowerCase()));
3107
3199
  const newIds = [];
3108
- for (const directive of directives) {
3200
+ for (const { directive, at } of directives) {
3109
3201
  const key = directive.title.toLowerCase();
3110
3202
  if (inFlight.has(key) || midStream.spawnedTitles.has(key))
3111
3203
  continue;
3204
+ applyStreamedPrefs(ctx, raw.slice(0, at));
3112
3205
  newIds.push(ctx.taskStore.spawnFromDirective(directive, message.id));
3113
3206
  midStream.spawnedTitles.add(key);
3114
3207
  }
@@ -3152,6 +3245,7 @@ function runRouterTurnIn(ctx, instruction) {
3152
3245
  const prompt = routerTurnPrompt(ctx, instruction, message.id, readPlanSnapshot(ctx.deckDir));
3153
3246
  void runAgentTurn({
3154
3247
  role: 'router',
3248
+ playtestTool: false,
3155
3249
  prompt: prompt.user,
3156
3250
  systemPrompt: prompt.system,
3157
3251
  claudeModel: ctx.claudeModel(),
@@ -3174,6 +3268,7 @@ function runRouterTurnIn(ctx, instruction) {
3174
3268
  // Spawning changes WHEN a fence is acted on, not what is displayed --
3175
3269
  // the holdback above still hides fenced text until the reply ends.
3176
3270
  spawnCompletedTaskFences(ctx, message, midStream, raw);
3271
+ applyStreamedPrefs(ctx, raw);
3177
3272
  },
3178
3273
  onActivity: (activity) => {
3179
3274
  if (activity === lastActivity)
@@ -3203,11 +3298,20 @@ function runRouterTurnIn(ctx, instruction) {
3203
3298
  settleInterruptedTurn(ctx, message);
3204
3299
  return;
3205
3300
  }
3206
- const { cleaned, directives, checkoffs, stops, plan } = extractDirectives(result.finalText);
3301
+ const { cleaned, directives, checkoffs, stops, prefs, plan } = extractDirectives(result.finalText);
3207
3302
  if (result.ok && checkoffs.length > 0)
3208
3303
  ctx.taskStore.checkOff(checkoffs);
3209
- if (result.ok && stops.length > 0)
3210
- 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
+ }
3211
3315
  // Settle-time only, unlike task fences: nothing is waiting on the file,
3212
3316
  // and a half-streamed op line is a line that says something else.
3213
3317
  if (result.ok && plan) {
@@ -3749,6 +3853,14 @@ function onRouterQueueSettled(ctx, retryable) {
3749
3853
  }
3750
3854
  broadcastQueueState(ctx);
3751
3855
  maybeStartRouterQueueTurn(ctx);
3856
+ if (!state.routerRunning) {
3857
+ try {
3858
+ ctx.onIdle?.();
3859
+ }
3860
+ catch (err) {
3861
+ console.error(`[router] onIdle threw: ${err instanceof Error ? err.message : String(err)}`);
3862
+ }
3863
+ }
3752
3864
  }
3753
3865
  // Auto-interrupt ("fold") a pre-text router turn into the very message that
3754
3866
  // triggered it: the turn hasn't produced anything visible yet, so restarting
@@ -3941,6 +4053,12 @@ function makePlaytestRunner(deps) {
3941
4053
  return result;
3942
4054
  };
3943
4055
  }
4056
+ // No task agent running or waiting its turn: the moment the board's work is all on disk.
4057
+ function taskBoardIdle(taskStore) {
4058
+ return !taskStore
4059
+ .sorted()
4060
+ .some((t) => t.status === 'running' || (t.status === 'waiting' && !t.acknowledged));
4061
+ }
3944
4062
  export function createAgentServer(opts) {
3945
4063
  const { deckDir, deckLabel } = opts;
3946
4064
  const welcomeMessage = readWelcomeMessage(deckDir) || DEFAULT_WELCOME_MESSAGE;
@@ -4031,6 +4149,15 @@ export function createAgentServer(opts) {
4031
4149
  };
4032
4150
  const taskFeeds = createTaskFeeds(broadcast, tasksDir);
4033
4151
  const messageThinking = createMessageThinking(broadcast);
4152
+ // Git in the cloud sandbox (CASTLE_GIT=on): commits at turn and task-board ends, and a
4153
+ // merge conflict becomes a router turn. Null with git off.
4154
+ const gitHooks = createServeGitHooks({
4155
+ deckDir,
4156
+ addLog,
4157
+ boardIdle: () => taskBoardIdle(taskStore),
4158
+ routerBusy: () => routerQueue.isRunning(),
4159
+ enqueueInstruction: (text) => routerQueue.handleUserMessage(text, undefined, undefined, undefined, true),
4160
+ });
4034
4161
  const taskStore = createTaskStore({
4035
4162
  deckDir,
4036
4163
  deckLabel,
@@ -4042,9 +4169,12 @@ export function createAgentServer(opts) {
4042
4169
  playtest,
4043
4170
  // Task lifecycle stays on the board only -- log lines for it were spam.
4044
4171
  onUpdate: (task) => broadcast({ type: 'task-update', task: asClientTask(task, opts.signPath) }),
4045
- onStarted: () => undefined,
4172
+ onStarted: () => gitHooks?.taskStarted(),
4046
4173
  onRetry: (task, attempt) => addLog(`agent died, retrying (${attempt}/${MAX_TASK_ATTEMPTS}): ${task.title}`),
4047
- onFinished: (task) => taskFeeds.persist(task),
4174
+ onFinished: (task) => {
4175
+ taskFeeds.persist(task);
4176
+ gitHooks?.taskFinished(task.title, task.status === 'done');
4177
+ },
4048
4178
  onFeed: (task, entry) => taskFeeds.push(task, entry),
4049
4179
  });
4050
4180
  // The mid-run send queue (queue-by-default, "send now"/Stop interrupt, epoch
@@ -4061,6 +4191,7 @@ export function createAgentServer(opts) {
4061
4191
  messageThinking,
4062
4192
  messages,
4063
4193
  settings,
4194
+ onIdle: () => gitHooks?.routerSettled(),
4064
4195
  });
4065
4196
  // The user answered an embedded ```ask picker: record the selections on the
4066
4197
  // assistant message (locks the widget for every client, persists across
@@ -4126,6 +4257,7 @@ export function createAgentServer(opts) {
4126
4257
  .map((message) => asClientMessage(message, opts.signPath)),
4127
4258
  tasks: taskStore.sorted().map((task) => asClientTask(task, opts.signPath)),
4128
4259
  settings,
4260
+ prefs: deckPrefsFrame(deckDir).prefs,
4129
4261
  feeds: Object.fromEntries(taskFeeds.map),
4130
4262
  thinking: messageThinking.snapshot(),
4131
4263
  running: routerQueue.isRunning(),
@@ -4189,6 +4321,12 @@ export function createAgentServer(opts) {
4189
4321
  else if (msg.type === 'set-settings') {
4190
4322
  applySettings(msg);
4191
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
+ }
4192
4330
  else if (msg.type === 'refresh-usage') {
4193
4331
  usageFeed.refresh();
4194
4332
  }
@@ -4239,6 +4377,7 @@ export function createAgentServer(opts) {
4239
4377
  return handleAttachment(req, res, reqPath) || handlePlaytestFrame(req, res, reqPath);
4240
4378
  }
4241
4379
  function shutdown() {
4380
+ gitHooks?.stop();
4242
4381
  taskStore.shutdown();
4243
4382
  for (const child of [...taskChildren, ...routerChildren]) {
4244
4383
  try {
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;
@@ -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;