castle-web-cli 0.4.195 → 0.4.197
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-prompts.js +7 -6
- package/dist/agent.d.ts +17 -0
- package/dist/agent.js +158 -6
- package/dist/shell/assets/{index-D6leLNUq.css → index-MSHtKPXt.css} +1 -1
- package/dist/shell/assets/index-yHGXRGlX.js +449 -0
- package/dist/shell/index.html +2 -2
- package/kits/base/castle.json +1 -1
- package/kits/base/package-lock.json +1 -1
- package/kits/physics-2d/CLAUDE.md +96 -11
- package/kits/physics-2d/behaviors/AnalogStick.jsx +28 -26
- package/kits/physics-2d/behaviors/Draggable.jsx +10 -8
- package/kits/physics-2d/behaviors/Goal.jsx +16 -3
- package/kits/physics-2d/behaviors/Slingshot.jsx +24 -22
- package/kits/physics-2d/behaviors/SoundPlayer.jsx +42 -5
- package/kits/physics-2d/behaviors/Sprite.jsx +21 -16
- package/kits/physics-2d/castle.json +2 -2
- package/kits/physics-2d/editors/SceneEditor.jsx +15 -1
- package/kits/physics-2d/editors/behaviorRegistry.js +14 -3
- package/kits/physics-2d/engine/SceneUI.jsx +11 -11
- package/kits/physics-2d/engine/scene.js +143 -20
- package/kits/physics-2d/engine/tap.js +9 -11
- package/package.json +1 -1
- package/dist/shell/assets/index-kMH1qj6D.js +0 -449
package/dist/agent-prompts.js
CHANGED
|
@@ -35,12 +35,13 @@ Hard rules:
|
|
|
35
35
|
- You NEVER edit files or run state-changing commands. All building and fixing happens through background task agents -- always hand the longer work to them.
|
|
36
36
|
- IMPORTS ARE YOURS, and they are the one exception to the rule above. Run \`castle-web list-decks --kind kits\` (also \`mine\` and \`saved\`) to see what this deck can import, and \`castle-web add-import <deckIdOrUrl>\` to add one -- both directly, not through a task. Do NOT claim you can list or import anything until you have actually run these; do not describe imports you have not looked at. \`list-decks\` prints one deck per line starting with the id \`add-import\` takes, and marks the ones this deck already has. A pasted castle.xyz deck link works in place of an id. Everything else about a deck's files still goes to task agents.
|
|
37
37
|
- Imported files are READ-ONLY, which is what to say when the user asks whether they can change something a kit or another import gave them (an editor tab included), or why an edit to one did not stick: the deck takes its own version of that one file -- a fork, stored beside the import and used in its place -- and that version is what runs. Forking is how their own data and code changes override an import's, and a task agent does it; the tradeoff, worth saying plainly, is that a file done this way stops picking up changes when the import itself is updated, so it stays to the few files the change actually needs. Often it does not come to a fork at all, which is the better thing to say first: a kit picks up the deck's own behaviors and systems, so new logic is usually just a new file in the deck.
|
|
38
|
-
-
|
|
38
|
+
- When the user reports something broken, do NOT dig into the code to diagnose it first -- spawn a task whose job is to investigate AND fix it. A QUESTION is not a fix request: "why is X happening?" gets a task told explicitly to diagnose and CHANGE NOTHING, and your reply says that it will only look and report back.
|
|
39
|
+
- Only read deck files when your reply itself needs them (answering a question about the deck, grounding a claim -- never make things up); never read as pre-work before spawning a task, and never read files just to learn conventions already covered by the Quick reference.${playtest ? `\n${PLAYTEST_ROUTER_RULE}` : ""}
|
|
39
40
|
- When you point the user at a file, a line, or a tunable value, write it as a link they can tap: \`[label](game.js)\` for a file, \`[label](game.js#L108)\` for a line, \`[label](game.js#params)\` for a file's tunable values and \`[label](game.js#params:enemySpeed)\` for ONE of them (the key exactly as it is written in that file's \`PARAMS\` object -- \`player.speed\` for a nested one). The label is your own words for the thing; the path must be exact and must be a file this deck actually has, or it renders as plain text. A bare \`game.js#108\` in a sentence links too. Cite a line number ONLY when you have read that file with numbered lines -- any deck contents in this prompt carry none, so never count them yourself; link the file or its params instead when you are unsure.
|
|
40
41
|
- Launch a SET of small steps the user tests one by one -- a pipeline, never one big task they wait on, never untestable fragments. One interacting mechanic = one task (paddle + ball + bricks = one playable core, not three). First step = the smallest genuinely playable thing; later steps build it out. Match breadth to ambition ("basic" = a few steps; "go wild" = many). You're optimizing the user's taste and feedback -- more small testable steps = more points where they steer it into something theirs.
|
|
41
|
-
-
|
|
42
|
+
- Every piece of work should be TESTABLE in actual gameplay. Run tasks in PARALLEL. Do NOT break tasks down by which files they touch, and never add \`after:\` just to avoid two tasks editing the same file -- tasks make surgical edits and overlap fine. The only real dependency between tasks is INFORMATION: a task is blocked only when it needs a fact it does not yet have.
|
|
42
43
|
- Dissolve those information-dependencies with a CONTRACT decided up front, instead of serializing tasks. Before spawning, pin the shared names the tasks will agree on -- scene file names, behavior names, drawing file names, tags -- and give each parallel task the exact names it must CREATE or REFERENCE. Pinned names must be EXACT filenames, extension included -- \`drawings/ship.sprite\` in a kit deck (the kit's CLAUDE.md names the format), \`drawings/ship.svg\` in a bare one. A bare deck has no kit to define a default art format or loader, so its contract must also state the format and loading approach every consumer will use. Then they all run at once and converge to a working game with NO follow-up wiring task: the scene task places actors referencing behaviors and drawings by their agreed names before those files even exist; the behavior tasks create those behavior names; the drawing tasks create those drawing files. (Art: pin an exact drawing filename like \`drawings/ship.sprite\` up front -> the scene task points an actor at it while another task draws it, in parallel; no place-it-later task.) Fall back to a separate waiting wire-in task (\`after:\` the maker, on the least possible) ONLY when a task truly needs another's actual produced output, not just its agreed name. Working out this breakdown -- what to parallelize, which names to pin up front -- is the core of your job and differs per game.
|
|
43
|
-
- Write each task prompt for
|
|
44
|
+
- Write each task prompt for a testable change that delivers a meaningful step up. Dive deep only if the user asked.
|
|
44
45
|
- Real, editable assets: drawing files under \`drawings/\` for game objects, characters, and scenery as real actors; data-driven UI (health/score/HUD) and effects stay code. The logic/scene task references the REAL drawing filenames immediately (e.g. \`drawings/paddle.sprite\`) -- a not-yet-created drawing auto-renders as a plain block, so the game is playable instantly AND the real art appears the moment the drawing task writes that file, with NO scene change. Ownership is EXCLUSIVE and reciprocal: the drawing task just CREATES the files at those agreed names and must NEVER edit the scene; the scene/logic task only REFERENCES those names and must NEVER create the drawing files (a sibling task owns them). When you split art into its own task, spell out BOTH sides in the prompts you write -- tell the art task exactly which drawing names to create, and tell every consumer task to reference those names and explicitly NOT draw them itself -- so two agents never make the same sprites. (The deck's CLAUDE.md / AGENTS.md gives the deck's drawing format, file extension, and how to make art.) Never say "greybox" or other dev jargon to the user.
|
|
45
46
|
- To spawn a background task, include a fenced block in your reply:
|
|
46
47
|
|
|
@@ -74,7 +75,7 @@ comma-separated active-task titles or ids, or \`all\`
|
|
|
74
75
|
- Task agents are capable coding agents working in this same deck directory, but they know nothing about this conversation beyond your prompt.
|
|
75
76
|
- The deck keeps its own version history, and you may READ it: \`castle-web list-versions\` shows the versions newest first, and \`castle-web show-version <id>\` shows what one changed, as diffs of just those files. Use them to answer "what changed" or to ground a claim about recent work. You NEVER run \`save-version\` -- you did not make the changes, so a version of yours would not correspond to a unit of work -- and you NEVER run \`restore-version\`: going back is the user's own decision, not something you do on their behalf. For the same reason, no task you spawn may ever revert, replace, or re-scaffold the deck's scenes, scripts, or behaviors back to kit or starter content -- a fix is always a targeted edit, and every task prompt you write has to be readable that way.
|
|
76
77
|
|
|
77
|
-
Asking with options (the \`\`\`ask block). When you need the user to settle a few choices at once, emit ONE fenced block tagged \`ask\` containing JSON -- it renders inline in the chat as grouped options they tap and submit together (far better than stacking questions they can only half-answer). Reach for it to pin a direction
|
|
78
|
+
Asking with options (the \`\`\`ask block). When you need the user to settle a few choices at once, emit ONE fenced block tagged \`ask\` containing JSON -- it renders inline in the chat as grouped options they tap and submit together (far better than stacking questions they can only half-answer). Reach for it to pin a direction when their ask is vague ("make me a game" -> ask what kind), NOT to interrogate.
|
|
78
79
|
|
|
79
80
|
\`\`\`ask
|
|
80
81
|
{ "questions": [ { "id": "kind", "q": "What kind of game?", "options": ["Arcade", "Puzzle", "Platformer"] }, { "id": "feel", "q": "What should it feel like?", "options": ["Cozy", "Frantic"], "multi": true } ] }
|
|
@@ -88,7 +89,7 @@ Asking with options (the \`\`\`ask block). When you need the user to settle a fe
|
|
|
88
89
|
Conversation style:
|
|
89
90
|
- As short and focused as possible -- a few tight sentences. Concrete, energetic.
|
|
90
91
|
- Plain, everyday language for a CREATOR who may not be a programmer. No dev or game-industry jargon -- not "greybox", "scaffold", "refactor", "wire up", "placeholder art", "core loop", etc. -- in ANYTHING the user sees, including task TITLES. Say what's happening simply ("a rough playable version first, then the real art"; "Player movement", "Enemies you can fight", "Real artwork"). Task titles read like plain to-do items a non-coder understands.
|
|
91
|
-
- After spawning tasks,
|
|
92
|
+
- After spawning tasks, NEVER reply with only task directives: always include a short line of plain text. That line is for the choices you made, not for the work -- the board shows the work. Whatever these tasks will do that they did not ask for (a mechanic, where something happens in the game, a rule, how it works) was your choice: name those in one or two plain sentences, biggest first, so they can catch a wrong one before the task finishes. A question you ask in the same reply is not one of them -- asking and choosing are different acts. Work built from their own words needs only a few words that it is underway. Do NOT tack a follow-up question onto your replies by default; ask a question (at most one) only when you genuinely need the answer to proceed.
|
|
92
93
|
- When the user asks HOW to do something or to see an example, answer it yourself -- a couple of sentences, plus a short standalone snippet if it helps -- and do not spawn a task that drops a demo behavior or actor into their scene. Build it only when they want it in their game; if a task did add files, name each one and what it attached to so they can find and remove them.
|
|
93
94
|
- Do not narrate before tool calls ("Checking the deck...") -- that reads as noise in the chat. Read silently, then give one reply after your final tool call.
|
|
94
95
|
- The user sees a live task board above the chat -- never re-announce task status yourself.
|
|
@@ -143,7 +144,7 @@ now- food-hauling
|
|
|
143
144
|
- Ops are for inflection points -- a decision crystallizes, an experiment concludes, the user reflects, an item starts or finishes. A turn that changed nothing about the plan carries no fence at all.
|
|
144
145
|
- THE USER SHAPING THE GAME IS AN INFLECTION POINT. A mechanic, a rule, an entity, a mood, a difficulty they ask for is taste, not a chore: it goes in with \`decide+\` quoting the words they used, in the same reply that spawns the work. Early on nearly every ask is one of these, and a plan that holds only what is in flight has kept nothing.
|
|
145
146
|
- A bare number, a knob setting, or a bug they want gone is not taste -- just do the tweak. The REASON they give for one is: "make the islands bigger, it's already pretty hard" is a \`decide+\` about the difficulty they want, not about island size.
|
|
146
|
-
- Put the fence AFTER your task fences: tasks spawn the moment their fence closes
|
|
147
|
+
- Put the fence AFTER your task fences: tasks spawn the moment their fence closes.
|
|
147
148
|
- NOTHING in \`## Open questions\` may be answered by anything else in the same reply, fence or task: asking and deciding are different acts. A probe IS the top open question, asked in its own words.
|
|
148
149
|
- An open question you have asked outright twice, and the user passed over both times, is TABLED: \`open- <label>\` it in that reply's fence and stop asking it. Passing over it twice is their answer about the question. It comes back only if they bring it up.
|
|
149
150
|
- An ask that goes against a \`## Decisions\` line: say what was decided and why in one sentence BEFORE you build it. They may well have changed their mind -- that is theirs to say, and the line is yours to raise.
|
package/dist/agent.d.ts
CHANGED
|
@@ -20,6 +20,15 @@ type SettingsWarnings = Partial<Record<OpenrouterSlugKey, {
|
|
|
20
20
|
suggestion?: string;
|
|
21
21
|
}>>;
|
|
22
22
|
type TaskStatus = 'waiting' | 'running' | 'blocked' | 'done' | 'failed' | 'interrupted';
|
|
23
|
+
interface TaskUsage {
|
|
24
|
+
input?: number;
|
|
25
|
+
output?: number;
|
|
26
|
+
cacheRead?: number;
|
|
27
|
+
cacheCreation?: number;
|
|
28
|
+
}
|
|
29
|
+
type TaskModelUsage = TaskUsage & {
|
|
30
|
+
costUsd?: number;
|
|
31
|
+
};
|
|
23
32
|
interface TaskRecord {
|
|
24
33
|
id: string;
|
|
25
34
|
title: string;
|
|
@@ -49,6 +58,14 @@ interface TaskRecord {
|
|
|
49
58
|
knobs?: string[];
|
|
50
59
|
durablePending?: boolean;
|
|
51
60
|
blockedBy?: string[];
|
|
61
|
+
model?: string;
|
|
62
|
+
backend?: string;
|
|
63
|
+
effort?: EffortLevel;
|
|
64
|
+
costUsd?: number;
|
|
65
|
+
durationApiMs?: number;
|
|
66
|
+
numTurns?: number;
|
|
67
|
+
usage?: TaskUsage;
|
|
68
|
+
modelUsage?: Record<string, TaskModelUsage>;
|
|
52
69
|
}
|
|
53
70
|
export interface DepsState {
|
|
54
71
|
kind: 'ready' | 'waiting' | 'blocked';
|
package/dist/agent.js
CHANGED
|
@@ -376,6 +376,14 @@ function claudeSettingsArg(auth) {
|
|
|
376
376
|
...(auth?.mode === 'user-key' ? { apiKeyHelper: anthropicKeyHelperCommand() } : {}),
|
|
377
377
|
});
|
|
378
378
|
}
|
|
379
|
+
// The slug a run is actually spawned on. A task records it too, so the receipt
|
|
380
|
+
// and the spawn cannot name different models.
|
|
381
|
+
function spawnModelFor(claudeModel, openrouterModel) {
|
|
382
|
+
return claudeModel === 'openrouter' ? openrouterModel : claudeModel;
|
|
383
|
+
}
|
|
384
|
+
// The only harness left (the native loop is dormant), recorded on both the run
|
|
385
|
+
// log header and the task so a second one would read as a different value.
|
|
386
|
+
const AGENT_BACKEND = 'claude';
|
|
379
387
|
function buildAgentInvocation(role, prompt, claudeModel,
|
|
380
388
|
// Already resolved for this role by the caller (router turns pass
|
|
381
389
|
// settings.routerOpenrouterModel, task spawns settings.tasksOpenrouterModel).
|
|
@@ -390,7 +398,7 @@ taskId,
|
|
|
390
398
|
// CLI's own cache breakpoints cover it.
|
|
391
399
|
systemPrompt) {
|
|
392
400
|
const viaOpenrouter = claudeModel === 'openrouter';
|
|
393
|
-
const spawnModel =
|
|
401
|
+
const spawnModel = spawnModelFor(claudeModel, openrouterModel);
|
|
394
402
|
const systemText = [systemPrompt, role === 'task' ? CLAUDE_TASK_SYSTEM_REMINDER : undefined, role === 'task' ? modelTaskAddendum(spawnModel) : undefined]
|
|
395
403
|
.filter((text) => Boolean(text))
|
|
396
404
|
.join('\n\n');
|
|
@@ -1111,6 +1119,7 @@ function createAgentStreamState() {
|
|
|
1111
1119
|
finalText: '',
|
|
1112
1120
|
resultIsError: false,
|
|
1113
1121
|
usage: undefined,
|
|
1122
|
+
stats: undefined,
|
|
1114
1123
|
sawResult: false,
|
|
1115
1124
|
needsGap: false,
|
|
1116
1125
|
pendingTools: new Map(),
|
|
@@ -1133,6 +1142,67 @@ function parseCliUsage(raw) {
|
|
|
1133
1142
|
}
|
|
1134
1143
|
return Object.keys(usage).length > 0 ? usage : undefined;
|
|
1135
1144
|
}
|
|
1145
|
+
// task.json's token names, filled from either spelling a runner reports:
|
|
1146
|
+
// snake_case on the result event's own `usage`, camelCase inside its per-model
|
|
1147
|
+
// `modelUsage` entries.
|
|
1148
|
+
const TASK_USAGE_FIELDS = [
|
|
1149
|
+
['input', 'input_tokens', 'inputTokens'],
|
|
1150
|
+
['output', 'output_tokens', 'outputTokens'],
|
|
1151
|
+
['cacheRead', 'cache_read_input_tokens', 'cacheReadInputTokens'],
|
|
1152
|
+
['cacheCreation', 'cache_creation_input_tokens', 'cacheCreationInputTokens'],
|
|
1153
|
+
];
|
|
1154
|
+
// Infinity and NaN survive as `null` through JSON.stringify, and the loader
|
|
1155
|
+
// then drops the field -- so a bad number never enters the record at all.
|
|
1156
|
+
function finiteNumber(value) {
|
|
1157
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
1158
|
+
}
|
|
1159
|
+
// An array is not a usage map, same as the task loader's own guard.
|
|
1160
|
+
function isUsageRecord(raw) {
|
|
1161
|
+
return Boolean(raw) && typeof raw === 'object' && !Array.isArray(raw);
|
|
1162
|
+
}
|
|
1163
|
+
function taskUsageFrom(raw) {
|
|
1164
|
+
if (!isUsageRecord(raw))
|
|
1165
|
+
return undefined;
|
|
1166
|
+
const usage = {};
|
|
1167
|
+
for (const [key, snake, camel] of TASK_USAGE_FIELDS) {
|
|
1168
|
+
const value = finiteNumber(raw[snake] ?? raw[camel]);
|
|
1169
|
+
if (value !== undefined)
|
|
1170
|
+
usage[key] = value;
|
|
1171
|
+
}
|
|
1172
|
+
return Object.keys(usage).length > 0 ? usage : undefined;
|
|
1173
|
+
}
|
|
1174
|
+
function parseModelUsage(raw) {
|
|
1175
|
+
if (!isUsageRecord(raw))
|
|
1176
|
+
return undefined;
|
|
1177
|
+
const models = {};
|
|
1178
|
+
for (const [model, value] of Object.entries(raw)) {
|
|
1179
|
+
if (!isUsageRecord(value))
|
|
1180
|
+
continue;
|
|
1181
|
+
const entry = { ...taskUsageFrom(value) };
|
|
1182
|
+
const cost = finiteNumber(value.costUSD);
|
|
1183
|
+
if (cost !== undefined)
|
|
1184
|
+
entry.costUsd = cost;
|
|
1185
|
+
if (Object.keys(entry).length > 0)
|
|
1186
|
+
models[model] = entry;
|
|
1187
|
+
}
|
|
1188
|
+
return Object.keys(models).length > 0 ? models : undefined;
|
|
1189
|
+
}
|
|
1190
|
+
function parseCliRunStats(ev) {
|
|
1191
|
+
const stats = {};
|
|
1192
|
+
const costUsd = finiteNumber(ev.total_cost_usd);
|
|
1193
|
+
const durationApiMs = finiteNumber(ev.duration_api_ms);
|
|
1194
|
+
const numTurns = finiteNumber(ev.num_turns);
|
|
1195
|
+
if (costUsd !== undefined)
|
|
1196
|
+
stats.costUsd = costUsd;
|
|
1197
|
+
if (durationApiMs !== undefined)
|
|
1198
|
+
stats.durationApiMs = durationApiMs;
|
|
1199
|
+
if (numTurns !== undefined)
|
|
1200
|
+
stats.numTurns = numTurns;
|
|
1201
|
+
const modelUsage = parseModelUsage(ev.modelUsage);
|
|
1202
|
+
if (modelUsage)
|
|
1203
|
+
stats.modelUsage = modelUsage;
|
|
1204
|
+
return Object.keys(stats).length > 0 ? stats : undefined;
|
|
1205
|
+
}
|
|
1136
1206
|
function formatTokenCount(value) {
|
|
1137
1207
|
if (typeof value !== 'number')
|
|
1138
1208
|
return '?';
|
|
@@ -1236,6 +1306,7 @@ function makeAgentEventHandler(opts, state) {
|
|
|
1236
1306
|
state.finalText = typeof ev.result === 'string' && ev.result ? ev.result : state.accumulated;
|
|
1237
1307
|
state.resultIsError = ev.is_error === true;
|
|
1238
1308
|
state.usage = parseCliUsage(ev.usage);
|
|
1309
|
+
state.stats = parseCliRunStats(ev);
|
|
1239
1310
|
}
|
|
1240
1311
|
};
|
|
1241
1312
|
return handleClaudeEvent;
|
|
@@ -1368,6 +1439,7 @@ function runAgentCli(opts) {
|
|
|
1368
1439
|
finalText: state.finalText || state.accumulated,
|
|
1369
1440
|
error: 'agent run timed out',
|
|
1370
1441
|
usage: state.usage,
|
|
1442
|
+
stats: state.stats,
|
|
1371
1443
|
});
|
|
1372
1444
|
}, opts.timeoutMs);
|
|
1373
1445
|
const handleEvent = makeAgentEventHandler(opts, state);
|
|
@@ -1427,6 +1499,7 @@ function runAgentCli(opts) {
|
|
|
1427
1499
|
ok,
|
|
1428
1500
|
finalText: state.finalText || state.accumulated,
|
|
1429
1501
|
usage: state.usage,
|
|
1502
|
+
stats: state.stats,
|
|
1430
1503
|
crashed: !state.sawResult,
|
|
1431
1504
|
error,
|
|
1432
1505
|
failure: classified
|
|
@@ -1781,7 +1854,7 @@ async function runAgentTurn(opts) {
|
|
|
1781
1854
|
logHeader: {
|
|
1782
1855
|
role: opts.role,
|
|
1783
1856
|
sessionId,
|
|
1784
|
-
backend:
|
|
1857
|
+
backend: AGENT_BACKEND,
|
|
1785
1858
|
model: invocation.model,
|
|
1786
1859
|
effort: opts.effort,
|
|
1787
1860
|
systemPrompt: invocation.systemText || undefined,
|
|
@@ -1858,10 +1931,63 @@ function writeTaskIndex(tasksDir, tasks) {
|
|
|
1858
1931
|
// persisted "blocked" task is left as-is: it is not "waiting", so maybeStart
|
|
1859
1932
|
// never reconsiders it and it can't wedge or auto-start; it just sits on the
|
|
1860
1933
|
// board (blockedBy intact) until the router stops it, same as before restart.
|
|
1934
|
+
const TASK_STATUSES = ['waiting', 'running', 'blocked', 'done', 'failed', 'interrupted'];
|
|
1935
|
+
const TASK_OPTIONAL_STRINGS = [
|
|
1936
|
+
'item', 'startedAt', 'finishedAt', 'originMessageId', 'resultSummary', 'errorCopy',
|
|
1937
|
+
'errorDetail', 'avatar', 'phase', 'durable', 'what', 'model', 'backend',
|
|
1938
|
+
];
|
|
1939
|
+
const TASK_OPTIONAL_NUMBERS = ['pid', 'costUsd', 'durationApiMs', 'numTurns'];
|
|
1940
|
+
const TASK_OPTIONAL_OBJECTS = ['usage', 'modelUsage'];
|
|
1941
|
+
const TASK_OPTIONAL_BOOLEANS = ['acknowledged', 'rejected', 'durablePending'];
|
|
1942
|
+
const TASK_OPTIONAL_STRING_LISTS = ['playtestFrames', 'files', 'knobs', 'blockedBy'];
|
|
1943
|
+
const isStringList = (v) => Array.isArray(v) && v.every((s) => typeof s === 'string');
|
|
1944
|
+
// tasks/ sits in the deck, where the agent (or anything else) can write, and a
|
|
1945
|
+
// record the store can't handle used to throw inside createTaskStore and take
|
|
1946
|
+
// the whole serve down -- the deck then couldn't be opened at all. A record
|
|
1947
|
+
// without its identity (id matching its directory, title, createdAt, a known
|
|
1948
|
+
// status) is skipped; anything else that is missing or the wrong type falls
|
|
1949
|
+
// back to its default or is dropped, which also keeps older minimal records.
|
|
1950
|
+
function normalizeLoadedTask(entry, raw) {
|
|
1951
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
1952
|
+
return null;
|
|
1953
|
+
const r = raw;
|
|
1954
|
+
if (r.id !== entry ||
|
|
1955
|
+
typeof r.title !== 'string' ||
|
|
1956
|
+
typeof r.createdAt !== 'string' ||
|
|
1957
|
+
!TASK_STATUSES.includes(r.status)) {
|
|
1958
|
+
return null;
|
|
1959
|
+
}
|
|
1960
|
+
const task = {
|
|
1961
|
+
...r,
|
|
1962
|
+
prompt: typeof r.prompt === 'string' ? r.prompt : '',
|
|
1963
|
+
after: isStringList(r.after) ? r.after : [],
|
|
1964
|
+
progress: typeof r.progress === 'number' && Number.isFinite(r.progress) ? r.progress : 0,
|
|
1965
|
+
notes: typeof r.notes === 'string' ? r.notes : '',
|
|
1966
|
+
updatedAt: typeof r.updatedAt === 'string' ? r.updatedAt : r.createdAt,
|
|
1967
|
+
};
|
|
1968
|
+
if (!normalizeEffort(r.effort))
|
|
1969
|
+
delete task.effort;
|
|
1970
|
+
for (const k of TASK_OPTIONAL_NUMBERS)
|
|
1971
|
+
if (finiteNumber(r[k]) === undefined)
|
|
1972
|
+
delete task[k];
|
|
1973
|
+
for (const k of TASK_OPTIONAL_OBJECTS)
|
|
1974
|
+
if (!isUsageRecord(r[k]))
|
|
1975
|
+
delete task[k];
|
|
1976
|
+
for (const k of TASK_OPTIONAL_STRINGS)
|
|
1977
|
+
if (typeof r[k] !== 'string')
|
|
1978
|
+
delete task[k];
|
|
1979
|
+
for (const k of TASK_OPTIONAL_BOOLEANS)
|
|
1980
|
+
if (typeof r[k] !== 'boolean')
|
|
1981
|
+
delete task[k];
|
|
1982
|
+
for (const k of TASK_OPTIONAL_STRING_LISTS)
|
|
1983
|
+
if (!isStringList(r[k]))
|
|
1984
|
+
delete task[k];
|
|
1985
|
+
return task;
|
|
1986
|
+
}
|
|
1861
1987
|
function loadTasks(tasksDir) {
|
|
1862
1988
|
const tasks = new Map();
|
|
1863
1989
|
for (const entry of fs.existsSync(tasksDir) ? fs.readdirSync(tasksDir) : []) {
|
|
1864
|
-
const rec = readJsonFile(path.join(tasksDir, entry, 'task.json'));
|
|
1990
|
+
const rec = normalizeLoadedTask(entry, readJsonFile(path.join(tasksDir, entry, 'task.json')));
|
|
1865
1991
|
if (!rec)
|
|
1866
1992
|
continue;
|
|
1867
1993
|
if (rec.status === 'running' || rec.status === 'waiting') {
|
|
@@ -2171,6 +2297,23 @@ async function runTaskAgentIn(ctx, task) {
|
|
|
2171
2297
|
result.error = `agent process kept dying (${MAX_TASK_ATTEMPTS} attempts): ${result.error ?? ''}`;
|
|
2172
2298
|
return result;
|
|
2173
2299
|
}
|
|
2300
|
+
// The finishing attempt's numbers onto the record. Only one attempt ever has
|
|
2301
|
+
// any: runTaskAgentIn retries exactly the attempts that died before a result
|
|
2302
|
+
// event, so there is never an earlier set to add this one to.
|
|
2303
|
+
function recordRunLedger(task, result) {
|
|
2304
|
+
const usage = taskUsageFrom(result.usage);
|
|
2305
|
+
if (usage)
|
|
2306
|
+
task.usage = usage;
|
|
2307
|
+
const { costUsd, durationApiMs, numTurns, modelUsage } = result.stats ?? {};
|
|
2308
|
+
if (costUsd !== undefined)
|
|
2309
|
+
task.costUsd = costUsd;
|
|
2310
|
+
if (durationApiMs !== undefined)
|
|
2311
|
+
task.durationApiMs = durationApiMs;
|
|
2312
|
+
if (numTurns !== undefined)
|
|
2313
|
+
task.numTurns = numTurns;
|
|
2314
|
+
if (modelUsage)
|
|
2315
|
+
task.modelUsage = modelUsage;
|
|
2316
|
+
}
|
|
2174
2317
|
// Launch a task's agent run and wire up its finalization. The settle path is
|
|
2175
2318
|
// hardened: result-finalization, onFinished, and the reschedule sweep each run
|
|
2176
2319
|
// under their own try/catch so one bad task turn can neither wedge the board
|
|
@@ -2180,8 +2323,14 @@ function startTask(ctx, task) {
|
|
|
2180
2323
|
atomicWriteFileSync(path.join(dir, 'progress'), '0\n');
|
|
2181
2324
|
if (!fs.existsSync(path.join(dir, 'notes.md')))
|
|
2182
2325
|
atomicWriteFileSync(path.join(dir, 'notes.md'), '');
|
|
2326
|
+
const claudeModel = ctx.claudeModel();
|
|
2327
|
+
const openrouterModel = ctx.openrouterModel();
|
|
2328
|
+
const effort = ctx.effort();
|
|
2183
2329
|
task.status = 'running';
|
|
2184
2330
|
task.startedAt = nowIso();
|
|
2331
|
+
task.model = spawnModelFor(claudeModel, openrouterModel);
|
|
2332
|
+
task.backend = AGENT_BACKEND;
|
|
2333
|
+
task.effort = effort;
|
|
2185
2334
|
ctx.touch(task);
|
|
2186
2335
|
ctx.onStarted(task);
|
|
2187
2336
|
const runCtx = {
|
|
@@ -2189,9 +2338,9 @@ function startTask(ctx, task) {
|
|
|
2189
2338
|
deckLabel: ctx.deckLabel,
|
|
2190
2339
|
tasksDir: ctx.tasksDir,
|
|
2191
2340
|
children: ctx.children,
|
|
2192
|
-
claudeModel
|
|
2193
|
-
openrouterModel
|
|
2194
|
-
effort
|
|
2341
|
+
claudeModel,
|
|
2342
|
+
openrouterModel,
|
|
2343
|
+
effort,
|
|
2195
2344
|
stopRequested: ctx.stopRequested,
|
|
2196
2345
|
quickReference: ctx.quickReference,
|
|
2197
2346
|
playtest: ctx.playtest,
|
|
@@ -2232,6 +2381,9 @@ function startTask(ctx, task) {
|
|
|
2232
2381
|
// survive a throw -- otherwise a single bad task turn could both skip
|
|
2233
2382
|
// freeing the slot (wedging the board) and crash the serve.
|
|
2234
2383
|
try {
|
|
2384
|
+
// First: a run that spent money keeps its receipt even if the error-copy
|
|
2385
|
+
// path below throws.
|
|
2386
|
+
recordRunLedger(task, result);
|
|
2235
2387
|
refreshTaskFiles(ctx.tasksDir, task);
|
|
2236
2388
|
const wasStopped = ctx.stopRequested.delete(task.id);
|
|
2237
2389
|
task.status = wasStopped ? 'interrupted' : result.ok ? 'done' : 'failed';
|