castle-web-cli 0.4.224 → 0.4.226
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-failures.js +4 -2
- package/dist/agent-prompts.d.ts +27 -1
- package/dist/agent-prompts.js +99 -24
- package/dist/agent.d.ts +61 -3
- package/dist/agent.js +825 -89
- package/dist/castle-host/host.js +57 -0
- package/dist/castleJson.d.ts +0 -1
- package/dist/init.js +1 -1
- package/dist/routerFences.d.ts +6 -1
- package/dist/routerFences.js +33 -7
- package/dist/routerTaskEndings.d.ts +13 -0
- package/dist/routerTaskEndings.js +29 -0
- package/dist/save-deck.d.ts +11 -1
- package/dist/save-deck.js +130 -22
- package/dist/serve.js +3 -0
- package/dist/shell/assets/index-4G5NKIQ8.css +1 -0
- package/dist/shell/assets/{index-D9oRe6Yi.js → index-C7ksEq3_.js} +96 -93
- package/dist/shell/index.html +2 -2
- package/dist/taskSteer.d.ts +24 -0
- package/dist/taskSteer.js +58 -0
- package/kits/base/CLAUDE.md +1 -1
- package/kits/base/castle.json +1 -1
- package/kits/base/sdk/README.md +38 -6
- package/kits/base/sdk/castle.d.ts +1 -1
- package/kits/base/sdk/commands.d.ts +16 -0
- package/kits/base/sdk/store.d.ts +17 -0
- package/kits/base/sdk/store.js +10 -0
- package/package.json +2 -2
- package/dist/shell/assets/index-BrKPEU3b.css +0 -1
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
|
|
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;
|
|
@@ -628,23 +653,6 @@ function planSession(deckDir) {
|
|
|
628
653
|
planSessions.set(deckDir, session);
|
|
629
654
|
return session;
|
|
630
655
|
}
|
|
631
|
-
const askCallsSessions = new Map();
|
|
632
|
-
// The inverse of planDefault: dormant until someone asks for it.
|
|
633
|
-
function askCallsDefault() {
|
|
634
|
-
return process.env.CASTLE_AGENT_ASK_CALLS === 'on';
|
|
635
|
-
}
|
|
636
|
-
// Resolved once per deck and cached for the reason planSession is: it decides
|
|
637
|
-
// what sits in the prompt's cached prefix, so honoring a mid-session change
|
|
638
|
-
// would split the prompt cache. Changing it takes a serve restart.
|
|
639
|
-
export function askCallsEnabled(deckDir) {
|
|
640
|
-
const cached = askCallsSessions.get(deckDir);
|
|
641
|
-
if (cached !== undefined)
|
|
642
|
-
return cached;
|
|
643
|
-
const declared = readCastleJson(deckDir)?.agent?.askCalls;
|
|
644
|
-
const enabled = declared === 'on' ? true : declared === 'off' ? false : askCallsDefault();
|
|
645
|
-
askCallsSessions.set(deckDir, enabled);
|
|
646
|
-
return enabled;
|
|
647
|
-
}
|
|
648
656
|
function readPlanSnapshot(deckDir) {
|
|
649
657
|
let raw;
|
|
650
658
|
try {
|
|
@@ -717,7 +725,9 @@ function planOpSources(taskStore, messages) {
|
|
|
717
725
|
const taskReports = new Map();
|
|
718
726
|
for (const task of taskStore.sorted()) {
|
|
719
727
|
const row = asPromptTask(task);
|
|
720
|
-
const text = [task.durable, row.error, row.notes]
|
|
728
|
+
const text = [task.durable, row.error, row.interrupted, row.notes]
|
|
729
|
+
.filter((s) => s?.trim())
|
|
730
|
+
.join('\n');
|
|
721
731
|
if (text)
|
|
722
732
|
taskReports.set(task.id, text);
|
|
723
733
|
}
|
|
@@ -1128,8 +1138,10 @@ function createAgentStreamState() {
|
|
|
1128
1138
|
usage: undefined,
|
|
1129
1139
|
stats: undefined,
|
|
1130
1140
|
sawResult: false,
|
|
1141
|
+
sessionId: undefined,
|
|
1131
1142
|
needsGap: false,
|
|
1132
1143
|
pendingTools: new Map(),
|
|
1144
|
+
resultMark: 0,
|
|
1133
1145
|
};
|
|
1134
1146
|
}
|
|
1135
1147
|
function parseCliUsage(raw) {
|
|
@@ -1249,7 +1261,10 @@ function makeAgentEventHandler(opts, state) {
|
|
|
1249
1261
|
opts.onActivity?.(null);
|
|
1250
1262
|
};
|
|
1251
1263
|
const handleClaudeEvent = (ev) => {
|
|
1252
|
-
if (ev.type === '
|
|
1264
|
+
if (ev.type === 'system' && ev.subtype === 'init' && typeof ev.session_id === 'string') {
|
|
1265
|
+
state.sessionId = ev.session_id;
|
|
1266
|
+
}
|
|
1267
|
+
else if (ev.type === 'stream_event') {
|
|
1253
1268
|
const e = ev.event;
|
|
1254
1269
|
if (e?.type === 'content_block_start') {
|
|
1255
1270
|
if (e.content_block?.type === 'tool_use') {
|
|
@@ -1305,12 +1320,17 @@ function makeAgentEventHandler(opts, state) {
|
|
|
1305
1320
|
}
|
|
1306
1321
|
}
|
|
1307
1322
|
else if (ev.type === 'result') {
|
|
1308
|
-
state.sawResult = true;
|
|
1309
1323
|
// An EMPTY string result falls back to the streamed text. Models that
|
|
1310
1324
|
// return their blocks as `text, thinking` (gemini through OpenRouter's
|
|
1311
1325
|
// anthropic-compatible endpoint) end the turn on an empty thinking block,
|
|
1312
1326
|
// and the CLI reports `result: ""` even though the answer streamed fine.
|
|
1313
|
-
const closing = closingMessageOf(ev.result, state.accumulated);
|
|
1327
|
+
const closing = closingMessageOf(ev.result, state.accumulated.slice(state.resultMark));
|
|
1328
|
+
state.resultMark = state.accumulated.length;
|
|
1329
|
+
if (state.sawResult) {
|
|
1330
|
+
mergeLaterResult(state, closing, ev);
|
|
1331
|
+
return;
|
|
1332
|
+
}
|
|
1333
|
+
state.sawResult = true;
|
|
1314
1334
|
state.finalText = closing.finalText;
|
|
1315
1335
|
state.finalTextFromResult = closing.fromResult;
|
|
1316
1336
|
state.resultIsError = ev.is_error === true;
|
|
@@ -1320,6 +1340,30 @@ function makeAgentEventHandler(opts, state) {
|
|
|
1320
1340
|
};
|
|
1321
1341
|
return handleClaudeEvent;
|
|
1322
1342
|
}
|
|
1343
|
+
// A stream-json run answers each stdin message that arrived after its first
|
|
1344
|
+
// turn ended with a turn of its own, and a result for each. Measured on claude
|
|
1345
|
+
// 2.1.284: total_cost_usd, duration_api_ms and modelUsage are running totals for
|
|
1346
|
+
// the process, so the latest wins; usage and num_turns cover that turn alone,
|
|
1347
|
+
// so they add up. The closing text keeps every turn's answer in order. A later
|
|
1348
|
+
// turn's error is that message's outcome (AgentStdin.onResult), not the run's.
|
|
1349
|
+
function mergeLaterResult(state, closing, ev) {
|
|
1350
|
+
state.finalText = [state.finalText, closing.finalText].filter(Boolean).join('\n\n');
|
|
1351
|
+
state.finalTextFromResult = state.finalTextFromResult && closing.fromResult;
|
|
1352
|
+
state.usage = addCliUsage(state.usage, parseCliUsage(ev.usage));
|
|
1353
|
+
const later = parseCliRunStats(ev);
|
|
1354
|
+
if (!later)
|
|
1355
|
+
return;
|
|
1356
|
+
const numTurns = state.stats?.numTurns !== undefined && later.numTurns !== undefined
|
|
1357
|
+
? state.stats.numTurns + later.numTurns
|
|
1358
|
+
: (later.numTurns ?? state.stats?.numTurns);
|
|
1359
|
+
state.stats = { ...state.stats, ...later, ...(numTurns !== undefined ? { numTurns } : {}) };
|
|
1360
|
+
}
|
|
1361
|
+
// A stream-json run whose first turn succeeded did the work it was spawned for
|
|
1362
|
+
// even if the process then dies or hangs in a later turn; that turn's message
|
|
1363
|
+
// is still `taken`, which is pending, and goes to a resume.
|
|
1364
|
+
function streamRunOk(opts, state) {
|
|
1365
|
+
return opts.stdin !== undefined && state.sawResult && !state.resultIsError;
|
|
1366
|
+
}
|
|
1323
1367
|
// How long a settled run waits for its log stream to flush before resolving
|
|
1324
1368
|
// anyway. Long enough that an ordinary append always lands first (so a retry's
|
|
1325
1369
|
// next attempt cannot interleave with it), short enough that a wedged disk
|
|
@@ -1338,13 +1382,13 @@ function runAgentCli(opts) {
|
|
|
1338
1382
|
// unclassified and the composer spins forever with nothing shown. Settle
|
|
1339
1383
|
// it here in the same shape that handler uses so it lands on the normal
|
|
1340
1384
|
// "spawn" copy instead. The declared type mirrors the stdio tuple below:
|
|
1341
|
-
// stdin
|
|
1385
|
+
// stdin piped only for a stream-json run, stdout/stderr piped.
|
|
1342
1386
|
let child;
|
|
1343
1387
|
try {
|
|
1344
1388
|
child = spawn(opts.command, opts.args, {
|
|
1345
1389
|
cwd: opts.cwd,
|
|
1346
1390
|
env: opts.env,
|
|
1347
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1391
|
+
stdio: [opts.stdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],
|
|
1348
1392
|
});
|
|
1349
1393
|
}
|
|
1350
1394
|
catch (err) {
|
|
@@ -1399,10 +1443,28 @@ function runAgentCli(opts) {
|
|
|
1399
1443
|
let stderrTail = '';
|
|
1400
1444
|
let lineBuffer = '';
|
|
1401
1445
|
const state = createAgentStreamState();
|
|
1446
|
+
// The CLI stays up after a result for as long as stdin is open, and this
|
|
1447
|
+
// run only settles on exit -- so stdin closes at the first result. Every
|
|
1448
|
+
// line already written by then is still answered, each as a turn of its
|
|
1449
|
+
// own, before the process exits (measured on claude 2.1.284).
|
|
1450
|
+
let stdinOpen = false;
|
|
1451
|
+
const closeStdin = () => {
|
|
1452
|
+
if (!stdinOpen)
|
|
1453
|
+
return;
|
|
1454
|
+
stdinOpen = false;
|
|
1455
|
+
opts.stdin?.bind(null);
|
|
1456
|
+
try {
|
|
1457
|
+
child.stdin?.end();
|
|
1458
|
+
}
|
|
1459
|
+
catch {
|
|
1460
|
+
/* already gone */
|
|
1461
|
+
}
|
|
1462
|
+
};
|
|
1402
1463
|
const settle = (result) => {
|
|
1403
1464
|
if (settled)
|
|
1404
1465
|
return;
|
|
1405
1466
|
settled = true;
|
|
1467
|
+
closeStdin();
|
|
1406
1468
|
clearTimeout(timeout);
|
|
1407
1469
|
opts.children.delete(child);
|
|
1408
1470
|
// Resolve only once the log's buffered lines have actually reached disk.
|
|
@@ -1436,20 +1498,39 @@ function runAgentCli(opts) {
|
|
|
1436
1498
|
finishFlush();
|
|
1437
1499
|
}
|
|
1438
1500
|
};
|
|
1501
|
+
// A timed-out stream run settles once its stdout has drained (the close event),
|
|
1502
|
+
// so every frame the process wrote before it died is counted and none
|
|
1503
|
+
// arrives after the caller has moved on -- a resume must never see the old
|
|
1504
|
+
// run's replay or result. The drain wait is bounded; past it, later frames
|
|
1505
|
+
// are dropped rather than applied. A one-shot run settles at the kill.
|
|
1506
|
+
let timedOut = false;
|
|
1507
|
+
let drainTimer;
|
|
1508
|
+
const settleTimedOut = () => {
|
|
1509
|
+
clearTimeout(drainTimer);
|
|
1510
|
+
const ok = streamRunOk(opts, state);
|
|
1511
|
+
settle({
|
|
1512
|
+
ok,
|
|
1513
|
+
finalText: state.finalText || state.accumulated,
|
|
1514
|
+
error: ok ? undefined : 'agent run timed out',
|
|
1515
|
+
usage: state.usage,
|
|
1516
|
+
stats: state.stats,
|
|
1517
|
+
timedOut: !ok,
|
|
1518
|
+
sessionId: state.sessionId,
|
|
1519
|
+
resultError: state.resultIsError,
|
|
1520
|
+
});
|
|
1521
|
+
};
|
|
1439
1522
|
const timeout = setTimeout(() => {
|
|
1523
|
+
timedOut = true;
|
|
1440
1524
|
try {
|
|
1441
1525
|
child.kill('SIGKILL');
|
|
1442
1526
|
}
|
|
1443
1527
|
catch {
|
|
1444
1528
|
/* already gone */
|
|
1445
1529
|
}
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
usage: state.usage,
|
|
1451
|
-
stats: state.stats,
|
|
1452
|
-
});
|
|
1530
|
+
if (opts.stdin)
|
|
1531
|
+
drainTimer = setTimeout(settleTimedOut, TIMEOUT_DRAIN_MS);
|
|
1532
|
+
else
|
|
1533
|
+
settleTimedOut();
|
|
1453
1534
|
}, opts.timeoutMs);
|
|
1454
1535
|
const handleEvent = makeAgentEventHandler(opts, state);
|
|
1455
1536
|
child.stdout.on('data', (chunk) => {
|
|
@@ -1458,10 +1539,18 @@ function runAgentCli(opts) {
|
|
|
1458
1539
|
while (nl >= 0) {
|
|
1459
1540
|
const line = lineBuffer.slice(0, nl);
|
|
1460
1541
|
lineBuffer = lineBuffer.slice(nl + 1);
|
|
1461
|
-
if (line.trim()) {
|
|
1542
|
+
if (line.trim() && !(settled && opts.stdin)) {
|
|
1462
1543
|
writeLog(line + '\n');
|
|
1463
1544
|
try {
|
|
1464
|
-
|
|
1545
|
+
const ev = JSON.parse(line);
|
|
1546
|
+
handleEvent(ev);
|
|
1547
|
+
const replayed = replayedUuid(ev);
|
|
1548
|
+
if (replayed)
|
|
1549
|
+
opts.stdin?.onReplay(replayed);
|
|
1550
|
+
if (ev.type === 'result') {
|
|
1551
|
+
opts.stdin?.onResult(ev.is_error !== true);
|
|
1552
|
+
closeStdin();
|
|
1553
|
+
}
|
|
1465
1554
|
}
|
|
1466
1555
|
catch {
|
|
1467
1556
|
/* non-JSON noise on stdout -- ignore */
|
|
@@ -1482,8 +1571,35 @@ function runAgentCli(opts) {
|
|
|
1482
1571
|
failure: { kind: 'spawn', detail: `${opts.command}: ${err.message}` },
|
|
1483
1572
|
});
|
|
1484
1573
|
});
|
|
1574
|
+
// Opened last, once the timeout and every handler exist: bind runs caller
|
|
1575
|
+
// code that persists task state, and a throw there must not leave a child
|
|
1576
|
+
// with stdin open and nothing to reap it.
|
|
1577
|
+
if (opts.stdin && child.stdin) {
|
|
1578
|
+
const pipe = child.stdin;
|
|
1579
|
+
// EPIPE from a child that died mid-write arrives here; the close handler
|
|
1580
|
+
// reports the death.
|
|
1581
|
+
pipe.on('error', () => {
|
|
1582
|
+
stdinOpen = false;
|
|
1583
|
+
opts.stdin?.bind(null);
|
|
1584
|
+
});
|
|
1585
|
+
stdinOpen = true;
|
|
1586
|
+
pipe.write(streamUserLine(opts.stdin.prompt, opts.stdin.promptUuid));
|
|
1587
|
+
try {
|
|
1588
|
+
opts.stdin.bind((line) => {
|
|
1589
|
+
if (stdinOpen)
|
|
1590
|
+
pipe.write(line);
|
|
1591
|
+
});
|
|
1592
|
+
}
|
|
1593
|
+
catch (err) {
|
|
1594
|
+
console.error(`[agent] binding a run's stdin threw: ${err instanceof Error ? err.message : String(err)}`);
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1485
1597
|
child.on('close', (code) => {
|
|
1486
|
-
|
|
1598
|
+
if (timedOut) {
|
|
1599
|
+
settleTimedOut();
|
|
1600
|
+
return;
|
|
1601
|
+
}
|
|
1602
|
+
const ok = code === 0 ? state.sawResult && !state.resultIsError : streamRunOk(opts, state);
|
|
1487
1603
|
// A provider error does NOT arrive on stderr: the claude CLI reports it
|
|
1488
1604
|
// in the stream-json result event (is_error:true) and exits 0, leaving
|
|
1489
1605
|
// stderr empty -- verified against the real binary. So classify against
|
|
@@ -1510,7 +1626,9 @@ function runAgentCli(opts) {
|
|
|
1510
1626
|
finalTextFromResult: state.finalTextFromResult,
|
|
1511
1627
|
usage: state.usage,
|
|
1512
1628
|
stats: state.stats,
|
|
1629
|
+
sessionId: state.sessionId,
|
|
1513
1630
|
crashed: !state.sawResult,
|
|
1631
|
+
resultError: state.resultIsError,
|
|
1514
1632
|
error,
|
|
1515
1633
|
failure: classified
|
|
1516
1634
|
? {
|
|
@@ -1808,6 +1926,9 @@ function createUsageFeed(opts) {
|
|
|
1808
1926
|
refresh();
|
|
1809
1927
|
return {
|
|
1810
1928
|
latest: () => latest,
|
|
1929
|
+
// The budget outlives a switch to the user's own OpenRouter key; the chip
|
|
1930
|
+
// stops saying Muse then (usageFrame's freeModel), so the router must too.
|
|
1931
|
+
freeModelPrefixes: () => runIsCastlePaid('openrouter', null) ? (budget?.freeModelPrefixes ?? []) : [],
|
|
1811
1932
|
recompute,
|
|
1812
1933
|
refresh,
|
|
1813
1934
|
stop: () => {
|
|
@@ -1851,7 +1972,7 @@ async function runAgentTurn(opts) {
|
|
|
1851
1972
|
// conversation -- nothing is resumed).
|
|
1852
1973
|
const sessionId = newAgentSessionId(opts.role);
|
|
1853
1974
|
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);
|
|
1975
|
+
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
1976
|
const run = runAgentCli({
|
|
1856
1977
|
cwd: opts.cwd,
|
|
1857
1978
|
command: invocation.command,
|
|
@@ -1871,6 +1992,7 @@ async function runAgentTurn(opts) {
|
|
|
1871
1992
|
effort: invocation.effort,
|
|
1872
1993
|
systemPrompt: invocation.systemText || undefined,
|
|
1873
1994
|
prompt: opts.prompt,
|
|
1995
|
+
...(opts.resumeSessionId ? { resumeSessionId: opts.resumeSessionId } : {}),
|
|
1874
1996
|
},
|
|
1875
1997
|
children: opts.children,
|
|
1876
1998
|
onDelta: opts.onDelta,
|
|
@@ -1879,6 +2001,7 @@ async function runAgentTurn(opts) {
|
|
|
1879
2001
|
onSpawn: opts.onSpawn,
|
|
1880
2002
|
labelUnknownTools: opts.labelUnknownTools,
|
|
1881
2003
|
openrouterModel: opts.claudeModel === 'openrouter' ? opts.openrouterModel : undefined,
|
|
2004
|
+
stdin: opts.stdin ? { ...opts.stdin, prompt: opts.prompt } : undefined,
|
|
1882
2005
|
});
|
|
1883
2006
|
return settled(run);
|
|
1884
2007
|
}
|
|
@@ -1938,21 +2061,33 @@ function writeTaskIndex(tasksDir, tasks) {
|
|
|
1938
2061
|
console.error(`[tasks] could not write ${TASK_INDEX_FILE}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1939
2062
|
}
|
|
1940
2063
|
}
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
2064
|
+
const TASK_STATUSES = [
|
|
2065
|
+
'held',
|
|
2066
|
+
'waiting',
|
|
2067
|
+
'running',
|
|
2068
|
+
'blocked',
|
|
2069
|
+
'done',
|
|
2070
|
+
'failed',
|
|
2071
|
+
'interrupted',
|
|
2072
|
+
];
|
|
1947
2073
|
const TASK_OPTIONAL_STRINGS = [
|
|
1948
2074
|
'item', 'startedAt', 'finishedAt', 'originMessageId', 'resultSummary', 'account', 'errorCopy',
|
|
1949
2075
|
'errorDetail', 'failure', 'avatar', 'phase', 'durable', 'what', 'model', 'backend',
|
|
2076
|
+
'interruptedFrom', 'interruptedAt', 'answer',
|
|
1950
2077
|
];
|
|
1951
|
-
const TASK_OPTIONAL_NUMBERS = ['pid', 'costUsd', 'durationApiMs', 'numTurns'];
|
|
2078
|
+
const TASK_OPTIONAL_NUMBERS = ['pid', 'costUsd', 'durationApiMs', 'numTurns', 'resumeCount'];
|
|
1952
2079
|
const TASK_OPTIONAL_OBJECTS = ['usage', 'modelUsage'];
|
|
1953
2080
|
const TASK_OPTIONAL_BOOLEANS = ['acknowledged', 'rejected', 'durablePending'];
|
|
1954
2081
|
const TASK_OPTIONAL_STRING_LISTS = ['playtestFrames', 'files', 'knobs', 'blockedBy'];
|
|
1955
2082
|
const isStringList = (v) => Array.isArray(v) && v.every((s) => typeof s === 'string');
|
|
2083
|
+
function isHeldFor(v) {
|
|
2084
|
+
if (!v || typeof v !== 'object' || Array.isArray(v))
|
|
2085
|
+
return false;
|
|
2086
|
+
const heldFor = v;
|
|
2087
|
+
return (typeof heldFor.messageId === 'string' &&
|
|
2088
|
+
typeof heldFor.question === 'string' &&
|
|
2089
|
+
isStringList(heldFor.chips));
|
|
2090
|
+
}
|
|
1956
2091
|
// tasks/ sits in the deck, where the agent (or anything else) can write, and a
|
|
1957
2092
|
// record the store can't handle used to throw inside createTaskStore and take
|
|
1958
2093
|
// the whole serve down -- the deck then couldn't be opened at all. A record
|
|
@@ -1988,12 +2123,25 @@ function normalizeLoadedTask(entry, raw) {
|
|
|
1988
2123
|
for (const k of TASK_OPTIONAL_STRINGS)
|
|
1989
2124
|
if (typeof r[k] !== 'string')
|
|
1990
2125
|
delete task[k];
|
|
2126
|
+
if (!isHeldFor(r.heldFor))
|
|
2127
|
+
delete task.heldFor;
|
|
2128
|
+
if (task.interruptedFrom !== 'running' && task.interruptedFrom !== 'waiting') {
|
|
2129
|
+
delete task.interruptedFrom;
|
|
2130
|
+
}
|
|
2131
|
+
if (!Number.isInteger(task.resumeCount) || task.resumeCount < 0) {
|
|
2132
|
+
delete task.resumeCount;
|
|
2133
|
+
}
|
|
1991
2134
|
for (const k of TASK_OPTIONAL_BOOLEANS)
|
|
1992
2135
|
if (typeof r[k] !== 'boolean')
|
|
1993
2136
|
delete task[k];
|
|
1994
2137
|
for (const k of TASK_OPTIONAL_STRING_LISTS)
|
|
1995
2138
|
if (!isStringList(r[k]))
|
|
1996
2139
|
delete task[k];
|
|
2140
|
+
const steers = normalizeSteers(r.steers);
|
|
2141
|
+
if (steers)
|
|
2142
|
+
task.steers = steers;
|
|
2143
|
+
else
|
|
2144
|
+
delete task.steers;
|
|
1997
2145
|
return task;
|
|
1998
2146
|
}
|
|
1999
2147
|
function loadTasks(tasksDir) {
|
|
@@ -2003,6 +2151,10 @@ function loadTasks(tasksDir) {
|
|
|
2003
2151
|
if (!rec)
|
|
2004
2152
|
continue;
|
|
2005
2153
|
if (rec.status === 'running' || rec.status === 'waiting') {
|
|
2154
|
+
rec.interruptedFrom = rec.status;
|
|
2155
|
+
// The serve died without a shutdown, so its last write is the best
|
|
2156
|
+
// guess at when -- stamping now would make a week-old crash look fresh.
|
|
2157
|
+
rec.interruptedAt = rec.updatedAt;
|
|
2006
2158
|
rec.status = 'interrupted';
|
|
2007
2159
|
rec.updatedAt = nowIso();
|
|
2008
2160
|
persistTaskFile(tasksDir, rec);
|
|
@@ -2187,6 +2339,171 @@ async function waitBeforeTaskRetry(attempt, stopRequested, taskId) {
|
|
|
2187
2339
|
await sleep(backoffMs);
|
|
2188
2340
|
return stopRequested.has(taskId);
|
|
2189
2341
|
}
|
|
2342
|
+
// The log is append-only across crash retries, so the newest session is the
|
|
2343
|
+
// one the interrupted attempt was running.
|
|
2344
|
+
function claudeSessionIdOf(taskDir) {
|
|
2345
|
+
try {
|
|
2346
|
+
const log = fs.readFileSync(path.join(taskDir, 'log.jsonl'), 'utf8');
|
|
2347
|
+
for (const line of log.split('\n').reverse()) {
|
|
2348
|
+
try {
|
|
2349
|
+
const event = JSON.parse(line);
|
|
2350
|
+
if (typeof event.session_id === 'string')
|
|
2351
|
+
return event.session_id;
|
|
2352
|
+
}
|
|
2353
|
+
catch {
|
|
2354
|
+
/* a trailing partial line or non-JSON output */
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
}
|
|
2358
|
+
catch {
|
|
2359
|
+
/* no transcript */
|
|
2360
|
+
}
|
|
2361
|
+
return undefined;
|
|
2362
|
+
}
|
|
2363
|
+
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.';
|
|
2364
|
+
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.';
|
|
2365
|
+
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.';
|
|
2366
|
+
function missingResumeSession(result) {
|
|
2367
|
+
const text = [result.error, result.finalText, result.failure?.detail, result.failure?.verbose]
|
|
2368
|
+
.filter((part) => Boolean(part))
|
|
2369
|
+
.join('\n');
|
|
2370
|
+
return /(?:no (?:conversation|session) found|(?:conversation|session).{0,80}(?:not found|does not exist)|unable to find (?:conversation|session))/i.test(text);
|
|
2371
|
+
}
|
|
2372
|
+
function addCliUsage(left, right) {
|
|
2373
|
+
if (!left)
|
|
2374
|
+
return right;
|
|
2375
|
+
if (!right)
|
|
2376
|
+
return left;
|
|
2377
|
+
const usage = {};
|
|
2378
|
+
for (const key of [
|
|
2379
|
+
'input_tokens',
|
|
2380
|
+
'output_tokens',
|
|
2381
|
+
'cache_creation_input_tokens',
|
|
2382
|
+
'cache_read_input_tokens',
|
|
2383
|
+
]) {
|
|
2384
|
+
const total = (left[key] ?? 0) + (right[key] ?? 0);
|
|
2385
|
+
if (total > 0)
|
|
2386
|
+
usage[key] = total;
|
|
2387
|
+
}
|
|
2388
|
+
return Object.keys(usage).length > 0 ? usage : undefined;
|
|
2389
|
+
}
|
|
2390
|
+
function addModelUsage(left, right) {
|
|
2391
|
+
if (!left)
|
|
2392
|
+
return right;
|
|
2393
|
+
if (!right)
|
|
2394
|
+
return left;
|
|
2395
|
+
const merged = {};
|
|
2396
|
+
for (const model of new Set([...Object.keys(left), ...Object.keys(right)])) {
|
|
2397
|
+
const a = left[model] ?? {};
|
|
2398
|
+
const b = right[model] ?? {};
|
|
2399
|
+
const entry = {};
|
|
2400
|
+
for (const key of ['input', 'output', 'cacheRead', 'cacheCreation', 'costUsd']) {
|
|
2401
|
+
const total = (a[key] ?? 0) + (b[key] ?? 0);
|
|
2402
|
+
if (total > 0)
|
|
2403
|
+
entry[key] = total;
|
|
2404
|
+
}
|
|
2405
|
+
if (Object.keys(entry).length > 0)
|
|
2406
|
+
merged[model] = entry;
|
|
2407
|
+
}
|
|
2408
|
+
return Object.keys(merged).length > 0 ? merged : undefined;
|
|
2409
|
+
}
|
|
2410
|
+
function addRunLedger(result, extra) {
|
|
2411
|
+
result.usage = addCliUsage(result.usage, extra.usage);
|
|
2412
|
+
const left = result.stats;
|
|
2413
|
+
const right = extra.stats;
|
|
2414
|
+
if (!left) {
|
|
2415
|
+
result.stats = right;
|
|
2416
|
+
return;
|
|
2417
|
+
}
|
|
2418
|
+
if (!right)
|
|
2419
|
+
return;
|
|
2420
|
+
const sum = (a, b) => a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);
|
|
2421
|
+
result.stats = {
|
|
2422
|
+
costUsd: sum(left.costUsd, right.costUsd),
|
|
2423
|
+
durationApiMs: sum(left.durationApiMs, right.durationApiMs),
|
|
2424
|
+
numTurns: sum(left.numTurns, right.numTurns),
|
|
2425
|
+
modelUsage: addModelUsage(left.modelUsage, right.modelUsage),
|
|
2426
|
+
};
|
|
2427
|
+
}
|
|
2428
|
+
function writeSteer(write, steer) {
|
|
2429
|
+
steer.state = 'queued';
|
|
2430
|
+
write(streamUserLine(steerMessageText(steer.text), steer.id));
|
|
2431
|
+
}
|
|
2432
|
+
// One attempt's stdin. A fresh attempt is a new conversation, so it is sent
|
|
2433
|
+
// every message the task has been given; a resume already holds the delivered
|
|
2434
|
+
// ones and gets only what is still pending, minus the one riding as its prompt.
|
|
2435
|
+
function taskStdin(ctx, task, opts) {
|
|
2436
|
+
const channel = ctx.steerChannel;
|
|
2437
|
+
if (!channel)
|
|
2438
|
+
return undefined;
|
|
2439
|
+
channel.write = null;
|
|
2440
|
+
channel.closed = false;
|
|
2441
|
+
return {
|
|
2442
|
+
promptUuid: opts.promptUuid,
|
|
2443
|
+
bind: (write) => {
|
|
2444
|
+
channel.write = write;
|
|
2445
|
+
if (!write) {
|
|
2446
|
+
channel.closed = true;
|
|
2447
|
+
return;
|
|
2448
|
+
}
|
|
2449
|
+
const resent = (task.steers ?? []).filter(opts.resend);
|
|
2450
|
+
for (const steer of resent)
|
|
2451
|
+
writeSteer(write, steer);
|
|
2452
|
+
if (resent.length > 0)
|
|
2453
|
+
ctx.onSteerChange();
|
|
2454
|
+
},
|
|
2455
|
+
onReplay: (uuid) => {
|
|
2456
|
+
const steer = task.steers?.find((s) => s.id === uuid);
|
|
2457
|
+
if (!steer || !isPendingSteer(steer))
|
|
2458
|
+
return;
|
|
2459
|
+
steer.state = 'taken';
|
|
2460
|
+
ctx.onFeed('[the task read your message]');
|
|
2461
|
+
ctx.onSteerChange();
|
|
2462
|
+
},
|
|
2463
|
+
onResult: (ok) => {
|
|
2464
|
+
const taken = (task.steers ?? []).filter((s) => s.state === 'taken');
|
|
2465
|
+
for (const steer of taken) {
|
|
2466
|
+
steer.state = ok ? 'delivered' : 'late';
|
|
2467
|
+
if (ok)
|
|
2468
|
+
steer.deliveredAt = nowIso();
|
|
2469
|
+
}
|
|
2470
|
+
if (taken.length > 0)
|
|
2471
|
+
ctx.onSteerChange();
|
|
2472
|
+
},
|
|
2473
|
+
};
|
|
2474
|
+
}
|
|
2475
|
+
// A resume is a separate process, so unlike mergeLaterResult nothing here is a
|
|
2476
|
+
// running total: every count adds up (addRunLedger).
|
|
2477
|
+
function combineRunResults(a, b) {
|
|
2478
|
+
const combined = {
|
|
2479
|
+
...b,
|
|
2480
|
+
finalText: [a.finalText, b.finalText].filter(Boolean).join('\n\n'),
|
|
2481
|
+
finalTextFromResult: a.finalTextFromResult === true && b.finalTextFromResult === true,
|
|
2482
|
+
usage: a.usage,
|
|
2483
|
+
stats: a.stats,
|
|
2484
|
+
sessionId: b.sessionId ?? a.sessionId,
|
|
2485
|
+
};
|
|
2486
|
+
addRunLedger(combined, b);
|
|
2487
|
+
return combined;
|
|
2488
|
+
}
|
|
2489
|
+
function terminalSteerReason(status) {
|
|
2490
|
+
if (status === 'interrupted')
|
|
2491
|
+
return 'the task was stopped';
|
|
2492
|
+
if (status === 'failed')
|
|
2493
|
+
return 'the task failed before it read it';
|
|
2494
|
+
return 'the task had already finished';
|
|
2495
|
+
}
|
|
2496
|
+
function settleUndeliveredSteers(task, reason) {
|
|
2497
|
+
let changed = false;
|
|
2498
|
+
for (const steer of task.steers ?? []) {
|
|
2499
|
+
if (!isPendingSteer(steer))
|
|
2500
|
+
continue;
|
|
2501
|
+
steer.state = 'undelivered';
|
|
2502
|
+
steer.reason = reason;
|
|
2503
|
+
changed = true;
|
|
2504
|
+
}
|
|
2505
|
+
return changed;
|
|
2506
|
+
}
|
|
2190
2507
|
async function runTaskAgentIn(ctx, task) {
|
|
2191
2508
|
const dir = path.join(ctx.tasksDir, task.id);
|
|
2192
2509
|
const relDir = path.relative(ctx.deckDir, dir);
|
|
@@ -2252,19 +2569,21 @@ async function runTaskAgentIn(ctx, task) {
|
|
|
2252
2569
|
ctx.onFeed(line);
|
|
2253
2570
|
}
|
|
2254
2571
|
};
|
|
2255
|
-
|
|
2572
|
+
const runOnce = async (prompt, run) => {
|
|
2256
2573
|
await staggerTaskSpawn();
|
|
2257
|
-
|
|
2574
|
+
return runAgentTurn({
|
|
2258
2575
|
role: 'task',
|
|
2259
|
-
prompt
|
|
2576
|
+
prompt,
|
|
2260
2577
|
claudeModel: ctx.claudeModel,
|
|
2261
2578
|
openrouterModel: ctx.openrouterModel,
|
|
2262
2579
|
effort: ctx.effort,
|
|
2263
2580
|
cwd: ctx.deckDir,
|
|
2264
|
-
timeoutMs:
|
|
2581
|
+
timeoutMs: run.timeoutMs,
|
|
2265
2582
|
logPath: path.join(dir, 'log.jsonl'),
|
|
2266
2583
|
taskId: task.id,
|
|
2267
2584
|
playtestTool: playtest.tool,
|
|
2585
|
+
resumeSessionId: run.resumeSessionId,
|
|
2586
|
+
toolsDisabled: run.toolsDisabled,
|
|
2268
2587
|
children: ctx.children,
|
|
2269
2588
|
cancelled: () => ctx.stopRequested.has(task.id),
|
|
2270
2589
|
onSpawn: (pid) => {
|
|
@@ -2276,12 +2595,57 @@ async function runTaskAgentIn(ctx, task) {
|
|
|
2276
2595
|
if (activity)
|
|
2277
2596
|
ctx.onFeed(`[${activity}]`);
|
|
2278
2597
|
},
|
|
2598
|
+
stdin: run.stdin,
|
|
2599
|
+
});
|
|
2600
|
+
};
|
|
2601
|
+
// The wrap-up runs without the message channel: it is told to change
|
|
2602
|
+
// nothing, so a message has to wait for the task's end, not reach it.
|
|
2603
|
+
const finishTimedOut = async (timedOut) => {
|
|
2604
|
+
if (!timedOut.sessionId || ctx.stopRequested.has(task.id))
|
|
2605
|
+
return timedOut;
|
|
2606
|
+
const wrapUp = await runOnce(WRAP_UP_PROMPT, {
|
|
2607
|
+
timeoutMs: WRAP_UP_TIMEOUT_MS,
|
|
2608
|
+
resumeSessionId: timedOut.sessionId,
|
|
2609
|
+
toolsDisabled: true,
|
|
2610
|
+
});
|
|
2611
|
+
logAgentUsage(`task ${task.id} wrap-up`, wrapUp.usage);
|
|
2612
|
+
addRunLedger(timedOut, wrapUp);
|
|
2613
|
+
if (!wrapUp.ok)
|
|
2614
|
+
return timedOut;
|
|
2615
|
+
timedOut.finalText = wrapUp.finalText;
|
|
2616
|
+
timedOut.finalTextFromResult = wrapUp.finalTextFromResult;
|
|
2617
|
+
return timedOut;
|
|
2618
|
+
};
|
|
2619
|
+
const resuming = task.interruptedFrom === 'running' && (task.resumeCount ?? 0) > 0;
|
|
2620
|
+
let resumeSessionId = resuming ? claudeSessionIdOf(dir) : undefined;
|
|
2621
|
+
const freshPrompt = resuming ? `${FRESH_AFTER_INTERRUPTION_PREFIX}\n\n${taskPrompt}` : taskPrompt;
|
|
2622
|
+
for (let attempt = 1; attempt <= MAX_TASK_ATTEMPTS; attempt++) {
|
|
2623
|
+
// A resumed session already holds the messages it was given; a fresh
|
|
2624
|
+
// conversation needs every one again.
|
|
2625
|
+
const resumed = resumeSessionId !== undefined;
|
|
2626
|
+
const stdin = taskStdin(ctx, task, {
|
|
2627
|
+
promptUuid: randomUUID(),
|
|
2628
|
+
resend: (steer) => (resumed ? isPendingSteer(steer) : steer.state !== 'undelivered'),
|
|
2629
|
+
});
|
|
2630
|
+
result = await runOnce(resumed ? RESUME_TASK_PROMPT : freshPrompt, {
|
|
2631
|
+
timeoutMs: TASK_TIMEOUT_MS,
|
|
2632
|
+
stdin,
|
|
2633
|
+
resumeSessionId,
|
|
2279
2634
|
});
|
|
2280
2635
|
logAgentUsage(`task ${task.id}`, result.usage);
|
|
2281
2636
|
if (ctx.stopRequested.has(task.id))
|
|
2282
2637
|
return result;
|
|
2638
|
+
if (resumeSessionId && missingResumeSession(result)) {
|
|
2639
|
+
resumeSessionId = undefined;
|
|
2640
|
+
// The fresh run gets a full set of attempts, even when the missing
|
|
2641
|
+
// session only surfaced after resume crashes had used some up.
|
|
2642
|
+
attempt = 0;
|
|
2643
|
+
continue;
|
|
2644
|
+
}
|
|
2645
|
+
if (result.timedOut)
|
|
2646
|
+
return finishTimedOut(result);
|
|
2283
2647
|
if (!result.crashed)
|
|
2284
|
-
return result;
|
|
2648
|
+
return resumeForLateSteers(ctx, task, result, runOnce);
|
|
2285
2649
|
// A crash normally means "the process died, try again" -- but a claude CLI
|
|
2286
2650
|
// that dies on a bad key or slug BEFORE emitting its result event also
|
|
2287
2651
|
// lands here (crashed = never saw a result), and retrying that burns all
|
|
@@ -2298,6 +2662,96 @@ async function runTaskAgentIn(ctx, task) {
|
|
|
2298
2662
|
result.error = `agent process kept dying (${MAX_TASK_ATTEMPTS} attempts): ${result.error ?? ''}`;
|
|
2299
2663
|
return result;
|
|
2300
2664
|
}
|
|
2665
|
+
// A message that reached the task after its run closed stdin, or one the run
|
|
2666
|
+
// never took in, goes to a resume of the same session: the task sees it as the
|
|
2667
|
+
// next message in the conversation it just had, not as a new brief.
|
|
2668
|
+
async function resumeForLateSteers(ctx, task, first, runOnce) {
|
|
2669
|
+
let result = first;
|
|
2670
|
+
for (let resume = 0; resume < MAX_TASK_RESUMES; resume++) {
|
|
2671
|
+
if (!ctx.steerChannel || !result.ok || !result.sessionId)
|
|
2672
|
+
break;
|
|
2673
|
+
if (!(task.steers ?? []).some(isPendingSteer) || ctx.stopRequested.has(task.id))
|
|
2674
|
+
break;
|
|
2675
|
+
const next = await resumeOnce(ctx, task, result.sessionId, runOnce);
|
|
2676
|
+
if (!next.ok) {
|
|
2677
|
+
// The task's own work finished; only the message failed to reach it, so
|
|
2678
|
+
// the task keeps its result and the message says why it never arrived.
|
|
2679
|
+
if (settleUndeliveredSteers(task, 'the task could not be resumed to read it'))
|
|
2680
|
+
ctx.onSteerChange();
|
|
2681
|
+
const ledger = combineRunResults(result, next);
|
|
2682
|
+
return { ...result, usage: ledger.usage, stats: ledger.stats };
|
|
2683
|
+
}
|
|
2684
|
+
result = combineRunResults(result, next);
|
|
2685
|
+
}
|
|
2686
|
+
return result;
|
|
2687
|
+
}
|
|
2688
|
+
// One resume of `sessionId` carrying the oldest pending message. Every message
|
|
2689
|
+
// it did not finish a turn on is still pending when it ends, so a retry -- for
|
|
2690
|
+
// any end but a provider's error result or a config failure -- carries them
|
|
2691
|
+
// all again.
|
|
2692
|
+
async function resumeOnce(ctx, task, sessionId, runOnce) {
|
|
2693
|
+
let next = { ok: false, finalText: '', error: 'not run' };
|
|
2694
|
+
for (let attempt = 1; attempt <= MAX_TASK_ATTEMPTS; attempt++) {
|
|
2695
|
+
const lead = (task.steers ?? []).find(isPendingSteer);
|
|
2696
|
+
if (!lead)
|
|
2697
|
+
return next;
|
|
2698
|
+
lead.state = 'queued';
|
|
2699
|
+
ctx.onSteerChange();
|
|
2700
|
+
const stdin = taskStdin(ctx, task, {
|
|
2701
|
+
promptUuid: lead.id,
|
|
2702
|
+
resend: (steer) => steer !== lead && isPendingSteer(steer),
|
|
2703
|
+
});
|
|
2704
|
+
next = await runOnce(steerMessageText(lead.text), { timeoutMs: TASK_TIMEOUT_MS, stdin, resumeSessionId: sessionId });
|
|
2705
|
+
logAgentUsage(`task ${task.id} resume`, next.usage);
|
|
2706
|
+
const final = next.ok || next.resultError || next.timedOut || next.failure?.kind === 'config';
|
|
2707
|
+
if (final || ctx.stopRequested.has(task.id))
|
|
2708
|
+
return next;
|
|
2709
|
+
if (attempt < MAX_TASK_ATTEMPTS && (await waitBeforeTaskRetry(attempt, ctx.stopRequested, task.id)))
|
|
2710
|
+
return next;
|
|
2711
|
+
}
|
|
2712
|
+
return next;
|
|
2713
|
+
}
|
|
2714
|
+
function heldForFromReply(messageId, text) {
|
|
2715
|
+
const chipPattern = /\[\[([^[\]\n]+)\]\]/g;
|
|
2716
|
+
const chips = [];
|
|
2717
|
+
let firstChipAt = -1;
|
|
2718
|
+
for (const match of text.matchAll(chipPattern)) {
|
|
2719
|
+
if (firstChipAt < 0)
|
|
2720
|
+
firstChipAt = match.index;
|
|
2721
|
+
const chip = match[1].trim();
|
|
2722
|
+
if (chip && !chips.includes(chip))
|
|
2723
|
+
chips.push(chip);
|
|
2724
|
+
}
|
|
2725
|
+
const beforeChips = firstChipAt < 0 ? text : text.slice(0, firstChipAt);
|
|
2726
|
+
const proseLines = beforeChips
|
|
2727
|
+
.replace(chipPattern, '')
|
|
2728
|
+
.split('\n')
|
|
2729
|
+
.map((line) => line.trim())
|
|
2730
|
+
.filter(Boolean);
|
|
2731
|
+
return {
|
|
2732
|
+
messageId,
|
|
2733
|
+
question: proseLines[proseLines.length - 1] ?? '',
|
|
2734
|
+
chips,
|
|
2735
|
+
};
|
|
2736
|
+
}
|
|
2737
|
+
function releaseHeldTasks(tasks, answer, touch, maybeStart) {
|
|
2738
|
+
const trimmed = answer.trim();
|
|
2739
|
+
if (!trimmed)
|
|
2740
|
+
return [];
|
|
2741
|
+
const released = [];
|
|
2742
|
+
const sorted = [...tasks.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
2743
|
+
for (const task of sorted) {
|
|
2744
|
+
if (task.status !== 'held' || !task.heldFor?.chips.includes(trimmed))
|
|
2745
|
+
continue;
|
|
2746
|
+
task.answer = trimmed;
|
|
2747
|
+
task.prompt += `\n\nThe user answered: ${trimmed}`;
|
|
2748
|
+
task.status = 'waiting';
|
|
2749
|
+
touch(task);
|
|
2750
|
+
maybeStart(task);
|
|
2751
|
+
released.push(task.id);
|
|
2752
|
+
}
|
|
2753
|
+
return released;
|
|
2754
|
+
}
|
|
2301
2755
|
// The finishing attempt's numbers onto the record. Only one attempt ever has
|
|
2302
2756
|
// any: runTaskAgentIn retries exactly the attempts that died before a result
|
|
2303
2757
|
// event, so there is never an earlier set to add this one to.
|
|
@@ -2315,18 +2769,28 @@ function recordRunLedger(task, result) {
|
|
|
2315
2769
|
if (modelUsage)
|
|
2316
2770
|
task.modelUsage = modelUsage;
|
|
2317
2771
|
}
|
|
2772
|
+
function steerChannelFor(ctx, taskId) {
|
|
2773
|
+
if (!TASK_STEER_ENABLED)
|
|
2774
|
+
return undefined;
|
|
2775
|
+
const channel = { write: null, closed: false };
|
|
2776
|
+
ctx.steerChannels.set(taskId, channel);
|
|
2777
|
+
return channel;
|
|
2778
|
+
}
|
|
2318
2779
|
// Launch a task's agent run and wire up its finalization. The settle path is
|
|
2319
2780
|
// hardened: result-finalization, onFinished, and the reschedule sweep each run
|
|
2320
2781
|
// under their own try/catch so one bad task turn can neither wedge the board
|
|
2321
2782
|
// (by skipping the slot free) nor crash the serve.
|
|
2322
2783
|
function startTask(ctx, task) {
|
|
2323
2784
|
const dir = path.join(ctx.tasksDir, task.id);
|
|
2324
|
-
|
|
2785
|
+
if (!task.interruptedFrom)
|
|
2786
|
+
atomicWriteFileSync(path.join(dir, 'progress'), '0\n');
|
|
2325
2787
|
if (!fs.existsSync(path.join(dir, 'notes.md')))
|
|
2326
2788
|
atomicWriteFileSync(path.join(dir, 'notes.md'), '');
|
|
2327
2789
|
const claudeModel = ctx.claudeModel();
|
|
2328
2790
|
const openrouterModel = ctx.openrouterModel();
|
|
2329
2791
|
const effort = ctx.effort();
|
|
2792
|
+
if (task.interruptedFrom && (task.resumeCount ?? 0) === 0)
|
|
2793
|
+
task.resumeCount = 1;
|
|
2330
2794
|
task.status = 'running';
|
|
2331
2795
|
task.startedAt = nowIso();
|
|
2332
2796
|
task.model = spawnModelFor(claudeModel, openrouterModel);
|
|
@@ -2357,6 +2821,8 @@ function startTask(ctx, task) {
|
|
|
2357
2821
|
finishedWork: planFinishedWork(ctx.sorted()),
|
|
2358
2822
|
onFeed: (entry) => ctx.onFeed(task, entry),
|
|
2359
2823
|
onRetry: (attempt) => ctx.onRetry(task, attempt),
|
|
2824
|
+
steerChannel: steerChannelFor(ctx, task.id),
|
|
2825
|
+
onSteerChange: () => ctx.touch(task),
|
|
2360
2826
|
onSignal: (signal) => {
|
|
2361
2827
|
let changed = false;
|
|
2362
2828
|
if (typeof signal.progress === 'number' && signal.progress !== task.progress) {
|
|
@@ -2377,6 +2843,8 @@ function startTask(ctx, task) {
|
|
|
2377
2843
|
};
|
|
2378
2844
|
void runTaskAgentIn(runCtx, task)
|
|
2379
2845
|
.then((result) => {
|
|
2846
|
+
if (ctx.finalizedAtShutdown.has(task.id))
|
|
2847
|
+
return;
|
|
2380
2848
|
// Finalization (fs writes), onFinished, and the reschedule sweep must all
|
|
2381
2849
|
// survive a throw -- otherwise a single bad task turn could both skip
|
|
2382
2850
|
// freeing the slot (wedging the board) and crash the serve.
|
|
@@ -2385,16 +2853,20 @@ function startTask(ctx, task) {
|
|
|
2385
2853
|
// path below throws.
|
|
2386
2854
|
recordRunLedger(task, result);
|
|
2387
2855
|
refreshTaskFiles(ctx.tasksDir, task);
|
|
2856
|
+
ctx.steerChannels.delete(task.id);
|
|
2388
2857
|
const wasStopped = ctx.stopRequested.delete(task.id);
|
|
2389
2858
|
task.status = wasStopped ? 'interrupted' : result.ok ? 'done' : 'failed';
|
|
2390
2859
|
// A stopped task is cleared off the board (castle-stop = halt + remove).
|
|
2391
|
-
if (wasStopped)
|
|
2860
|
+
if (wasStopped) {
|
|
2392
2861
|
task.acknowledged = true;
|
|
2862
|
+
delete task.interruptedFrom;
|
|
2863
|
+
delete task.interruptedAt;
|
|
2864
|
+
}
|
|
2393
2865
|
if (result.ok && !wasStopped)
|
|
2394
2866
|
task.progress = 100;
|
|
2395
2867
|
task.finishedAt = nowIso();
|
|
2396
2868
|
task.resultSummary = wasStopped
|
|
2397
|
-
?
|
|
2869
|
+
? ROUTER_STOPPED_RESULT
|
|
2398
2870
|
: result.ok
|
|
2399
2871
|
? result.finalText.slice(-RESULT_SUMMARY_CHARS)
|
|
2400
2872
|
: `${result.error ?? 'failed'}\n${result.finalText.slice(-RESULT_SUMMARY_CHARS)}`;
|
|
@@ -2423,6 +2895,7 @@ function startTask(ctx, task) {
|
|
|
2423
2895
|
console.error(`[task ${task.id}] finalization threw: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);
|
|
2424
2896
|
// Best-effort: still mark the task terminal so it can't hang forever.
|
|
2425
2897
|
try {
|
|
2898
|
+
ctx.steerChannels.delete(task.id);
|
|
2426
2899
|
ctx.stopRequested.delete(task.id);
|
|
2427
2900
|
task.status = 'failed';
|
|
2428
2901
|
task.finishedAt = nowIso();
|
|
@@ -2445,9 +2918,12 @@ function startTask(ctx, task) {
|
|
|
2445
2918
|
}
|
|
2446
2919
|
})
|
|
2447
2920
|
.catch((err) => {
|
|
2921
|
+
if (ctx.finalizedAtShutdown.has(task.id))
|
|
2922
|
+
return;
|
|
2448
2923
|
// runTaskAgentIn itself rejected. Free the slot so the board keeps moving.
|
|
2449
2924
|
console.error(`[task ${task.id}] run promise rejected: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);
|
|
2450
2925
|
try {
|
|
2926
|
+
ctx.steerChannels.delete(task.id);
|
|
2451
2927
|
ctx.stopRequested.delete(task.id);
|
|
2452
2928
|
task.status = 'failed';
|
|
2453
2929
|
task.finishedAt = nowIso();
|
|
@@ -2461,16 +2937,54 @@ function startTask(ctx, task) {
|
|
|
2461
2937
|
ctx.rescheduleAll();
|
|
2462
2938
|
});
|
|
2463
2939
|
}
|
|
2464
|
-
|
|
2940
|
+
function sendToTasks(store, directives, originMessageId) {
|
|
2941
|
+
const unsent = [];
|
|
2942
|
+
for (const directive of directives) {
|
|
2943
|
+
const [id] = resolveTargets(store.tasks, [directive.target]);
|
|
2944
|
+
const task = id ? store.tasks.get(id) : undefined;
|
|
2945
|
+
if (!task) {
|
|
2946
|
+
unsent.push(directive.target);
|
|
2947
|
+
continue;
|
|
2948
|
+
}
|
|
2949
|
+
sendToTask(task, directive.text, originMessageId, store.steerChannels.get(task.id));
|
|
2950
|
+
store.onFeed(task, '[message sent to this task]');
|
|
2951
|
+
store.touch(task);
|
|
2952
|
+
}
|
|
2953
|
+
return unsent;
|
|
2954
|
+
}
|
|
2955
|
+
// A waiting or held task gets the message with its prompt when it starts, and a
|
|
2956
|
+
// running one as soon as its stdin is up. A running task whose stdin already
|
|
2957
|
+
// closed holds it for a resume (resumeForLateSteers). Anything else cannot take
|
|
2958
|
+
// a message, and the board says so on the router's next turn.
|
|
2959
|
+
function sendToTask(task, text, originMessageId, channel) {
|
|
2960
|
+
const steer = newTaskSteer(text, nowIso(), originMessageId);
|
|
2961
|
+
task.steers = [...(task.steers ?? []), steer];
|
|
2962
|
+
if (task.status === 'waiting' || task.status === 'held')
|
|
2963
|
+
return steer;
|
|
2964
|
+
if (task.status !== 'running' || !channel) {
|
|
2965
|
+
steer.state = 'undelivered';
|
|
2966
|
+
steer.reason =
|
|
2967
|
+
task.status === 'blocked' ? 'the task is blocked and will not start' : 'the task had already finished';
|
|
2968
|
+
return steer;
|
|
2969
|
+
}
|
|
2970
|
+
if (channel.write)
|
|
2971
|
+
writeSteer(channel.write, steer);
|
|
2972
|
+
else if (channel.closed)
|
|
2973
|
+
steer.state = 'late';
|
|
2974
|
+
return steer;
|
|
2975
|
+
}
|
|
2976
|
+
// Halt + remove an active task (castle-stop): a held, waiting, or blocked one is
|
|
2465
2977
|
// cancelled and cleared off the board immediately; a running one gets its
|
|
2466
2978
|
// agent process killed and is cleared when it finalizes (the stopRequested
|
|
2467
2979
|
// path acks it). No-op on terminal tasks. A "blocked" task never got a
|
|
2468
2980
|
// process, so it collapses the same way "waiting" does -- this is the only
|
|
2469
2981
|
// way a blocked row ever clears (see ROUTER_RULES).
|
|
2470
2982
|
function haltTask(task, children, stopRequested, touch) {
|
|
2471
|
-
if (task.status === 'waiting' || task.status === 'blocked') {
|
|
2983
|
+
if (task.status === 'held' || task.status === 'waiting' || task.status === 'blocked') {
|
|
2472
2984
|
task.status = 'interrupted';
|
|
2473
2985
|
task.acknowledged = true;
|
|
2986
|
+
delete task.interruptedFrom;
|
|
2987
|
+
delete task.interruptedAt;
|
|
2474
2988
|
touch(task);
|
|
2475
2989
|
}
|
|
2476
2990
|
else if (task.status === 'running') {
|
|
@@ -2487,19 +3001,75 @@ function haltTask(task, children, stopRequested, touch) {
|
|
|
2487
3001
|
}
|
|
2488
3002
|
}
|
|
2489
3003
|
}
|
|
2490
|
-
|
|
3004
|
+
// A recovered task runs again and is sent its pending messages then; one that
|
|
3005
|
+
// stays ended can never read them.
|
|
3006
|
+
function settleUnrecoveredSteers(tasksDir, tasks) {
|
|
3007
|
+
for (const task of tasks.values()) {
|
|
3008
|
+
if (!isTerminal(task.status))
|
|
3009
|
+
continue;
|
|
3010
|
+
const reason = task.status === 'interrupted' ? 'the task was interrupted when Castle restarted' : terminalSteerReason(task.status);
|
|
3011
|
+
if (settleUndeliveredSteers(task, reason))
|
|
3012
|
+
persistTaskFile(tasksDir, task);
|
|
3013
|
+
}
|
|
3014
|
+
}
|
|
3015
|
+
function recoverInterruptedTasks(tasksDir, tasks) {
|
|
3016
|
+
const now = Date.now();
|
|
3017
|
+
const recovered = new Set();
|
|
3018
|
+
for (const task of tasks.values()) {
|
|
3019
|
+
if (task.status !== 'interrupted' ||
|
|
3020
|
+
task.acknowledged ||
|
|
3021
|
+
task.resultSummary?.trim() ||
|
|
3022
|
+
!task.interruptedFrom ||
|
|
3023
|
+
(task.resumeCount ?? 0) > 0) {
|
|
3024
|
+
continue;
|
|
3025
|
+
}
|
|
3026
|
+
const interruptedAt = Date.parse(task.interruptedAt ?? '');
|
|
3027
|
+
const age = now - interruptedAt;
|
|
3028
|
+
if (!Number.isFinite(interruptedAt) || age < 0 || age > RESUME_MAX_AGE_MS)
|
|
3029
|
+
continue;
|
|
3030
|
+
task.status = 'waiting';
|
|
3031
|
+
task.updatedAt = nowIso();
|
|
3032
|
+
delete task.finishedAt;
|
|
3033
|
+
persistTaskFile(tasksDir, task);
|
|
3034
|
+
recovered.add(task.id);
|
|
3035
|
+
}
|
|
3036
|
+
for (const task of tasks.values()) {
|
|
3037
|
+
if (task.status !== 'blocked' ||
|
|
3038
|
+
!task.after.some((id) => recovered.has(id)) ||
|
|
3039
|
+
classifyDeps(tasks, task).kind === 'blocked') {
|
|
3040
|
+
continue;
|
|
3041
|
+
}
|
|
3042
|
+
task.status = 'waiting';
|
|
3043
|
+
task.updatedAt = nowIso();
|
|
3044
|
+
delete task.blockedBy;
|
|
3045
|
+
persistTaskFile(tasksDir, task);
|
|
3046
|
+
}
|
|
3047
|
+
}
|
|
3048
|
+
export function createTaskStore(opts) {
|
|
2491
3049
|
const { deckDir, deckLabel, tasksDir, children } = opts;
|
|
2492
3050
|
const tasks = loadTasks(tasksDir);
|
|
3051
|
+
recoverInterruptedTasks(tasksDir, tasks);
|
|
3052
|
+
settleUnrecoveredSteers(tasksDir, tasks);
|
|
2493
3053
|
// Covers both a deck whose tasks predate the index and the interrupted-status
|
|
2494
3054
|
// rewrites loadTasks just did.
|
|
2495
3055
|
writeTaskIndex(tasksDir, tasks);
|
|
2496
3056
|
// Tasks the router asked to stop: their killed process must not read as a
|
|
2497
3057
|
// crash (no retry) and they finalize as interrupted, not failed.
|
|
2498
3058
|
const stopRequested = new Set();
|
|
3059
|
+
const finalizedAtShutdown = new Set();
|
|
3060
|
+
const steerChannels = new Map();
|
|
2499
3061
|
function sorted() {
|
|
2500
3062
|
return [...tasks.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
2501
3063
|
}
|
|
2502
3064
|
function touch(task) {
|
|
3065
|
+
// Every terminal state is persisted through here, so this is where a
|
|
3066
|
+
// message the task can no longer read is settled -- whichever path ended it.
|
|
3067
|
+
// A record left interrupted for recovery (interruptedFrom) runs again and
|
|
3068
|
+
// is sent its pending messages then, so it keeps them; once that recovered
|
|
3069
|
+
// run ends, it settles like any other.
|
|
3070
|
+
if (isTerminal(task.status) && !(task.status === 'interrupted' && task.interruptedFrom)) {
|
|
3071
|
+
settleUndeliveredSteers(task, terminalSteerReason(task.status));
|
|
3072
|
+
}
|
|
2503
3073
|
task.updatedAt = nowIso();
|
|
2504
3074
|
persistTaskFile(tasksDir, task);
|
|
2505
3075
|
writeTaskIndex(tasksDir, tasks);
|
|
@@ -2524,6 +3094,7 @@ function createTaskStore(opts) {
|
|
|
2524
3094
|
if (deps.kind === 'blocked') {
|
|
2525
3095
|
task.status = 'blocked';
|
|
2526
3096
|
task.blockedBy = deps.blockedBy;
|
|
3097
|
+
settleUndeliveredSteers(task, 'the task is blocked and will not start');
|
|
2527
3098
|
touch(task);
|
|
2528
3099
|
return;
|
|
2529
3100
|
}
|
|
@@ -2554,6 +3125,8 @@ function createTaskStore(opts) {
|
|
|
2554
3125
|
children,
|
|
2555
3126
|
tasks,
|
|
2556
3127
|
stopRequested,
|
|
3128
|
+
finalizedAtShutdown,
|
|
3129
|
+
steerChannels,
|
|
2557
3130
|
claudeModel: opts.claudeModel,
|
|
2558
3131
|
openrouterModel: opts.openrouterModel,
|
|
2559
3132
|
effort: opts.effort,
|
|
@@ -2566,7 +3139,7 @@ function createTaskStore(opts) {
|
|
|
2566
3139
|
sorted,
|
|
2567
3140
|
rescheduleAll,
|
|
2568
3141
|
};
|
|
2569
|
-
function spawnFromDirective(directive, originMessageId) {
|
|
3142
|
+
function spawnFromDirective(directive, originMessageId, originText = '') {
|
|
2570
3143
|
const task = {
|
|
2571
3144
|
id: nanoid(8),
|
|
2572
3145
|
title: directive.title,
|
|
@@ -2574,12 +3147,13 @@ function createTaskStore(opts) {
|
|
|
2574
3147
|
after: resolveTargets(tasks, directive.after),
|
|
2575
3148
|
item: directive.item,
|
|
2576
3149
|
playtest: taskPlaytestFor(deckDir),
|
|
2577
|
-
status: 'waiting',
|
|
3150
|
+
status: directive.hold ? 'held' : 'waiting',
|
|
2578
3151
|
progress: 0,
|
|
2579
3152
|
notes: '',
|
|
2580
3153
|
createdAt: nowIso(),
|
|
2581
3154
|
updatedAt: nowIso(),
|
|
2582
3155
|
originMessageId,
|
|
3156
|
+
...(directive.hold ? { heldFor: heldForFromReply(originMessageId, originText) } : {}),
|
|
2583
3157
|
};
|
|
2584
3158
|
fs.mkdirSync(path.join(tasksDir, task.id), { recursive: true });
|
|
2585
3159
|
tasks.set(task.id, task);
|
|
@@ -2589,6 +3163,7 @@ function createTaskStore(opts) {
|
|
|
2589
3163
|
maybeStart(task);
|
|
2590
3164
|
return task.id;
|
|
2591
3165
|
}
|
|
3166
|
+
const releaseHeld = (answer) => releaseHeldTasks(tasks, answer, touch, maybeStart);
|
|
2592
3167
|
function acknowledge(id, rejected) {
|
|
2593
3168
|
const task = tasks.get(id);
|
|
2594
3169
|
if (!task || !isTerminal(task.status) || task.acknowledged)
|
|
@@ -2626,7 +3201,23 @@ function createTaskStore(opts) {
|
|
|
2626
3201
|
clearInterval(pollTimer);
|
|
2627
3202
|
for (const task of tasks.values()) {
|
|
2628
3203
|
if (task.status === 'running' || task.status === 'waiting') {
|
|
3204
|
+
const interruptedFrom = task.status;
|
|
3205
|
+
const routerStopped = stopRequested.has(task.id);
|
|
3206
|
+
if (interruptedFrom === 'running') {
|
|
3207
|
+
finalizedAtShutdown.add(task.id);
|
|
3208
|
+
stopRequested.add(task.id);
|
|
3209
|
+
}
|
|
2629
3210
|
task.status = 'interrupted';
|
|
3211
|
+
if (routerStopped) {
|
|
3212
|
+
task.acknowledged = true;
|
|
3213
|
+
task.resultSummary = ROUTER_STOPPED_RESULT;
|
|
3214
|
+
task.finishedAt = nowIso();
|
|
3215
|
+
settleUndeliveredSteers(task, terminalSteerReason('interrupted'));
|
|
3216
|
+
}
|
|
3217
|
+
else {
|
|
3218
|
+
task.interruptedFrom = interruptedFrom;
|
|
3219
|
+
task.interruptedAt = nowIso();
|
|
3220
|
+
}
|
|
2630
3221
|
task.updatedAt = nowIso();
|
|
2631
3222
|
persistTaskFile(tasksDir, task);
|
|
2632
3223
|
}
|
|
@@ -2643,14 +3234,17 @@ function createTaskStore(opts) {
|
|
|
2643
3234
|
acknowledge(id, false);
|
|
2644
3235
|
}
|
|
2645
3236
|
// The router stops tasks by title or id (castle-stop fence), or "all" to
|
|
2646
|
-
// stop everything still active.
|
|
2647
|
-
//
|
|
3237
|
+
// stop everything still active. Held, waiting, and blocked tasks are
|
|
3238
|
+
// cancelled outright; running ones get their
|
|
2648
3239
|
// agent process killed and finalize as interrupted via the stopRequested
|
|
2649
3240
|
// path (see haltTask).
|
|
2650
3241
|
function stop(tokens) {
|
|
2651
3242
|
const ids = meansAll(tokens)
|
|
2652
3243
|
? [...tasks.values()]
|
|
2653
|
-
.filter((t) => t.status === '
|
|
3244
|
+
.filter((t) => t.status === 'held' ||
|
|
3245
|
+
t.status === 'running' ||
|
|
3246
|
+
t.status === 'waiting' ||
|
|
3247
|
+
t.status === 'blocked')
|
|
2654
3248
|
.map((t) => t.id)
|
|
2655
3249
|
: resolveTargets(tasks, tokens);
|
|
2656
3250
|
const targets = [];
|
|
@@ -2661,16 +3255,23 @@ function createTaskStore(opts) {
|
|
|
2661
3255
|
targets.push({ id: task.id, title: task.title, status: task.status, progress: task.progress });
|
|
2662
3256
|
haltTask(task, children, stopRequested, touch);
|
|
2663
3257
|
}
|
|
3258
|
+
// A cancelled held or waiting row finalizes no run, so nothing else would
|
|
3259
|
+
// re-check the tasks waiting `after:` it; they flip to blocked here.
|
|
3260
|
+
if (targets.length > 0)
|
|
3261
|
+
rescheduleAll();
|
|
2664
3262
|
return targets;
|
|
2665
3263
|
}
|
|
2666
3264
|
return {
|
|
3265
|
+
resumeRecovered: rescheduleAll,
|
|
2667
3266
|
sorted,
|
|
2668
3267
|
get: (id) => tasks.get(id),
|
|
2669
3268
|
touch,
|
|
2670
3269
|
spawnFromDirective,
|
|
3270
|
+
releaseHeld,
|
|
2671
3271
|
acknowledge,
|
|
2672
3272
|
checkOff,
|
|
2673
3273
|
stop,
|
|
3274
|
+
send: (directives, originMessageId) => sendToTasks({ tasks, steerChannels, onFeed: opts.onFeed, touch }, directives, originMessageId),
|
|
2674
3275
|
pendingDurables,
|
|
2675
3276
|
clearPendingDurables,
|
|
2676
3277
|
shutdown,
|
|
@@ -2685,11 +3286,12 @@ const ATTACHMENT_MIME = {
|
|
|
2685
3286
|
webp: 'image/webp',
|
|
2686
3287
|
};
|
|
2687
3288
|
// Decode pasted/attached images (data URLs) into .castle/agent/attachments/.
|
|
2688
|
-
// Returns the saved file names.
|
|
3289
|
+
// Returns the saved file names, and which of them carry the user's marks.
|
|
2689
3290
|
function saveAttachments(attachmentsDir, messageId, images) {
|
|
2690
|
-
if (!Array.isArray(images))
|
|
2691
|
-
return [];
|
|
2692
3291
|
const saved = [];
|
|
3292
|
+
const marked = [];
|
|
3293
|
+
if (!Array.isArray(images))
|
|
3294
|
+
return { saved, marked };
|
|
2693
3295
|
for (const [index, image] of images.slice(0, MAX_ATTACHMENTS).entries()) {
|
|
2694
3296
|
const dataUrl = image?.dataUrl;
|
|
2695
3297
|
if (typeof dataUrl !== 'string' || dataUrl.length > MAX_ATTACHMENT_BYTES * 1.4)
|
|
@@ -2703,12 +3305,14 @@ function saveAttachments(attachmentsDir, messageId, images) {
|
|
|
2703
3305
|
fs.mkdirSync(attachmentsDir, { recursive: true });
|
|
2704
3306
|
atomicWriteFileSync(path.join(attachmentsDir, fileName), Buffer.from(match[2], 'base64'));
|
|
2705
3307
|
saved.push(fileName);
|
|
3308
|
+
if (image.marked === true)
|
|
3309
|
+
marked.push(fileName);
|
|
2706
3310
|
}
|
|
2707
3311
|
catch {
|
|
2708
3312
|
/* disk trouble -- skip this image */
|
|
2709
3313
|
}
|
|
2710
3314
|
}
|
|
2711
|
-
return saved;
|
|
3315
|
+
return { saved, marked };
|
|
2712
3316
|
}
|
|
2713
3317
|
function isExistingFile(abs) {
|
|
2714
3318
|
try {
|
|
@@ -2848,11 +3452,17 @@ function asPromptTask(task) {
|
|
|
2848
3452
|
status: task.rejected ? 'rejected by user' : task.status,
|
|
2849
3453
|
progress: task.progress,
|
|
2850
3454
|
notes: task.notes,
|
|
3455
|
+
...(task.model ? { model: task.model } : {}),
|
|
3456
|
+
...(task.effort ? { effort: task.effort } : {}),
|
|
2851
3457
|
item: task.item,
|
|
2852
3458
|
error: task.status === 'failed'
|
|
2853
|
-
? routerTaskError(firstErrorLine(task.resultSummary), task.failure, task.errorCopy)
|
|
3459
|
+
? withTimeoutReport(routerTaskError(firstErrorLine(task.resultSummary), task.failure, task.errorCopy), task)
|
|
2854
3460
|
: undefined,
|
|
3461
|
+
interrupted: platformInterruptionReason(task),
|
|
2855
3462
|
blockedBy: task.status === 'blocked' ? task.blockedBy : undefined,
|
|
3463
|
+
sent: TASK_STEER_ENABLED ? steerBoardNote(task.steers) : undefined,
|
|
3464
|
+
heldQuestion: task.status === 'held' ? task.heldFor?.question : undefined,
|
|
3465
|
+
answer: task.answer,
|
|
2856
3466
|
};
|
|
2857
3467
|
}
|
|
2858
3468
|
function asClientTask(task, signPath) {
|
|
@@ -2869,6 +3479,8 @@ function asClientTask(task, signPath) {
|
|
|
2869
3479
|
account: task.account,
|
|
2870
3480
|
avatar: task.avatar,
|
|
2871
3481
|
phase: task.phase,
|
|
3482
|
+
heldFor: task.heldFor,
|
|
3483
|
+
answer: task.answer,
|
|
2872
3484
|
acknowledged: task.acknowledged,
|
|
2873
3485
|
rejected: task.rejected,
|
|
2874
3486
|
errorCopy: task.errorCopy,
|
|
@@ -3098,6 +3710,10 @@ function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
|
|
|
3098
3710
|
// rewrites CLAUDE.md, and the next turn has to see the kit's guide.
|
|
3099
3711
|
const deckGuide = readQuickReference(ctx.deckDir);
|
|
3100
3712
|
const messages = ctx.log.messages.filter((message) => message.role !== 'log' && message.id !== selfMessageId && message.status !== 'streaming');
|
|
3713
|
+
const tasks = ctx.taskStore.sorted();
|
|
3714
|
+
const lastReplyAtMs = panelWriteWatermark(ctx.log.messages, selfMessageId);
|
|
3715
|
+
const taskClaudeModel = ctx.taskClaudeModel();
|
|
3716
|
+
const taskOpenrouterModel = ctx.taskOpenrouterModel();
|
|
3101
3717
|
return buildRouterPromptParts({
|
|
3102
3718
|
deckLabel: ctx.deckLabel,
|
|
3103
3719
|
quickReference: quickReferenceFor(ctx.deckDir, deckGuide, 'router'),
|
|
@@ -3106,7 +3722,19 @@ function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
|
|
|
3106
3722
|
deckTree: buildDeckTree(ctx.deckDir),
|
|
3107
3723
|
playtest: playtestEnabled(ctx.deckDir),
|
|
3108
3724
|
playtestPref: playtestPrefFor(ctx.deckDir),
|
|
3109
|
-
|
|
3725
|
+
steer: TASK_STEER_ENABLED || undefined,
|
|
3726
|
+
unsentSends: TASK_STEER_ENABLED
|
|
3727
|
+
? messages.filter((m) => m.role === 'assistant').at(-1)?.unsent
|
|
3728
|
+
: undefined,
|
|
3729
|
+
isFreeModel: (model) => modelIsFree(model, ctx.freeModelPrefixes()),
|
|
3730
|
+
routerModel: {
|
|
3731
|
+
model: spawnModelFor(ctx.claudeModel(), ctx.openrouterModel()),
|
|
3732
|
+
effort: spawnEffortFor(ctx.claudeModel(), ctx.openrouterModel(), ctx.effort()),
|
|
3733
|
+
},
|
|
3734
|
+
taskModel: {
|
|
3735
|
+
model: spawnModelFor(taskClaudeModel, taskOpenrouterModel),
|
|
3736
|
+
effort: spawnEffortFor(taskClaudeModel, taskOpenrouterModel, ctx.taskEffort()),
|
|
3737
|
+
},
|
|
3110
3738
|
messages: messages.map((m) => ({
|
|
3111
3739
|
role: m.role,
|
|
3112
3740
|
// Replace a prior turn's raw ```ask JSON with a readable question list
|
|
@@ -3120,15 +3748,15 @@ function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
|
|
|
3120
3748
|
progress: note.progress,
|
|
3121
3749
|
repliesAgo: note.repliesAgo,
|
|
3122
3750
|
})),
|
|
3751
|
+
endedBadly: badTaskEndingsSince(tasks, lastReplyAtMs).map(asPromptTask),
|
|
3123
3752
|
// Only the live board -- match what the user sees. Hide tasks that are
|
|
3124
3753
|
// BOTH acknowledged AND finished; an active (running/waiting) task always
|
|
3125
3754
|
// shows even if somehow acked, so nothing can ever go invisible mid-work.
|
|
3126
|
-
tasks:
|
|
3127
|
-
.sorted()
|
|
3755
|
+
tasks: tasks
|
|
3128
3756
|
.filter((t) => !(t.acknowledged && isTerminal(t.status)))
|
|
3129
3757
|
.map(asPromptTask),
|
|
3130
|
-
plan: routerPlanOpts(ctx.deckDir, plan, ctx.taskStore.pendingDurables(),
|
|
3131
|
-
paramsWrites: panelWritesSince(ctx.deckDir,
|
|
3758
|
+
plan: routerPlanOpts(ctx.deckDir, plan, ctx.taskStore.pendingDurables(), tasks),
|
|
3759
|
+
paramsWrites: panelWritesSince(ctx.deckDir, lastReplyAtMs),
|
|
3132
3760
|
instruction,
|
|
3133
3761
|
});
|
|
3134
3762
|
}
|
|
@@ -3194,15 +3822,23 @@ function spawnCompletedTaskFences(ctx, message, midStream, raw) {
|
|
|
3194
3822
|
return;
|
|
3195
3823
|
const inFlight = new Set(ctx.taskStore
|
|
3196
3824
|
.sorted()
|
|
3197
|
-
.filter((t) => t.status === 'running' || t.status === 'waiting')
|
|
3825
|
+
.filter((t) => t.status === 'held' || t.status === 'running' || t.status === 'waiting')
|
|
3198
3826
|
.map((t) => t.title.toLowerCase()));
|
|
3199
3827
|
const newIds = [];
|
|
3200
3828
|
for (const { directive, at } of directives) {
|
|
3201
3829
|
const key = directive.title.toLowerCase();
|
|
3830
|
+
// A held task needs the reply's question and chips, which may stream after
|
|
3831
|
+
// its fence; the settle-time parse spawns it from the whole reply instead.
|
|
3832
|
+
// Every fence after it waits too: one may name it in `after:`, and that
|
|
3833
|
+
// only resolves once the held row exists.
|
|
3834
|
+
if (directive.hold)
|
|
3835
|
+
midStream.sawHold = true;
|
|
3836
|
+
if (midStream.sawHold)
|
|
3837
|
+
continue;
|
|
3202
3838
|
if (inFlight.has(key) || midStream.spawnedTitles.has(key))
|
|
3203
3839
|
continue;
|
|
3204
3840
|
applyStreamedPrefs(ctx, raw.slice(0, at));
|
|
3205
|
-
newIds.push(ctx.taskStore.spawnFromDirective(directive, message.id));
|
|
3841
|
+
newIds.push(ctx.taskStore.spawnFromDirective(directive, message.id, message.text));
|
|
3206
3842
|
midStream.spawnedTitles.add(key);
|
|
3207
3843
|
}
|
|
3208
3844
|
if (newIds.length === 0)
|
|
@@ -3298,9 +3934,16 @@ function runRouterTurnIn(ctx, instruction) {
|
|
|
3298
3934
|
settleInterruptedTurn(ctx, message);
|
|
3299
3935
|
return;
|
|
3300
3936
|
}
|
|
3301
|
-
const { cleaned, directives, checkoffs, stops, prefs, plan } = extractDirectives(result.finalText
|
|
3937
|
+
const { cleaned, directives, checkoffs, stops, prefs, sends, plan } = extractDirectives(result.finalText, {
|
|
3938
|
+
sends: TASK_STEER_ENABLED,
|
|
3939
|
+
});
|
|
3302
3940
|
if (result.ok && checkoffs.length > 0)
|
|
3303
3941
|
ctx.taskStore.checkOff(checkoffs);
|
|
3942
|
+
if (result.ok && sends.length > 0) {
|
|
3943
|
+
const unsent = ctx.taskStore.send(sends, message.id);
|
|
3944
|
+
if (unsent.length > 0)
|
|
3945
|
+
message.unsent = unsent;
|
|
3946
|
+
}
|
|
3304
3947
|
if (result.ok && stops.length > 0) {
|
|
3305
3948
|
const notes = stopNotes(ctx.taskStore.stop(stops));
|
|
3306
3949
|
if (notes.length > 0)
|
|
@@ -3333,13 +3976,19 @@ function runRouterTurnIn(ctx, instruction) {
|
|
|
3333
3976
|
const stale = epoch !== ctx.currentEpoch();
|
|
3334
3977
|
const inFlight = new Set(ctx.taskStore
|
|
3335
3978
|
.sorted()
|
|
3336
|
-
.filter((t) => t.status === 'running' || t.status === 'waiting')
|
|
3979
|
+
.filter((t) => t.status === 'held' || t.status === 'running' || t.status === 'waiting')
|
|
3337
3980
|
.map((t) => t.title.toLowerCase()));
|
|
3981
|
+
// A failed reply may have died before its chips, and a held row with
|
|
3982
|
+
// none can never be released by a tap. Everything after that fence goes
|
|
3983
|
+
// with it: a later one may wait on it, and without the row it would
|
|
3984
|
+
// start at once.
|
|
3985
|
+
const firstHold = directives.findIndex((d) => d.hold);
|
|
3986
|
+
const settled = result.ok || firstHold < 0 ? directives : directives.slice(0, firstHold);
|
|
3338
3987
|
const toSpawn = stale
|
|
3339
3988
|
? []
|
|
3340
|
-
:
|
|
3989
|
+
: settled.filter((d) => !inFlight.has(d.title.toLowerCase()) &&
|
|
3341
3990
|
!midStream.spawnedTitles.has(d.title.toLowerCase()));
|
|
3342
|
-
const newlySpawnedIds = toSpawn.map((d) => ctx.taskStore.spawnFromDirective(d, message.id));
|
|
3991
|
+
const newlySpawnedIds = toSpawn.map((d) => ctx.taskStore.spawnFromDirective(d, message.id, cleaned));
|
|
3343
3992
|
const taskIds = [...(message.taskIds ?? []), ...newlySpawnedIds];
|
|
3344
3993
|
if (result.ok) {
|
|
3345
3994
|
message.text = cleaned;
|
|
@@ -3663,6 +4312,47 @@ function startChildRegistry(registryPath, groups) {
|
|
|
3663
4312
|
}
|
|
3664
4313
|
};
|
|
3665
4314
|
}
|
|
4315
|
+
// -- agent server -------------------------------------------------------------
|
|
4316
|
+
// The eval's way to put a message into a task at the moment a user sent it,
|
|
4317
|
+
// without a router turn in between: the same send a castle-send fence makes.
|
|
4318
|
+
function handleSendTask(taskStore, socket, msg) {
|
|
4319
|
+
const requestId = typeof msg.requestId === 'string' ? msg.requestId : undefined;
|
|
4320
|
+
const task = typeof msg.task === 'string' ? msg.task.trim() : '';
|
|
4321
|
+
const text = typeof msg.text === 'string' ? msg.text.trim() : '';
|
|
4322
|
+
const reply = (payload) => {
|
|
4323
|
+
if (socket.readyState === socket.OPEN) {
|
|
4324
|
+
socket.send(JSON.stringify({ type: 'send-task-result', requestId, ...payload }));
|
|
4325
|
+
}
|
|
4326
|
+
};
|
|
4327
|
+
if (!task || !text) {
|
|
4328
|
+
reply({ error: 'send-task needs a task title or id and a non-empty text' });
|
|
4329
|
+
return;
|
|
4330
|
+
}
|
|
4331
|
+
const unsent = taskStore.send([{ target: task, text }], `send-task:${requestId ?? 'anon'}`);
|
|
4332
|
+
reply(unsent.length > 0 ? { error: `send-task named no task on the board: ${task}` } : { ok: true });
|
|
4333
|
+
}
|
|
4334
|
+
// The eval's castle-stop: the same halt a router fence makes, so a stopped task
|
|
4335
|
+
// finalizes interrupted instead of reading as a crash that gets retried.
|
|
4336
|
+
function handleStopTask(taskStore, socket, msg) {
|
|
4337
|
+
const requestId = typeof msg.requestId === 'string' ? msg.requestId : undefined;
|
|
4338
|
+
const task = typeof msg.task === 'string' ? msg.task.trim() : '';
|
|
4339
|
+
const stopped = (task ? taskStore.stop([task]) : []).filter((t) => ['running', 'waiting', 'blocked'].includes(t.status));
|
|
4340
|
+
if (socket.readyState === socket.OPEN) {
|
|
4341
|
+
socket.send(JSON.stringify({
|
|
4342
|
+
type: 'stop-task-result',
|
|
4343
|
+
requestId,
|
|
4344
|
+
...(stopped.length > 0 ? { stopped: stopped.map((t) => t.id) } : { error: `stop-task named no task: ${task}` }),
|
|
4345
|
+
}));
|
|
4346
|
+
}
|
|
4347
|
+
}
|
|
4348
|
+
// A mirror on disk is not evidence: only names that are also this send's
|
|
4349
|
+
// attachments count as marked.
|
|
4350
|
+
function markedOf(item) {
|
|
4351
|
+
if (!Array.isArray(item.marked))
|
|
4352
|
+
return {};
|
|
4353
|
+
const marked = item.marked.filter((name) => typeof name === 'string' && item.attachments.includes(name));
|
|
4354
|
+
return marked.length > 0 ? { marked } : {};
|
|
4355
|
+
}
|
|
3666
4356
|
// Restart recovery: load the durable queue mirror, keeping only well-formed
|
|
3667
4357
|
// sends that never reached the message log. A send whose id is already in
|
|
3668
4358
|
// messages.json was committed by a prior drain (its turn ran, finished or
|
|
@@ -3683,6 +4373,7 @@ function loadRecoverableSends(deckDir, pendingPath, committedIds) {
|
|
|
3683
4373
|
id: item.id,
|
|
3684
4374
|
text: item.text,
|
|
3685
4375
|
attachments: item.attachments.filter((a) => typeof a === 'string'),
|
|
4376
|
+
...markedOf(item),
|
|
3686
4377
|
// Re-validated rather than trusted: enqueue is where a ref earns its
|
|
3687
4378
|
// place, and a mirror on disk is not evidence it ever did. A build that
|
|
3688
4379
|
// predates @-mentions wrote none at all, which is a send worth
|
|
@@ -3767,6 +4458,10 @@ function startRouterTurn(ctx, instruction) {
|
|
|
3767
4458
|
claudeModel: () => ctx.settings.routerClaudeModel,
|
|
3768
4459
|
openrouterModel: () => ctx.settings.routerOpenrouterModel,
|
|
3769
4460
|
effort: () => ctx.settings.routerEffort,
|
|
4461
|
+
taskClaudeModel: () => ctx.settings.tasksClaudeModel,
|
|
4462
|
+
taskOpenrouterModel: () => ctx.settings.tasksOpenrouterModel,
|
|
4463
|
+
taskEffort: () => ctx.settings.tasksEffort,
|
|
4464
|
+
freeModelPrefixes: ctx.freeModelPrefixes,
|
|
3770
4465
|
canAutoRetry: () => !ctx.state.autoRetryUsed && ctx.state.pendingSends.length === 0,
|
|
3771
4466
|
onSettled: (retryable) => onRouterQueueSettled(ctx, retryable),
|
|
3772
4467
|
}, instruction);
|
|
@@ -3778,6 +4473,7 @@ function startRouterTurn(ctx, instruction) {
|
|
|
3778
4473
|
function commitDrainedSends(drained, log) {
|
|
3779
4474
|
const texts = [];
|
|
3780
4475
|
const attachmentPaths = [];
|
|
4476
|
+
const markedPaths = [];
|
|
3781
4477
|
const refs = [];
|
|
3782
4478
|
for (const item of drained) {
|
|
3783
4479
|
if (!item.logged) {
|
|
@@ -3799,11 +4495,14 @@ function commitDrainedSends(drained, log) {
|
|
|
3799
4495
|
if (item.text.trim())
|
|
3800
4496
|
texts.push(item.text);
|
|
3801
4497
|
for (const name of item.attachments) {
|
|
3802
|
-
|
|
4498
|
+
const attachmentPath = path.join('.castle', 'agent', 'attachments', name);
|
|
4499
|
+
attachmentPaths.push(attachmentPath);
|
|
4500
|
+
if (item.marked?.includes(name))
|
|
4501
|
+
markedPaths.push(attachmentPath);
|
|
3803
4502
|
}
|
|
3804
4503
|
refs.push(...item.refs);
|
|
3805
4504
|
}
|
|
3806
|
-
return { texts, attachmentPaths, refs: uniqueLocators(refs) };
|
|
4505
|
+
return { texts, attachmentPaths, markedPaths, refs: uniqueLocators(refs) };
|
|
3807
4506
|
}
|
|
3808
4507
|
// Drain the queue into the log as real user messages and start one follow-up
|
|
3809
4508
|
// turn addressing them all (a burst batches into a single turn). A pending
|
|
@@ -3819,7 +4518,13 @@ function maybeStartRouterQueueTurn(ctx) {
|
|
|
3819
4518
|
// Kept so a fold or manual interrupt of THIS turn can hand these sends back
|
|
3820
4519
|
// to reclaimInFlightSends if it dies before producing anything visible.
|
|
3821
4520
|
state.inFlightSends = drained;
|
|
3822
|
-
|
|
4521
|
+
// Released at drain, not enqueue: a queued tap can still be cancelled. And
|
|
4522
|
+
// before the commit: recovery skips a committed send, so a crash between
|
|
4523
|
+
// the two must find the send still pending, where replaying it is a no-op.
|
|
4524
|
+
for (const send of drained)
|
|
4525
|
+
if (!send.hideFromUi)
|
|
4526
|
+
ctx.taskStore.releaseHeld(send.text);
|
|
4527
|
+
const { texts, attachmentPaths, markedPaths, refs } = commitDrainedSends(drained, ctx.log);
|
|
3823
4528
|
// The queue is now committed to messages.json; clear its durable mirror.
|
|
3824
4529
|
persistPendingSends(ctx);
|
|
3825
4530
|
const draft = state.pendingInterruptedDraft;
|
|
@@ -3830,6 +4535,7 @@ function maybeStartRouterQueueTurn(ctx) {
|
|
|
3830
4535
|
messages: texts,
|
|
3831
4536
|
interruptedDraft: draft || undefined,
|
|
3832
4537
|
attachments: attachmentPaths,
|
|
4538
|
+
marked: markedPaths,
|
|
3833
4539
|
refs,
|
|
3834
4540
|
}));
|
|
3835
4541
|
}
|
|
@@ -3909,11 +4615,12 @@ function handleQueueUserMessage(ctx, text, images, refs, clientId, hideFromUi) {
|
|
|
3909
4615
|
return;
|
|
3910
4616
|
}
|
|
3911
4617
|
const id = sentId ?? nanoid(8);
|
|
3912
|
-
const attachments = saveAttachments(ctx.attachmentsDir, id, images);
|
|
4618
|
+
const { saved: attachments, marked } = saveAttachments(ctx.attachmentsDir, id, images);
|
|
3913
4619
|
state.pendingSends.push({
|
|
3914
4620
|
id,
|
|
3915
4621
|
text,
|
|
3916
4622
|
attachments,
|
|
4623
|
+
...(marked.length > 0 ? { marked } : {}),
|
|
3917
4624
|
refs: validMessageRefs(ctx.deckDir, refs),
|
|
3918
4625
|
...(hideFromUi ? { hideFromUi: true } : {}),
|
|
3919
4626
|
});
|
|
@@ -4054,10 +4761,22 @@ function makePlaytestRunner(deps) {
|
|
|
4054
4761
|
};
|
|
4055
4762
|
}
|
|
4056
4763
|
// No task agent running or waiting its turn: the moment the board's work is all on disk.
|
|
4057
|
-
|
|
4058
|
-
|
|
4059
|
-
|
|
4060
|
-
|
|
4764
|
+
// A held task writes nothing until its answer comes, which may be never, so it
|
|
4765
|
+
// must not hold the deck busy or block its commits.
|
|
4766
|
+
export function taskBoardIdle(taskStore) {
|
|
4767
|
+
const all = taskStore.sorted();
|
|
4768
|
+
const byId = new Map(all.map((t) => [t.id, t]));
|
|
4769
|
+
return !all.some((t) => t.status === 'running' ||
|
|
4770
|
+
(t.status === 'waiting' && !t.acknowledged && !waitsOnHeld(t, byId, new Set())));
|
|
4771
|
+
}
|
|
4772
|
+
function waitsOnHeld(task, byId, seen) {
|
|
4773
|
+
seen.add(task.id);
|
|
4774
|
+
return task.after.some((depId) => {
|
|
4775
|
+
const dep = byId.get(depId);
|
|
4776
|
+
if (!dep || seen.has(dep.id))
|
|
4777
|
+
return false;
|
|
4778
|
+
return dep.status === 'held' || (dep.status === 'waiting' && waitsOnHeld(dep, byId, seen));
|
|
4779
|
+
});
|
|
4061
4780
|
}
|
|
4062
4781
|
export function createAgentServer(opts) {
|
|
4063
4782
|
const { deckDir, deckLabel } = opts;
|
|
@@ -4067,10 +4786,9 @@ export function createAgentServer(opts) {
|
|
|
4067
4786
|
const attachmentsDir = path.join(agentDir, 'attachments');
|
|
4068
4787
|
const messagesPath = path.join(agentDir, 'messages.json');
|
|
4069
4788
|
fs.mkdirSync(tasksDir, { recursive: true });
|
|
4070
|
-
// Read the
|
|
4071
|
-
//
|
|
4789
|
+
// Read the plan switch this deck declares now, so the whole serve shares one
|
|
4790
|
+
// answer -- see planSession.
|
|
4072
4791
|
planSession(deckDir);
|
|
4073
|
-
askCallsEnabled(deckDir);
|
|
4074
4792
|
// Warm the OpenRouter catalog now so the first pre-flight and the first
|
|
4075
4793
|
// popover open read a cache instead of paying for the fetch. Fire-and-forget
|
|
4076
4794
|
// by design -- nothing here depends on it, and it falls open if it fails.
|
|
@@ -4190,6 +4908,7 @@ export function createAgentServer(opts) {
|
|
|
4190
4908
|
// guard). Lives in its own factory; createAgentServer just wires it up.
|
|
4191
4909
|
const routerQueue = createRouterQueue({
|
|
4192
4910
|
deckDir,
|
|
4911
|
+
freeModelPrefixes: usageFeed.freeModelPrefixes,
|
|
4193
4912
|
deckLabel,
|
|
4194
4913
|
agentDir,
|
|
4195
4914
|
attachmentsDir,
|
|
@@ -4218,6 +4937,11 @@ export function createAgentServer(opts) {
|
|
|
4218
4937
|
}
|
|
4219
4938
|
}
|
|
4220
4939
|
function handleTaskAck(id, rejected) {
|
|
4940
|
+
const task = taskStore.get(id);
|
|
4941
|
+
if (task?.status === 'held') {
|
|
4942
|
+
taskStore.stop([id]);
|
|
4943
|
+
return;
|
|
4944
|
+
}
|
|
4221
4945
|
taskStore.acknowledge(id, rejected);
|
|
4222
4946
|
}
|
|
4223
4947
|
// `after` goes through the same resolveTargets the router's fences use, so a
|
|
@@ -4327,6 +5051,12 @@ export function createAgentServer(opts) {
|
|
|
4327
5051
|
else if (msg.type === 'spawn-task' && SPAWN_TASK_MESSAGE_ENABLED) {
|
|
4328
5052
|
handleSpawnTask(socket, msg);
|
|
4329
5053
|
}
|
|
5054
|
+
else if (msg.type === 'send-task' && SPAWN_TASK_MESSAGE_ENABLED && TASK_STEER_ENABLED) {
|
|
5055
|
+
handleSendTask(taskStore, socket, msg);
|
|
5056
|
+
}
|
|
5057
|
+
else if (msg.type === 'stop-task' && SPAWN_TASK_MESSAGE_ENABLED) {
|
|
5058
|
+
handleStopTask(taskStore, socket, msg);
|
|
5059
|
+
}
|
|
4330
5060
|
else if (msg.type === 'set-settings') {
|
|
4331
5061
|
applySettings(msg);
|
|
4332
5062
|
}
|
|
@@ -4403,5 +5133,11 @@ export function createAgentServer(opts) {
|
|
|
4403
5133
|
wss.close();
|
|
4404
5134
|
void playtestBrowserManager?.shutdown();
|
|
4405
5135
|
}
|
|
4406
|
-
return {
|
|
5136
|
+
return {
|
|
5137
|
+
handleUpgrade,
|
|
5138
|
+
handleHttpRequest,
|
|
5139
|
+
runPlaytestFor,
|
|
5140
|
+
resumeRecovered: () => taskStore.resumeRecovered(),
|
|
5141
|
+
shutdown,
|
|
5142
|
+
};
|
|
4407
5143
|
}
|