castle-web-cli 0.4.204 → 0.4.206

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.
Files changed (134) hide show
  1. package/dist/agent-failures.d.ts +3 -1
  2. package/dist/agent-failures.js +19 -0
  3. package/dist/agent-prompts.d.ts +1 -0
  4. package/dist/agent-prompts.js +7 -2
  5. package/dist/agent.d.ts +3 -2
  6. package/dist/agent.js +29 -18
  7. package/dist/castle-host/host.d.ts +17 -0
  8. package/dist/castle-host/host.js +551 -4
  9. package/dist/devSessionStorage.js +65 -4
  10. package/dist/effortSupport.d.ts +7 -0
  11. package/dist/effortSupport.js +31 -0
  12. package/dist/imports.d.ts +1 -1
  13. package/dist/imports.js +59 -19
  14. package/dist/index.js +4 -3
  15. package/dist/init.d.ts +9 -1
  16. package/dist/init.js +64 -25
  17. package/dist/kitCatalog.d.ts +13 -0
  18. package/dist/kitCatalog.js +111 -0
  19. package/dist/platformDoc.js +7 -2
  20. package/dist/serve.js +35 -2
  21. package/dist/shell/assets/{index-DHzA0-Sj.js → index-hWQTC8q6.js} +5 -5
  22. package/dist/shell/index.html +1 -1
  23. package/dist/vitePlugins.js +19 -1
  24. package/kits/base/CLAUDE.md +2 -0
  25. package/kits/base/castle.json +1 -1
  26. package/kits/base/sdk/README.md +131 -0
  27. package/kits/base/sdk/agent.d.ts +6 -0
  28. package/kits/base/sdk/agent.js +70 -0
  29. package/kits/base/sdk/castle.d.ts +4 -0
  30. package/kits/base/sdk/castle.js +2 -0
  31. package/kits/base/sdk/commands.d.ts +106 -0
  32. package/kits/base/sdk/commands.js +21 -0
  33. package/kits/base/sdk/decks.d.ts +7 -0
  34. package/kits/base/sdk/decks.js +31 -0
  35. package/kits/base/sdk/runtime.d.ts +4 -2
  36. package/kits/base/sdk/runtime.js +51 -40
  37. package/kits/base/sdk/server/storage.d.ts +44 -0
  38. package/kits/base/sdk/server/storage.js +54 -0
  39. package/kits/base/sdk/transport.d.ts +5 -1
  40. package/kits/base/sdk/transport.js +106 -23
  41. package/kits/multiplayer-2d/castle.json +5 -4
  42. package/kits/multiplayer-2d/code/client/poses.js +7 -0
  43. package/kits/multiplayer-2d/code/server/limits.js +3 -0
  44. package/kits/multiplayer-2d/code/server/ownership.js +36 -8
  45. package/kits/multiplayer-2d/code/systems/multiplayer.js +23 -2
  46. package/kits/multiplayer-3d/CLAUDE.md +12 -1
  47. package/kits/multiplayer-3d/castle.json +5 -4
  48. package/kits/multiplayer-3d/code/client/avatars.js +7 -1
  49. package/kits/multiplayer-3d/code/client/poses.js +61 -1
  50. package/kits/multiplayer-3d/code/client/steer.js +383 -0
  51. package/kits/multiplayer-3d/code/server/limits.js +3 -0
  52. package/kits/multiplayer-3d/code/server/ownership.js +114 -18
  53. package/kits/multiplayer-3d/code/server/world.js +12 -4
  54. package/kits/multiplayer-3d/code/systems/multiplayer.js +315 -34
  55. package/kits/physics-2d/castle.json +1 -0
  56. package/kits/physics-3d/CLAUDE.md +65 -7
  57. package/kits/physics-3d/castle.json +4 -3
  58. package/kits/physics-3d/docs/pxmodel-format.md +916 -15
  59. package/kits/physics-3d/engine3d/PxModelEditor.jsx +2 -2
  60. package/kits/physics-3d/engine3d/artobjects.js +218 -0
  61. package/kits/physics-3d/engine3d/blob.js +1058 -0
  62. package/kits/physics-3d/engine3d/branches.js +300 -0
  63. package/kits/physics-3d/engine3d/cage.js +496 -0
  64. package/kits/physics-3d/engine3d/cageops.js +516 -0
  65. package/kits/physics-3d/engine3d/frame.js +669 -0
  66. package/kits/physics-3d/engine3d/look.js +675 -0
  67. package/kits/physics-3d/engine3d/materialpresets.js +486 -0
  68. package/kits/physics-3d/engine3d/modelEditorWorld.js +3 -2
  69. package/kits/physics-3d/engine3d/modelrefs.js +120 -0
  70. package/kits/physics-3d/engine3d/motion.js +560 -0
  71. package/kits/physics-3d/engine3d/objtext.js +37 -0
  72. package/kits/physics-3d/engine3d/optimize.js +1083 -0
  73. package/kits/physics-3d/engine3d/paint.js +674 -0
  74. package/kits/physics-3d/engine3d/partgeometry.js +467 -0
  75. package/kits/physics-3d/engine3d/paths.js +324 -0
  76. package/kits/physics-3d/engine3d/pxmodel.js +429 -26
  77. package/kits/physics-3d/engine3d/scatter.js +102 -0
  78. package/kits/physics-3d/engine3d/sculpt.js +1148 -0
  79. package/kits/physics-3d/engine3d/surfacedetail.js +267 -0
  80. package/kits/physics-3d/engine3d/sweep.js +480 -0
  81. package/kits/physics-3d/engine3d/thumbnails.js +6 -4
  82. package/kits/physics-3d/engine3d/world3d.js +119 -17
  83. package/kits/physics-3d/eslint.config.js +13 -0
  84. package/kits/physics-3d/models/parts/axe.pxmodel +40 -0
  85. package/kits/physics-3d/models/parts/backpack.pxmodel +47 -0
  86. package/kits/physics-3d/models/parts/barrel.pxmodel +22 -0
  87. package/kits/physics-3d/models/parts/bedroll.pxmodel +28 -0
  88. package/kits/physics-3d/models/parts/belt-pouch.pxmodel +22 -0
  89. package/kits/physics-3d/models/parts/bolt.pxmodel +10 -0
  90. package/kits/physics-3d/models/parts/bracer.pxmodel +26 -0
  91. package/kits/physics-3d/models/parts/chain-span.pxmodel +12 -0
  92. package/kits/physics-3d/models/parts/chimney.pxmodel +11 -0
  93. package/kits/physics-3d/models/parts/crate.pxmodel +44 -0
  94. package/kits/physics-3d/models/parts/crystal.pxmodel +22 -0
  95. package/kits/physics-3d/models/parts/door-arched.pxmodel +12 -0
  96. package/kits/physics-3d/models/parts/engine-block.pxmodel +39 -0
  97. package/kits/physics-3d/models/parts/exhaust-pipe.pxmodel +30 -0
  98. package/kits/physics-3d/models/parts/fence-span.pxmodel +10 -0
  99. package/kits/physics-3d/models/parts/fender.pxmodel +19 -0
  100. package/kits/physics-3d/models/parts/headlight.pxmodel +24 -0
  101. package/kits/physics-3d/models/parts/hood.pxmodel +17 -0
  102. package/kits/physics-3d/models/parts/horned-helmet.pxmodel +37 -0
  103. package/kits/physics-3d/models/parts/jerry-can.pxmodel +26 -0
  104. package/kits/physics-3d/models/parts/ladder.pxmodel +10 -0
  105. package/kits/physics-3d/models/parts/lamp.pxmodel +20 -0
  106. package/kits/physics-3d/models/parts/lantern.pxmodel +30 -0
  107. package/kits/physics-3d/models/parts/leaf-cluster.pxmodel +21 -0
  108. package/kits/physics-3d/models/parts/offroad-tire.pxmodel +48 -0
  109. package/kits/physics-3d/models/parts/pauldron.pxmodel +26 -0
  110. package/kits/physics-3d/models/parts/rivet.pxmodel +8 -0
  111. package/kits/physics-3d/models/parts/rock.pxmodel +21 -0
  112. package/kits/physics-3d/models/parts/roll-bar-light.pxmodel +26 -0
  113. package/kits/physics-3d/models/parts/round-shield.pxmodel +31 -0
  114. package/kits/physics-3d/models/parts/saddlebag.pxmodel +30 -0
  115. package/kits/physics-3d/models/parts/spoked-wheel.pxmodel +39 -0
  116. package/kits/physics-3d/models/parts/staff.pxmodel +33 -0
  117. package/kits/physics-3d/models/parts/stepping-stones.pxmodel +8 -0
  118. package/kits/physics-3d/models/parts/stone-base.pxmodel +10 -0
  119. package/kits/physics-3d/models/parts/sword.pxmodel +33 -0
  120. package/kits/physics-3d/models/parts/window-lit.pxmodel +13 -0
  121. package/kits/physics-3d/models/parts/wizard-hat.pxmodel +28 -0
  122. package/kits/physics-3d/models/templates/biped-stout.pxmodel +59 -0
  123. package/kits/physics-3d/models/templates/biped-tall.pxmodel +63 -0
  124. package/kits/physics-3d/models/templates/quadruped.pxmodel +52 -0
  125. package/kits/physics-3d/scripts/render/filmstrip.js +217 -0
  126. package/kits/physics-3d/scripts/render/index.html +20 -0
  127. package/kits/physics-3d/scripts/render/sheet.js +411 -0
  128. package/kits/physics-3d/scripts/render.mjs +646 -0
  129. package/kits/real-time/castle.json +2 -2
  130. package/kits/real-time/code/client/ownership.js +14 -4
  131. package/kits/real-time/code/client/smooth.js +2 -2
  132. package/kits/real-time/code/server/session.js +20 -4
  133. package/kits/turn-based/castle.json +1 -0
  134. package/package.json +2 -2
@@ -1,5 +1,5 @@
1
1
  export type FailureKind = "config" | "limit" | "transient" | "no-work" | "spawn" | "timeout" | "exit";
2
- export type ConfigReason = "no-key" | "bad-key" | "no-credits" | "model-not-allowed" | "unknown-model" | "no-tools" | "no-endpoints" | "flagged" | "context-length";
2
+ export type ConfigReason = "no-key" | "bad-key" | "no-credits" | "model-not-allowed" | "unknown-model" | "no-tools" | "no-endpoints" | "flagged" | "context-length" | "rejected-parameters";
3
3
  export interface AgentFailure {
4
4
  kind: FailureKind;
5
5
  reason?: ConfigReason;
@@ -21,6 +21,8 @@ export declare function classifyProviderError(text: string | undefined, model?:
21
21
  * the error path, which must not fail.
22
22
  */
23
23
  export declare function setReaderTimeZone(zone: string): void;
24
+ export declare function failureLabel(failure: AgentFailure): string;
25
+ export declare function routerTaskError(errorLine: string | undefined, failure: string | undefined, errorCopy: string | undefined): string | undefined;
24
26
  export declare function failureCopy(opts: {
25
27
  failure: AgentFailure;
26
28
  spawnedTasks: boolean;
@@ -109,6 +109,12 @@ export function failureForStatus(status, body, model) {
109
109
  if (/model[ _-]?not[ _-]?found|not a valid model|unknown model/i.test(body)) {
110
110
  return config("unknown-model");
111
111
  }
112
+ // Meta's own sentence, relayed verbatim by OpenRouter, for any parameter
113
+ // its endpoint refuses (seen for effort max on muse-spark-1.3-contributor).
114
+ // Only this exact prose: an unrecognised 400 must stay unclassified.
115
+ if (/The request contains invalid parameters/i.test(body)) {
116
+ return config("rejected-parameters");
117
+ }
112
118
  }
113
119
  // Unrecognised: leave it unlabelled so the caller keeps its existing
114
120
  // behavior rather than inventing a diagnosis.
@@ -212,10 +218,23 @@ function configCopy(failure) {
212
218
  return `${model} refused that request. Try rewording it, or switch to a different model in settings.`;
213
219
  case "context-length":
214
220
  return `That turn got too big for ${model} to hold. Try breaking it into smaller steps, or switch to a model with more room in settings.`;
221
+ case "rejected-parameters":
222
+ return `${model} rejected the request as invalid, so sending the same thing again won't help. Try a different effort level or model in settings, or reach out to Castle.`;
215
223
  default:
216
224
  return "Something about this session's model setup isn't right. Check the model in settings, or reach out to Castle.";
217
225
  }
218
226
  }
227
+ export function failureLabel(failure) {
228
+ return failure.reason ? `${failure.kind}/${failure.reason}` : failure.kind;
229
+ }
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.
233
+ export function routerTaskError(errorLine, failure, errorCopy) {
234
+ if (!errorLine || !errorCopy || !failure?.startsWith("config"))
235
+ return errorLine;
236
+ return `${errorLine} -- ${errorCopy}`;
237
+ }
219
238
  export function failureCopy(opts) {
220
239
  if (opts.willRetry) {
221
240
  return "Something went wrong on my end -- give me a moment to try that again.";
@@ -89,6 +89,7 @@ export interface RouterPromptOpts {
89
89
  playtest?: boolean;
90
90
  askCalls?: boolean;
91
91
  editorTabs?: string[];
92
+ kits?: string[];
92
93
  paramsWrites?: string[];
93
94
  instruction: string;
94
95
  }
@@ -29,15 +29,17 @@ function baseRouterRules(playtest) {
29
29
 
30
30
  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.
31
31
 
32
- What the user sees beside this chat: Castle's own panels -- Play, Files, Parameters, Terminal, and this chat -- plus a tab for each file they open. Those panels belong to Castle, and nothing in the deck can change them. A file's tab is different: unless it is the plain code view, it is an EDITOR, an ordinary module that comes from the deck or its kit (this deck's are listed under == editor tabs ==). Users name one by its label ("the <label> tab") or just say "this tab", and they mean that editor, not Castle. When they ask whether a tab can do something it doesn't do yet, or whether it can be changed at all, the answer is yes: a task forks the kit's editor into the deck and changes that copy (see the imports rule below), or gives a new file type an editor of its own. Never tell the user a file's tab is part of Castle.
32
+ What the user sees beside this chat: Castle's own panels -- Play, Files, Parameters, Terminal, and this chat -- plus a tab for each file they open. Those panels belong to Castle, and nothing in the deck can change them. The Parameters panel is where the deck's tunable values live: everything any file exposes as \`PARAMS\`. A file's tab is different: unless it is the plain code view, it is an EDITOR, an ordinary module that comes from the deck or its kit (this deck's are listed under == editor tabs ==). Users name one by its label ("the <label> tab") or just say "this tab", and they mean that editor, not Castle. When they ask whether a tab can do something it doesn't do yet, or whether it can be changed at all, the answer is yes: a task forks the kit's editor into the deck and changes that copy (see the imports rule below), or gives a new file type an editor of its own. Never tell the user a file's tab is part of Castle.
33
33
 
34
34
  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
+ - A deck can lack what a kit provides. == kits this deck can import == (present only on a deck that runs no kit) lists each kit this platform ships: what it is for and the file types its editors open. When the user asks for one of those things -- a file type, an editor, a way of working the listing names -- and this deck's guide says it has no such thing, they are asking for that kit, whether they phrase it as a request or as a how-to question. Do not explain the absence, do not paste code that imitates it, and do not spawn a task to build a substitute: import the kit yourself in that same turn with the exact command the listing gives, and read its output. "This deck now runs" in the output means the deck switched over -- its starter content and editors are in place -- so say in one line what the deck now has, tell them to reload the Play panel (its Restart button) to see it, since it keeps running the old code until then, and handle the rest of their ask the way you would on any deck built on that kit. Any other output means the deck kept its own code: the kit is imported but not running, and switching over replaces what they built -- say that and ask which they want before anything else; on a yes, a task repoints the entry point the output names. When the deck's own guide already covers what they asked for, this rule is not in play.
37
38
  - 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
39
  - 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. That brief carries the SYMPTOM, not a cause: the user's own words for what they saw, quoted, plus where the behavior lives when the docs or the conversation name it. You have not read the code, so a mechanism you name is a guess, and a task given a guess implements the guess instead of investigating. 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
40
  - 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}` : ""}
40
41
  - 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.
42
+ - When the user asks what they can tune, what controls something, or where to change a value, first see whether that value is already tunable: a key in that file's \`PARAMS\` object, or one of the \`knobs:\` a \`## Built\` line lists. If it is, do not spawn a task to move it -- link that one value with \`#params:key\`. If they asked for it to change, make that change the way any tweak is made, with a task that sets it, and say they can keep adjusting it in the Parameters panel; otherwise tell them they can change it there now. If it is not -- a plain constant or expression in code -- spawn the task that moves it into that file's \`PARAMS\` object, keeping its current value as the default and adding a \`PARAMS_META\` range where one is obvious, and say in your plain-text line that it is going into the Parameters panel, linking that file's \`#params\` where it will land. If they also asked for a new value, the same task sets it. If they asked where it is set, link the file too (the line, if you have read it) -- the move does not replace the answer. Do not just point them at the line. Three different things get called a parameter: an argument a function takes (plain code, nothing to do with the panel); a setting each placed thing carries for itself, so two of them can differ -- the deck's own guide says what those are called and where they are set, and they never go in \`PARAMS\`; and one value for the whole deck that someone tunes while playing, which is the only kind the panel holds. The deciding question is scope: does each one need its own value, or is there one value for everyone? Read that from what they are trying to do; when it is genuinely unclear, ask.
41
43
  - 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.
42
44
  - 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.
43
45
  - 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.
@@ -850,6 +852,9 @@ export function buildRouterPromptParts(opts) {
850
852
  const editorTabs = opts.editorTabs?.length
851
853
  ? `\n\n== editor tabs ==\n${opts.editorTabs.map((tab) => `- ${tab}`).join("\n")}`
852
854
  : "";
855
+ const kits = opts.kits?.length
856
+ ? `\n\n== kits this deck can import ==\n${opts.kits.join("\n")}`
857
+ : "";
853
858
  const deckFiles = opts.deckTree?.trim()
854
859
  ? `\n\n== deck files ==\n${opts.deckTree.trim()}`
855
860
  : "";
@@ -875,7 +880,7 @@ export function buildRouterPromptParts(opts) {
875
880
  system: `${routerRules(opts.plan !== undefined, opts.playtest === true, opts.askCalls === true)}
876
881
 
877
882
  == deck ==
878
- ${opts.deckLabel}${quickReference}${editorTabs}${deckFiles}`,
883
+ ${opts.deckLabel}${quickReference}${editorTabs}${kits}${deckFiles}`,
879
884
  user: `== conversation so far ==
880
885
  ${renderTranscript(opts.messages)}${plan}
881
886
 
package/dist/agent.d.ts CHANGED
@@ -1,9 +1,10 @@
1
+ import { type EffortLevel } from './effortSupport.js';
1
2
  import * as http from 'http';
2
3
  import { Duplex } from 'stream';
3
4
  import { type PlaytestToolResult } from './native/playtest.js';
4
5
  export declare const AGENT_WS_PATH = "/__castle/agent";
5
6
  export type ClaudeModel = 'sonnet' | 'opus' | 'fable' | 'openrouter';
6
- export type EffortLevel = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
7
+ export type { EffortLevel };
7
8
  interface AgentSettings {
8
9
  routerClaudeModel: ClaudeModel;
9
10
  tasksClaudeModel: ClaudeModel;
@@ -49,6 +50,7 @@ interface TaskRecord {
49
50
  account?: string;
50
51
  errorCopy?: string;
51
52
  errorDetail?: string;
53
+ failure?: string;
52
54
  avatar?: string;
53
55
  phase?: string;
54
56
  acknowledged?: boolean;
@@ -102,4 +104,3 @@ export declare function createAgentServer(opts: {
102
104
  restart?: () => void;
103
105
  authorizeUpgrade?: (req: http.IncomingMessage, endpoint: 'agent') => boolean;
104
106
  }): AgentServer;
105
- export {};
package/dist/agent.js CHANGED
@@ -16,11 +16,13 @@
16
16
  import { execFileSync, spawn } from 'child_process';
17
17
  import { claudeContextEnv, quickReferenceFor } from './platformDoc.js';
18
18
  import { resolveFileTypes } from './editorConfig.js';
19
+ import { kitCatalogLines } from './kitCatalog.js';
19
20
  import { panelWritesSince } from './paramsWrites.js';
20
21
  import { IMPORTS_DIR } from './imports.js';
21
22
  import { isSameOriginUpgrade } from './wsOrigin.js';
22
23
  import { resolveDeckPath } from './ide.js';
23
24
  import { lineRange, uniqueLocators } from './deckLocatorShape.js';
25
+ import { supportedEffort } from './effortSupport.js';
24
26
  import * as fs from 'fs';
25
27
  import * as os from 'os';
26
28
  import * as path from 'path';
@@ -34,7 +36,7 @@ import { AGENT_ATTACHMENT_PREFIX, AGENT_PLAYTEST_PREFIX, PLAN_FILE } from './loc
34
36
  import { applyPlanOps, buildRouterPromptParts, buildTaskPrompt, parsePlanOps, planOpenQuestionLines, truncateToBytes, userTurnInstruction, CLAUDE_TASK_SYSTEM_REMINDER, modelTaskAddendum, isMuseModel, } from './agent-prompts.js';
35
37
  import { readCastleJson } from './castleJson.js';
36
38
  import { checkOpenrouterKey, checkOpenrouterModel, primeOpenrouterCatalog, } from './openrouter-catalog.js';
37
- import { classifyProviderError, failureCopy, setReaderTimeZone, } from './agent-failures.js';
39
+ import { classifyProviderError, failureCopy, failureLabel, routerTaskError, setReaderTimeZone, } from './agent-failures.js';
38
40
  import { castleCreditsExhausted, createBudgetRefreshRetry, createRefreshQueue, fetchAiCredits, fetchBudget, freeRolesFor, freeTierForRoles, meteringHeaders, modelIsFree, newAgentSessionId, spendableMicros, withCustomHeaders, } from './metering.js';
39
41
  import { anthropicKeyHelperCommand, resolveAnthropicAuth, userKey, ANTHROPIC_CREDENTIAL_ENV, ANTHROPIC_PROXY_ENV, CASTLE_USER_KEYS_PATH, } from './byo-auth.js';
40
42
  import { accountsSnapshot, loginProviderFor, watchCredentials, writeCredential, } from './byo-accounts.js';
@@ -384,6 +386,11 @@ function claudeSettingsArg(auth) {
384
386
  function spawnModelFor(claudeModel, openrouterModel) {
385
387
  return claudeModel === 'openrouter' ? openrouterModel : claudeModel;
386
388
  }
389
+ // Like the model, the effort a task records is the one it was spawned at, which
390
+ // differs from the stored setting when the model refuses that level.
391
+ function spawnEffortFor(claudeModel, openrouterModel, effort) {
392
+ return claudeModel === 'openrouter' ? supportedEffort(openrouterModel, effort) : effort;
393
+ }
387
394
  // The only harness left (the native loop is dormant), recorded on both the run
388
395
  // log header and the task so a second one would read as a different value.
389
396
  const AGENT_BACKEND = 'claude';
@@ -402,6 +409,7 @@ taskId,
402
409
  systemPrompt) {
403
410
  const viaOpenrouter = claudeModel === 'openrouter';
404
411
  const spawnModel = spawnModelFor(claudeModel, openrouterModel);
412
+ const spawnEffort = spawnEffortFor(claudeModel, openrouterModel, effort);
405
413
  const systemText = [systemPrompt, role === 'task' ? CLAUDE_TASK_SYSTEM_REMINDER : undefined, role === 'task' ? modelTaskAddendum(spawnModel) : undefined]
406
414
  .filter((text) => Boolean(text))
407
415
  .join('\n\n');
@@ -415,6 +423,7 @@ systemPrompt) {
415
423
  return {
416
424
  command: 'claude',
417
425
  model: spawnModel,
426
+ effort: spawnEffort,
418
427
  systemText,
419
428
  args: [
420
429
  '-p',
@@ -428,7 +437,7 @@ systemPrompt) {
428
437
  '--model',
429
438
  spawnModel,
430
439
  '--effort',
431
- effort,
440
+ spawnEffort,
432
441
  // Newer claude models default thinking display to "omitted" (empty
433
442
  // thinking_delta text, signature only); "summarized" restores actual
434
443
  // summary text so the shell's expandable thinking transcript has
@@ -1796,7 +1805,7 @@ async function runAgentTurn(opts) {
1796
1805
  sessionId,
1797
1806
  backend: AGENT_BACKEND,
1798
1807
  model: invocation.model,
1799
- effort: opts.effort,
1808
+ effort: invocation.effort,
1800
1809
  systemPrompt: invocation.systemText || undefined,
1801
1810
  prompt: opts.prompt,
1802
1811
  },
@@ -1874,7 +1883,7 @@ function writeTaskIndex(tasksDir, tasks) {
1874
1883
  const TASK_STATUSES = ['waiting', 'running', 'blocked', 'done', 'failed', 'interrupted'];
1875
1884
  const TASK_OPTIONAL_STRINGS = [
1876
1885
  'item', 'startedAt', 'finishedAt', 'originMessageId', 'resultSummary', 'account', 'errorCopy',
1877
- 'errorDetail', 'avatar', 'phase', 'durable', 'what', 'model', 'backend',
1886
+ 'errorDetail', 'failure', 'avatar', 'phase', 'durable', 'what', 'model', 'backend',
1878
1887
  ];
1879
1888
  const TASK_OPTIONAL_NUMBERS = ['pid', 'costUsd', 'durationApiMs', 'numTurns'];
1880
1889
  const TASK_OPTIONAL_OBJECTS = ['usage', 'modelUsage'];
@@ -2118,6 +2127,9 @@ async function waitBeforeTaskRetry(attempt, stopRequested, taskId) {
2118
2127
  async function runTaskAgentIn(ctx, task) {
2119
2128
  const dir = path.join(ctx.tasksDir, task.id);
2120
2129
  const relDir = path.relative(ctx.deckDir, dir);
2130
+ // Read at task start, like the router's per turn: a task the router spawns
2131
+ // right after adopting a kit must be briefed with the kit's guide.
2132
+ const deckGuide = readQuickReference(ctx.deckDir);
2121
2133
  const taskPrompt = buildTaskPrompt({
2122
2134
  deckLabel: ctx.deckLabel,
2123
2135
  taskId: task.id,
@@ -2129,7 +2141,7 @@ async function runTaskAgentIn(ctx, task) {
2129
2141
  depsSummary: ctx.depsSummary,
2130
2142
  playtest: playtestSteering(),
2131
2143
  deckTree: buildDeckTree(ctx.deckDir),
2132
- quickReference: quickReferenceFor(ctx.deckDir, ctx.quickReference, 'task'),
2144
+ quickReference: quickReferenceFor(ctx.deckDir, deckGuide, 'task'),
2133
2145
  plan: taskPlanOpts(ctx.deckDir, task.item, ctx.finishedWork),
2134
2146
  siblings: ctx.siblings,
2135
2147
  });
@@ -2252,7 +2264,7 @@ function startTask(ctx, task) {
2252
2264
  task.startedAt = nowIso();
2253
2265
  task.model = spawnModelFor(claudeModel, openrouterModel);
2254
2266
  task.backend = AGENT_BACKEND;
2255
- task.effort = effort;
2267
+ task.effort = spawnEffortFor(claudeModel, openrouterModel, effort);
2256
2268
  ctx.touch(task);
2257
2269
  ctx.onStarted(task);
2258
2270
  const runCtx = {
@@ -2264,7 +2276,6 @@ function startTask(ctx, task) {
2264
2276
  openrouterModel,
2265
2277
  effort,
2266
2278
  stopRequested: ctx.stopRequested,
2267
- quickReference: ctx.quickReference,
2268
2279
  playtest: ctx.playtest,
2269
2280
  depsSummary: depsSummaryFor(ctx.tasks, task),
2270
2281
  // Same visibility rule as the router's board (hide acked+finished rows),
@@ -2336,8 +2347,8 @@ function startTask(ctx, task) {
2336
2347
  willRetry: false,
2337
2348
  });
2338
2349
  task.errorDetail = failure.detail || result.error;
2339
- const label = failure.reason ? `${failure.kind}/${failure.reason}` : failure.kind;
2340
- console.error(`[task ${task.id}] failed (${label}): ${failure.verbose ?? task.errorDetail}`);
2350
+ task.failure = failureLabel(failure);
2351
+ console.error(`[task ${task.id}] failed (${task.failure}): ${failure.verbose ?? task.errorDetail}`);
2341
2352
  }
2342
2353
  ctx.touch(task);
2343
2354
  }
@@ -2476,7 +2487,6 @@ function createTaskStore(opts) {
2476
2487
  children,
2477
2488
  tasks,
2478
2489
  stopRequested,
2479
- quickReference: opts.quickReference,
2480
2490
  claudeModel: opts.claudeModel,
2481
2491
  openrouterModel: opts.openrouterModel,
2482
2492
  effort: opts.effort,
@@ -2767,7 +2777,9 @@ function asPromptTask(task) {
2767
2777
  progress: task.progress,
2768
2778
  notes: task.notes,
2769
2779
  item: task.item,
2770
- error: task.status === 'failed' ? firstErrorLine(task.resultSummary) : undefined,
2780
+ error: task.status === 'failed'
2781
+ ? routerTaskError(firstErrorLine(task.resultSummary), task.failure, task.errorCopy)
2782
+ : undefined,
2771
2783
  blockedBy: task.status === 'blocked' ? task.blockedBy : undefined,
2772
2784
  };
2773
2785
  }
@@ -3005,10 +3017,14 @@ function panelWriteWatermark(messages, selfMessageId) {
3005
3017
  // context + transcript replay (minus log lines and the in-flight reply) +
3006
3018
  // the live board + this turn's instruction.
3007
3019
  function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
3020
+ // Read per turn, not once per serve: adopting a kit mid-conversation
3021
+ // rewrites CLAUDE.md, and the next turn has to see the kit's guide.
3022
+ const deckGuide = readQuickReference(ctx.deckDir);
3008
3023
  return buildRouterPromptParts({
3009
3024
  deckLabel: ctx.deckLabel,
3010
- quickReference: quickReferenceFor(ctx.deckDir, ctx.quickReference, 'router'),
3025
+ quickReference: quickReferenceFor(ctx.deckDir, deckGuide, 'router'),
3011
3026
  editorTabs: editorTabsFor(ctx.deckDir),
3027
+ kits: kitCatalogLines(ctx.deckDir),
3012
3028
  deckTree: buildDeckTree(ctx.deckDir),
3013
3029
  playtest: playtestSteering(),
3014
3030
  askCalls: askCallsEnabled(ctx.deckDir),
@@ -3252,8 +3268,7 @@ function runRouterTurnIn(ctx, instruction) {
3252
3268
  message.status = 'error';
3253
3269
  message.errorDetail = failure.detail || result.error || 'unknown failure';
3254
3270
  errorVerbose = failure.verbose;
3255
- const label = failure.reason ? `${failure.kind}/${failure.reason}` : failure.kind;
3256
- console.error(`[router] turn failed (${label}): ${failure.verbose ?? message.errorDetail}`);
3271
+ console.error(`[router] turn failed (${failureLabel(failure)}): ${failure.verbose ?? message.errorDetail}`);
3257
3272
  }
3258
3273
  if (taskIds.length > 0)
3259
3274
  message.taskIds = taskIds;
@@ -3638,7 +3653,6 @@ function startRouterTurn(ctx, instruction) {
3638
3653
  runRouterTurnIn({
3639
3654
  deckDir: ctx.deckDir,
3640
3655
  deckLabel: ctx.deckLabel,
3641
- quickReference: ctx.quickReference,
3642
3656
  agentDir: ctx.agentDir,
3643
3657
  children: ctx.routerChildren,
3644
3658
  log: ctx.log,
@@ -3929,7 +3943,6 @@ function makePlaytestRunner(deps) {
3929
3943
  }
3930
3944
  export function createAgentServer(opts) {
3931
3945
  const { deckDir, deckLabel } = opts;
3932
- const quickReference = readQuickReference(deckDir);
3933
3946
  const welcomeMessage = readWelcomeMessage(deckDir) || DEFAULT_WELCOME_MESSAGE;
3934
3947
  const agentDir = path.join(deckDir, '.castle', 'agent');
3935
3948
  const tasksDir = path.join(agentDir, 'tasks');
@@ -4023,7 +4036,6 @@ export function createAgentServer(opts) {
4023
4036
  deckLabel,
4024
4037
  tasksDir,
4025
4038
  children: taskChildren,
4026
- quickReference,
4027
4039
  openrouterModel: () => settings.tasksOpenrouterModel,
4028
4040
  claudeModel: () => settings.tasksClaudeModel,
4029
4041
  effort: () => settings.tasksEffort,
@@ -4040,7 +4052,6 @@ export function createAgentServer(opts) {
4040
4052
  const routerQueue = createRouterQueue({
4041
4053
  deckDir,
4042
4054
  deckLabel,
4043
- quickReference,
4044
4055
  agentDir,
4045
4056
  attachmentsDir,
4046
4057
  routerChildren,
@@ -40,6 +40,7 @@ export type PlatformHandler = (
40
40
  export interface HostCapabilities {
41
41
  graphqlFetch: GraphqlFetch;
42
42
  platformHandler?: PlatformHandler;
43
+ oracleStream?: OracleStream;
43
44
  localPassGrant?: (passId: string) => boolean;
44
45
  showLeaderboard?: (payload: CastleLeaderboardPayload) => void;
45
46
  canShowLeaderboard?: () => boolean;
@@ -52,6 +53,21 @@ export interface HostCapabilities {
52
53
  ) => Promise<MultiplayerGetSessionResult>;
53
54
  }
54
55
 
56
+ export type OracleStream = (url: string, body: string, sink: OracleStreamSink) => () => void;
57
+
58
+ export interface OracleStreamSink {
59
+ event(name: string, data: string): void;
60
+ end(): void;
61
+ fail(status: number, text: string): void;
62
+ }
63
+
64
+ export interface CommandOptions {
65
+ onStream?: (event: unknown) => void;
66
+ signal?: AbortSignal;
67
+ }
68
+
69
+ export function fetchOracleStream(getToken: () => string | null | undefined): OracleStream;
70
+
55
71
  export interface MultiplayerGetSessionParams {
56
72
  mode: 'named' | 'party' | 'public';
57
73
  key?: string | null;
@@ -91,4 +107,5 @@ export function executeCommand(
91
107
  command: unknown,
92
108
  params: unknown,
93
109
  capabilities: HostCapabilities,
110
+ options?: CommandOptions,
94
111
  ): Promise<HostResult>;