@causyne/agent 1.20.13 → 1.20.15

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 (71) hide show
  1. package/package.json +1 -1
  2. package/src/SmartTools.js +33 -0
  3. package/src/SmartTools.ts +37 -0
  4. package/src/acp/client.js +157 -4
  5. package/src/acp/client.ts +152 -5
  6. package/src/agentLoop.js +857 -178
  7. package/src/agentLoop.ts +865 -183
  8. package/src/browser/browserRuntime.js +8 -1
  9. package/src/browser/browserRuntime.ts +8 -1
  10. package/src/browser/causyneBrowser.js +20 -4
  11. package/src/browser/causyneBrowser.ts +20 -4
  12. package/src/browser/urlPolicy.js +35 -0
  13. package/src/browser/urlPolicy.ts +34 -0
  14. package/src/cliMode.js +6 -2
  15. package/src/commands.js +14 -0
  16. package/src/contextManager.d.ts +1 -0
  17. package/src/core/contextCompactor.js +277 -0
  18. package/src/core/contextCompactor.ts +353 -0
  19. package/src/decideTools.js +157 -0
  20. package/src/decideTools.ts +195 -0
  21. package/src/decisionPolicy.js +5 -3
  22. package/src/decisionPolicy.ts +5 -3
  23. package/src/implementationPlan.js +284 -0
  24. package/src/implementationPlan.ts +275 -0
  25. package/src/observer/coldObserver.js +10 -4
  26. package/src/observer/coldObserver.ts +15 -7
  27. package/src/observer/evidence.js +11 -5
  28. package/src/observer/evidence.ts +13 -6
  29. package/src/observer.js +196 -0
  30. package/src/observer.ts +287 -0
  31. package/src/providers/acp.js +362 -109
  32. package/src/providers/acp.ts +359 -111
  33. package/src/providers/antigravity.js +133 -105
  34. package/src/providers/antigravity.ts +130 -109
  35. package/src/providers/base.d.ts +3 -0
  36. package/src/providers/budgetEnforcer.js +23 -2
  37. package/src/providers/budgetEnforcer.ts +20 -5
  38. package/src/provisioning/capabilityProvisioner.js +14 -10
  39. package/src/sandbox.js +4 -2
  40. package/src/saveTools.js +146 -0
  41. package/src/saveTools.ts +169 -0
  42. package/src/session/cachePressure.js +77 -0
  43. package/src/session/cachePressure.ts +122 -0
  44. package/src/smartToolsUse.js +96 -15
  45. package/src/smartToolsUse.ts +133 -15
  46. package/src/taskShape.js +7 -7
  47. package/src/taskShape.ts +7 -7
  48. package/src/timeMachine.js +55 -20
  49. package/src/timeMachine.ts +64 -20
  50. package/src/toolPacks.js +217 -310
  51. package/src/toolPacks.ts +505 -0
  52. package/src/tools/deferredMcpSearch.js +21 -13
  53. package/src/tools/deferredMcpSearch.ts +23 -15
  54. package/src/tools/updatePlan.js +2 -2
  55. package/src/tools/updatePlan.ts +2 -2
  56. package/src/toolsList.js +203 -0
  57. package/src/toolsList.ts +224 -0
  58. package/src/tui/chatRenderer.js +49 -14
  59. package/src/tui/codeStreamRenderer.js +16 -5
  60. package/src/tui/codeStreamRenderer.ts +14 -4
  61. package/src/tui/prompt.js +4 -2
  62. package/src/tui/sessionSidebar.js +10 -2
  63. package/src/tui/sessionSidebar.ts +10 -3
  64. package/src/tui/stageSurface.js +27 -1
  65. package/src/tui/text.d.ts +1 -0
  66. package/src/tui/turnRail.js +274 -0
  67. package/src/tui/turnRail.ts +334 -0
  68. package/src/types/contracts.ts +103 -0
  69. package/src/verificationPlan.js +141 -0
  70. package/src/verificationPlan.ts +166 -0
  71. package/src/toolPacks.d.ts +0 -10
@@ -0,0 +1,505 @@
1
+ // Sovereign Progressive Disclosure — Capability Packs
2
+ //
3
+ // Causyne ships 69 native tools. Sending every schema on every LLM call costs
4
+ // ~14,700 tokens per step before the agent has done any work, and half of that
5
+ // is game tooling that a "rename my files" task never touches.
6
+ //
7
+ // This module does NOT remove any capability. It only controls *when* a schema
8
+ // enters the context window. Every tool stays reachable through three routes:
9
+ // 1. Intent pre-warm — routePacks() unlocks the right packs before step 1
10
+ // 2. tool_search — the agent discovers and unlocks any pack on demand
11
+ // 3. Auto-unlock recovery — calling a locked-but-real tool unlocks its pack
12
+ //
13
+ // Set config.grantAllTools = true to disable deferral entirely.
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Pack membership. Names match the `name` field of each tool schema, with dots
17
+ // already normalised to underscores (see tools/registry.js TOOL_DEFINITIONS).
18
+ // ---------------------------------------------------------------------------
19
+
20
+ export type PackName = 'game' | 'web' | 'media' | 'system' | 'advanced';
21
+
22
+ export interface WorkspaceRoutingContext {
23
+ framework?: string | null | undefined;
24
+ projectType?: string | null | undefined;
25
+ designSystem?: string | null | undefined;
26
+ keyFiles?: string[] | null | undefined;
27
+ }
28
+
29
+ export interface ToolDefinitionLike {
30
+ name: string;
31
+ xCausyneDeferred?: boolean | undefined;
32
+ [key: string]: any;
33
+ }
34
+
35
+ export interface ResolveActiveToolsOptions {
36
+ residentOnly?: boolean | undefined;
37
+ }
38
+
39
+ export const CORE_TOOLS: string[] = [
40
+ 'sysRun',
41
+ 'sysRunBg',
42
+ 'terminal_persistent_shell',
43
+ 'fs_read',
44
+ 'fs_write',
45
+ 'fs_edit',
46
+ 'MultiEdit',
47
+ 'fs_list',
48
+ 'fs_search',
49
+ 'fs_find',
50
+ 'fs_move',
51
+ 'fs_delete',
52
+ 'gitOp',
53
+ 'code_search_ripgrep',
54
+ 'codebase_search',
55
+ 'code_verify_syntax',
56
+ 'web_search',
57
+ 'web_fetch',
58
+ 'update_plan',
59
+ 'request_decision',
60
+ 'memory_write',
61
+ 'fs_read_skill',
62
+ 'skill_create',
63
+ 'tool_search'
64
+ ];
65
+
66
+ export const PACKS: Record<PackName, string[]> = {
67
+ game: [
68
+ // Stage 1 of the game cascade calls check_system_specs to verify the
69
+ // engine, so it must travel with this pack as well as with media.
70
+ 'check_system_specs',
71
+ 'godot_act',
72
+ 'game_build_html5',
73
+ 'game_asset_fetch',
74
+ 'game_asset_harvest',
75
+ 'game_lore_forge',
76
+ 'game_dialogue_tree_gen',
77
+ 'game_quest_arc_builder',
78
+ 'game_animation_rig',
79
+ 'game_ai_behavior_tree',
80
+ 'game_cinematic_sequencer',
81
+ 'game_audio_synth',
82
+ 'game_vfx_emitter_gen',
83
+ 'game_shader_forge',
84
+ 'game_scene_build',
85
+ 'game_entity_spawner',
86
+ 'game_tilemap_gen',
87
+ 'game_ui_hud_builder',
88
+ 'game_economy_balancer',
89
+ 'game_data_forge',
90
+ 'game_web_runtime_inspector',
91
+ 'game_canvas_audit'
92
+ ],
93
+ web: [
94
+ 'browser_act',
95
+ 'screenshot',
96
+ 'vision_inspect_ui',
97
+ 'view_image',
98
+ 'astryx_oracle',
99
+ 'ui_forge'
100
+ ],
101
+ media: [
102
+ 'generate_media_via_api',
103
+ 'execute_procedural_media',
104
+ 'check_system_specs',
105
+ 'manage_local_dependencies',
106
+ 'blender_act',
107
+ 'creative_apps',
108
+ 'native_engine',
109
+ 'resolve_act',
110
+ 'palmier_act',
111
+ 'document_forge',
112
+ 'open_source_tool_provisioner'
113
+ ],
114
+ system: [
115
+ // Channel B of the Three-Channel Doctrine: reading the screen as structured
116
+ // text instead of pixels. Lives here rather than in core because most tasks
117
+ // never touch a GUI, and tool_search brings it in the moment one does.
118
+ 'ax_snapshot',
119
+ // Channel C. Ships beside its observer on purpose: acting on a screen you
120
+ // have not read is how an agent clicks the wrong button confidently.
121
+ 'desktop_act',
122
+ 'computer_use',
123
+ 'process_list',
124
+ 'proc_term',
125
+ 'archive',
126
+ 'clipboard',
127
+ 'desktop_open',
128
+ 'printer_print',
129
+ 'printer_list_printers',
130
+ 'printer_get_status'
131
+ ],
132
+ advanced: [
133
+ 'tool_forge',
134
+ 'plugin_manager',
135
+ 'document_forge',
136
+ 'agent_subagent_orchestrate',
137
+ 'peer_agent_delegate',
138
+ 'code_search_ast',
139
+ 'code_list_symbols',
140
+ 'pdf_read'
141
+ ]
142
+ };
143
+
144
+ export const PACK_NAMES: PackName[] = Object.keys(PACKS) as PackName[];
145
+
146
+ /**
147
+ * The core tools that ship in EVERY request on a provider with no native
148
+ * schema deferral. The rest of CORE_TOOLS is withheld until the model asks for
149
+ * it with `tool_search`, exactly as a capability pack is.
150
+ */
151
+ export const RESIDENT_TOOLS: string[] = [
152
+ 'fs_read',
153
+ 'fs_write',
154
+ 'fs_edit',
155
+ 'fs_list',
156
+ 'fs_search',
157
+ 'sysRun',
158
+ 'update_plan',
159
+ 'tool_search'
160
+ ];
161
+
162
+ const RESIDENT_TOOL_SET = new Set<string>(RESIDENT_TOOLS);
163
+
164
+ /** True when this core tool ships in every request even without native deferral. */
165
+ export function isResidentTool(toolName: string): boolean {
166
+ return RESIDENT_TOOL_SET.has(toolName);
167
+ }
168
+
169
+ // A tool may legitimately belong to more than one pack — check_system_specs is
170
+ // Stage 1 of the game cascade and Stage 2 of the media hierarchy — so
171
+ // membership is a set, not a single value.
172
+ const TOOL_TO_PACKS: Map<string, Set<PackName>> = (() => {
173
+ const map = new Map<string, Set<PackName>>();
174
+ for (const packName of PACK_NAMES) {
175
+ for (const toolName of PACKS[packName]) {
176
+ let set = map.get(toolName);
177
+ if (!set) {
178
+ set = new Set<PackName>();
179
+ map.set(toolName, set);
180
+ }
181
+ set.add(packName);
182
+ }
183
+ }
184
+ return map;
185
+ })();
186
+
187
+ const CORE_TOOL_SET = new Set<string>(CORE_TOOLS);
188
+
189
+ /** Every pack a tool belongs to. Empty for core and forged tools. */
190
+ export function packsForTool(toolName: string): Set<PackName> | null {
191
+ return TOOL_TO_PACKS.get(toolName) || null;
192
+ }
193
+
194
+ /** Primary pack for a tool, or 'core' if it is always loaded. */
195
+ export function packForTool(toolName: string): PackName | 'core' | null {
196
+ if (CORE_TOOL_SET.has(toolName)) return 'core';
197
+ const packs = TOOL_TO_PACKS.get(toolName);
198
+ return packs ? ([...packs][0] ?? null) : null;
199
+ }
200
+
201
+ export function isCoreTool(toolName: string): boolean {
202
+ return CORE_TOOL_SET.has(toolName);
203
+ }
204
+
205
+ // ---------------------------------------------------------------------------
206
+ // Pack playbooks. These were previously hardcoded into the always-on
207
+ // SYSTEM_PROMPT, costing every task ~2,000 tokens of instructions about game
208
+ // cascades and media hierarchies it would never use. They now travel with their
209
+ // pack, so they arrive exactly when they become relevant.
210
+ // ---------------------------------------------------------------------------
211
+
212
+ export const PACK_PLAYBOOKS: Record<'web' | 'media' | 'game', string> = {
213
+ web: `# FRONTEND ENGINEERING MANDATE (CREATIVE DIVERSITY ENGINE)
214
+ When building websites, UIs, dashboards, or web applications, follow this design system hierarchy:
215
+ ## Design System Selection
216
+ 1. **If the user specifies a design system** (Tailwind, Material-UI, Astryx, etc.) — use it without question.
217
+ 2. **If the project already has a design system installed** (detected via package.json) — use the existing one. Never mix systems.
218
+ 3. **If building from scratch with no preference stated** — You have CREATIVE FREEDOM. Intelligently choose the approach that best fits the project's personality and user intent:
219
+ - **Astryx (@astryxdesign/core)**: Use the 'astryx_oracle' tool for docs. Best for enterprise dashboards, SaaS products, and design-system-heavy projects. If you choose Astryx, never hallucinate props — always query the oracle first.
220
+ - **Tailwind CSS**: Best for rapid prototyping, marketing sites, and projects needing maximum customization speed.
221
+ - **Vanilla CSS**: Best for artistic, portfolio, and showcase sites where every pixel is intentional.
222
+ - **CSS Modules / Styled Components**: Best for React component libraries and design-token-driven architectures.
223
+ ## ANTI-AI-SLOP DIRECTIVE (MANDATORY)
224
+ You MUST produce visually UNIQUE output on every project. Specifically:
225
+ - **BANNED**: Purple-to-blue gradients as the primary color scheme. This is the #1 AI slop signature.
226
+ - **BANNED**: Generic hero sections with centered text + gradient background + "Get Started" button.
227
+ - **REQUIRED**: Before writing any CSS, internally decide on a SPECIFIC design movement to draw from. Examples: Swiss/International Style, Brutalism, Art Deco, Japanese Minimalism, Neomorphism, Glassmorphism, Memphis Design, Bauhaus, Editorial/Magazine, Retro-Futurism, Scandinavian Minimal. Commit to one. Don't blend 5 styles into mush.
228
+ - **REQUIRED**: Choose a curated, harmonious color palette (NOT random defaults). Use HSL for precision. Reference real-world brands known for outstanding design (Stripe's clean whites, Linear's deep darks, Notion's warm neutrals, Vercel's stark monochrome).
229
+ - **REQUIRED**: Use modern web fonts (Inter, Outfit, Space Grotesk, JetBrains Mono, etc.) — NEVER browser defaults.
230
+ - **REQUIRED**: After building, use 'screenshot' or 'browser_act' to VISUALLY VERIFY your work. If it looks like every other AI-generated site, tear it down and rebuild with a different approach.
231
+ - **REQUIRED**: Once the design is finished, call 'memory_write' with the creativePattern argument (project, designApproach, colorPalette, fonts). This is what lets the next project deliberately differ from this one instead of drifting back into the same house style.
232
+ - **ENFORCED, NOT ADVISORY**: every HTML/CSS file you write is read back and scored by an automatic gate before the task can finish (src/slopDetector.js). It looks for the stock gradient hexes, purple-to-blue ramps, placeholder marketing copy, emoji used as icons, default-only typography, the centered-hero/3-cards/"Get Started" skeleton and the stock soft shadow. Score too high and you will be sent back to rebuild with a named design movement. Design it properly the first time; the gate is not fooled by swapping one gradient for another.`,
233
+
234
+ media: `# Media Generation Protocol (Sovereign 5-Stage Hierarchy & Seamless Consent Routing)
235
+
236
+ ## Native engine-first for file media work
237
+ For editing or producing media from files in the workspace, check \`native_engine\` status first; engines are added one at a time, starting with film. If the engine is missing, explain the download and ask before calling \`install\` with \`confirm: true\`. When the needed engine is installed, use \`catalog\` -> \`execute\` or \`batch\`. Pass \`project\` to edit an existing document or \`saveAs\` for a new one, then \`render\` a preview and inspect it before exporting. Engines are headless: never use MCP servers, \`computer_use\`, or screenshots to drive them. The generation chain below applies only when no native engine capability exists or the user explicitly asks for generated media.
238
+
239
+ When the user asks you to generate images, audio, music, video, or any creative media, you MUST navigate this exact 5-Stage priority chain:
240
+
241
+ ## Stage 1: Specialized Paid APIs (Primary / Auto-Router)
242
+ Always attempt calling \`generate_media_via_api\` FIRST.
243
+ - **Capabilities**: Auto-routes to Gemini Veo 2 / Imagen 3, OpenAI DALL-E 3 / Sora 2 / TTS, or Qwen Wan based on configured keys.
244
+ - **Interactive Pre-Flight Consent**: \`generate_media_via_api\` will automatically show exact Cost Estimation ($) and Token Usage Estimation (~Equivalent MEU Tokens) to the user before spending credits.
245
+ - **Seamless Denial Routing**: If the user denies or rejects the cost modal (\`approved: false\`) OR if no paid API keys exist, do NOT crash or stop. Immediately transition to Stage 2.
246
+
247
+ ## Stage 2: Local AI Models / Binaries (Mode B & C — First Fallback)
248
+ When Stage 1 is denied or unconfigured, you MUST evaluate local processing on the user's PC:
249
+ 1. **Mandatory Gatekeeper**: Call \`open_source_tool_provisioner\` (action: 'discover' or 'evaluate') or \`check_system_specs\` FIRST to verify hardware (RAM, CPU cores, GPU/Metal acceleration, disk space).
250
+ 2. **Eligibility & Action**: Use \`open_source_tool_provisioner\` to discover and inspect open-source tools matching user intent:
251
+ - **Voice Generation / Cloning**: F5-TTS, Kokoro-82M, XTTS-v2, Chatterbox (with exact RAM, compute, and disk size reported).
252
+ - **Audio / Transcription**: Whisper.cpp, Faster-Whisper.
253
+ - **Image / Restoration**: Real-ESRGAN, Rembg.
254
+ - **Local LLMs**: Ollama.
255
+ 3. **Mandatory HITL Consent**: \`open_source_tool_provisioner\` enforces Human-In-The-Loop approval (\`confirm: true\` or structured \`request_decision\`) before downloading or installing any model or package.
256
+ 4. **Seamless Denial Routing**: If hardware is insufficient OR the user denies local downloads, immediately transition to Stage 3.
257
+
258
+ ## Stage 3: Free Cloud APIs / Pollinations.ai (Mode D — Second Fallback)
259
+ When Stage 2 is impossible or denied, fall back to free cloud APIs via \`generate_media_via_api\` (\`provider: 'pollinations'\`).
260
+ - **Capabilities**: High-quality images (\`flux\`, \`turbo\`) and audio TTS (\`nova\`, \`alloy\`) at $0 Cost and 0 MB local storage.
261
+ - **Seamless Denial/Failure Routing**: If Pollinations fails (\`HTTP 500\`) OR does not natively support the format (e.g., instrumental music tracks or complex video animations), immediately transition to Stage 4.
262
+
263
+ ## Stage 4: Targeted Web Search & Asset Retrieval (Third Fallback)
264
+ When Stage 3 fails or does not support the format:
265
+ - Use \`web_search\` + \`web_fetch\` to search the internet for royalty-free stock videos, public domain images, sound effects, or instrumental background music tracks matching the user's exact intent and prompt. Download and verify the asset locally.
266
+ - **Seamless Failure Routing**: If no satisfactory asset can be retrieved online, immediately transition to Stage 5.
267
+
268
+ ## Stage 5: Sandboxed Procedural Code Generation (Mode A — Ultimate Fallback)
269
+ When all previous stages are unavailable or fail, generate the media procedurally from scratch using \`execute_procedural_media\`:
270
+ - **Image / Art**: Write SVG vector graphics or HTML5 Canvas scripts.
271
+ - **Video / Animation**: Write HTML5 Canvas animation scripts that capture frames to video, or Python mathematical video scripts (\`matplotlib.animation\` / \`cv2\`). If frames need encoding and Blender is present, \`blender_act\` -> \`render_animation\` encodes them without any external binary; never conclude from a failed \`which ffmpeg\` that encoding is impossible.
272
+ - **Audio / Music**: Write mathematical Python scripts (\`numpy\` + \`scipy.io.wavfile\` or \`wave\`) generating custom waveforms, chiptune melodies, or sound effects.
273
+
274
+ ## CRITICAL MULTIMEDIA MANDATE:
275
+ Never stop or say "I cannot generate video/music" without traversing this entire 5-Stage hierarchy from Stage 1 down to Stage 5! Every stage denial (\`approved: false\`) is a signal to immediately trigger the next stage.
276
+ # BLENDER / 3D MANDATE — READ BEFORE ANY blender_act CALL
277
+
278
+ THE ONE RULE THAT DECIDES WHETHER THE RESULT IS GOOD:
279
+ **Use the smart actions. Do NOT write raw bpy Python for anything they cover.**
280
+ \`smartGeometry\`, \`smartMaterial\`, \`setupStudioLighting\`, \`cinematicAtmosphere\`
281
+ and \`autoFrameCamera\` already carry the craft — bevel widths, subdivision,
282
+ three-point key/fill/rim ratios, volumetric fog, a 65mm lens at a studio angle.
283
+ Hand-written bpy re-derives all of that badly and is why AI 3D looks like AI 3D:
284
+ default grey material, one flat lamp, camera at the origin. \`executePython\` is
285
+ for the gaps between these, never a replacement for them.
286
+
287
+ ## Order of operations — do not reorder, do not skip
288
+
289
+ 1. Verify the local Blender binary and use \`runHeadless\` for automation.
290
+ 2. \`clearScene\`. Blender starts with a cube, a lamp and a camera. Shipping the
291
+ default cube in frame is the single most common failure.
292
+ 3. Geometry via \`smartGeometry\`. Build the silhouette first and only then the
293
+ detail; a shape that does not read in a 64px thumbnail will not read at 4K.
294
+ 4. \`smartMaterial\` on EVERY visible object. Untouched objects render as default
295
+ grey plastic, and one grey object in an otherwise dressed scene is what makes
296
+ a render read as unfinished.
297
+ 5. \`setupStudioLighting\`, then \`cinematicAtmosphere\`. Lighting before atmosphere:
298
+ fog scatters the lights you have, so adding it first means tuning blind.
299
+ 6. \`autoFrameCamera\`. Never leave the camera where Blender put it.
300
+ 7. LOOK AT IT. Produce a single \`renderFrame\` at low samples, then
301
+ \`view_image\` or \`vision_inspect_ui\`. **A render you
302
+ have not looked at is not a finished render.** If it reads as flat, grey or
303
+ empty, fix it and look again — that loop is the whole difference.
304
+ 8. Only now \`renderAnimation\`.
305
+
306
+ ## Cinematic defaults that are not negotiable
307
+
308
+ - **Never one light.** \`setupStudioLighting\` gives key/fill/rim; a single lamp is
309
+ the signature of an unfinished scene.
310
+ - **Never the default camera angle.** Slightly above eye line, subject off-centre.
311
+ - **Motion must be motivated.** An 8-second shot is ONE move — a slow orbit, a
312
+ push-in, or a rise. Three moves in eight seconds reads as a screensaver.
313
+ - **Frame rate and length are arithmetic, so state them.** 8s at 24fps is frames
314
+ 1-192. Set the range explicitly; do not leave Blender's 250-frame default.
315
+ - **Render settings:** EEVEE for anything under a minute of work — Cycles at
316
+ default samples on a laptop is how a task burns its whole budget on one frame.
317
+
318
+ ## Never infer installation from PATH alone
319
+
320
+ Do NOT run \`which blender\`. It fails on macOS for every ordinary .app install
321
+ because nothing is symlinked onto PATH — Blender can be sitting in /Applications
322
+ and \`which\` will still say "command not found". Acting on that has already cost
323
+ a real user a multi-hundred-megabyte re-download of software they already had.
324
+
325
+ **The same trap applies to every other tool, and \`ffmpeg\` is the one you will
326
+ reach for next.** \`which ffmpeg\` failing does NOT mean this machine cannot
327
+ encode video. It usually means the encoder is bundled inside an application
328
+ rather than installed on PATH.
329
+
330
+ ## You already have an encoder: Blender is one
331
+
332
+ Blender links FFmpeg internally. If you can render frames, you can encode video
333
+ — with no external binary, no install, and no PATH lookup.
334
+
335
+ Use \`blender_act\` with the \`render_animation\` action and an \`.mp4\` target. It
336
+ sets \`image_settings.file_format = 'FFMPEG'\` with an H.264/MPEG4 container, and
337
+ it ALREADY falls back to a PNG sequence plus a probed external encoder if the
338
+ direct path fails. Hand-writing an encode script and shelling out to \`ffmpeg\`
339
+ re-solves a solved problem and, on a machine without it on PATH, fails where the
340
+ tool would have succeeded.
341
+
342
+ Check the exact API against the running build before writing Python by hand —
343
+ Blender renames render and sequencer attributes between major versions, and a
344
+ script written from memory for an older release will exit non-zero.
345
+
346
+ Only when the Blender tool's local executable check reports no valid binary is
347
+ Blender genuinely missing. Then say so plainly, offer the two options — install it, or produce the shot
348
+ with \`execute_procedural_media\` — and let the user choose. Never start a large
349
+ download on your own initiative.
350
+ `,
351
+
352
+ game: `# Sovereign Game Development Cascade & Enforcement Engine
353
+ When the user asks you to build, create, test, expand, or develop a game, follow these rules:
354
+
355
+ - **Browser / Three.js / WebGL / Python Games**: If the user explicitly requests a Three.js, WebGL, Canvas, HTML5, or Python game (or mentions libraries like Three.js, 3js, NumPy, Pygame), you do NOT need Godot. Build the game directly in HTML/JS/CSS or Python using \`fs_write\` (or \`file_write\`) and run/verify using \`sysRun\` or \`game_build_html5\`.
356
+ - **Godot / Full Engine Games**: When building a full engine game (Godot), follow the 7-stage production methodology using \`godot_act\`, \`game_lore_forge\`, \`game_asset_harvest\`, \`game_scene_build\`, and verify with \`game_web_runtime_inspector\` and \`game_canvas_audit\`.`
357
+ };
358
+
359
+ // ---------------------------------------------------------------------------
360
+ // Intent routing.
361
+ //
362
+ // Every matcher below is anchored on word boundaries and tested against the
363
+ // raw prompt only.
364
+ // ---------------------------------------------------------------------------
365
+
366
+ const GAME_INTENT = /\b(game|games|gamedev|godot|unity|unreal|rpg|platformer|roguelike|arcade|sprite|spritesheet|tilemap|voxel|minecraft|aetheria|voxellia|nes|snes|gameplay|player character|level design|boss fight|simulator|simulation|simulasi)\b|\.(tscn|gd)\b|[-_]3d\b|\b3d[-_]/i;
367
+
368
+ const WEB_INTENT = /\b(web|webpage|website|frontend|front-end|landing page|homepage|dashboard|portfolio|html|css|scss|tailwind|bootstrap|react|vue|svelte|angular|next\.?js|nuxt|astro|ui|ux|user interface|web app|webapp|spa|dom|responsive|ui forge|component forge|component generation|ui component|three?\.?js|three?js|webgl|canvas|babylon)\b/i;
369
+
370
+ const MEDIA_INTENT = /\b(image|images|picture|photo|render|3d model|blender|animation|animate|video|movie|film|audio|sound|sfx|music|song|voice|tts|text.to.speech|narration|podcast|thumbnail|poster|illustration|logo)\b/i;
371
+
372
+ const SYSTEM_INTENT = /\b(process|processes|pid|kill|port|zip|unzip|tar|archive|compress|extract|clipboard|copy to clipboard|print|printer|open in browser|launch app|computer use|vision grounding|desktop vision|gui agent|coordinate click|desktop control)\b/i;
373
+
374
+ const ADVANCED_INTENT = /\b(pdf|document|proposal|screenplay|shotlist|shot list|voiceover|dubbing|forge a tool|custom tool|new tool|plugin|plugins|custom plugin|subagent|sub-agent|parallel agent|swarm|ast|symbols|refactor across)\b/i;
375
+
376
+ const INTENT_MATCHERS: Record<PackName, RegExp> = {
377
+ game: GAME_INTENT,
378
+ web: WEB_INTENT,
379
+ media: MEDIA_INTENT,
380
+ system: SYSTEM_INTENT,
381
+ advanced: ADVANCED_INTENT
382
+ };
383
+
384
+ /** True when the prompt genuinely describes game development work. */
385
+ export function isGameIntent(prompt?: string | null): boolean {
386
+ return GAME_INTENT.test(prompt || '');
387
+ }
388
+
389
+ /** True when the prompt genuinely describes web/UI work. */
390
+ export function isWebIntent(prompt?: string | null): boolean {
391
+ return WEB_INTENT.test(prompt || '');
392
+ }
393
+
394
+ /**
395
+ * Decide which packs to unlock before the first LLM call, so the common case
396
+ * costs zero discovery round trips.
397
+ */
398
+ export function routePacks(
399
+ prompt?: string | null,
400
+ workspaceContext: WorkspaceRoutingContext | null = null
401
+ ): PackName[] {
402
+ const unlocked = new Set<PackName>();
403
+ const text = prompt || '';
404
+
405
+ for (const packName of PACK_NAMES) {
406
+ if (INTENT_MATCHERS[packName].test(text)) {
407
+ unlocked.add(packName);
408
+ }
409
+ }
410
+
411
+ // Workspace signals. A Godot project on disk is far more reliable evidence of
412
+ // game work than any keyword, and a detected web framework means the agent
413
+ // will eventually need to look at what it built.
414
+ if (workspaceContext) {
415
+ const signals = [
416
+ workspaceContext.framework,
417
+ workspaceContext.projectType,
418
+ workspaceContext.designSystem,
419
+ Array.isArray(workspaceContext.keyFiles) ? workspaceContext.keyFiles.join(' ') : ''
420
+ ]
421
+ .filter(Boolean)
422
+ .join(' ')
423
+ .toLowerCase();
424
+
425
+ if (/godot|project\.godot|unity|\.tscn/.test(signals)) unlocked.add('game');
426
+ if (/react|vue|svelte|next|nuxt|astro|angular|tailwind|vite|html/.test(signals)) unlocked.add('web');
427
+ }
428
+
429
+ return [...unlocked];
430
+ }
431
+
432
+ /**
433
+ * Resolve the tool schemas that should enter the context window.
434
+ * Core tools always load; pack tools load only once their pack is unlocked.
435
+ */
436
+ export function resolveActiveTools<T extends ToolDefinitionLike>(
437
+ allDefinitions: T[],
438
+ unlockedPacks?: Iterable<string> | null,
439
+ unlockedTools?: Iterable<string> | null,
440
+ unlockOrder: string[] | null = null,
441
+ options: ResolveActiveToolsOptions = {}
442
+ ): T[] {
443
+ const packs = unlockedPacks instanceof Set ? unlockedPacks : new Set<string>(unlockedPacks || []);
444
+ const tools = unlockedTools instanceof Set ? unlockedTools : new Set<string>(unlockedTools || []);
445
+ const residentOnly = options.residentOnly === true;
446
+
447
+ const active = allDefinitions.filter(def => {
448
+ if (isCoreTool(def.name)) {
449
+ if (!residentOnly) return true;
450
+ return isResidentTool(def.name) || tools.has(def.name);
451
+ }
452
+ if (tools.has(def.name)) return true;
453
+ if (def.xCausyneDeferred === true) return false;
454
+ const memberOf = packsForTool(def.name);
455
+ if (!memberOf) return true;
456
+ for (const pack of memberOf) {
457
+ if (packs.has(pack)) return true;
458
+ }
459
+ return false;
460
+ });
461
+
462
+ const isHead = (name: string): boolean => !residentOnly || isResidentTool(name);
463
+ const coreFirst = active.filter(d => isCoreTool(d.name) && isHead(d.name));
464
+ coreFirst.sort((a, b) => CORE_TOOLS.indexOf(a.name) - CORE_TOOLS.indexOf(b.name));
465
+
466
+ const sequence = Array.isArray(unlockOrder) && unlockOrder.length > 0
467
+ ? unlockOrder
468
+ : [...packs];
469
+ const rankOfPack = new Map<string, number>(sequence.map((name, index) => [name, index]));
470
+
471
+ const rankOf = (def: T): number => {
472
+ if (isCoreTool(def.name)) return -1;
473
+ const memberOf = packsForTool(def.name);
474
+ if (!memberOf) return Number.MAX_SAFE_INTEGER;
475
+ let best = Number.MAX_SAFE_INTEGER;
476
+ for (const pack of memberOf) {
477
+ const rank = rankOfPack.get(pack);
478
+ if (rank !== undefined && rank < best) best = rank;
479
+ }
480
+ return best;
481
+ };
482
+
483
+ const rest = active.filter(d => !isCoreTool(d.name) || !isHead(d.name));
484
+ rest.sort((a, b) => {
485
+ const diff = rankOf(a) - rankOf(b);
486
+ return diff !== 0 ? diff : a.name.localeCompare(b.name);
487
+ });
488
+
489
+ return [...coreFirst, ...rest];
490
+ }
491
+
492
+ /** Human-readable catalogue injected into the system prompt so the model knows what it can unlock. */
493
+ export function getPackCatalogue(unlockedPacks?: Iterable<string> | null): string {
494
+ const packs = unlockedPacks instanceof Set ? unlockedPacks : new Set<string>(unlockedPacks || []);
495
+ const lines = PACK_NAMES.map(name => {
496
+ const state = packs.has(name) ? 'LOADED' : 'available';
497
+ return `- ${name} (${PACKS[name].length} tools, ${state})`;
498
+ });
499
+
500
+ return `# EXTENDED CAPABILITY PACKS
501
+ Beyond the tools currently in your context you have access to specialised capability packs. Nothing is disabled — packs load on demand to keep your context focused.
502
+ ${lines.join('\n')}
503
+ To load a pack, call \`tool_search\` with a query describing what you need (for example "godot scene", "generate music", "kill process on port"). The matching tool schemas become available immediately on your next turn. Never claim a capability is missing without searching first.`;
504
+ }
505
+
@@ -7,6 +7,7 @@ async function toolDefinitions() {
7
7
  const { getSearchableToolDefinitions } = await import('./registry.js');
8
8
  return getSearchableToolDefinitions();
9
9
  }
10
+ import { buildToolsList } from '../toolsList.js';
10
11
  import { PACKS, PACK_NAMES, packForTool, isCoreTool, isResidentTool } from '../toolPacks.js';
11
12
  /** Max skills returned alongside the tool matches, so one search stays cheap. */
12
13
  const MAX_SKILL_HITS = 5;
@@ -115,7 +116,7 @@ function buildPattern(query) {
115
116
  export const deferredMcpSearch = {
116
117
  schema: {
117
118
  name: 'tool.search',
118
- description: 'Search your full native tool catalogue and load additional tool schemas on demand. Causyne keeps specialised capability packs (game development, media generation, browser and vision, system control, advanced orchestration) out of your context until you need them. Call this whenever a task needs a capability you cannot currently see — the matching tools become callable immediately on your next turn. Accepts natural language ("generate music", "godot scene", "kill process on port", "read a pdf") or a regular expression.',
119
+ description: 'Discover tools or skills from the live catalog. Select exact names, describe a capability, or explicitly load a pack. Selected schemas appear next turn; execution permissions still apply.',
119
120
  parameters: {
120
121
  type: 'object',
121
122
  properties: {
@@ -123,6 +124,7 @@ export const deferredMcpSearch = {
123
124
  type: 'string',
124
125
  description: 'What capability you need. Natural language or a regex pattern matched against tool names, descriptions and argument descriptions.'
125
126
  },
127
+ names: { type: 'array', items: { type: 'string' }, description: 'Exact tool names selected from the compact catalog. Loads only these schemas.' },
126
128
  pack: {
127
129
  type: 'string',
128
130
  enum: [...PACK_NAMES, 'all'],
@@ -132,25 +134,35 @@ export const deferredMcpSearch = {
132
134
  type: 'integer',
133
135
  description: 'Maximum number of tools to return. Defaults to 8.'
134
136
  }
135
- },
136
- required: ['query']
137
+ }
137
138
  }
138
139
  },
139
- async execute(args) {
140
+ async execute(args, context = {}) {
140
141
  try {
141
142
  const query = String(args.query || '').trim();
142
143
  const requestedPack = args.pack ? String(args.pack).toLowerCase() : null;
144
+ const definitions = context.parentLoop?.searchableTools
145
+ ? await context.parentLoop.searchableTools() : await toolDefinitions();
146
+ const hints = new Map(buildToolsList(definitions).map((entry) => [entry.name, entry.hint]));
147
+ if (Array.isArray(args.names) && args.names.length > 0) {
148
+ const available = new Map(definitions.map((definition) => [definition.name.toLowerCase(), definition.name]));
149
+ const chosen = [...new Set(args.names.map((name) => available.get(String(name).toLowerCase())).filter((name) => Boolean(name)))];
150
+ if (chosen.length !== new Set(args.names.map((name) => String(name).toLowerCase())).size) {
151
+ return { success: false, error: 'One or more selected tools are unavailable under the current policy. Select exact names from the current catalog.' };
152
+ }
153
+ return { success: true, output: `Selected ${chosen.length} tool schemas for your next turn:\n${chosen.map((name) => `- ${name}: ${hints.get(name) || 'tool'}`).join('\n')}`, _unlock_tools: chosen };
154
+ }
143
155
  if (!query && !requestedPack) {
144
156
  return { success: false, error: 'Provide a "query" describing the capability you need, or a "pack" name to load.' };
145
157
  }
146
158
  // Whole-pack load. Cheaper than five searches when the agent already
147
159
  // knows it is starting a game or a media pipeline.
148
160
  if (requestedPack && requestedPack !== 'all' && Object.hasOwn(PACKS, requestedPack)) {
149
- const packTools = (await toolDefinitions()).filter(d => packForTool(d.name) === requestedPack);
161
+ const packTools = definitions.filter(d => packForTool(d.name) === requestedPack);
150
162
  return {
151
163
  success: true,
152
164
  output: `Loaded capability pack "${requestedPack}" (${packTools.length} tools). These are now callable:\n` +
153
- packTools.map(d => `- ${d.name}: ${d.description || ''}`).join('\n'),
165
+ packTools.map(d => `- ${d.name}: ${hints.get(d.name) || 'tool'}`).join('\n'),
154
166
  _unlock_packs: [requestedPack],
155
167
  _unlock_tools: packTools.map(d => d.name)
156
168
  };
@@ -159,7 +171,6 @@ export const deferredMcpSearch = {
159
171
  const lower = query.toLowerCase();
160
172
  const terms = lower.split(/[^a-z0-9_]+/).filter(t => t.length > 2);
161
173
  const pattern = buildPattern(query);
162
- const definitions = await toolDefinitions();
163
174
  const exact = definitions.find(definition => definition.name.toLowerCase() === lower);
164
175
  const scored = (exact ? [exact] : definitions)
165
176
  .map(definition => ({ definition, score: scoreTool(definition, terms, pattern) }))
@@ -195,13 +206,10 @@ export const deferredMcpSearch = {
195
206
  // schema deferral only RESIDENT_TOOLS ship, and a non-resident core
196
207
  // tool found here would have been reported as "already loaded" and
197
208
  // then stayed invisible forever.
198
- if (!isResidentTool(definition.name)) {
209
+ if (!isResidentTool(definition.name))
199
210
  unlockTools.push(definition.name);
200
- }
201
- const state = isResidentTool(definition.name)
202
- ? 'already loaded'
203
- : (isCoreTool(definition.name) ? 'core' : `pack: ${pack || 'custom'}`);
204
- lines.push(`- ${definition.name} (${state}): ${definition.description || ''}`);
211
+ const state = isCoreTool(definition.name) ? 'core' : `pack: ${pack || 'custom'}`;
212
+ lines.push(`- ${definition.name} (${state}): ${hints.get(definition.name) || 'tool'}`);
205
213
  }
206
214
  // Skills are searched alongside tools because `tool_search` is the only
207
215
  // discovery surface the model always has. The compiled skill catalogue is