castle-web-cli 0.4.223 → 0.4.225

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
@@ -26,11 +26,14 @@ import { supportedEffort } from './effortSupport.js';
26
26
  import * as fs from 'fs';
27
27
  import * as os from 'os';
28
28
  import * as path from 'path';
29
+ import { randomUUID } from 'crypto';
29
30
  import { nanoid } from 'nanoid';
30
31
  import { WebSocketServer } from 'ws';
31
32
  import { rawDataToString } from './rawData.js';
32
33
  import { extractDirectives, meansAll, closedPrefLines, parsePrefLines, parseTaskFenceBody, resolveTargets, taskFenceRegex, } from './routerFences.js';
34
+ import { isPendingSteer, newTaskSteer, normalizeSteers, replayedUuid, steerBoardNote, steerMessageText, streamUserLine, } from './taskSteer.js';
33
35
  import { carriesStopNotes, recentStops, stopNotes, } from './routerStops.js';
36
+ import { badTaskEndingsSince, platformInterruptionReason, ROUTER_STOPPED_RESULT, withTimeoutReport, } from './routerTaskEndings.js';
34
37
  import { accountForRun, closingMessageOf } from './taskAccount.js';
35
38
  import { atomicWriteFileSync } from './atomicFile.js';
36
39
  import { AGENT_ATTACHMENT_PREFIX, AGENT_PLAYTEST_PREFIX, PLAN_FILE } from './localPaths.js';
@@ -420,7 +423,10 @@ metering,
420
423
  taskId, playtestTool,
421
424
  // The stable part of a router prompt, passed as appended system text so the
422
425
  // CLI's own cache breakpoints cover it.
423
- systemPrompt) {
426
+ systemPrompt, resumeSessionId, toolsDisabled = false,
427
+ // A run that reads its prompt from stream-json stdin (runAgentCli's `stdin`),
428
+ // so the prompt stays off argv.
429
+ streamInput = false) {
424
430
  const viaOpenrouter = claudeModel === 'openrouter';
425
431
  const spawnModel = spawnModelFor(claudeModel, openrouterModel);
426
432
  const spawnEffort = spawnEffortFor(claudeModel, openrouterModel, effort);
@@ -442,13 +448,19 @@ systemPrompt) {
442
448
  systemText,
443
449
  args: [
444
450
  '-p',
451
+ ...(resumeSessionId ? ['--resume', resumeSessionId] : []),
445
452
  '--verbose',
446
453
  '--output-format',
447
454
  'stream-json',
448
455
  '--include-partial-messages',
449
456
  '--permission-mode',
450
457
  hosted ? 'bypassPermissions' : 'auto',
451
- ...(!hosted && viaOpenrouter ? [openrouterAllowedToolsArg(playtestArgs.length > 0)] : []),
458
+ ...(!toolsDisabled && !hosted && viaOpenrouter
459
+ ? [openrouterAllowedToolsArg(playtestArgs.length > 0)]
460
+ : []),
461
+ ...(toolsDisabled
462
+ ? ['--tools=', `--disallowedTools=${CLAUDE_PLAYTEST_TOOL}`]
463
+ : []),
452
464
  '--model',
453
465
  spawnModel,
454
466
  '--effort',
@@ -465,7 +477,7 @@ systemPrompt) {
465
477
  '--strict-mcp-config',
466
478
  ...playtestArgs,
467
479
  ...(systemText ? ['--append-system-prompt', systemText] : []),
468
- prompt,
480
+ ...(streamInput ? ['--input-format', 'stream-json', '--replay-user-messages'] : [prompt]),
469
481
  ],
470
482
  env: {
471
483
  ...withCustomHeaders(viaOpenrouter ? envForOpenrouterSpawn(orAuth) : envForClaudeSpawn(anAuth), meteringHeaders({
@@ -483,7 +495,12 @@ systemPrompt) {
483
495
  };
484
496
  }
485
497
  const ROUTER_TIMEOUT_MS = 3 * 60_000;
486
- const TASK_TIMEOUT_MS = 30 * 60_000;
498
+ export const TASK_TIMEOUT_MS = Number(process.env.CASTLE_TASK_TIMEOUT_MS) || 30 * 60_000;
499
+ export const WRAP_UP_TIMEOUT_MS = Number(process.env.CASTLE_TASK_WRAP_UP_TIMEOUT_MS) || 2 * 60_000;
500
+ export const RESUME_MAX_AGE_MS = 12 * 60 * 60_000;
501
+ // How long a killed run's stdout may take to drain before its timeout settles
502
+ // anyway (runAgentCli).
503
+ const TIMEOUT_DRAIN_MS = 5_000;
487
504
  const MAX_TASK_ATTEMPTS = 3;
488
505
  // Cap on task agents running at once -- keeps us under e2b / provider rate
489
506
  // limits. Over-cap tasks stay queued ('waiting') and start, earliest-created
@@ -513,6 +530,14 @@ const TASK_SPAWN_STAGGER_MS = Number(process.env.CASTLE_TASK_SPAWN_STAGGER_MS) |
513
530
  // that, so `spawn-task` on the agent socket is gated behind this and a real
514
531
  // serve never accepts task creation from a socket message.
515
532
  const SPAWN_TASK_MESSAGE_ENABLED = process.env.CASTLE_AGENT_SPAWN_TASK === '1';
533
+ // Dormant until measured: task agents read their prompt and any ```castle-send
534
+ // message from stream-json stdin, and the router is told the fence exists. Off,
535
+ // a task is the one-shot argv run it always was and the router prompt is
536
+ // byte-identical.
537
+ const TASK_STEER_ENABLED = process.env.CASTLE_TASK_STEER === '1';
538
+ // A message that reaches a task after its run closed stdin resumes the same
539
+ // session; this bounds how many times one task can be resumed that way.
540
+ const MAX_TASK_RESUMES = 3;
516
541
  const TASK_POLL_MS = 1_000;
517
542
  const FENCE_HOLDBACK = '```castle-';
518
543
  const RESULT_SUMMARY_CHARS = 600;
@@ -717,7 +742,9 @@ function planOpSources(taskStore, messages) {
717
742
  const taskReports = new Map();
718
743
  for (const task of taskStore.sorted()) {
719
744
  const row = asPromptTask(task);
720
- const text = [task.durable, row.error, row.notes].filter((s) => s?.trim()).join('\n');
745
+ const text = [task.durable, row.error, row.interrupted, row.notes]
746
+ .filter((s) => s?.trim())
747
+ .join('\n');
721
748
  if (text)
722
749
  taskReports.set(task.id, text);
723
750
  }
@@ -1128,8 +1155,10 @@ function createAgentStreamState() {
1128
1155
  usage: undefined,
1129
1156
  stats: undefined,
1130
1157
  sawResult: false,
1158
+ sessionId: undefined,
1131
1159
  needsGap: false,
1132
1160
  pendingTools: new Map(),
1161
+ resultMark: 0,
1133
1162
  };
1134
1163
  }
1135
1164
  function parseCliUsage(raw) {
@@ -1249,7 +1278,10 @@ function makeAgentEventHandler(opts, state) {
1249
1278
  opts.onActivity?.(null);
1250
1279
  };
1251
1280
  const handleClaudeEvent = (ev) => {
1252
- if (ev.type === 'stream_event') {
1281
+ if (ev.type === 'system' && ev.subtype === 'init' && typeof ev.session_id === 'string') {
1282
+ state.sessionId = ev.session_id;
1283
+ }
1284
+ else if (ev.type === 'stream_event') {
1253
1285
  const e = ev.event;
1254
1286
  if (e?.type === 'content_block_start') {
1255
1287
  if (e.content_block?.type === 'tool_use') {
@@ -1305,12 +1337,17 @@ function makeAgentEventHandler(opts, state) {
1305
1337
  }
1306
1338
  }
1307
1339
  else if (ev.type === 'result') {
1308
- state.sawResult = true;
1309
1340
  // An EMPTY string result falls back to the streamed text. Models that
1310
1341
  // return their blocks as `text, thinking` (gemini through OpenRouter's
1311
1342
  // anthropic-compatible endpoint) end the turn on an empty thinking block,
1312
1343
  // and the CLI reports `result: ""` even though the answer streamed fine.
1313
- const closing = closingMessageOf(ev.result, state.accumulated);
1344
+ const closing = closingMessageOf(ev.result, state.accumulated.slice(state.resultMark));
1345
+ state.resultMark = state.accumulated.length;
1346
+ if (state.sawResult) {
1347
+ mergeLaterResult(state, closing, ev);
1348
+ return;
1349
+ }
1350
+ state.sawResult = true;
1314
1351
  state.finalText = closing.finalText;
1315
1352
  state.finalTextFromResult = closing.fromResult;
1316
1353
  state.resultIsError = ev.is_error === true;
@@ -1320,6 +1357,30 @@ function makeAgentEventHandler(opts, state) {
1320
1357
  };
1321
1358
  return handleClaudeEvent;
1322
1359
  }
1360
+ // A stream-json run answers each stdin message that arrived after its first
1361
+ // turn ended with a turn of its own, and a result for each. Measured on claude
1362
+ // 2.1.284: total_cost_usd, duration_api_ms and modelUsage are running totals for
1363
+ // the process, so the latest wins; usage and num_turns cover that turn alone,
1364
+ // so they add up. The closing text keeps every turn's answer in order. A later
1365
+ // turn's error is that message's outcome (AgentStdin.onResult), not the run's.
1366
+ function mergeLaterResult(state, closing, ev) {
1367
+ state.finalText = [state.finalText, closing.finalText].filter(Boolean).join('\n\n');
1368
+ state.finalTextFromResult = state.finalTextFromResult && closing.fromResult;
1369
+ state.usage = addCliUsage(state.usage, parseCliUsage(ev.usage));
1370
+ const later = parseCliRunStats(ev);
1371
+ if (!later)
1372
+ return;
1373
+ const numTurns = state.stats?.numTurns !== undefined && later.numTurns !== undefined
1374
+ ? state.stats.numTurns + later.numTurns
1375
+ : (later.numTurns ?? state.stats?.numTurns);
1376
+ state.stats = { ...state.stats, ...later, ...(numTurns !== undefined ? { numTurns } : {}) };
1377
+ }
1378
+ // A stream-json run whose first turn succeeded did the work it was spawned for
1379
+ // even if the process then dies or hangs in a later turn; that turn's message
1380
+ // is still `taken`, which is pending, and goes to a resume.
1381
+ function streamRunOk(opts, state) {
1382
+ return opts.stdin !== undefined && state.sawResult && !state.resultIsError;
1383
+ }
1323
1384
  // How long a settled run waits for its log stream to flush before resolving
1324
1385
  // anyway. Long enough that an ordinary append always lands first (so a retry's
1325
1386
  // next attempt cannot interleave with it), short enough that a wedged disk
@@ -1338,13 +1399,13 @@ function runAgentCli(opts) {
1338
1399
  // unclassified and the composer spins forever with nothing shown. Settle
1339
1400
  // it here in the same shape that handler uses so it lands on the normal
1340
1401
  // "spawn" copy instead. The declared type mirrors the stdio tuple below:
1341
- // stdin ignored, stdout/stderr piped.
1402
+ // stdin piped only for a stream-json run, stdout/stderr piped.
1342
1403
  let child;
1343
1404
  try {
1344
1405
  child = spawn(opts.command, opts.args, {
1345
1406
  cwd: opts.cwd,
1346
1407
  env: opts.env,
1347
- stdio: ['ignore', 'pipe', 'pipe'],
1408
+ stdio: [opts.stdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],
1348
1409
  });
1349
1410
  }
1350
1411
  catch (err) {
@@ -1399,10 +1460,28 @@ function runAgentCli(opts) {
1399
1460
  let stderrTail = '';
1400
1461
  let lineBuffer = '';
1401
1462
  const state = createAgentStreamState();
1463
+ // The CLI stays up after a result for as long as stdin is open, and this
1464
+ // run only settles on exit -- so stdin closes at the first result. Every
1465
+ // line already written by then is still answered, each as a turn of its
1466
+ // own, before the process exits (measured on claude 2.1.284).
1467
+ let stdinOpen = false;
1468
+ const closeStdin = () => {
1469
+ if (!stdinOpen)
1470
+ return;
1471
+ stdinOpen = false;
1472
+ opts.stdin?.bind(null);
1473
+ try {
1474
+ child.stdin?.end();
1475
+ }
1476
+ catch {
1477
+ /* already gone */
1478
+ }
1479
+ };
1402
1480
  const settle = (result) => {
1403
1481
  if (settled)
1404
1482
  return;
1405
1483
  settled = true;
1484
+ closeStdin();
1406
1485
  clearTimeout(timeout);
1407
1486
  opts.children.delete(child);
1408
1487
  // Resolve only once the log's buffered lines have actually reached disk.
@@ -1436,20 +1515,39 @@ function runAgentCli(opts) {
1436
1515
  finishFlush();
1437
1516
  }
1438
1517
  };
1518
+ // A timed-out stream run settles once its stdout has drained (the close event),
1519
+ // so every frame the process wrote before it died is counted and none
1520
+ // arrives after the caller has moved on -- a resume must never see the old
1521
+ // run's replay or result. The drain wait is bounded; past it, later frames
1522
+ // are dropped rather than applied. A one-shot run settles at the kill.
1523
+ let timedOut = false;
1524
+ let drainTimer;
1525
+ const settleTimedOut = () => {
1526
+ clearTimeout(drainTimer);
1527
+ const ok = streamRunOk(opts, state);
1528
+ settle({
1529
+ ok,
1530
+ finalText: state.finalText || state.accumulated,
1531
+ error: ok ? undefined : 'agent run timed out',
1532
+ usage: state.usage,
1533
+ stats: state.stats,
1534
+ timedOut: !ok,
1535
+ sessionId: state.sessionId,
1536
+ resultError: state.resultIsError,
1537
+ });
1538
+ };
1439
1539
  const timeout = setTimeout(() => {
1540
+ timedOut = true;
1440
1541
  try {
1441
1542
  child.kill('SIGKILL');
1442
1543
  }
1443
1544
  catch {
1444
1545
  /* already gone */
1445
1546
  }
1446
- settle({
1447
- ok: false,
1448
- finalText: state.finalText || state.accumulated,
1449
- error: 'agent run timed out',
1450
- usage: state.usage,
1451
- stats: state.stats,
1452
- });
1547
+ if (opts.stdin)
1548
+ drainTimer = setTimeout(settleTimedOut, TIMEOUT_DRAIN_MS);
1549
+ else
1550
+ settleTimedOut();
1453
1551
  }, opts.timeoutMs);
1454
1552
  const handleEvent = makeAgentEventHandler(opts, state);
1455
1553
  child.stdout.on('data', (chunk) => {
@@ -1458,10 +1556,18 @@ function runAgentCli(opts) {
1458
1556
  while (nl >= 0) {
1459
1557
  const line = lineBuffer.slice(0, nl);
1460
1558
  lineBuffer = lineBuffer.slice(nl + 1);
1461
- if (line.trim()) {
1559
+ if (line.trim() && !(settled && opts.stdin)) {
1462
1560
  writeLog(line + '\n');
1463
1561
  try {
1464
- handleEvent(JSON.parse(line));
1562
+ const ev = JSON.parse(line);
1563
+ handleEvent(ev);
1564
+ const replayed = replayedUuid(ev);
1565
+ if (replayed)
1566
+ opts.stdin?.onReplay(replayed);
1567
+ if (ev.type === 'result') {
1568
+ opts.stdin?.onResult(ev.is_error !== true);
1569
+ closeStdin();
1570
+ }
1465
1571
  }
1466
1572
  catch {
1467
1573
  /* non-JSON noise on stdout -- ignore */
@@ -1482,8 +1588,35 @@ function runAgentCli(opts) {
1482
1588
  failure: { kind: 'spawn', detail: `${opts.command}: ${err.message}` },
1483
1589
  });
1484
1590
  });
1591
+ // Opened last, once the timeout and every handler exist: bind runs caller
1592
+ // code that persists task state, and a throw there must not leave a child
1593
+ // with stdin open and nothing to reap it.
1594
+ if (opts.stdin && child.stdin) {
1595
+ const pipe = child.stdin;
1596
+ // EPIPE from a child that died mid-write arrives here; the close handler
1597
+ // reports the death.
1598
+ pipe.on('error', () => {
1599
+ stdinOpen = false;
1600
+ opts.stdin?.bind(null);
1601
+ });
1602
+ stdinOpen = true;
1603
+ pipe.write(streamUserLine(opts.stdin.prompt, opts.stdin.promptUuid));
1604
+ try {
1605
+ opts.stdin.bind((line) => {
1606
+ if (stdinOpen)
1607
+ pipe.write(line);
1608
+ });
1609
+ }
1610
+ catch (err) {
1611
+ console.error(`[agent] binding a run's stdin threw: ${err instanceof Error ? err.message : String(err)}`);
1612
+ }
1613
+ }
1485
1614
  child.on('close', (code) => {
1486
- const ok = code === 0 && !state.resultIsError && state.sawResult;
1615
+ if (timedOut) {
1616
+ settleTimedOut();
1617
+ return;
1618
+ }
1619
+ const ok = code === 0 ? state.sawResult && !state.resultIsError : streamRunOk(opts, state);
1487
1620
  // A provider error does NOT arrive on stderr: the claude CLI reports it
1488
1621
  // in the stream-json result event (is_error:true) and exits 0, leaving
1489
1622
  // stderr empty -- verified against the real binary. So classify against
@@ -1510,7 +1643,9 @@ function runAgentCli(opts) {
1510
1643
  finalTextFromResult: state.finalTextFromResult,
1511
1644
  usage: state.usage,
1512
1645
  stats: state.stats,
1646
+ sessionId: state.sessionId,
1513
1647
  crashed: !state.sawResult,
1648
+ resultError: state.resultIsError,
1514
1649
  error,
1515
1650
  failure: classified
1516
1651
  ? {
@@ -1851,7 +1986,7 @@ async function runAgentTurn(opts) {
1851
1986
  // conversation -- nothing is resumed).
1852
1987
  const sessionId = newAgentSessionId(opts.role);
1853
1988
  const settled = (run) => run.finally(() => notifyAgentRunFinished());
1854
- const invocation = buildAgentInvocation(opts.role, opts.prompt, opts.claudeModel, opts.openrouterModel, opts.effort, { sessionId, deckDir: opts.cwd }, opts.taskId, opts.playtestTool, opts.systemPrompt);
1989
+ const invocation = buildAgentInvocation(opts.role, opts.prompt, opts.claudeModel, opts.openrouterModel, opts.effort, { sessionId, deckDir: opts.cwd }, opts.taskId, opts.playtestTool, opts.systemPrompt, opts.resumeSessionId, opts.toolsDisabled, opts.stdin !== undefined);
1855
1990
  const run = runAgentCli({
1856
1991
  cwd: opts.cwd,
1857
1992
  command: invocation.command,
@@ -1871,6 +2006,7 @@ async function runAgentTurn(opts) {
1871
2006
  effort: invocation.effort,
1872
2007
  systemPrompt: invocation.systemText || undefined,
1873
2008
  prompt: opts.prompt,
2009
+ ...(opts.resumeSessionId ? { resumeSessionId: opts.resumeSessionId } : {}),
1874
2010
  },
1875
2011
  children: opts.children,
1876
2012
  onDelta: opts.onDelta,
@@ -1879,6 +2015,7 @@ async function runAgentTurn(opts) {
1879
2015
  onSpawn: opts.onSpawn,
1880
2016
  labelUnknownTools: opts.labelUnknownTools,
1881
2017
  openrouterModel: opts.claudeModel === 'openrouter' ? opts.openrouterModel : undefined,
2018
+ stdin: opts.stdin ? { ...opts.stdin, prompt: opts.prompt } : undefined,
1882
2019
  });
1883
2020
  return settled(run);
1884
2021
  }
@@ -1938,21 +2075,33 @@ function writeTaskIndex(tasksDir, tasks) {
1938
2075
  console.error(`[tasks] could not write ${TASK_INDEX_FILE}: ${err instanceof Error ? err.message : String(err)}`);
1939
2076
  }
1940
2077
  }
1941
- // Tasks left "running" or "waiting" by a dead serve are as finished as they
1942
- // will get. They are interrupted rather than scheduled again on boot. A
1943
- // persisted "blocked" task is left as-is: it is not "waiting", so maybeStart
1944
- // never reconsiders it and it can't wedge or auto-start; it just sits on the
1945
- // board (blockedBy intact) until the router stops it, same as before restart.
1946
- const TASK_STATUSES = ['waiting', 'running', 'blocked', 'done', 'failed', 'interrupted'];
2078
+ const TASK_STATUSES = [
2079
+ 'held',
2080
+ 'waiting',
2081
+ 'running',
2082
+ 'blocked',
2083
+ 'done',
2084
+ 'failed',
2085
+ 'interrupted',
2086
+ ];
1947
2087
  const TASK_OPTIONAL_STRINGS = [
1948
2088
  'item', 'startedAt', 'finishedAt', 'originMessageId', 'resultSummary', 'account', 'errorCopy',
1949
2089
  'errorDetail', 'failure', 'avatar', 'phase', 'durable', 'what', 'model', 'backend',
2090
+ 'interruptedFrom', 'interruptedAt', 'answer',
1950
2091
  ];
1951
- const TASK_OPTIONAL_NUMBERS = ['pid', 'costUsd', 'durationApiMs', 'numTurns'];
2092
+ const TASK_OPTIONAL_NUMBERS = ['pid', 'costUsd', 'durationApiMs', 'numTurns', 'resumeCount'];
1952
2093
  const TASK_OPTIONAL_OBJECTS = ['usage', 'modelUsage'];
1953
2094
  const TASK_OPTIONAL_BOOLEANS = ['acknowledged', 'rejected', 'durablePending'];
1954
2095
  const TASK_OPTIONAL_STRING_LISTS = ['playtestFrames', 'files', 'knobs', 'blockedBy'];
1955
2096
  const isStringList = (v) => Array.isArray(v) && v.every((s) => typeof s === 'string');
2097
+ function isHeldFor(v) {
2098
+ if (!v || typeof v !== 'object' || Array.isArray(v))
2099
+ return false;
2100
+ const heldFor = v;
2101
+ return (typeof heldFor.messageId === 'string' &&
2102
+ typeof heldFor.question === 'string' &&
2103
+ isStringList(heldFor.chips));
2104
+ }
1956
2105
  // tasks/ sits in the deck, where the agent (or anything else) can write, and a
1957
2106
  // record the store can't handle used to throw inside createTaskStore and take
1958
2107
  // the whole serve down -- the deck then couldn't be opened at all. A record
@@ -1988,12 +2137,25 @@ function normalizeLoadedTask(entry, raw) {
1988
2137
  for (const k of TASK_OPTIONAL_STRINGS)
1989
2138
  if (typeof r[k] !== 'string')
1990
2139
  delete task[k];
2140
+ if (!isHeldFor(r.heldFor))
2141
+ delete task.heldFor;
2142
+ if (task.interruptedFrom !== 'running' && task.interruptedFrom !== 'waiting') {
2143
+ delete task.interruptedFrom;
2144
+ }
2145
+ if (!Number.isInteger(task.resumeCount) || task.resumeCount < 0) {
2146
+ delete task.resumeCount;
2147
+ }
1991
2148
  for (const k of TASK_OPTIONAL_BOOLEANS)
1992
2149
  if (typeof r[k] !== 'boolean')
1993
2150
  delete task[k];
1994
2151
  for (const k of TASK_OPTIONAL_STRING_LISTS)
1995
2152
  if (!isStringList(r[k]))
1996
2153
  delete task[k];
2154
+ const steers = normalizeSteers(r.steers);
2155
+ if (steers)
2156
+ task.steers = steers;
2157
+ else
2158
+ delete task.steers;
1997
2159
  return task;
1998
2160
  }
1999
2161
  function loadTasks(tasksDir) {
@@ -2003,6 +2165,10 @@ function loadTasks(tasksDir) {
2003
2165
  if (!rec)
2004
2166
  continue;
2005
2167
  if (rec.status === 'running' || rec.status === 'waiting') {
2168
+ rec.interruptedFrom = rec.status;
2169
+ // The serve died without a shutdown, so its last write is the best
2170
+ // guess at when -- stamping now would make a week-old crash look fresh.
2171
+ rec.interruptedAt = rec.updatedAt;
2006
2172
  rec.status = 'interrupted';
2007
2173
  rec.updatedAt = nowIso();
2008
2174
  persistTaskFile(tasksDir, rec);
@@ -2187,6 +2353,171 @@ async function waitBeforeTaskRetry(attempt, stopRequested, taskId) {
2187
2353
  await sleep(backoffMs);
2188
2354
  return stopRequested.has(taskId);
2189
2355
  }
2356
+ // The log is append-only across crash retries, so the newest session is the
2357
+ // one the interrupted attempt was running.
2358
+ function claudeSessionIdOf(taskDir) {
2359
+ try {
2360
+ const log = fs.readFileSync(path.join(taskDir, 'log.jsonl'), 'utf8');
2361
+ for (const line of log.split('\n').reverse()) {
2362
+ try {
2363
+ const event = JSON.parse(line);
2364
+ if (typeof event.session_id === 'string')
2365
+ return event.session_id;
2366
+ }
2367
+ catch {
2368
+ /* a trailing partial line or non-JSON output */
2369
+ }
2370
+ }
2371
+ }
2372
+ catch {
2373
+ /* no transcript */
2374
+ }
2375
+ return undefined;
2376
+ }
2377
+ const RESUME_TASK_PROMPT = 'The workspace restarted while you were working on this task and your run was cut off. Check what you already changed on disk, then finish the task and report exactly as the original instructions say.';
2378
+ const FRESH_AFTER_INTERRUPTION_PREFIX = 'A previous run was cut off and part of the work may already be on disk, so check before redoing it.';
2379
+ const WRAP_UP_PROMPT = 'You ran out of time and were stopped. Make no more changes. In a few sentences say what is done, what is left, and whether the deck is in a working state.';
2380
+ function missingResumeSession(result) {
2381
+ const text = [result.error, result.finalText, result.failure?.detail, result.failure?.verbose]
2382
+ .filter((part) => Boolean(part))
2383
+ .join('\n');
2384
+ return /(?:no (?:conversation|session) found|(?:conversation|session).{0,80}(?:not found|does not exist)|unable to find (?:conversation|session))/i.test(text);
2385
+ }
2386
+ function addCliUsage(left, right) {
2387
+ if (!left)
2388
+ return right;
2389
+ if (!right)
2390
+ return left;
2391
+ const usage = {};
2392
+ for (const key of [
2393
+ 'input_tokens',
2394
+ 'output_tokens',
2395
+ 'cache_creation_input_tokens',
2396
+ 'cache_read_input_tokens',
2397
+ ]) {
2398
+ const total = (left[key] ?? 0) + (right[key] ?? 0);
2399
+ if (total > 0)
2400
+ usage[key] = total;
2401
+ }
2402
+ return Object.keys(usage).length > 0 ? usage : undefined;
2403
+ }
2404
+ function addModelUsage(left, right) {
2405
+ if (!left)
2406
+ return right;
2407
+ if (!right)
2408
+ return left;
2409
+ const merged = {};
2410
+ for (const model of new Set([...Object.keys(left), ...Object.keys(right)])) {
2411
+ const a = left[model] ?? {};
2412
+ const b = right[model] ?? {};
2413
+ const entry = {};
2414
+ for (const key of ['input', 'output', 'cacheRead', 'cacheCreation', 'costUsd']) {
2415
+ const total = (a[key] ?? 0) + (b[key] ?? 0);
2416
+ if (total > 0)
2417
+ entry[key] = total;
2418
+ }
2419
+ if (Object.keys(entry).length > 0)
2420
+ merged[model] = entry;
2421
+ }
2422
+ return Object.keys(merged).length > 0 ? merged : undefined;
2423
+ }
2424
+ function addRunLedger(result, extra) {
2425
+ result.usage = addCliUsage(result.usage, extra.usage);
2426
+ const left = result.stats;
2427
+ const right = extra.stats;
2428
+ if (!left) {
2429
+ result.stats = right;
2430
+ return;
2431
+ }
2432
+ if (!right)
2433
+ return;
2434
+ const sum = (a, b) => a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);
2435
+ result.stats = {
2436
+ costUsd: sum(left.costUsd, right.costUsd),
2437
+ durationApiMs: sum(left.durationApiMs, right.durationApiMs),
2438
+ numTurns: sum(left.numTurns, right.numTurns),
2439
+ modelUsage: addModelUsage(left.modelUsage, right.modelUsage),
2440
+ };
2441
+ }
2442
+ function writeSteer(write, steer) {
2443
+ steer.state = 'queued';
2444
+ write(streamUserLine(steerMessageText(steer.text), steer.id));
2445
+ }
2446
+ // One attempt's stdin. A fresh attempt is a new conversation, so it is sent
2447
+ // every message the task has been given; a resume already holds the delivered
2448
+ // ones and gets only what is still pending, minus the one riding as its prompt.
2449
+ function taskStdin(ctx, task, opts) {
2450
+ const channel = ctx.steerChannel;
2451
+ if (!channel)
2452
+ return undefined;
2453
+ channel.write = null;
2454
+ channel.closed = false;
2455
+ return {
2456
+ promptUuid: opts.promptUuid,
2457
+ bind: (write) => {
2458
+ channel.write = write;
2459
+ if (!write) {
2460
+ channel.closed = true;
2461
+ return;
2462
+ }
2463
+ const resent = (task.steers ?? []).filter(opts.resend);
2464
+ for (const steer of resent)
2465
+ writeSteer(write, steer);
2466
+ if (resent.length > 0)
2467
+ ctx.onSteerChange();
2468
+ },
2469
+ onReplay: (uuid) => {
2470
+ const steer = task.steers?.find((s) => s.id === uuid);
2471
+ if (!steer || !isPendingSteer(steer))
2472
+ return;
2473
+ steer.state = 'taken';
2474
+ ctx.onFeed('[the task read your message]');
2475
+ ctx.onSteerChange();
2476
+ },
2477
+ onResult: (ok) => {
2478
+ const taken = (task.steers ?? []).filter((s) => s.state === 'taken');
2479
+ for (const steer of taken) {
2480
+ steer.state = ok ? 'delivered' : 'late';
2481
+ if (ok)
2482
+ steer.deliveredAt = nowIso();
2483
+ }
2484
+ if (taken.length > 0)
2485
+ ctx.onSteerChange();
2486
+ },
2487
+ };
2488
+ }
2489
+ // A resume is a separate process, so unlike mergeLaterResult nothing here is a
2490
+ // running total: every count adds up (addRunLedger).
2491
+ function combineRunResults(a, b) {
2492
+ const combined = {
2493
+ ...b,
2494
+ finalText: [a.finalText, b.finalText].filter(Boolean).join('\n\n'),
2495
+ finalTextFromResult: a.finalTextFromResult === true && b.finalTextFromResult === true,
2496
+ usage: a.usage,
2497
+ stats: a.stats,
2498
+ sessionId: b.sessionId ?? a.sessionId,
2499
+ };
2500
+ addRunLedger(combined, b);
2501
+ return combined;
2502
+ }
2503
+ function terminalSteerReason(status) {
2504
+ if (status === 'interrupted')
2505
+ return 'the task was stopped';
2506
+ if (status === 'failed')
2507
+ return 'the task failed before it read it';
2508
+ return 'the task had already finished';
2509
+ }
2510
+ function settleUndeliveredSteers(task, reason) {
2511
+ let changed = false;
2512
+ for (const steer of task.steers ?? []) {
2513
+ if (!isPendingSteer(steer))
2514
+ continue;
2515
+ steer.state = 'undelivered';
2516
+ steer.reason = reason;
2517
+ changed = true;
2518
+ }
2519
+ return changed;
2520
+ }
2190
2521
  async function runTaskAgentIn(ctx, task) {
2191
2522
  const dir = path.join(ctx.tasksDir, task.id);
2192
2523
  const relDir = path.relative(ctx.deckDir, dir);
@@ -2252,19 +2583,21 @@ async function runTaskAgentIn(ctx, task) {
2252
2583
  ctx.onFeed(line);
2253
2584
  }
2254
2585
  };
2255
- for (let attempt = 1; attempt <= MAX_TASK_ATTEMPTS; attempt++) {
2586
+ const runOnce = async (prompt, run) => {
2256
2587
  await staggerTaskSpawn();
2257
- result = await runAgentTurn({
2588
+ return runAgentTurn({
2258
2589
  role: 'task',
2259
- prompt: taskPrompt,
2590
+ prompt,
2260
2591
  claudeModel: ctx.claudeModel,
2261
2592
  openrouterModel: ctx.openrouterModel,
2262
2593
  effort: ctx.effort,
2263
2594
  cwd: ctx.deckDir,
2264
- timeoutMs: TASK_TIMEOUT_MS,
2595
+ timeoutMs: run.timeoutMs,
2265
2596
  logPath: path.join(dir, 'log.jsonl'),
2266
2597
  taskId: task.id,
2267
2598
  playtestTool: playtest.tool,
2599
+ resumeSessionId: run.resumeSessionId,
2600
+ toolsDisabled: run.toolsDisabled,
2268
2601
  children: ctx.children,
2269
2602
  cancelled: () => ctx.stopRequested.has(task.id),
2270
2603
  onSpawn: (pid) => {
@@ -2276,12 +2609,57 @@ async function runTaskAgentIn(ctx, task) {
2276
2609
  if (activity)
2277
2610
  ctx.onFeed(`[${activity}]`);
2278
2611
  },
2612
+ stdin: run.stdin,
2613
+ });
2614
+ };
2615
+ // The wrap-up runs without the message channel: it is told to change
2616
+ // nothing, so a message has to wait for the task's end, not reach it.
2617
+ const finishTimedOut = async (timedOut) => {
2618
+ if (!timedOut.sessionId || ctx.stopRequested.has(task.id))
2619
+ return timedOut;
2620
+ const wrapUp = await runOnce(WRAP_UP_PROMPT, {
2621
+ timeoutMs: WRAP_UP_TIMEOUT_MS,
2622
+ resumeSessionId: timedOut.sessionId,
2623
+ toolsDisabled: true,
2624
+ });
2625
+ logAgentUsage(`task ${task.id} wrap-up`, wrapUp.usage);
2626
+ addRunLedger(timedOut, wrapUp);
2627
+ if (!wrapUp.ok)
2628
+ return timedOut;
2629
+ timedOut.finalText = wrapUp.finalText;
2630
+ timedOut.finalTextFromResult = wrapUp.finalTextFromResult;
2631
+ return timedOut;
2632
+ };
2633
+ const resuming = task.interruptedFrom === 'running' && (task.resumeCount ?? 0) > 0;
2634
+ let resumeSessionId = resuming ? claudeSessionIdOf(dir) : undefined;
2635
+ const freshPrompt = resuming ? `${FRESH_AFTER_INTERRUPTION_PREFIX}\n\n${taskPrompt}` : taskPrompt;
2636
+ for (let attempt = 1; attempt <= MAX_TASK_ATTEMPTS; attempt++) {
2637
+ // A resumed session already holds the messages it was given; a fresh
2638
+ // conversation needs every one again.
2639
+ const resumed = resumeSessionId !== undefined;
2640
+ const stdin = taskStdin(ctx, task, {
2641
+ promptUuid: randomUUID(),
2642
+ resend: (steer) => (resumed ? isPendingSteer(steer) : steer.state !== 'undelivered'),
2643
+ });
2644
+ result = await runOnce(resumed ? RESUME_TASK_PROMPT : freshPrompt, {
2645
+ timeoutMs: TASK_TIMEOUT_MS,
2646
+ stdin,
2647
+ resumeSessionId,
2279
2648
  });
2280
2649
  logAgentUsage(`task ${task.id}`, result.usage);
2281
2650
  if (ctx.stopRequested.has(task.id))
2282
2651
  return result;
2652
+ if (resumeSessionId && missingResumeSession(result)) {
2653
+ resumeSessionId = undefined;
2654
+ // The fresh run gets a full set of attempts, even when the missing
2655
+ // session only surfaced after resume crashes had used some up.
2656
+ attempt = 0;
2657
+ continue;
2658
+ }
2659
+ if (result.timedOut)
2660
+ return finishTimedOut(result);
2283
2661
  if (!result.crashed)
2284
- return result;
2662
+ return resumeForLateSteers(ctx, task, result, runOnce);
2285
2663
  // A crash normally means "the process died, try again" -- but a claude CLI
2286
2664
  // that dies on a bad key or slug BEFORE emitting its result event also
2287
2665
  // lands here (crashed = never saw a result), and retrying that burns all
@@ -2298,6 +2676,96 @@ async function runTaskAgentIn(ctx, task) {
2298
2676
  result.error = `agent process kept dying (${MAX_TASK_ATTEMPTS} attempts): ${result.error ?? ''}`;
2299
2677
  return result;
2300
2678
  }
2679
+ // A message that reached the task after its run closed stdin, or one the run
2680
+ // never took in, goes to a resume of the same session: the task sees it as the
2681
+ // next message in the conversation it just had, not as a new brief.
2682
+ async function resumeForLateSteers(ctx, task, first, runOnce) {
2683
+ let result = first;
2684
+ for (let resume = 0; resume < MAX_TASK_RESUMES; resume++) {
2685
+ if (!ctx.steerChannel || !result.ok || !result.sessionId)
2686
+ break;
2687
+ if (!(task.steers ?? []).some(isPendingSteer) || ctx.stopRequested.has(task.id))
2688
+ break;
2689
+ const next = await resumeOnce(ctx, task, result.sessionId, runOnce);
2690
+ if (!next.ok) {
2691
+ // The task's own work finished; only the message failed to reach it, so
2692
+ // the task keeps its result and the message says why it never arrived.
2693
+ if (settleUndeliveredSteers(task, 'the task could not be resumed to read it'))
2694
+ ctx.onSteerChange();
2695
+ const ledger = combineRunResults(result, next);
2696
+ return { ...result, usage: ledger.usage, stats: ledger.stats };
2697
+ }
2698
+ result = combineRunResults(result, next);
2699
+ }
2700
+ return result;
2701
+ }
2702
+ // One resume of `sessionId` carrying the oldest pending message. Every message
2703
+ // it did not finish a turn on is still pending when it ends, so a retry -- for
2704
+ // any end but a provider's error result or a config failure -- carries them
2705
+ // all again.
2706
+ async function resumeOnce(ctx, task, sessionId, runOnce) {
2707
+ let next = { ok: false, finalText: '', error: 'not run' };
2708
+ for (let attempt = 1; attempt <= MAX_TASK_ATTEMPTS; attempt++) {
2709
+ const lead = (task.steers ?? []).find(isPendingSteer);
2710
+ if (!lead)
2711
+ return next;
2712
+ lead.state = 'queued';
2713
+ ctx.onSteerChange();
2714
+ const stdin = taskStdin(ctx, task, {
2715
+ promptUuid: lead.id,
2716
+ resend: (steer) => steer !== lead && isPendingSteer(steer),
2717
+ });
2718
+ next = await runOnce(steerMessageText(lead.text), { timeoutMs: TASK_TIMEOUT_MS, stdin, resumeSessionId: sessionId });
2719
+ logAgentUsage(`task ${task.id} resume`, next.usage);
2720
+ const final = next.ok || next.resultError || next.timedOut || next.failure?.kind === 'config';
2721
+ if (final || ctx.stopRequested.has(task.id))
2722
+ return next;
2723
+ if (attempt < MAX_TASK_ATTEMPTS && (await waitBeforeTaskRetry(attempt, ctx.stopRequested, task.id)))
2724
+ return next;
2725
+ }
2726
+ return next;
2727
+ }
2728
+ function heldForFromReply(messageId, text) {
2729
+ const chipPattern = /\[\[([^[\]\n]+)\]\]/g;
2730
+ const chips = [];
2731
+ let firstChipAt = -1;
2732
+ for (const match of text.matchAll(chipPattern)) {
2733
+ if (firstChipAt < 0)
2734
+ firstChipAt = match.index;
2735
+ const chip = match[1].trim();
2736
+ if (chip && !chips.includes(chip))
2737
+ chips.push(chip);
2738
+ }
2739
+ const beforeChips = firstChipAt < 0 ? text : text.slice(0, firstChipAt);
2740
+ const proseLines = beforeChips
2741
+ .replace(chipPattern, '')
2742
+ .split('\n')
2743
+ .map((line) => line.trim())
2744
+ .filter(Boolean);
2745
+ return {
2746
+ messageId,
2747
+ question: proseLines[proseLines.length - 1] ?? '',
2748
+ chips,
2749
+ };
2750
+ }
2751
+ function releaseHeldTasks(tasks, answer, touch, maybeStart) {
2752
+ const trimmed = answer.trim();
2753
+ if (!trimmed)
2754
+ return [];
2755
+ const released = [];
2756
+ const sorted = [...tasks.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
2757
+ for (const task of sorted) {
2758
+ if (task.status !== 'held' || !task.heldFor?.chips.includes(trimmed))
2759
+ continue;
2760
+ task.answer = trimmed;
2761
+ task.prompt += `\n\nThe user answered: ${trimmed}`;
2762
+ task.status = 'waiting';
2763
+ touch(task);
2764
+ maybeStart(task);
2765
+ released.push(task.id);
2766
+ }
2767
+ return released;
2768
+ }
2301
2769
  // The finishing attempt's numbers onto the record. Only one attempt ever has
2302
2770
  // any: runTaskAgentIn retries exactly the attempts that died before a result
2303
2771
  // event, so there is never an earlier set to add this one to.
@@ -2315,18 +2783,28 @@ function recordRunLedger(task, result) {
2315
2783
  if (modelUsage)
2316
2784
  task.modelUsage = modelUsage;
2317
2785
  }
2786
+ function steerChannelFor(ctx, taskId) {
2787
+ if (!TASK_STEER_ENABLED)
2788
+ return undefined;
2789
+ const channel = { write: null, closed: false };
2790
+ ctx.steerChannels.set(taskId, channel);
2791
+ return channel;
2792
+ }
2318
2793
  // Launch a task's agent run and wire up its finalization. The settle path is
2319
2794
  // hardened: result-finalization, onFinished, and the reschedule sweep each run
2320
2795
  // under their own try/catch so one bad task turn can neither wedge the board
2321
2796
  // (by skipping the slot free) nor crash the serve.
2322
2797
  function startTask(ctx, task) {
2323
2798
  const dir = path.join(ctx.tasksDir, task.id);
2324
- atomicWriteFileSync(path.join(dir, 'progress'), '0\n');
2799
+ if (!task.interruptedFrom)
2800
+ atomicWriteFileSync(path.join(dir, 'progress'), '0\n');
2325
2801
  if (!fs.existsSync(path.join(dir, 'notes.md')))
2326
2802
  atomicWriteFileSync(path.join(dir, 'notes.md'), '');
2327
2803
  const claudeModel = ctx.claudeModel();
2328
2804
  const openrouterModel = ctx.openrouterModel();
2329
2805
  const effort = ctx.effort();
2806
+ if (task.interruptedFrom && (task.resumeCount ?? 0) === 0)
2807
+ task.resumeCount = 1;
2330
2808
  task.status = 'running';
2331
2809
  task.startedAt = nowIso();
2332
2810
  task.model = spawnModelFor(claudeModel, openrouterModel);
@@ -2357,6 +2835,8 @@ function startTask(ctx, task) {
2357
2835
  finishedWork: planFinishedWork(ctx.sorted()),
2358
2836
  onFeed: (entry) => ctx.onFeed(task, entry),
2359
2837
  onRetry: (attempt) => ctx.onRetry(task, attempt),
2838
+ steerChannel: steerChannelFor(ctx, task.id),
2839
+ onSteerChange: () => ctx.touch(task),
2360
2840
  onSignal: (signal) => {
2361
2841
  let changed = false;
2362
2842
  if (typeof signal.progress === 'number' && signal.progress !== task.progress) {
@@ -2377,6 +2857,8 @@ function startTask(ctx, task) {
2377
2857
  };
2378
2858
  void runTaskAgentIn(runCtx, task)
2379
2859
  .then((result) => {
2860
+ if (ctx.finalizedAtShutdown.has(task.id))
2861
+ return;
2380
2862
  // Finalization (fs writes), onFinished, and the reschedule sweep must all
2381
2863
  // survive a throw -- otherwise a single bad task turn could both skip
2382
2864
  // freeing the slot (wedging the board) and crash the serve.
@@ -2385,16 +2867,20 @@ function startTask(ctx, task) {
2385
2867
  // path below throws.
2386
2868
  recordRunLedger(task, result);
2387
2869
  refreshTaskFiles(ctx.tasksDir, task);
2870
+ ctx.steerChannels.delete(task.id);
2388
2871
  const wasStopped = ctx.stopRequested.delete(task.id);
2389
2872
  task.status = wasStopped ? 'interrupted' : result.ok ? 'done' : 'failed';
2390
2873
  // A stopped task is cleared off the board (castle-stop = halt + remove).
2391
- if (wasStopped)
2874
+ if (wasStopped) {
2392
2875
  task.acknowledged = true;
2876
+ delete task.interruptedFrom;
2877
+ delete task.interruptedAt;
2878
+ }
2393
2879
  if (result.ok && !wasStopped)
2394
2880
  task.progress = 100;
2395
2881
  task.finishedAt = nowIso();
2396
2882
  task.resultSummary = wasStopped
2397
- ? 'stopped by the router'
2883
+ ? ROUTER_STOPPED_RESULT
2398
2884
  : result.ok
2399
2885
  ? result.finalText.slice(-RESULT_SUMMARY_CHARS)
2400
2886
  : `${result.error ?? 'failed'}\n${result.finalText.slice(-RESULT_SUMMARY_CHARS)}`;
@@ -2423,6 +2909,7 @@ function startTask(ctx, task) {
2423
2909
  console.error(`[task ${task.id}] finalization threw: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);
2424
2910
  // Best-effort: still mark the task terminal so it can't hang forever.
2425
2911
  try {
2912
+ ctx.steerChannels.delete(task.id);
2426
2913
  ctx.stopRequested.delete(task.id);
2427
2914
  task.status = 'failed';
2428
2915
  task.finishedAt = nowIso();
@@ -2445,9 +2932,12 @@ function startTask(ctx, task) {
2445
2932
  }
2446
2933
  })
2447
2934
  .catch((err) => {
2935
+ if (ctx.finalizedAtShutdown.has(task.id))
2936
+ return;
2448
2937
  // runTaskAgentIn itself rejected. Free the slot so the board keeps moving.
2449
2938
  console.error(`[task ${task.id}] run promise rejected: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);
2450
2939
  try {
2940
+ ctx.steerChannels.delete(task.id);
2451
2941
  ctx.stopRequested.delete(task.id);
2452
2942
  task.status = 'failed';
2453
2943
  task.finishedAt = nowIso();
@@ -2461,16 +2951,54 @@ function startTask(ctx, task) {
2461
2951
  ctx.rescheduleAll();
2462
2952
  });
2463
2953
  }
2464
- // Halt + remove an active task (castle-stop): a waiting or blocked one is
2954
+ function sendToTasks(store, directives, originMessageId) {
2955
+ const unsent = [];
2956
+ for (const directive of directives) {
2957
+ const [id] = resolveTargets(store.tasks, [directive.target]);
2958
+ const task = id ? store.tasks.get(id) : undefined;
2959
+ if (!task) {
2960
+ unsent.push(directive.target);
2961
+ continue;
2962
+ }
2963
+ sendToTask(task, directive.text, originMessageId, store.steerChannels.get(task.id));
2964
+ store.onFeed(task, '[message sent to this task]');
2965
+ store.touch(task);
2966
+ }
2967
+ return unsent;
2968
+ }
2969
+ // A waiting or held task gets the message with its prompt when it starts, and a
2970
+ // running one as soon as its stdin is up. A running task whose stdin already
2971
+ // closed holds it for a resume (resumeForLateSteers). Anything else cannot take
2972
+ // a message, and the board says so on the router's next turn.
2973
+ function sendToTask(task, text, originMessageId, channel) {
2974
+ const steer = newTaskSteer(text, nowIso(), originMessageId);
2975
+ task.steers = [...(task.steers ?? []), steer];
2976
+ if (task.status === 'waiting' || task.status === 'held')
2977
+ return steer;
2978
+ if (task.status !== 'running' || !channel) {
2979
+ steer.state = 'undelivered';
2980
+ steer.reason =
2981
+ task.status === 'blocked' ? 'the task is blocked and will not start' : 'the task had already finished';
2982
+ return steer;
2983
+ }
2984
+ if (channel.write)
2985
+ writeSteer(channel.write, steer);
2986
+ else if (channel.closed)
2987
+ steer.state = 'late';
2988
+ return steer;
2989
+ }
2990
+ // Halt + remove an active task (castle-stop): a held, waiting, or blocked one is
2465
2991
  // cancelled and cleared off the board immediately; a running one gets its
2466
2992
  // agent process killed and is cleared when it finalizes (the stopRequested
2467
2993
  // path acks it). No-op on terminal tasks. A "blocked" task never got a
2468
2994
  // process, so it collapses the same way "waiting" does -- this is the only
2469
2995
  // way a blocked row ever clears (see ROUTER_RULES).
2470
2996
  function haltTask(task, children, stopRequested, touch) {
2471
- if (task.status === 'waiting' || task.status === 'blocked') {
2997
+ if (task.status === 'held' || task.status === 'waiting' || task.status === 'blocked') {
2472
2998
  task.status = 'interrupted';
2473
2999
  task.acknowledged = true;
3000
+ delete task.interruptedFrom;
3001
+ delete task.interruptedAt;
2474
3002
  touch(task);
2475
3003
  }
2476
3004
  else if (task.status === 'running') {
@@ -2487,19 +3015,75 @@ function haltTask(task, children, stopRequested, touch) {
2487
3015
  }
2488
3016
  }
2489
3017
  }
2490
- function createTaskStore(opts) {
3018
+ // A recovered task runs again and is sent its pending messages then; one that
3019
+ // stays ended can never read them.
3020
+ function settleUnrecoveredSteers(tasksDir, tasks) {
3021
+ for (const task of tasks.values()) {
3022
+ if (!isTerminal(task.status))
3023
+ continue;
3024
+ const reason = task.status === 'interrupted' ? 'the task was interrupted when Castle restarted' : terminalSteerReason(task.status);
3025
+ if (settleUndeliveredSteers(task, reason))
3026
+ persistTaskFile(tasksDir, task);
3027
+ }
3028
+ }
3029
+ function recoverInterruptedTasks(tasksDir, tasks) {
3030
+ const now = Date.now();
3031
+ const recovered = new Set();
3032
+ for (const task of tasks.values()) {
3033
+ if (task.status !== 'interrupted' ||
3034
+ task.acknowledged ||
3035
+ task.resultSummary?.trim() ||
3036
+ !task.interruptedFrom ||
3037
+ (task.resumeCount ?? 0) > 0) {
3038
+ continue;
3039
+ }
3040
+ const interruptedAt = Date.parse(task.interruptedAt ?? '');
3041
+ const age = now - interruptedAt;
3042
+ if (!Number.isFinite(interruptedAt) || age < 0 || age > RESUME_MAX_AGE_MS)
3043
+ continue;
3044
+ task.status = 'waiting';
3045
+ task.updatedAt = nowIso();
3046
+ delete task.finishedAt;
3047
+ persistTaskFile(tasksDir, task);
3048
+ recovered.add(task.id);
3049
+ }
3050
+ for (const task of tasks.values()) {
3051
+ if (task.status !== 'blocked' ||
3052
+ !task.after.some((id) => recovered.has(id)) ||
3053
+ classifyDeps(tasks, task).kind === 'blocked') {
3054
+ continue;
3055
+ }
3056
+ task.status = 'waiting';
3057
+ task.updatedAt = nowIso();
3058
+ delete task.blockedBy;
3059
+ persistTaskFile(tasksDir, task);
3060
+ }
3061
+ }
3062
+ export function createTaskStore(opts) {
2491
3063
  const { deckDir, deckLabel, tasksDir, children } = opts;
2492
3064
  const tasks = loadTasks(tasksDir);
3065
+ recoverInterruptedTasks(tasksDir, tasks);
3066
+ settleUnrecoveredSteers(tasksDir, tasks);
2493
3067
  // Covers both a deck whose tasks predate the index and the interrupted-status
2494
3068
  // rewrites loadTasks just did.
2495
3069
  writeTaskIndex(tasksDir, tasks);
2496
3070
  // Tasks the router asked to stop: their killed process must not read as a
2497
3071
  // crash (no retry) and they finalize as interrupted, not failed.
2498
3072
  const stopRequested = new Set();
3073
+ const finalizedAtShutdown = new Set();
3074
+ const steerChannels = new Map();
2499
3075
  function sorted() {
2500
3076
  return [...tasks.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
2501
3077
  }
2502
3078
  function touch(task) {
3079
+ // Every terminal state is persisted through here, so this is where a
3080
+ // message the task can no longer read is settled -- whichever path ended it.
3081
+ // A record left interrupted for recovery (interruptedFrom) runs again and
3082
+ // is sent its pending messages then, so it keeps them; once that recovered
3083
+ // run ends, it settles like any other.
3084
+ if (isTerminal(task.status) && !(task.status === 'interrupted' && task.interruptedFrom)) {
3085
+ settleUndeliveredSteers(task, terminalSteerReason(task.status));
3086
+ }
2503
3087
  task.updatedAt = nowIso();
2504
3088
  persistTaskFile(tasksDir, task);
2505
3089
  writeTaskIndex(tasksDir, tasks);
@@ -2524,6 +3108,7 @@ function createTaskStore(opts) {
2524
3108
  if (deps.kind === 'blocked') {
2525
3109
  task.status = 'blocked';
2526
3110
  task.blockedBy = deps.blockedBy;
3111
+ settleUndeliveredSteers(task, 'the task is blocked and will not start');
2527
3112
  touch(task);
2528
3113
  return;
2529
3114
  }
@@ -2554,6 +3139,8 @@ function createTaskStore(opts) {
2554
3139
  children,
2555
3140
  tasks,
2556
3141
  stopRequested,
3142
+ finalizedAtShutdown,
3143
+ steerChannels,
2557
3144
  claudeModel: opts.claudeModel,
2558
3145
  openrouterModel: opts.openrouterModel,
2559
3146
  effort: opts.effort,
@@ -2566,7 +3153,7 @@ function createTaskStore(opts) {
2566
3153
  sorted,
2567
3154
  rescheduleAll,
2568
3155
  };
2569
- function spawnFromDirective(directive, originMessageId) {
3156
+ function spawnFromDirective(directive, originMessageId, originText = '') {
2570
3157
  const task = {
2571
3158
  id: nanoid(8),
2572
3159
  title: directive.title,
@@ -2574,12 +3161,13 @@ function createTaskStore(opts) {
2574
3161
  after: resolveTargets(tasks, directive.after),
2575
3162
  item: directive.item,
2576
3163
  playtest: taskPlaytestFor(deckDir),
2577
- status: 'waiting',
3164
+ status: directive.hold ? 'held' : 'waiting',
2578
3165
  progress: 0,
2579
3166
  notes: '',
2580
3167
  createdAt: nowIso(),
2581
3168
  updatedAt: nowIso(),
2582
3169
  originMessageId,
3170
+ ...(directive.hold ? { heldFor: heldForFromReply(originMessageId, originText) } : {}),
2583
3171
  };
2584
3172
  fs.mkdirSync(path.join(tasksDir, task.id), { recursive: true });
2585
3173
  tasks.set(task.id, task);
@@ -2589,6 +3177,7 @@ function createTaskStore(opts) {
2589
3177
  maybeStart(task);
2590
3178
  return task.id;
2591
3179
  }
3180
+ const releaseHeld = (answer) => releaseHeldTasks(tasks, answer, touch, maybeStart);
2592
3181
  function acknowledge(id, rejected) {
2593
3182
  const task = tasks.get(id);
2594
3183
  if (!task || !isTerminal(task.status) || task.acknowledged)
@@ -2626,7 +3215,23 @@ function createTaskStore(opts) {
2626
3215
  clearInterval(pollTimer);
2627
3216
  for (const task of tasks.values()) {
2628
3217
  if (task.status === 'running' || task.status === 'waiting') {
3218
+ const interruptedFrom = task.status;
3219
+ const routerStopped = stopRequested.has(task.id);
3220
+ if (interruptedFrom === 'running') {
3221
+ finalizedAtShutdown.add(task.id);
3222
+ stopRequested.add(task.id);
3223
+ }
2629
3224
  task.status = 'interrupted';
3225
+ if (routerStopped) {
3226
+ task.acknowledged = true;
3227
+ task.resultSummary = ROUTER_STOPPED_RESULT;
3228
+ task.finishedAt = nowIso();
3229
+ settleUndeliveredSteers(task, terminalSteerReason('interrupted'));
3230
+ }
3231
+ else {
3232
+ task.interruptedFrom = interruptedFrom;
3233
+ task.interruptedAt = nowIso();
3234
+ }
2630
3235
  task.updatedAt = nowIso();
2631
3236
  persistTaskFile(tasksDir, task);
2632
3237
  }
@@ -2643,14 +3248,17 @@ function createTaskStore(opts) {
2643
3248
  acknowledge(id, false);
2644
3249
  }
2645
3250
  // The router stops tasks by title or id (castle-stop fence), or "all" to
2646
- // stop everything still active. Waiting (and blocked -- a waiting task that
2647
- // will never start) tasks are cancelled outright; running ones get their
3251
+ // stop everything still active. Held, waiting, and blocked tasks are
3252
+ // cancelled outright; running ones get their
2648
3253
  // agent process killed and finalize as interrupted via the stopRequested
2649
3254
  // path (see haltTask).
2650
3255
  function stop(tokens) {
2651
3256
  const ids = meansAll(tokens)
2652
3257
  ? [...tasks.values()]
2653
- .filter((t) => t.status === 'running' || t.status === 'waiting' || t.status === 'blocked')
3258
+ .filter((t) => t.status === 'held' ||
3259
+ t.status === 'running' ||
3260
+ t.status === 'waiting' ||
3261
+ t.status === 'blocked')
2654
3262
  .map((t) => t.id)
2655
3263
  : resolveTargets(tasks, tokens);
2656
3264
  const targets = [];
@@ -2661,16 +3269,23 @@ function createTaskStore(opts) {
2661
3269
  targets.push({ id: task.id, title: task.title, status: task.status, progress: task.progress });
2662
3270
  haltTask(task, children, stopRequested, touch);
2663
3271
  }
3272
+ // A cancelled held or waiting row finalizes no run, so nothing else would
3273
+ // re-check the tasks waiting `after:` it; they flip to blocked here.
3274
+ if (targets.length > 0)
3275
+ rescheduleAll();
2664
3276
  return targets;
2665
3277
  }
2666
3278
  return {
3279
+ resumeRecovered: rescheduleAll,
2667
3280
  sorted,
2668
3281
  get: (id) => tasks.get(id),
2669
3282
  touch,
2670
3283
  spawnFromDirective,
3284
+ releaseHeld,
2671
3285
  acknowledge,
2672
3286
  checkOff,
2673
3287
  stop,
3288
+ send: (directives, originMessageId) => sendToTasks({ tasks, steerChannels, onFeed: opts.onFeed, touch }, directives, originMessageId),
2674
3289
  pendingDurables,
2675
3290
  clearPendingDurables,
2676
3291
  shutdown,
@@ -2685,11 +3300,12 @@ const ATTACHMENT_MIME = {
2685
3300
  webp: 'image/webp',
2686
3301
  };
2687
3302
  // Decode pasted/attached images (data URLs) into .castle/agent/attachments/.
2688
- // Returns the saved file names.
3303
+ // Returns the saved file names, and which of them carry the user's marks.
2689
3304
  function saveAttachments(attachmentsDir, messageId, images) {
2690
- if (!Array.isArray(images))
2691
- return [];
2692
3305
  const saved = [];
3306
+ const marked = [];
3307
+ if (!Array.isArray(images))
3308
+ return { saved, marked };
2693
3309
  for (const [index, image] of images.slice(0, MAX_ATTACHMENTS).entries()) {
2694
3310
  const dataUrl = image?.dataUrl;
2695
3311
  if (typeof dataUrl !== 'string' || dataUrl.length > MAX_ATTACHMENT_BYTES * 1.4)
@@ -2703,12 +3319,14 @@ function saveAttachments(attachmentsDir, messageId, images) {
2703
3319
  fs.mkdirSync(attachmentsDir, { recursive: true });
2704
3320
  atomicWriteFileSync(path.join(attachmentsDir, fileName), Buffer.from(match[2], 'base64'));
2705
3321
  saved.push(fileName);
3322
+ if (image.marked === true)
3323
+ marked.push(fileName);
2706
3324
  }
2707
3325
  catch {
2708
3326
  /* disk trouble -- skip this image */
2709
3327
  }
2710
3328
  }
2711
- return saved;
3329
+ return { saved, marked };
2712
3330
  }
2713
3331
  function isExistingFile(abs) {
2714
3332
  try {
@@ -2850,9 +3468,13 @@ function asPromptTask(task) {
2850
3468
  notes: task.notes,
2851
3469
  item: task.item,
2852
3470
  error: task.status === 'failed'
2853
- ? routerTaskError(firstErrorLine(task.resultSummary), task.failure, task.errorCopy)
3471
+ ? withTimeoutReport(routerTaskError(firstErrorLine(task.resultSummary), task.failure, task.errorCopy), task)
2854
3472
  : undefined,
3473
+ interrupted: platformInterruptionReason(task),
2855
3474
  blockedBy: task.status === 'blocked' ? task.blockedBy : undefined,
3475
+ sent: TASK_STEER_ENABLED ? steerBoardNote(task.steers) : undefined,
3476
+ heldQuestion: task.status === 'held' ? task.heldFor?.question : undefined,
3477
+ answer: task.answer,
2856
3478
  };
2857
3479
  }
2858
3480
  function asClientTask(task, signPath) {
@@ -2869,6 +3491,8 @@ function asClientTask(task, signPath) {
2869
3491
  account: task.account,
2870
3492
  avatar: task.avatar,
2871
3493
  phase: task.phase,
3494
+ heldFor: task.heldFor,
3495
+ answer: task.answer,
2872
3496
  acknowledged: task.acknowledged,
2873
3497
  rejected: task.rejected,
2874
3498
  errorCopy: task.errorCopy,
@@ -3098,6 +3722,8 @@ function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
3098
3722
  // rewrites CLAUDE.md, and the next turn has to see the kit's guide.
3099
3723
  const deckGuide = readQuickReference(ctx.deckDir);
3100
3724
  const messages = ctx.log.messages.filter((message) => message.role !== 'log' && message.id !== selfMessageId && message.status !== 'streaming');
3725
+ const tasks = ctx.taskStore.sorted();
3726
+ const lastReplyAtMs = panelWriteWatermark(ctx.log.messages, selfMessageId);
3101
3727
  return buildRouterPromptParts({
3102
3728
  deckLabel: ctx.deckLabel,
3103
3729
  quickReference: quickReferenceFor(ctx.deckDir, deckGuide, 'router'),
@@ -3107,6 +3733,10 @@ function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
3107
3733
  playtest: playtestEnabled(ctx.deckDir),
3108
3734
  playtestPref: playtestPrefFor(ctx.deckDir),
3109
3735
  askCalls: askCallsEnabled(ctx.deckDir),
3736
+ steer: TASK_STEER_ENABLED || undefined,
3737
+ unsentSends: TASK_STEER_ENABLED
3738
+ ? messages.filter((m) => m.role === 'assistant').at(-1)?.unsent
3739
+ : undefined,
3110
3740
  messages: messages.map((m) => ({
3111
3741
  role: m.role,
3112
3742
  // Replace a prior turn's raw ```ask JSON with a readable question list
@@ -3120,15 +3750,15 @@ function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
3120
3750
  progress: note.progress,
3121
3751
  repliesAgo: note.repliesAgo,
3122
3752
  })),
3753
+ endedBadly: badTaskEndingsSince(tasks, lastReplyAtMs).map(asPromptTask),
3123
3754
  // Only the live board -- match what the user sees. Hide tasks that are
3124
3755
  // BOTH acknowledged AND finished; an active (running/waiting) task always
3125
3756
  // shows even if somehow acked, so nothing can ever go invisible mid-work.
3126
- tasks: ctx.taskStore
3127
- .sorted()
3757
+ tasks: tasks
3128
3758
  .filter((t) => !(t.acknowledged && isTerminal(t.status)))
3129
3759
  .map(asPromptTask),
3130
- plan: routerPlanOpts(ctx.deckDir, plan, ctx.taskStore.pendingDurables(), ctx.taskStore.sorted()),
3131
- paramsWrites: panelWritesSince(ctx.deckDir, panelWriteWatermark(ctx.log.messages, selfMessageId)),
3760
+ plan: routerPlanOpts(ctx.deckDir, plan, ctx.taskStore.pendingDurables(), tasks),
3761
+ paramsWrites: panelWritesSince(ctx.deckDir, lastReplyAtMs),
3132
3762
  instruction,
3133
3763
  });
3134
3764
  }
@@ -3194,15 +3824,23 @@ function spawnCompletedTaskFences(ctx, message, midStream, raw) {
3194
3824
  return;
3195
3825
  const inFlight = new Set(ctx.taskStore
3196
3826
  .sorted()
3197
- .filter((t) => t.status === 'running' || t.status === 'waiting')
3827
+ .filter((t) => t.status === 'held' || t.status === 'running' || t.status === 'waiting')
3198
3828
  .map((t) => t.title.toLowerCase()));
3199
3829
  const newIds = [];
3200
3830
  for (const { directive, at } of directives) {
3201
3831
  const key = directive.title.toLowerCase();
3832
+ // A held task needs the reply's question and chips, which may stream after
3833
+ // its fence; the settle-time parse spawns it from the whole reply instead.
3834
+ // Every fence after it waits too: one may name it in `after:`, and that
3835
+ // only resolves once the held row exists.
3836
+ if (directive.hold)
3837
+ midStream.sawHold = true;
3838
+ if (midStream.sawHold)
3839
+ continue;
3202
3840
  if (inFlight.has(key) || midStream.spawnedTitles.has(key))
3203
3841
  continue;
3204
3842
  applyStreamedPrefs(ctx, raw.slice(0, at));
3205
- newIds.push(ctx.taskStore.spawnFromDirective(directive, message.id));
3843
+ newIds.push(ctx.taskStore.spawnFromDirective(directive, message.id, message.text));
3206
3844
  midStream.spawnedTitles.add(key);
3207
3845
  }
3208
3846
  if (newIds.length === 0)
@@ -3298,9 +3936,16 @@ function runRouterTurnIn(ctx, instruction) {
3298
3936
  settleInterruptedTurn(ctx, message);
3299
3937
  return;
3300
3938
  }
3301
- const { cleaned, directives, checkoffs, stops, prefs, plan } = extractDirectives(result.finalText);
3939
+ const { cleaned, directives, checkoffs, stops, prefs, sends, plan } = extractDirectives(result.finalText, {
3940
+ sends: TASK_STEER_ENABLED,
3941
+ });
3302
3942
  if (result.ok && checkoffs.length > 0)
3303
3943
  ctx.taskStore.checkOff(checkoffs);
3944
+ if (result.ok && sends.length > 0) {
3945
+ const unsent = ctx.taskStore.send(sends, message.id);
3946
+ if (unsent.length > 0)
3947
+ message.unsent = unsent;
3948
+ }
3304
3949
  if (result.ok && stops.length > 0) {
3305
3950
  const notes = stopNotes(ctx.taskStore.stop(stops));
3306
3951
  if (notes.length > 0)
@@ -3333,13 +3978,19 @@ function runRouterTurnIn(ctx, instruction) {
3333
3978
  const stale = epoch !== ctx.currentEpoch();
3334
3979
  const inFlight = new Set(ctx.taskStore
3335
3980
  .sorted()
3336
- .filter((t) => t.status === 'running' || t.status === 'waiting')
3981
+ .filter((t) => t.status === 'held' || t.status === 'running' || t.status === 'waiting')
3337
3982
  .map((t) => t.title.toLowerCase()));
3983
+ // A failed reply may have died before its chips, and a held row with
3984
+ // none can never be released by a tap. Everything after that fence goes
3985
+ // with it: a later one may wait on it, and without the row it would
3986
+ // start at once.
3987
+ const firstHold = directives.findIndex((d) => d.hold);
3988
+ const settled = result.ok || firstHold < 0 ? directives : directives.slice(0, firstHold);
3338
3989
  const toSpawn = stale
3339
3990
  ? []
3340
- : directives.filter((d) => !inFlight.has(d.title.toLowerCase()) &&
3991
+ : settled.filter((d) => !inFlight.has(d.title.toLowerCase()) &&
3341
3992
  !midStream.spawnedTitles.has(d.title.toLowerCase()));
3342
- const newlySpawnedIds = toSpawn.map((d) => ctx.taskStore.spawnFromDirective(d, message.id));
3993
+ const newlySpawnedIds = toSpawn.map((d) => ctx.taskStore.spawnFromDirective(d, message.id, cleaned));
3343
3994
  const taskIds = [...(message.taskIds ?? []), ...newlySpawnedIds];
3344
3995
  if (result.ok) {
3345
3996
  message.text = cleaned;
@@ -3663,6 +4314,47 @@ function startChildRegistry(registryPath, groups) {
3663
4314
  }
3664
4315
  };
3665
4316
  }
4317
+ // -- agent server -------------------------------------------------------------
4318
+ // The eval's way to put a message into a task at the moment a user sent it,
4319
+ // without a router turn in between: the same send a castle-send fence makes.
4320
+ function handleSendTask(taskStore, socket, msg) {
4321
+ const requestId = typeof msg.requestId === 'string' ? msg.requestId : undefined;
4322
+ const task = typeof msg.task === 'string' ? msg.task.trim() : '';
4323
+ const text = typeof msg.text === 'string' ? msg.text.trim() : '';
4324
+ const reply = (payload) => {
4325
+ if (socket.readyState === socket.OPEN) {
4326
+ socket.send(JSON.stringify({ type: 'send-task-result', requestId, ...payload }));
4327
+ }
4328
+ };
4329
+ if (!task || !text) {
4330
+ reply({ error: 'send-task needs a task title or id and a non-empty text' });
4331
+ return;
4332
+ }
4333
+ const unsent = taskStore.send([{ target: task, text }], `send-task:${requestId ?? 'anon'}`);
4334
+ reply(unsent.length > 0 ? { error: `send-task named no task on the board: ${task}` } : { ok: true });
4335
+ }
4336
+ // The eval's castle-stop: the same halt a router fence makes, so a stopped task
4337
+ // finalizes interrupted instead of reading as a crash that gets retried.
4338
+ function handleStopTask(taskStore, socket, msg) {
4339
+ const requestId = typeof msg.requestId === 'string' ? msg.requestId : undefined;
4340
+ const task = typeof msg.task === 'string' ? msg.task.trim() : '';
4341
+ const stopped = (task ? taskStore.stop([task]) : []).filter((t) => ['running', 'waiting', 'blocked'].includes(t.status));
4342
+ if (socket.readyState === socket.OPEN) {
4343
+ socket.send(JSON.stringify({
4344
+ type: 'stop-task-result',
4345
+ requestId,
4346
+ ...(stopped.length > 0 ? { stopped: stopped.map((t) => t.id) } : { error: `stop-task named no task: ${task}` }),
4347
+ }));
4348
+ }
4349
+ }
4350
+ // A mirror on disk is not evidence: only names that are also this send's
4351
+ // attachments count as marked.
4352
+ function markedOf(item) {
4353
+ if (!Array.isArray(item.marked))
4354
+ return {};
4355
+ const marked = item.marked.filter((name) => typeof name === 'string' && item.attachments.includes(name));
4356
+ return marked.length > 0 ? { marked } : {};
4357
+ }
3666
4358
  // Restart recovery: load the durable queue mirror, keeping only well-formed
3667
4359
  // sends that never reached the message log. A send whose id is already in
3668
4360
  // messages.json was committed by a prior drain (its turn ran, finished or
@@ -3683,6 +4375,7 @@ function loadRecoverableSends(deckDir, pendingPath, committedIds) {
3683
4375
  id: item.id,
3684
4376
  text: item.text,
3685
4377
  attachments: item.attachments.filter((a) => typeof a === 'string'),
4378
+ ...markedOf(item),
3686
4379
  // Re-validated rather than trusted: enqueue is where a ref earns its
3687
4380
  // place, and a mirror on disk is not evidence it ever did. A build that
3688
4381
  // predates @-mentions wrote none at all, which is a send worth
@@ -3778,6 +4471,7 @@ function startRouterTurn(ctx, instruction) {
3778
4471
  function commitDrainedSends(drained, log) {
3779
4472
  const texts = [];
3780
4473
  const attachmentPaths = [];
4474
+ const markedPaths = [];
3781
4475
  const refs = [];
3782
4476
  for (const item of drained) {
3783
4477
  if (!item.logged) {
@@ -3799,11 +4493,14 @@ function commitDrainedSends(drained, log) {
3799
4493
  if (item.text.trim())
3800
4494
  texts.push(item.text);
3801
4495
  for (const name of item.attachments) {
3802
- attachmentPaths.push(path.join('.castle', 'agent', 'attachments', name));
4496
+ const attachmentPath = path.join('.castle', 'agent', 'attachments', name);
4497
+ attachmentPaths.push(attachmentPath);
4498
+ if (item.marked?.includes(name))
4499
+ markedPaths.push(attachmentPath);
3803
4500
  }
3804
4501
  refs.push(...item.refs);
3805
4502
  }
3806
- return { texts, attachmentPaths, refs: uniqueLocators(refs) };
4503
+ return { texts, attachmentPaths, markedPaths, refs: uniqueLocators(refs) };
3807
4504
  }
3808
4505
  // Drain the queue into the log as real user messages and start one follow-up
3809
4506
  // turn addressing them all (a burst batches into a single turn). A pending
@@ -3819,7 +4516,13 @@ function maybeStartRouterQueueTurn(ctx) {
3819
4516
  // Kept so a fold or manual interrupt of THIS turn can hand these sends back
3820
4517
  // to reclaimInFlightSends if it dies before producing anything visible.
3821
4518
  state.inFlightSends = drained;
3822
- const { texts, attachmentPaths, refs } = commitDrainedSends(drained, ctx.log);
4519
+ // Released at drain, not enqueue: a queued tap can still be cancelled. And
4520
+ // before the commit: recovery skips a committed send, so a crash between
4521
+ // the two must find the send still pending, where replaying it is a no-op.
4522
+ for (const send of drained)
4523
+ if (!send.hideFromUi)
4524
+ ctx.taskStore.releaseHeld(send.text);
4525
+ const { texts, attachmentPaths, markedPaths, refs } = commitDrainedSends(drained, ctx.log);
3823
4526
  // The queue is now committed to messages.json; clear its durable mirror.
3824
4527
  persistPendingSends(ctx);
3825
4528
  const draft = state.pendingInterruptedDraft;
@@ -3830,6 +4533,7 @@ function maybeStartRouterQueueTurn(ctx) {
3830
4533
  messages: texts,
3831
4534
  interruptedDraft: draft || undefined,
3832
4535
  attachments: attachmentPaths,
4536
+ marked: markedPaths,
3833
4537
  refs,
3834
4538
  }));
3835
4539
  }
@@ -3909,11 +4613,12 @@ function handleQueueUserMessage(ctx, text, images, refs, clientId, hideFromUi) {
3909
4613
  return;
3910
4614
  }
3911
4615
  const id = sentId ?? nanoid(8);
3912
- const attachments = saveAttachments(ctx.attachmentsDir, id, images);
4616
+ const { saved: attachments, marked } = saveAttachments(ctx.attachmentsDir, id, images);
3913
4617
  state.pendingSends.push({
3914
4618
  id,
3915
4619
  text,
3916
4620
  attachments,
4621
+ ...(marked.length > 0 ? { marked } : {}),
3917
4622
  refs: validMessageRefs(ctx.deckDir, refs),
3918
4623
  ...(hideFromUi ? { hideFromUi: true } : {}),
3919
4624
  });
@@ -4054,10 +4759,22 @@ function makePlaytestRunner(deps) {
4054
4759
  };
4055
4760
  }
4056
4761
  // 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));
4762
+ // A held task writes nothing until its answer comes, which may be never, so it
4763
+ // must not hold the deck busy or block its commits.
4764
+ export function taskBoardIdle(taskStore) {
4765
+ const all = taskStore.sorted();
4766
+ const byId = new Map(all.map((t) => [t.id, t]));
4767
+ return !all.some((t) => t.status === 'running' ||
4768
+ (t.status === 'waiting' && !t.acknowledged && !waitsOnHeld(t, byId, new Set())));
4769
+ }
4770
+ function waitsOnHeld(task, byId, seen) {
4771
+ seen.add(task.id);
4772
+ return task.after.some((depId) => {
4773
+ const dep = byId.get(depId);
4774
+ if (!dep || seen.has(dep.id))
4775
+ return false;
4776
+ return dep.status === 'held' || (dep.status === 'waiting' && waitsOnHeld(dep, byId, seen));
4777
+ });
4061
4778
  }
4062
4779
  export function createAgentServer(opts) {
4063
4780
  const { deckDir, deckLabel } = opts;
@@ -4218,6 +4935,11 @@ export function createAgentServer(opts) {
4218
4935
  }
4219
4936
  }
4220
4937
  function handleTaskAck(id, rejected) {
4938
+ const task = taskStore.get(id);
4939
+ if (task?.status === 'held') {
4940
+ taskStore.stop([id]);
4941
+ return;
4942
+ }
4221
4943
  taskStore.acknowledge(id, rejected);
4222
4944
  }
4223
4945
  // `after` goes through the same resolveTargets the router's fences use, so a
@@ -4327,6 +5049,12 @@ export function createAgentServer(opts) {
4327
5049
  else if (msg.type === 'spawn-task' && SPAWN_TASK_MESSAGE_ENABLED) {
4328
5050
  handleSpawnTask(socket, msg);
4329
5051
  }
5052
+ else if (msg.type === 'send-task' && SPAWN_TASK_MESSAGE_ENABLED && TASK_STEER_ENABLED) {
5053
+ handleSendTask(taskStore, socket, msg);
5054
+ }
5055
+ else if (msg.type === 'stop-task' && SPAWN_TASK_MESSAGE_ENABLED) {
5056
+ handleStopTask(taskStore, socket, msg);
5057
+ }
4330
5058
  else if (msg.type === 'set-settings') {
4331
5059
  applySettings(msg);
4332
5060
  }
@@ -4403,5 +5131,11 @@ export function createAgentServer(opts) {
4403
5131
  wss.close();
4404
5132
  void playtestBrowserManager?.shutdown();
4405
5133
  }
4406
- return { handleUpgrade, handleHttpRequest, runPlaytestFor, shutdown };
5134
+ return {
5135
+ handleUpgrade,
5136
+ handleHttpRequest,
5137
+ runPlaytestFor,
5138
+ resumeRecovered: () => taskStore.resumeRecovered(),
5139
+ shutdown,
5140
+ };
4407
5141
  }