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.
@@ -228,9 +228,11 @@ export function failureLabel(failure) {
228
228
  return failure.reason ? `${failure.kind}/${failure.reason}` : failure.kind;
229
229
  }
230
230
  // The router reads only a failed task's technical error line, and its standing
231
- // advice is to spawn a replacement; a config failure would fail the same way
232
- // again, so its row also carries the copy that says so.
231
+ // advice is to spawn a replacement. Config failures also carry the recovery
232
+ // copy; limit failures use only that plain copy instead of the proxy denial.
233
233
  export function routerTaskError(errorLine, failure, errorCopy) {
234
+ if (failure?.startsWith("limit") && errorCopy)
235
+ return errorCopy;
234
236
  if (!errorLine || !errorCopy || !failure?.startsWith("config"))
235
237
  return errorLine;
236
238
  return `${errorLine} -- ${errorCopy}`;
@@ -9,9 +9,15 @@ export interface PromptTask {
9
9
  status: string;
10
10
  progress: number;
11
11
  notes: string;
12
+ model?: string;
13
+ effort?: string;
12
14
  item?: string;
13
15
  error?: string;
16
+ interrupted?: string;
14
17
  blockedBy?: string[];
18
+ sent?: string;
19
+ heldQuestion?: string;
20
+ answer?: string;
15
21
  }
16
22
  export interface PromptStop {
17
23
  title: string;
@@ -51,6 +57,10 @@ export declare const PLAYTEST_OFF_FENCE_RULE = "- If the user asks for no playte
51
57
  export declare const PLAYTEST_ON_FENCE_RULE = "- The user turned playtest checks off for this deck: never ask a task to verify with the playtest tool. If they ask for them back, emit this fence and confirm in one line:\n```castle-pref\nplaytest: on\n```";
52
58
  export declare const TASK_FENCE_PROMPT_EXAMPLE = "Then a SHORT self-contained prompt -- one tight paragraph (aim under 100\nwords): what to build or fix and what \"done\" looks like. Task agents read\nthe deck's own docs for framework/API detail, so never restate recipes,\nfile layouts, or implementation steps.";
53
59
  export declare const PLAYTEST_TASK_UNDRIVEN_RULE = "- The playtest tool is a headless preview, not the user's device. If you could not make the behavior in question happen there, or checking it needs something the preview did not give you (a microphone, a camera, a second player, a native app command, the phone's on-screen keyboard), your result says exactly that -- \"I could not drive X in the headless preview because Y; unverified\" -- instead of reporting what the code implies. Never write \"verified\" for something you did not observe, and when you did observe it, say it was verified in the headless preview.";
60
+ export declare const STOP_RULE_STEER = "- When a new message is about work a task is still running or waiting to run -- it corrects it, adds to it, narrows it, or answers a question you asked about it -- `castle-send` it to that task instead of stopping it: the task keeps what it has done and adjusts. Stop a running or waiting task only when the user said to stop or drop it, or took back what it is building so completely that nothing it has done would survive. When that change comes with new work, stop it in the SAME reply that spawns the replacement. When the new ask is about something else, leave the task running and spawn the new work as its own task: in parallel, or with `after:` naming it only when the new work needs that task's actual output. Never stop a task because a new one restates it or covers it more broadly.";
61
+ export declare const STEER_MODEL_CLAUSE = ", as a new task even when it changes a running one: a castle-send keeps that task's model.";
62
+ export declare const SEND_FENCE_RULES = "\n\nTo hand a message to a task that is running or waiting to run:\n\n```castle-send\nthe task's title or id, alone on the first line\nthe user's message for it -- their own words, quoted, plus only what from this conversation the task needs to act on them\n```\n\n- `castle-send` reaches a RUNNING or WAITING task: it reads the message at its next step and folds it into the work it is doing, without starting over. One fence per task. It is the ONLY thing that reaches a running task -- a reply that says a task will pick something up, without this fence, sends nothing. The board row shows each message you sent and whether the task has read it.\n- It cannot reach a finished task. For those, spawn a new task (see the one-and-done rule below).";
63
+ export declare const PROBE_CLAUSE_STEER = "But NEVER spawn work a pending probe could invalidate outright: castle-send can pass the answer to a running task, but it cannot undo work the answer throws away.";
54
64
  export declare function truncateToBytes(line: string, budget: number): string;
55
65
  export type PlanOpVerb = "decide" | "open" | "tried" | "now" | "identity";
56
66
  export interface PlanOpSource {
@@ -84,8 +94,12 @@ export declare function applyPlanOps(fileText: string, ops: PlanOp[], sources?:
84
94
  export declare function renderPlanDigest(plan: RouterPlanOpts, tasks: PromptTask[]): string;
85
95
  export declare function planOpenQuestionLines(fileText: string): string[];
86
96
  export declare function renderTaskPlanSlice(fileText: string, item: string | undefined, finishedWork?: PlanFinishedWork[]): string;
97
+ export type FreeModelCheck = (model: string) => boolean;
98
+ export declare function modelLabel(model: string, isFreeModel: FreeModelCheck): string;
87
99
  export declare const NO_DECK_DOCS = "This deck has no CLAUDE.md / AGENTS.md quick reference. There is no documentation to read -- do not search for one (CLAUDE.md, README, **/*.md, etc.).";
88
100
  export declare const STOPPED_TASKS_HEADER = "Tasks you stopped with castle-stop. They started and you cancelled them; none finished. What the user saw: the task appeared on their board and then vanished. So if the user says a task never started, or asks where it went, say plainly that you stopped it (not that it never started), then re-send it if they still want it";
101
+ export declare const BAD_TASK_ENDINGS_HEADER = "Tasks that ended badly since your last reply. Tell the user about these at the start of your reply, plainly. Do not talk as if they are still running";
102
+ export declare const UNSENT_HEADER = "Your last reply's castle-send named no task on the board, so NOTHING was sent for these. If you told the user it was passed on, correct that now, and send it to the right task or spawn it";
89
103
  export interface RouterPromptParts {
90
104
  system: string;
91
105
  user: string;
@@ -97,10 +111,21 @@ export interface RouterPromptOpts {
97
111
  messages: PromptMessage[];
98
112
  tasks: PromptTask[];
99
113
  stopped?: PromptStop[];
114
+ endedBadly?: PromptTask[];
100
115
  plan?: RouterPlanOpts;
101
116
  playtest?: boolean;
102
117
  playtestPref?: 'on' | 'off';
103
- askCalls?: boolean;
118
+ steer?: boolean;
119
+ unsentSends?: string[];
120
+ routerModel?: {
121
+ model: string;
122
+ effort: string;
123
+ };
124
+ taskModel?: {
125
+ model: string;
126
+ effort: string;
127
+ };
128
+ isFreeModel?: FreeModelCheck;
104
129
  editorTabs?: string[];
105
130
  kits?: string[];
106
131
  paramsWrites?: string[];
@@ -120,6 +145,7 @@ export declare function userTurnInstruction(opts: {
120
145
  messages: string[];
121
146
  interruptedDraft?: string;
122
147
  attachments?: string[];
148
+ marked?: string[];
123
149
  refs?: PromptRef[];
124
150
  }): string;
125
151
  export declare function buildTaskPrompt(opts: {
@@ -33,7 +33,25 @@ file layouts, or implementation steps.`;
33
33
  // Directive v2, the task half: added beside the v1 verify line rather than as an
34
34
  // edit of it (memo 26-09-03-13-27), so v1's measured wording stands.
35
35
  export const PLAYTEST_TASK_UNDRIVEN_RULE = '- The playtest tool is a headless preview, not the user\'s device. If you could not make the behavior in question happen there, or checking it needs something the preview did not give you (a microphone, a camera, a second player, a native app command, the phone\'s on-screen keyboard), your result says exactly that -- "I could not drive X in the headless preview because Y; unverified" -- instead of reporting what the code implies. Never write "verified" for something you did not observe, and when you did observe it, say it was verified in the headless preview.';
36
- function baseRouterRules(playtest, playtestPref) {
36
+ const STOP_RULE_NO_STEER = `- Stop a running or waiting task only when the new message makes its work unwanted: the user said to stop or drop it, took back or reversed what it is building, or corrected it -- it has the wrong idea, or they picked a different option than the one it is building -- so its result would have to be undone. When that change comes with new work, stop it in the SAME reply that spawns the replacement. When the new ask adds to a running task, extends it, or is about something else, leave it running and spawn the new work as its own task: in parallel, or with \`after:\` naming it only when the new work needs that task's actual output. Nothing reaches a running task, so leaving it running never covers the new ask by itself. Never stop a task because a new one restates it or covers it more broadly.`;
37
+ export const STOP_RULE_STEER = `- When a new message is about work a task is still running or waiting to run -- it corrects it, adds to it, narrows it, or answers a question you asked about it -- \`castle-send\` it to that task instead of stopping it: the task keeps what it has done and adjusts. Stop a running or waiting task only when the user said to stop or drop it, or took back what it is building so completely that nothing it has done would survive. When that change comes with new work, stop it in the SAME reply that spawns the replacement. When the new ask is about something else, leave the task running and spawn the new work as its own task: in parallel, or with \`after:\` naming it only when the new work needs that task's actual output. Never stop a task because a new one restates it or covers it more broadly.`;
38
+ // A castle-send keeps the running task's recorded model, so a change the user
39
+ // wants on another model cannot ride it.
40
+ export const STEER_MODEL_CLAUSE = ", as a new task even when it changes a running one: a castle-send keeps that task's model.";
41
+ export const SEND_FENCE_RULES = `
42
+
43
+ To hand a message to a task that is running or waiting to run:
44
+
45
+ \`\`\`castle-send
46
+ the task's title or id, alone on the first line
47
+ the user's message for it -- their own words, quoted, plus only what from this conversation the task needs to act on them
48
+ \`\`\`
49
+
50
+ - \`castle-send\` reaches a RUNNING or WAITING task: it reads the message at its next step and folds it into the work it is doing, without starting over. One fence per task. It is the ONLY thing that reaches a running task -- a reply that says a task will pick something up, without this fence, sends nothing. The board row shows each message you sent and whether the task has read it.
51
+ - It cannot reach a finished task. For those, spawn a new task (see the one-and-done rule below).`;
52
+ function baseRouterRules(playtest, playtestPref, steer = false) {
53
+ const runningTaskRules = steer ? STOP_RULE_STEER : STOP_RULE_NO_STEER;
54
+ const sendFenceRules = steer ? SEND_FENCE_RULES : '';
37
55
  const playtestRules = playtestPref === 'off'
38
56
  ? `\n${PLAYTEST_ON_FENCE_RULE}`
39
57
  : playtestPref === 'on'
@@ -41,6 +59,7 @@ function baseRouterRules(playtest, playtestPref) {
41
59
  : playtest
42
60
  ? `\n${PLAYTEST_ROUTER_RULE}`
43
61
  : '';
62
+ const modelsRule = `\n- You cannot change which models run. Both are set in the model chip under the message box (Agent & model settings): Operator model and Operator effort set the model you, this chat, run on; Task model and Task effort set the model new tasks run on. A change applies to what starts after it, not to anything already running. When the user asks which model you or their tasks run on, asks to switch to or use a model or effort, or says they have switched: answer from == models == (and, when relevant, the model on the rows they mean), which always shows the current settings; trust it over anything said earlier in this chat, which may be wrong. If it does not show what they say they picked, tell them that setting has not changed yet. Point them to the matching row; never say you switched it or that it has changed when == models == does not show it. If the same message asks for work they want done on a model or effort == models == does not show yet, do not spawn that work yet: tell them to change the setting and send the request again. When == models == already shows it, spawn the work as usual${steer ? STEER_MODEL_CLAUSE : '.'} Apart from a usage-limit failure (above), do not bring up models when the user did not.`;
44
63
  return `You are Castle's create assistant: the fast conversational router for a game-making session. The deck (game project) lives in the current directory and runs live in a pane right next to this chat.
45
64
 
46
65
  What a deck is: a normal web project served by vite -- index.html plus plain JS/JSX modules, with real npm dependencies (more can be installed), the castle-web-sdk package, and usually a kit framework whose engine, behaviors, scenes, editors, and drawings are ordinary files in this directory. The web platform is fully available (DOM, canvas, npm libraries like react, three, etc.). The deck's Quick reference and file list below describe its setup; the full CLAUDE.md / AGENTS.md has deeper detail. NEVER claim something is impossible or unsupported on the platform without checking that context (or, for specifics it doesn't cover, the deck's files) first.
@@ -66,6 +85,7 @@ Hard rules:
66
85
  \`\`\`castle-task
67
86
  short imperative title on the first line
68
87
  after: comma-separated titles or ids this task must wait for (optional line)
88
+ hold: answer (optional line -- only on the task a probe in this same reply decides)
69
89
  ${TASK_FENCE_PROMPT_EXAMPLE}
70
90
  \`\`\`
71
91
 
@@ -81,10 +101,12 @@ comma-separated active-task titles or ids, or \`all\`
81
101
  \`\`\`
82
102
 
83
103
  - \`castle-done\` removes FINISHED rows (done/failed). Use it when the user confirms a task works, or to clear a finished task that has become obsolete (replaced by newer work). \`all\` clears every finished row.
84
- - \`castle-stop\` stops AND removes ACTIVE rows (running/waiting/blocked) -- a running task's agent is killed. Its unfinished work is thrown away. Use it when the user asks to stop something, or under the rule below. \`all\` stops everything active.
104
+ - \`castle-stop\` stops AND removes ACTIVE rows (running/waiting/blocked) -- a running task's agent is killed. Its unfinished work is thrown away. Use it when the user asks to stop something, or under the rule below. \`all\` stops everything active.${sendFenceRules}
85
105
  - When you spawn a task that fixes or redoes a FINISHED one, \`castle-done\` the earlier row in the SAME reply. Keep the board meaning "what to look at right now".
86
- - Stop a running or waiting task only when the new message makes its work unwanted: the user said to stop or drop it, took back or reversed what it is building, or corrected it -- it has the wrong idea, or they picked a different option than the one it is building -- so its result would have to be undone. When that change comes with new work, stop it in the SAME reply that spawns the replacement. When the new ask adds to a running task, extends it, or is about something else, leave it running and spawn the new work as its own task: in parallel, or with \`after:\` naming it only when the new work needs that task's actual output. Nothing reaches a running task, so leaving it running never covers the new ask by itself. Never stop a task because a new one restates it or covers it more broadly.
106
+ ${runningTaskRules}
87
107
  - A \`failed\` row carries an \`error:\` line -- why it failed. A \`blocked\` row waited on a dep that failed or was stopped, so its output never arrived and it will never start on its own -- \`blocked by:\` names that dep. When you see one, decide for the user: usually spawn a replacement task (or pipeline) that redoes the failed work, and in the SAME reply \`castle-stop\` the blocked row and \`castle-done\` the failed one, so the board stays clean.
108
+ - A failed row whose error is a usage limit -- the free-model daily allowance, credits, or a spending limit -- will fail the same way if respawned. Do not respawn it. Tell the user what ran out, when it resets if the row says, and that they can pick another model in settings (or get credits) to keep going. Point them to the Task model setting described below; you cannot change it.${modelsRule}
109
+ - An interrupted row with an \`interrupted:\` platform reason was cut off, not stopped by you. Tell the user, and redo it only if they want it (their message may already ask); part of its work may already be on disk.
88
110
  - Do not mark a task done to imply YOU verified its quality -- the user playtests and confirms that. But DO keep the board tidy: clear finished work the user blessed, and remove anything clearly obsolete. When genuinely unsure, leave the row.
89
111
  - Never claim the board is cleared without actually emitting the fence.
90
112
  - Tasks are one-and-done -- when the user gives feedback on a finished task, spawn a new fix task (and \`castle-done\` the old row) rather than reopening it -- unless their words ask to go back to an earlier state, which is the version-history rule below.
@@ -112,14 +134,8 @@ Conversation style:
112
134
  - Spawning a task does NOT apply the change -- tasks run for minutes and finish on the board. Talk about spawned work in future tense ("this will dial the shake back"), and NEVER ask how a change feels right after spawning it -- the user cannot have tried it yet. Save "how is it?" for things whose task already finished.
113
135
  - The user playtests in the pane beside this chat; finished work shows up there after a reload.`;
114
136
  }
115
- const SPEC_RULE = `- CLEAR SPEC (mechanics named, a reference given, "like X but Y"): the gaps are closed. Build what they said; never probe taste they already expressed.`;
116
- const PROBE_CAP_RULE = `- At most ONE probe open at a time; none on spec, delegation, or conversation turns; never re-probe something answered. Probe feel and identity -- what the player DOES, how it should feel, the goal shape, the tone -- never implementation.`;
117
- // The q-a2 router arm (prompt-evals t1-router-ladder arms/q-a2.ts), for the
118
- // decks that opted in (`agent.askCalls` / CASTLE_AGENT_ASK_CALLS -- see
119
- // askCallsEnabled in agent.ts). Off for everyone by default, so the plan rules
120
- // stay byte-identical to a prompt built before it existed.
121
- const ASK_CALLS_SPEC_RULE = `- CLEAR SPEC (mechanics named, a reference given, "like X but Y"): build what they said; never probe taste they already expressed.`;
122
- const ASK_CALLS_PROBE_CAP_RULE = `- At most ONE probe open at a time; none on delegation or conversation turns; never re-probe something answered. Before you close a task fence, find the one thing that task will have to settle on its own: a word of theirs that reads two ways, or a case their ask never mentions. Quote the word and ask which, as a probe, your reading as the first chip and the other as the second. The work spawns either way; the chip only tells the next task which way it went.`;
137
+ const SPEC_RULE = `- CLEAR SPEC (mechanics named, a reference given, "like X but Y"): build what they said; never probe taste they already expressed.`;
138
+ const PROBE_CAP_RULE = `- At most ONE probe open at a time; none on delegation or conversation turns; never re-probe something answered. Before you close a task fence, find the one thing that task will have to settle on its own: a word of theirs that reads two ways, or a case their ask never mentions. Quote the word and ask which, as a probe, your reading as the first chip and the other as the second. Then split the work by that answer. Tasks the answer cannot change spawn now. The task it decides gets a \`hold: answer\` line: it waits on the board and starts with their reply appended, whichever chip they tap or whatever they type. When the answer decides everything they asked for, the probe and that held task are the whole reply -- a held task is still building. Before you close each unheld task fence, reread its brief: if it names or assumes any option of your probe -- even in passing, like a control scheme, a count, or which screen -- that task decides it too. Give it the \`hold: answer\` line, or move that choice out of it into the held task and write the rest so it works with either answer. When they tap a chip, the task you held for it starts on its own with their answer -- the board shows it running with that answer. Acknowledge it in one line; never spawn it again or stop it. A row still held means they typed instead: if their message answers the probe, castle-stop the held row and spawn it again with their answer; otherwise leave it held.`;
123
139
  // Appended to the rules above for a deck with the plan doc on -- see
124
140
  // planSession in agent.ts for which decks those are. One self-contained block,
125
141
  // so a deck without it gets the pre-plan prompt byte for byte.
@@ -128,9 +144,12 @@ const ASK_CALLS_PROBE_CAP_RULE = `- At most ONE probe open at a time; none on de
128
144
  // deliberately supersede rules in the block above (pairing a question with
129
145
  // task directives, and holding follow-up questions back), which is why they say
130
146
  // so out loud rather than quietly contradicting them.
131
- function planRules(askCalls) {
147
+ const PROBE_CLAUSE_NO_STEER = 'But NEVER spawn work a pending probe could invalidate: there is no telling a running task anything.';
148
+ export const PROBE_CLAUSE_STEER = 'But NEVER spawn work a pending probe could invalidate outright: castle-send can pass the answer to a running task, but it cannot undo work the answer throws away.';
149
+ function planRules(steer = false) {
150
+ const probeRunningTaskClause = steer ? PROBE_CLAUSE_STEER : PROBE_CLAUSE_NO_STEER;
132
151
  return `Reading the user, fresh from EACH message -- the same user hands you a spec, then a fragment, then delegates:
133
- ${askCalls ? ASK_CALLS_SPEC_RULE : SPEC_RULE}
152
+ ${SPEC_RULE}
134
153
  - FRAGMENT ("something with ants", "a cozy game about tea?"): gaps they cannot name yet. Draw their taste out on the few dimensions that decide whether this feels like THEIRS -- while building, never instead of building.
135
154
  - A fragment is not only a whole-game ask. "how about some obstacles?", "make it feel brighter" name a slice and leave its taste open: build the part they named, and probe the ONE dimension you were about to settle for them. Deciding it silently is how a deck becomes yours instead of theirs.
136
155
  - A build turn that was going to carry NO question at all is where a feel question belongs, and on a deck already underway most turns are that: they name a change, you make it, nothing is asked, and the feel of it was yours by default. If what you are about to build has a feel they have not named -- how hard it should be, how fast it should move, how it should land -- ask that one thing in the same reply as the work. This never replaces a question you were already going to ask: still one at a time, and if you already had one, keep it.
@@ -143,8 +162,8 @@ Probing while you build. A probe is one short plain question plus 2-4 tappable o
143
162
  [[Guide them with trails]] [[Command each ant]] [[Just watch them live]]
144
163
 
145
164
  - Tapping one sends its text as the user's next message; they can ignore it and type anything else, and the build continues either way. Never phrase a probe as if an answer were required.
146
- - Spawn the work the answer cannot invalidate AND attach the probe in the same reply -- this supersedes the rules above against pairing a question with task directives. But NEVER spawn work a pending probe could invalidate: there is no telling a running task anything.
147
- ${askCalls ? ASK_CALLS_PROBE_CAP_RULE : PROBE_CAP_RULE}
165
+ - Spawn the work the answer cannot invalidate AND attach the probe in the same reply -- this supersedes the rules above against pairing a question with task directives. ${probeRunningTaskClause}
166
+ ${PROBE_CAP_RULE}
148
167
  - Chips NEVER stand on their own: a probe's question is the line right before them, and a probe is the only thing they are for. Alone they read as answers to a question nobody asked.
149
168
  - Praise is where the pull to offer something is strongest and most wrong: "oh nice, that works great" gets one plain sentence and nothing else. Vary it -- a compliment that always gets the same reply stops reading as one.
150
169
 
@@ -179,9 +198,9 @@ Promotion. Finished tasks leave notes worth keeping, listed above with the id of
179
198
 
180
199
  If the user asks you to ease off the questions or the plan upkeep, record that with a \`decide+\` quoting the ask, and honor it -- keep \`## Now\` current, quietly.`;
181
200
  }
182
- function routerRules(plan, playtest, askCalls, playtestPref) {
183
- const base = baseRouterRules(playtest, playtestPref);
184
- return plan ? `${base}\n\n${planRules(askCalls)}` : base;
201
+ function routerRules(plan, playtest, playtestPref, steer = false) {
202
+ const base = baseRouterRules(playtest, playtestPref, steer);
203
+ return plan ? `${base}\n\n${planRules(steer)}` : base;
185
204
  }
186
205
  function renderTranscriptLine(m) {
187
206
  if (m.role === "user")
@@ -863,18 +882,44 @@ export function renderTaskPlanSlice(fileText, item, finishedWork) {
863
882
  // deck that opted out -- which is both meaningless there (nothing tells that
864
883
  // router what an item is) and a break in the byte-identity the opt-out
865
884
  // promises.
866
- function renderTasks(tasks, showItems) {
885
+ // The names the composer's model chip shows (formatRoleSettings in
886
+ // shell/operator.tsx), so the router's answer matches what the user sees in
887
+ // settings rather than a provider slug. "Muse" is the chip's name for a model
888
+ // Castle pays for, which only the budget's free prefixes decide.
889
+ const CLAUDE_MODEL_LABELS = { sonnet: "Sonnet", opus: "Opus", fable: "Fable" };
890
+ const noFreeModels = () => false;
891
+ export function modelLabel(model, isFreeModel) {
892
+ const trimmed = model.trim();
893
+ if (CLAUDE_MODEL_LABELS[trimmed])
894
+ return CLAUDE_MODEL_LABELS[trimmed];
895
+ if (isFreeModel(trimmed))
896
+ return "Muse";
897
+ return trimmed.slice(trimmed.lastIndexOf("/") + 1);
898
+ }
899
+ function renderTasks(tasks, showItems, isFreeModel) {
867
900
  if (tasks.length === 0)
868
901
  return "(none yet)";
869
902
  return tasks
870
903
  .map((t) => {
871
904
  const item = showItems && t.item ? ` -- item: ${t.item}` : "";
905
+ const model = t.model || t.effort
906
+ ? ` -- model: ${[t.model && modelLabel(t.model, isFreeModel), t.effort].filter(Boolean).join(" ")}`
907
+ : "";
872
908
  const notes = t.notes.trim() ? ` -- notes: ${t.notes.trim()}` : "";
873
909
  const error = t.error ? ` -- error: ${t.error}` : "";
910
+ const interrupted = t.interrupted ? ` -- interrupted: ${t.interrupted}` : "";
874
911
  const blockedBy = t.blockedBy && t.blockedBy.length > 0
875
912
  ? ` -- blocked by: ${t.blockedBy.join(", ")}`
876
913
  : "";
877
- return `- [${t.status} ${t.progress}%] ${t.title} (${t.id})${item}${notes}${error}${blockedBy}`;
914
+ const sent = t.sent ? ` -- messages you sent it: ${t.sent}` : "";
915
+ const row = `- [${t.status} ${t.progress}%] ${t.title} (${t.id})${item}${model}${notes}${error}${interrupted}${blockedBy}${sent}`;
916
+ const held = t.status === "held" && t.heldQuestion !== undefined
917
+ ? `\n held -- waiting on the answer to: ${t.heldQuestion}`
918
+ : "";
919
+ const answered = (t.status === "waiting" || t.status === "running") && t.answer !== undefined
920
+ ? `\n started with their answer: "${t.answer}"`
921
+ : "";
922
+ return `${row}${held}${answered}`;
878
923
  })
879
924
  .join("\n");
880
925
  }
@@ -888,6 +933,8 @@ export const NO_DECK_DOCS = "This deck has no CLAUDE.md / AGENTS.md quick refere
888
933
  // Muse agreed with them until told how it looked from their side (memo
889
934
  // 26-09-25-20-55: 7/27 -> 17/27 true answers).
890
935
  export const STOPPED_TASKS_HEADER = "Tasks you stopped with castle-stop. They started and you cancelled them; none finished. What the user saw: the task appeared on their board and then vanished. So if the user says a task never started, or asks where it went, say plainly that you stopped it (not that it never started), then re-send it if they still want it";
936
+ export const BAD_TASK_ENDINGS_HEADER = "Tasks that ended badly since your last reply. Tell the user about these at the start of your reply, plainly. Do not talk as if they are still running";
937
+ export const UNSENT_HEADER = "Your last reply's castle-send named no task on the board, so NOTHING was sent for these. If you told the user it was passed on, correct that now, and send it to the right task or spawn it";
891
938
  export function buildRouterPromptParts(opts) {
892
939
  // Making the ABSENCE explicit, not just omitting the section, matters: a
893
940
  // router on a bare/greenfield deck otherwise has no way to tell "no docs
@@ -919,6 +966,18 @@ export function buildRouterPromptParts(opts) {
919
966
  const paramsWrites = opts.paramsWrites?.length
920
967
  ? `\n\n== parameters panel ==\nThe user set these from the Parameters panel since your last turn:\n${opts.paramsWrites.map((slot) => `- ${slot}`).join("\n")}`
921
968
  : "";
969
+ const models = [
970
+ opts.routerModel
971
+ ? `This chat (you) runs on: ${modelLabel(opts.routerModel.model, opts.isFreeModel ?? noFreeModels)} (effort ${opts.routerModel.effort})`
972
+ : undefined,
973
+ opts.taskModel
974
+ ? `New tasks run on: ${modelLabel(opts.taskModel.model, opts.isFreeModel ?? noFreeModels)} (effort ${opts.taskModel.effort})`
975
+ : undefined,
976
+ ].filter((line) => line !== undefined);
977
+ // Above the board, not beside the user's message: last in the prompt, the
978
+ // models lines tipped the router into spawning (n19-cover-host, 26-09-28:
979
+ // 19/19 spawns vs 6/19 off; 5/10 once moved here).
980
+ const modelsSection = models.length ? `\n\n== models ==\n${models.join("\n")}` : "";
922
981
  const stopped = opts.stopped?.length
923
982
  ? `\n\n${STOPPED_TASKS_HEADER}:\n${opts.stopped
924
983
  .map((stop) => {
@@ -927,6 +986,18 @@ export function buildRouterPromptParts(opts) {
927
986
  })
928
987
  .join("\n")}`
929
988
  : "";
989
+ const endedBadly = opts.endedBadly?.length
990
+ ? `\n\n${BAD_TASK_ENDINGS_HEADER}:\n${opts.endedBadly
991
+ .map((task) => {
992
+ const reason = task.error ?? task.interrupted;
993
+ const status = task.interrupted ? "interrupted" : "failed";
994
+ return `- "${task.title}" (${task.id}): ${status} at ${task.progress}%${reason ? ` -- ${reason}` : ""}`;
995
+ })
996
+ .join("\n")}`
997
+ : "";
998
+ const unsent = opts.unsentSends?.length
999
+ ? `\n\n${UNSENT_HEADER}:\n${opts.unsentSends.map((target) => `- "${target}"`).join("\n")}`
1000
+ : "";
930
1001
  // Two parts, split for prompt caching. `system` holds what is the same from
931
1002
  // one turn to the next within a serve -- the rules, the deck identity and
932
1003
  // the file tree -- and is sent as system text, which is the prefix the
@@ -934,15 +1005,15 @@ export function buildRouterPromptParts(opts) {
934
1005
  // does not. `user` holds what changes every turn: the transcript, the plan,
935
1006
  // the board and this instruction.
936
1007
  return {
937
- system: `${routerRules(opts.plan !== undefined, opts.playtest === true, opts.askCalls === true, opts.playtestPref)}
1008
+ system: `${routerRules(opts.plan !== undefined, opts.playtest === true, opts.playtestPref, opts.steer === true)}
938
1009
 
939
1010
  == deck ==
940
1011
  ${opts.deckLabel}${quickReference}${editorTabs}${kits}${deckFiles}`,
941
1012
  user: `== conversation so far ==
942
- ${renderTranscript(opts.messages)}${plan}
1013
+ ${renderTranscript(opts.messages)}${plan}${modelsSection}
943
1014
 
944
1015
  == background tasks ==
945
- ${renderTasks(opts.tasks, opts.plan !== undefined)}${stopped}${paramsWrites}
1016
+ ${renderTasks(opts.tasks, opts.plan !== undefined, opts.isFreeModel ?? noFreeModels)}${endedBadly}${stopped}${unsent}${paramsWrites}
946
1017
 
947
1018
  == now ==
948
1019
  ${opts.instruction}
@@ -983,7 +1054,11 @@ export function userTurnInstruction(opts) {
983
1054
  .join("\n\n")}`);
984
1055
  }
985
1056
  if (opts.attachments && opts.attachments.length > 0) {
986
- parts.push(`The user attached image file(s), saved in the deck at: ${opts.attachments.join(", ")}. Open them with your read tool. Take them into account; pass the paths along to task agents that need them.`);
1057
+ const marked = opts.marked ?? [];
1058
+ const markNote = marked.length > 0
1059
+ ? ` ${marked.join(", ")} ${marked.length === 1 ? "carries" : "carry"} the user's marks drawn on top of the game in red; numbered pins match the numbered lines in their message.`
1060
+ : "";
1061
+ parts.push(`The user attached image file(s), saved in the deck at: ${opts.attachments.join(", ")}. Open them with your read tool. Take them into account; pass the paths along to task agents that need them.${markNote}`);
987
1062
  }
988
1063
  if (opts.refs && opts.refs.length > 0) {
989
1064
  parts.push(`The user pointed at: ${opts.refs.map(refPhrase).join(", ")}. Read them with your read tool if you need them to reply. When you spawn a task one of these concerns, name it the same way in that task's prompt -- the path and the lines, or the path and the param -- so the agent reads that place; do not mention it to tasks it does not concern.`);
package/dist/agent.d.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  import { type EffortLevel } from './effortSupport.js';
2
2
  import * as http from 'http';
3
3
  import { Duplex } from 'stream';
4
- import { type PlaytestToolResult } from './native/playtest.js';
4
+ import { type TaskDirective } from './routerFences.js';
5
+ import { type SendDirective, type TaskSteer } from './taskSteer.js';
6
+ import { type StopTarget } from './routerStops.js';
7
+ import { type PlaytestExecutor, type PlaytestToolResult } from './native/playtest.js';
5
8
  export declare const AGENT_WS_PATH = "/__castle/agent";
6
9
  export type ClaudeModel = 'sonnet' | 'opus' | 'fable' | 'openrouter';
7
10
  export type { EffortLevel };
@@ -25,7 +28,10 @@ export declare function taskPlaytestFor(deckDir: string): {
25
28
  tool: boolean;
26
29
  };
27
30
  export declare function playtestToolArgs(tool: boolean, deckDir: string, taskId: string | undefined): string[];
28
- type TaskStatus = 'waiting' | 'running' | 'blocked' | 'done' | 'failed' | 'interrupted';
31
+ export declare const TASK_TIMEOUT_MS: number;
32
+ export declare const WRAP_UP_TIMEOUT_MS: number;
33
+ export declare const RESUME_MAX_AGE_MS: number;
34
+ type TaskStatus = 'held' | 'waiting' | 'running' | 'blocked' | 'done' | 'failed' | 'interrupted';
29
35
  interface TaskUsage {
30
36
  input?: number;
31
37
  output?: number;
@@ -54,6 +60,12 @@ interface TaskRecord {
54
60
  finishedAt?: string;
55
61
  pid?: number;
56
62
  originMessageId?: string;
63
+ heldFor?: {
64
+ messageId: string;
65
+ question: string;
66
+ chips: string[];
67
+ };
68
+ answer?: string;
57
69
  playtestFrames?: string[];
58
70
  resultSummary?: string;
59
71
  account?: string;
@@ -64,6 +76,9 @@ interface TaskRecord {
64
76
  phase?: string;
65
77
  acknowledged?: boolean;
66
78
  rejected?: boolean;
79
+ interruptedFrom?: 'running' | 'waiting';
80
+ interruptedAt?: string;
81
+ resumeCount?: number;
67
82
  durable?: string;
68
83
  what?: string;
69
84
  files?: string[];
@@ -78,18 +93,60 @@ interface TaskRecord {
78
93
  numTurns?: number;
79
94
  usage?: TaskUsage;
80
95
  modelUsage?: Record<string, TaskModelUsage>;
96
+ steers?: TaskSteer[];
81
97
  }
82
98
  export declare function playtestEnabled(deckDir: string): boolean;
83
99
  export declare function playtestPrefFor(deckDir: string): 'on' | 'off' | undefined;
84
100
  export declare function setPlaytestPref(deckDir: string, value: 'on' | 'off'): boolean;
85
- export declare function askCallsEnabled(deckDir: string): boolean;
101
+ interface AgentRunHandle {
102
+ pid?: number | undefined;
103
+ exitCode: number | null;
104
+ spawnfile: string;
105
+ kill(signal?: NodeJS.Signals): boolean;
106
+ }
86
107
  export interface DepsState {
87
108
  kind: 'ready' | 'waiting' | 'blocked';
88
109
  blockedBy?: string[];
89
110
  }
90
111
  export declare function classifyDeps(tasks: Map<string, TaskRecord>, task: TaskRecord): DepsState;
112
+ interface TaskStore {
113
+ sorted(): TaskRecord[];
114
+ get(id: string): TaskRecord | undefined;
115
+ /** Persist + broadcast a record the caller mutated in place. */
116
+ touch(task: TaskRecord): void;
117
+ spawnFromDirective(directive: TaskDirective, originMessageId: string, originText?: string): string;
118
+ releaseHeld(answer: string): string[];
119
+ acknowledge(id: string, rejected: boolean): TaskRecord | undefined;
120
+ checkOff(tokens: string[]): void;
121
+ stop(tokens: string[]): StopTarget[];
122
+ send(directives: SendDirective[], originMessageId?: string): string[];
123
+ pendingDurables(): TaskRecord[];
124
+ clearPendingDurables(): void;
125
+ resumeRecovered(): void;
126
+ shutdown(): void;
127
+ }
128
+ export declare function createTaskStore(opts: {
129
+ deckDir: string;
130
+ deckLabel: string;
131
+ tasksDir: string;
132
+ children: Set<AgentRunHandle>;
133
+ claudeModel: () => ClaudeModel;
134
+ openrouterModel: () => string;
135
+ effort: () => EffortLevel;
136
+ playtest?: {
137
+ executor: PlaytestExecutor;
138
+ serveUrl: string;
139
+ };
140
+ onUpdate: (task: TaskRecord) => void;
141
+ onStarted: (task: TaskRecord) => void;
142
+ onFinished: (task: TaskRecord) => void;
143
+ onRetry: (task: TaskRecord, attempt: number) => void;
144
+ onFeed: (task: TaskRecord, entry: string) => void;
145
+ }): TaskStore;
91
146
  export declare function computeSettingsWarnings(settings: AgentSettings): Promise<SettingsWarnings>;
92
147
  export interface AgentServer {
148
+ /** Start tasks recovered from a restart; call once the serve is listening. */
149
+ resumeRecovered(): void;
93
150
  /** Attach the agent WebSocket if the upgrade targets the agent path. */
94
151
  handleUpgrade(req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean;
95
152
  /** Serve attachment images. Returns true if it handled the request. */
@@ -106,6 +163,7 @@ export interface AgentServer {
106
163
  }): Promise<PlaytestToolResult>;
107
164
  shutdown(): void;
108
165
  }
166
+ export declare function taskBoardIdle(taskStore: Pick<TaskStore, 'sorted'>): boolean;
109
167
  export declare function createAgentServer(opts: {
110
168
  deckDir: string;
111
169
  deckLabel: string;