@causyne/agent 1.18.0 → 1.19.0

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 (69) hide show
  1. package/package.json +1 -1
  2. package/src/agentLoop.js +2348 -2531
  3. package/src/agentLoop.ts +2865 -0
  4. package/src/checkpoints.d.ts +4 -0
  5. package/src/cliMode.js +10 -3
  6. package/src/commands.js +109 -6
  7. package/src/config.js +22 -0
  8. package/src/contextManager.d.ts +10 -0
  9. package/src/continuum/adapters/antigravity.js +193 -0
  10. package/src/continuum/adapters/antigravity.ts +204 -0
  11. package/src/continuum/adapters/base.js +48 -0
  12. package/src/continuum/adapters/base.ts +57 -0
  13. package/src/continuum/adapters/causyne.js +66 -0
  14. package/src/continuum/adapters/causyne.ts +72 -0
  15. package/src/continuum/adapters/claudeCode.js +171 -0
  16. package/src/continuum/adapters/claudeCode.ts +179 -0
  17. package/src/continuum/adapters/codex.js +181 -0
  18. package/src/continuum/adapters/codex.ts +193 -0
  19. package/src/continuum/adapters/opencode.js +134 -0
  20. package/src/continuum/adapters/opencode.ts +153 -0
  21. package/src/continuum/compactor.js +54 -0
  22. package/src/continuum/compactor.ts +83 -0
  23. package/src/continuum/index.js +8 -0
  24. package/src/continuum/index.ts +9 -0
  25. package/src/continuum/ingest.js +63 -0
  26. package/src/continuum/ingest.ts +89 -0
  27. package/src/continuum/sanitizer.js +55 -0
  28. package/src/continuum/sanitizer.ts +59 -0
  29. package/src/continuum/scanner.js +86 -0
  30. package/src/continuum/scanner.ts +106 -0
  31. package/src/continuum/types.js +3 -0
  32. package/src/continuum/types.ts +51 -0
  33. package/src/continuum/ui/continuumPicker.js +111 -0
  34. package/src/continuum/ui/continuumPicker.ts +145 -0
  35. package/src/cortex/autoCondenser.d.ts +2 -0
  36. package/src/cortex/vectorDb.d.ts +1 -0
  37. package/src/designPalettes.d.ts +2 -0
  38. package/src/devMode.d.ts +1 -0
  39. package/src/dynamicCatalogue.js +5 -3
  40. package/src/dynamicCatalogue.ts +7 -4
  41. package/src/embodimentSession.d.ts +2 -0
  42. package/src/entrypoint.js +12 -0
  43. package/src/memory.d.ts +1 -0
  44. package/src/memoryManager.d.ts +1 -0
  45. package/src/modelIds.d.ts +2 -0
  46. package/src/outputStore.d.ts +4 -0
  47. package/src/providers/acp.js +320 -299
  48. package/src/providers/acp.ts +360 -0
  49. package/src/providers/antigravity.js +387 -278
  50. package/src/providers/antigravity.ts +450 -0
  51. package/src/providers/base.d.ts +68 -0
  52. package/src/providers/factory.d.ts +1 -0
  53. package/src/provisioning/capabilityProvisioner.d.ts +2 -0
  54. package/src/sandbox.d.ts +1 -0
  55. package/src/skillsManager.d.ts +3 -0
  56. package/src/slopDetector.d.ts +3 -0
  57. package/src/taskBuffer.d.ts +1 -0
  58. package/src/tokenTracker.d.ts +1 -0
  59. package/src/toolPacks.d.ts +8 -0
  60. package/src/tools/registry.d.ts +4 -0
  61. package/src/tui/chatRenderer.js +62 -8
  62. package/src/tui/clipboardSync.js +36 -0
  63. package/src/tui/clipboardSync.ts +36 -0
  64. package/src/tui/dialogs.js +15 -2
  65. package/src/tui/home.js +2 -1
  66. package/src/tui/modelPicker.js +221 -0
  67. package/src/tui/modelPicker.ts +290 -0
  68. package/src/tui/prompt.js +17 -6
  69. package/src/tui/selectList.js +20 -0
@@ -0,0 +1,2865 @@
1
+ import { createHash } from 'crypto';
2
+ import { processApprovalScope } from './approvalGrants.js';
3
+ import { pruneSessions as pruneEmbodimentSessions, describeSession } from './embodimentSession.js';
4
+ import { WorkspacePerception } from './perception.js';
5
+ import { audioFormatForMimeType } from './providers/base.js';
6
+ import { TaskBuffer } from './taskBuffer.js';
7
+ import { TOOL_DEFINITIONS, getDynamicTools, resolveTool, canonicalToolName } from './tools/registry.js';
8
+ import { selfRepairToolCall, generateSelfRepairDiagnostic } from './tools/toolSelfRepair.js';
9
+ import { Sandbox } from './sandbox.js';
10
+ import { auditLog } from './auditLog.js';
11
+ import { hasMatchingHook, runConfiguredHooks } from './hooks.js';
12
+ import { loadConfig } from './config.js';
13
+ import { isDevEmulator } from './devMode.js';
14
+ import { TokenTracker } from './tokenTracker.js';
15
+
16
+ import { getMemoryContextString } from './memory.js';
17
+ import { MemoryManager } from './memoryManager.js';
18
+ import { cortexDb } from './cortex/vectorDb.js';
19
+ import { buildStructuralSummary, condenseAndSave } from './cortex/autoCondenser.js';
20
+ import { analyzeTask, buildTaskBrief, packsFromShape } from './taskShape.js';
21
+ import { lookupPlan, recordPlan, recordMiss, renderPlanHint, toStep } from './planCache.js';
22
+ import { routedConfig } from './modelRouter.js';
23
+ import { assessStep, isThrashing } from './uncertainty.js';
24
+ import { assessDecisionRequirement, isMutatingToolCall, requiresImplementationPlan } from './decisionPolicy.js';
25
+ import { VFETracker } from './vfeTracker.js';
26
+ import { coldObserver } from './observer/coldObserver.js';
27
+ import {
28
+ routePacks,
29
+ packForTool,
30
+ isCoreTool,
31
+ isGameIntent,
32
+ isWebIntent,
33
+ getPackCatalogue,
34
+ PACK_PLAYBOOKS,
35
+ PACKS
36
+ } from './toolPacks.js';
37
+ import {
38
+ resolveCharPool,
39
+ measureMessages,
40
+ resultCapFor,
41
+ decayToolResults,
42
+ buildWindow,
43
+ compactInPlace,
44
+ describeDroppedMessages,
45
+ sanitizeSequences,
46
+ applyProgressiveCompaction,
47
+ snipOversizedToolOutputs
48
+ } from './contextManager.js';
49
+
50
+ // Provider imports
51
+ import { detectWorkspaceDomains, ensureSkillRepo, getSkillDomainHeader } from './skillsManager.js';
52
+ import { spillToolResult, buildSpillNotice, buildDecayPointer, pruneOutputStore } from './outputStore.js';
53
+ import { beginTask as beginCheckpointTask, captureBeforeMutation, pruneStore as pruneCheckpointStore, resolveProjectRoot } from './checkpoints.js';
54
+ import fsSync from 'fs';
55
+ import os from 'os';
56
+ import { analyzeFiles, formatFindings, isScannableFile } from './slopDetector.js';
57
+ import { suggestMovements, formatMovementBrief } from './designPalettes.js';
58
+ import { createProvider } from './providers/factory.js';
59
+ import { resolveMentionedContext } from './promptMentions.js';
60
+
61
+ export interface AgentLoopEvent {
62
+ type: string;
63
+ [key: string]: unknown;
64
+ }
65
+
66
+ export interface AgentLoopEventSink {
67
+ readyState?: number;
68
+ send(payload: string): void;
69
+ }
70
+
71
+ export interface AgentLoopConfig {
72
+ autonomyMode?: 'A' | 'B' | 'C' | string;
73
+ maxStepsPerTask?: number;
74
+ tokenBudget?: Record<string, unknown>;
75
+ [key: string]: unknown;
76
+ }
77
+
78
+ export interface ApprovalDecision {
79
+ approved: boolean;
80
+ [key: string]: unknown;
81
+ }
82
+
83
+ export interface AgentLoopApprovalScope {
84
+ grantAlways(toolName: unknown): void;
85
+ isAlwaysAllowed(toolName: unknown): boolean;
86
+ listAlwaysAllowed(): string[];
87
+ revokeAllAlways(): number;
88
+ revokeAlways(toolName: unknown): boolean;
89
+ }
90
+
91
+ export interface AgentLoopOptions {
92
+ workspaceRoot?: string;
93
+ memorySessionId?: string | null;
94
+ approvalScope?: AgentLoopApprovalScope;
95
+ }
96
+
97
+ const SYSTEM_PROMPT = `You are Causyne Agent, a God-Tier Autonomous AI. You operate the user's computer through a local desktop harness. You are not just a coding assistant; you are a general-purpose superintelligence.
98
+
99
+ # Your Capabilities
100
+ You can do anything a human can do from a terminal: write code, build apps, manage files, install software, configure systems, run tests, deploy projects, analyze security vulnerabilities, and more. If a human can do it, you can do it.
101
+ Specifically, you excel at:
102
+ - **System Administration**: Organizing folders, cleaning the desktop, categorizing downloads, finding lost files.
103
+ - **Office & Creative Work**: Researching and writing massive 100-page theses, novels, or film scripts. Writing scripts to output Excel, Word, or PDF files from raw data.
104
+ - **Web & Media**: Searching the web, downloading files, and opening browsers to specific videos (YouTube, Netflix) using cross-platform terminal commands (e.g., AppleScript for macOS, PowerShell for Windows, or xdg-open for Linux).
105
+
106
+ # Core Mandates
107
+ 1. **Autonomy & Completion**: You are an agent. Keep going until the user's query is completely resolved before yielding back. Do not stop until the problem is solved. Autonomously resolve the query to the best of your ability using tools.
108
+ 2. **Ambition vs. Precision**: Be highly ambitious and creative on new tasks. Be surgically precise on existing codebases. Treat existing code with respect, never touching unrelated files or fixing unrelated bugs.
109
+ 3. **Conventions**: Rigorously adhere to existing project conventions. Mimic the style, structure, framework choices, and architectural patterns of existing code. NEVER assume a library/framework is available; verify it first.
110
+
111
+ # Operational Guidelines & Communication
112
+ - **Ruthless Conciseness**: Answer concisely with fewer than 4 lines unless detail is requested. No preambles ("Okay, I will now...") or postambles ("I have finished..."). One-word answers are best for simple questions.
113
+ - **Status Updates**: Write in a continuous conversational style. Give a brief progress note (1-2 sentences) BEFORE executing a tool. **CRITICAL: You MUST output this text and invoke the tool in the EXACT SAME RESPONSE.** If you output text without invoking a tool, the system will assume you are finished and terminate the task.
114
+ - **Confirm Ambiguity**: Do not take significant actions beyond the clear scope of the request without confirming. If asked *how* to do something, explain first, don't just do it.
115
+ - **No Chitchat**: Tools are for actions, text output is *only* for communication. Do not add explanatory comments within tool calls or code blocks.
116
+ - **File Paths**: ALWAYS output the absolute path of any file you create, modify, or generate so the user knows exactly where it is.
117
+
118
+ # Task Management & Planning
119
+ - Use update_plan to create a visible implementation checklist before complex implementation. Create atomic, verb-led, verifiable steps and keep exactly one step in progress.
120
+ - Check off completed TODOs immediately before reporting progress. Do not batch up multiple task completions.
121
+ - Reconcile and close the todo list when all goal tasks are done. If the user asks you to implement, do not output a separate text-based plan. Just build and display the todo list.
122
+
123
+ # Durable Decisions
124
+ - Use request_decision when multiple materially different architecture, product, data, security, or workflow directions are valid. Give 2-4 concrete options with consequences; the UI adds a custom-answer choice.
125
+ - A decision is separate from permission. Do not ask for routine implementation details that can be resolved from the repository. Even in Mode C, pause for an unresolved durable architecture decision before changing the system.
126
+
127
+ # Maximize Parallel Tool Calls (Speed is Key)
128
+ - CRITICAL INSTRUCTION: For maximum efficiency, whenever you perform multiple operations, invoke all relevant tools concurrently (in parallel) rather than sequentially.
129
+ - Searching for different patterns (imports, usage, definitions) MUST happen in parallel. Reading multiple files MUST happen in parallel.
130
+ - Sequential calls can ONLY be used when you genuinely REQUIRE the output of one tool to determine the usage of the next tool. Parallel tool execution is 3-5x faster and is the expected behavior.
131
+
132
+ # Context Understanding & Searching
133
+ - Semantic search (or grep) is your MAIN exploration tool. Start with a broad, high-level query.
134
+ - MANDATORY: Run multiple searches with different wording in parallel; first-pass results often miss key details.
135
+ - Keep searching new areas until you're CONFIDENT nothing important remains. Bias towards not asking the user for help if you can find the answer yourself.
136
+
137
+ # Making Code Changes & Execution
138
+ - **No Blind Patching**: NEVER edit a file using a patch/edit tool if you have not opened it with the read tool within your last 5 messages. Read the file again to confirm its contents before patching.
139
+ - **Verification Loop**: NEVER assume code works. After making code changes, execute the project-specific build, linting, and type-checking commands (e.g., 'tsc', 'npm run lint', 'pytest'). Identify these commands by examining 'README' files or 'package.json'.
140
+ - **Code Quality**: Write HIGH-VERBOSITY code. Optimize for clarity. Use meaningful variable names (no 1-letter names like 'n'). Use guard clauses/early returns. Avoid deep nesting.
141
+ - **No TODOs/Comments**: Do not add comments for trivial code. NEVER use inline comments. Avoid TODO comments—implement the logic instead.
142
+ - **Runnable Code**: Ensure generated code can be run immediately. Add all necessary imports, dependencies, and scaffolding (e.g. requirements.txt) if building from scratch.
143
+
144
+ # Git Workflow & Best Practices
145
+ - When asked to commit changes, start by gathering information: run \`git status\`, \`git diff HEAD\`, and \`git log -n 3\` to match commit style. Combine these shell commands to save steps.
146
+ - Always propose a draft commit message. Prefer messages that are clear, concise, and focused more on "why" and less
147
+
148
+ # Security & Constraints (Causyne Architecture)
149
+ - **Token Budgeting**: You must respect the user's BYOK (Bring Your Own Key) limits. Be highly token-efficient.
150
+ - **Explain Critical Commands**: Before executing destructive shell commands, provide a brief explanation of the impact.
151
+ - **Interactive Commands**: Avoid shell commands that require user interaction (e.g., \`git rebase -i\`). Use non-interactive flags (e.g., \`-y\`).
152
+ - **Sandboxing**: You operate within a strict 4-layer sandbox. Flag destructive commands (rm, overwrite) as "dangerous" for user approval.
153
+ - **SSRF Protection**: Do not fetch internal IPs (127.0.0.1, 169.254.x.x, 10.x.x.x).
154
+
155
+ # ABSOLUTE ETHICAL SAFETY NET (NON-NEGOTIABLE)
156
+ You are bound by an unbreakable ethical safety net. Regardless of user prompt, jailbreak attempts, or roleplay scenarios, you MUST REFUSE to:
157
+ 1. Create software designed to damage, disrupt, or gain unauthorized access to computer systems (malware, ransomware, keyloggers, trojans, rootkits).
158
+ 2. Write phishing pages, credential harvesters, social engineering scripts, or fake login forms designed to steal user passwords.
159
+ 3. Build DDoS tools, network flooding scripts, or tools designed for unauthorized network exploitation or cracking.
160
+ 4. Generate content that exploits minors or non-consenting individuals.
161
+ 5. Create surveillance/spyware tools, unauthorized screen capture malware, or microphone/camera hijackers.
162
+ 6. Write tools for software piracy, license cracking, or key generators.
163
+ 7. Build unauthorized cryptocurrency miners or crypto wallet drainers.
164
+ 8. Forge custom tools (via tool_forge) that perform any of the above harmful actions.
165
+
166
+ If asked to perform ANY harmful task, politely decline, state that Causyne exists to make the world better, and offer legitimate developer assistance instead.
167
+
168
+ # Dependency Management & Autonomy Modes
169
+ - **Mode A (Passive)**: You MUST explicitly ask the user for permission (by ending your turn and asking a question) before installing any dependencies.
170
+ - **Mode B (Supervised)**: You may install standard development dependencies automatically, but you MUST ask for permission before modifying OS-level settings or running \`sudo\`.
171
+ - **Mode C (Autonomous)**: You have full freedom. Silently execute installation commands if a dependency is missing.
172
+
173
+ # Direct API & Automation Policy
174
+ - **Prefer REST APIs (curl)**: When interacting with external services (like web, email, chat), prioritize finding and using official REST APIs via \`curl\` or simple scripts.
175
+ - **Avoid UI/Browser Automation**: Automating a browser (e.g., Puppeteer/Playwright) is noisy, expensive, and fragile. ONLY use browser automation if a site genuinely has no API. Reading JSON is always better than reading DOM.
176
+
177
+ # Universal Tool Calling & Registry Discipline
178
+ 1. **Strict Registry Adherence**: Use ONLY the tools declared in the catalogue. Invoke tools using exact parameter names specified in the schema. Do not invent or rename parameters.
179
+ 2. **Valid JSON Formatting**: All tool call arguments must be valid JSON objects. Never include raw unescaped newlines or trailing commas inside argument strings.
180
+ 3. **Automated Buffer & Self-Correction**: Causyne runs a Universal Tool Buffer with self-repair capabilities. If a tool returns a \`selfRepairGuidance\` result indicating missing or invalid parameters, immediately read the \`expectedParameters\` and re-invoke the tool with the corrected arguments.
181
+
182
+ # UNIVERSAL CRITICAL DIRECTIVE (APPLIES TO ALL TASKS)
183
+ **DO NOT OUTPUT CONVERSATIONAL TEXT WITHOUT INVOKING A TOOL CALL SIMULTANEOUSLY.**
184
+ If the task is not 100% finished, you MUST invoke a tool (like web_search, fs_read, sysRun, etc.) in the exact same response as your text. If you output text without a tool call, the system will assume you are completely done and immediately terminate the task!
185
+ `;
186
+
187
+ function getProviderSpecificPrompt(provider: string = '') {
188
+ const p = provider.toLowerCase();
189
+
190
+ if (p === 'anthropic') {
191
+ return `ANTHROPIC BRAIN ACTIVATION:
192
+ You are Claude — a model with exceptional analytical depth and nuanced reasoning. Leverage your strengths:
193
+ - Use <thinking> tags for complex multi-step reasoning before acting.
194
+ - You excel at understanding subtle context and edge cases. Apply this to architecture decisions.
195
+ - Your creativity is rooted in deep understanding, not randomness. When designing UIs, draw from your vast knowledge of design history, typography, and color theory.
196
+ - Self-critique: Before finalizing any creative output, internally evaluate "Does this look like generic AI output?" If yes, redesign.
197
+ - Ensure all tool calls strictly match the schema without omitting required fields. Avoid conversational filler completely.`;
198
+ }
199
+
200
+ if (p === 'openai') {
201
+ return `OPENAI BRAIN ACTIVATION:
202
+ You are GPT — a model with exceptional parallel reasoning and creative synthesis. Leverage your strengths:
203
+ - Execute maximum parallel tool calls. You can read 5 files, search 3 patterns, and write 2 files simultaneously.
204
+ - Your training includes vast exposure to award-winning web design. Channel this: think of specific real-world sites you've seen (Stripe, Linear, Vercel, Apple) and synthesize NEW aesthetics from them.
205
+ - When generating creative work, push beyond the first idea. Your strength is in synthesis — combine unexpected influences.`;
206
+ }
207
+
208
+ if (p === 'deepseek') {
209
+ return `DEEPSEEK BRAIN ACTIVATION:
210
+ You are DeepSeek — a model with outstanding code generation and mathematical reasoning. Leverage your strengths:
211
+ - Pay close attention to raw JSON formatting. Avoid escaping quotes unnecessarily.
212
+ - Your code output is exceptionally clean and well-structured. Use this for building pixel-perfect CSS layouts.
213
+ - For creative tasks: your training data includes massive open-source design repositories. Access this knowledge — don't default to generic patterns.
214
+ - Self-verify: After generating UI code, mentally render it. Does it look unique? If not, iterate.`;
215
+ }
216
+
217
+ if (p === 'qwen') {
218
+ return `QWEN BRAIN ACTIVATION:
219
+ You are Qwen — a model with exceptional multilingual capability and creative breadth. Leverage your strengths:
220
+ - Pay close attention to raw JSON formatting. Avoid escaping quotes unnecessarily.
221
+ - Your training includes diverse cultural design traditions (Eastern minimalism, European modernism, etc.). Draw from this diversity.
222
+ - For web tasks: vary your design approach. Don't repeat the same layout structure across projects.`;
223
+ }
224
+
225
+ if (p === 'muse' || p === 'meta') {
226
+ return `MUSE BRAIN ACTIVATION:
227
+ You are Muse Spark — a model built for long-horizon coding and multi-step agentic work, with a 1,048,576-token context window. Leverage your strengths:
228
+ - You are tuned for tool loops that run for many steps. Do not stop early to summarise progress; keep acting until the task is actually finished.
229
+ - Your context is enormous. Read the surrounding files before you edit — you can afford to understand the whole module, and guessing is a choice, not a constraint.
230
+ - You emit fewer tokens than earlier versions for the same work. Spend that budget on correctness, not on narration.
231
+ - You can see: images, video frames, and PDFs all reach you. After building any UI, screenshot it and look at what you actually produced.
232
+ - For creative work: your training spans design history far beyond the templates. A layout that looks like every other AI-generated page is a failure, not a default.`;
233
+ }
234
+
235
+ if (p === 'gemini') {
236
+ return `GEMINI BRAIN ACTIVATION:
237
+ You are Gemini — a multimodal model with strong visual-spatial reasoning. Leverage your strengths:
238
+ - You can reason about visual layouts spatially. Use this when designing page compositions.
239
+ - Your training includes vast visual data. When building UIs, think in terms of visual hierarchy, whitespace rhythm, and typographic scale.
240
+ - After building a web page, use the screenshot tool to visually verify your work. You can see — use this advantage.`;
241
+ }
242
+
243
+ if (p === 'ollama') {
244
+ return `LOCAL MODEL ACTIVATION:
245
+ You are running locally — respect the user's hardware constraints. Be token-efficient but don't sacrifice quality.
246
+ - Focus on clean, minimal implementations that work on first try.
247
+ - For creative work: simplicity can be beautiful. Japanese minimalism, Swiss design — these are aesthetically powerful AND computationally light.`;
248
+ }
249
+
250
+ if (p === 'xai' || p === 'grok') {
251
+ return `GROK BRAIN ACTIVATION:
252
+ You are Grok — a model highly optimized for speed and parallel tool execution.
253
+ - Prioritize direct, functional solutions over verbose explanations.
254
+ - Execute maximum parallel tool calls when searching or refactoring code.
255
+ - Your personality is unapologetic and highly technical. Focus purely on the most efficient code path.`;
256
+ }
257
+
258
+ if (p === 'moonshot' || p === 'kimi') {
259
+ return `KIMI BRAIN ACTIVATION:
260
+ You are Kimi — a model powered by KDA (Kimi Delta Attention) with a massive context window.
261
+ - Leverage your massive memory to reason holistically about the entire codebase structure before making surgical edits.
262
+ - You excel at end-to-end programming and agentic task decomposition.
263
+ - When reading large files, synthesize the global context. Do not lose track of the big picture.`;
264
+ }
265
+
266
+ return "";
267
+ }
268
+
269
+ /**
270
+ * The system message carrying an invoked skill — or null when none is active.
271
+ *
272
+ * A pure function, and deliberately exported: this is the single link that was
273
+ * missing. `/skills <id>` printed the file to the terminal and returned, so the
274
+ * body never entered a request and no API call was made at all. Building it
275
+ * here rather than inline in run() means it can be tested for what it actually
276
+ * produces, instead of by reading the source and hoping.
277
+ *
278
+ * Returned as an ARRAY so the caller spreads it, which keeps the systemMessages
279
+ * literal readable.
280
+ */
281
+ export function skillSystemMessage(skill: any) {
282
+ if (!skill || typeof skill.content !== 'string' || !skill.content.trim()) return null;
283
+ return [{
284
+ role: 'system',
285
+ content:
286
+ `THE USER HAS INVOKED A SKILL: ${skill.id}\n\n`
287
+ + 'Follow this procedure for the current task. It is a working method, not a document to '
288
+ + 'summarise back — carry out its steps, and treat each "Done when:" line as the condition '
289
+ + 'that must actually hold before moving on. Where it conflicts with your general approach, '
290
+ + 'the skill wins; where it conflicts with your safety rules or the workspace boundaries, '
291
+ + 'those win and you say so.\n\n'
292
+ + '--- BEGIN SKILL ---\n'
293
+ + skill.content
294
+ + '\n--- END SKILL ---',
295
+ // Stable for the whole task, so it anchors the cache rather than
296
+ // invalidating the cached prefix on every step.
297
+ cacheAnchor: true
298
+ }];
299
+ }
300
+
301
+
302
+ export function explainNetworkError(error: any, config: any = {}) {
303
+ const cause = error && error.cause;
304
+ const code = (cause && (cause.code || cause.errno)) || '';
305
+
306
+ let host = '';
307
+ try {
308
+ const raw = config.baseUrl && String(config.baseUrl).trim();
309
+ if (raw) host = new URL(raw).host;
310
+ } catch (e: any) { /* a malformed base URL is itself worth reporting, below */ }
311
+
312
+ const REASONS: Record<string, string> = {
313
+ ENOTFOUND: 'the host could not be resolved (DNS)',
314
+ EAI_AGAIN: 'DNS lookup failed — the network may be down or captive',
315
+ ECONNREFUSED: 'nothing accepted the connection on that host and port',
316
+ ECONNRESET: 'the connection was reset before a reply arrived',
317
+ ETIMEDOUT: 'the connection timed out',
318
+ UND_ERR_CONNECT_TIMEOUT: 'the connection timed out',
319
+ UND_ERR_HEADERS_TIMEOUT: 'the server accepted the connection but never replied',
320
+ EHOSTUNREACH: 'that host is unreachable from this network',
321
+ ENETUNREACH: 'this machine has no route to the network',
322
+ EPIPE: 'the connection closed mid-request',
323
+ CERT_HAS_EXPIRED: 'the TLS certificate has expired',
324
+ DEPTH_ZERO_SELF_SIGNED_CERT: 'the TLS certificate is self-signed — a proxy may be intercepting',
325
+ UNABLE_TO_VERIFY_LEAF_SIGNATURE: 'the TLS certificate could not be verified — a proxy may be intercepting',
326
+ SELF_SIGNED_CERT_IN_CHAIN: 'a self-signed certificate is in the chain — a proxy may be intercepting'
327
+ };
328
+
329
+ const reason = REASONS[code] || (code ? `the connection failed (${code})` : 'the connection failed');
330
+ const where = host ? ` reaching ${host}` : '';
331
+ const provider = config.provider ? ` via ${config.provider}` : '';
332
+
333
+ const checks = [];
334
+ if (code === 'ENOTFOUND' || code === 'EAI_AGAIN' || code === 'ENETUNREACH') {
335
+ checks.push('confirm this machine is online');
336
+ if (host) checks.push(`confirm ${host} is the endpoint you meant — /config changes it`);
337
+ } else if (code === 'ECONNREFUSED') {
338
+ checks.push(host
339
+ ? `confirm something is listening on ${host}`
340
+ : 'confirm your local model server is running');
341
+ } else if (String(code).startsWith('CERT') || String(code).includes('SELF_SIGNED')) {
342
+ checks.push('a corporate proxy is likely intercepting TLS — the CA needs to be trusted');
343
+ } else {
344
+ checks.push('retry in a moment; if it persists, check the network and the configured endpoint');
345
+ }
346
+
347
+ return `Could not reach the model${provider}${where}: ${reason}.\n`
348
+ + checks.map((check) => ` - ${check}`).join('\n');
349
+ }
350
+
351
+ // classifyError() returns this for every connection-level failure. Assembled
352
+ // the same way the classifier does, so the two can never drift apart.
353
+ const NETWORK_ERROR_TYPE = "network_error";
354
+
355
+ export class AgentLoop {
356
+ // Task state is assembled across the constructor and helpers below. This
357
+ // signature keeps those reads and writes explicitly dynamic while each field
358
+ // is migrated to a precise type; it emits no JavaScript.
359
+ [key: string]: any;
360
+
361
+ /**
362
+ * How many times in a row the same class of failure may repeat before the
363
+ * loop gives up.
364
+ *
365
+ * Three is enough to ride out a blip and few enough that a genuinely broken
366
+ * endpoint is reported in seconds rather than after the whole step budget.
367
+ */
368
+ static MAX_CONSECUTIVE_FAILURES = 3;
369
+ constructor(eventSink: AgentLoopEventSink | null, taskId: string, userPrompt: string | null, options: AgentLoopOptions = {}) {
370
+ this.eventSink = eventSink;
371
+ this.taskId = taskId;
372
+ this.userPrompt = userPrompt;
373
+ this.workspaceRoot = typeof options.workspaceRoot === 'string' && options.workspaceRoot
374
+ ? options.workspaceRoot
375
+ : process.cwd();
376
+ this.autonomyOverride = null;
377
+ this.approvalScope = options.approvalScope && typeof options.approvalScope.isAlwaysAllowed === 'function'
378
+ ? options.approvalScope
379
+ : processApprovalScope;
380
+
381
+ this.config = loadConfig();
382
+ this.sandbox = new Sandbox();
383
+
384
+ // Retire spilled tool outputs past their retention window. Fire-and-forget
385
+ // at task start rather than on a timer: nothing may run in the background
386
+ // (rule ZM-01), and a task boundary is often enough for a 7-day window.
387
+ try { pruneOutputStore(); } catch (e: any) { /* never block a task on housekeeping */ }
388
+ try { pruneCheckpointStore(); } catch (e: any) { /* never block a task on housekeeping */ }
389
+ try { pruneEmbodimentSessions(); } catch (e: any) { /* never block a task on housekeeping */ }
390
+ // Set by the caller when the user invokes a skill by name. Its body becomes
391
+ // a system message for the task; see systemMessages [4].
392
+ this.activeSkill = null;
393
+ // Consecutive same-class failures, for the retry ceiling below.
394
+ this.consecutiveFailures = 0;
395
+ this.lastFailureType = null;
396
+ this.perception = new WorkspacePerception();
397
+ this.taskBuffer = new TaskBuffer();
398
+ this.tokenTracker = new TokenTracker();
399
+
400
+ this.llm = this.initializeProvider();
401
+ this.memoryManager = new MemoryManager(this.workspaceRoot, options.memorySessionId || null);
402
+ this.messages = this.memoryManager.loadHistory(); // Persistent context window
403
+ this.stepsCompleted = 0;
404
+ this.consecutiveCommands = 0;
405
+ this.circuitBreakerUnlocked = false;
406
+ this.stopRequested = false;
407
+ this.pendingApprovals = new Map(); // Maps toolCallId -> resolve function
408
+ this.waitForDecision = async () => null;
409
+ this._decisionAnswers = new Map();
410
+ this._decisionRequirement = { required: false, kind: 'architecture', reason: '' };
411
+ this._decisionResolved = true;
412
+ this._implementationPlan = [];
413
+ this._implementationPlanRequired = false;
414
+ // A delegated subagent can tighten these two ceilings. They are applied
415
+ // after every config refresh so run() cannot accidentally replace a
416
+ // worker's declared bounds with the parent tier defaults.
417
+ this.maxStepsCeiling = null;
418
+ this.taskTokenLimit = null;
419
+
420
+ // Limits based on tier/budget & emulator fast bypass
421
+ this.updateTierLimits();
422
+
423
+ this.consecutiveThinkingSteps = 0;
424
+ this.consecutiveBlockedActions = 0; // V8 Transcendence: Circuit Breaker
425
+
426
+ // Sovereign Progressive Disclosure: which capability packs have entered the
427
+ // context window for this task. Nothing is disabled — see src/toolPacks.js.
428
+ this.unlockedPacks = new Set();
429
+ this.unlockedTools = new Set();
430
+ // sha256 of every large tool result seen this task -> the step that produced
431
+ // it. Lets a verbatim repeat collapse to a pointer instead of paying twice.
432
+ this._observationDigests = new Map();
433
+ // Unlock sequence drives append-only tool ordering, which is what keeps the
434
+ // prompt-cache prefix intact when a pack loads mid-task.
435
+ this.unlockOrder = [];
436
+ this.workspaceContext = null;
437
+ this.activeSubproject = null;
438
+ this.taskShape = null;
439
+ // Budget for the billed Tier 2 Cortex condensation pass.
440
+ this._cortexPassesUsed = 0;
441
+ // Per-task memo for context that is constant for the whole task but used to
442
+ // be recomputed on every single step (cortex retrieval, skills index,
443
+ // design detection, workspace domain scan).
444
+ this.staticContext = null;
445
+ this.vfeTracker = new VFETracker();
446
+ this._lessonSimilarity = 0;
447
+ this._paradigmShiftPending = false;
448
+
449
+ // Completion guards fire at most once per task. Previously they were gated
450
+ // on consecutiveThinkingSteps, which resets on every tool call, so the
451
+ // agent could be blocked from finishing over and over until it burned the
452
+ // entire 300-step budget on a task that was already done.
453
+ this.gameGuardFired = false;
454
+ this.webGuardFired = false;
455
+ // P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
456
+ this.webArtifacts = new Set();
457
+ this.slopGateFired = false;
458
+ this.coldObserverGuardFired = false;
459
+
460
+ this.gameCascadeState = { active: true, currentStage: 1, stageHistory: [], verificationPassed: false };
461
+ this.gameToolStats = { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
462
+ this.webVerificationState = { screenshotTaken: false, browserActUsed: false }; // V8 Transcendence: Anti-Slop Guard
463
+
464
+ this.abortController = new AbortController();
465
+
466
+ // V5: Context compaction tracking
467
+ this._lastCompactionIndex = null;
468
+ // V5: Error recovery tracking (per tool call)
469
+ // V5: Error recovery tracking (per tool call)
470
+ this._toolRetryCount = new Map();
471
+ this.isInitialized = false;
472
+ this.taskTemperature = 0.1; // Default
473
+ // Set only on a delegated subagent loop; null means "the full catalogue".
474
+ this.toolScope = null;
475
+ }
476
+
477
+ /** True when this loop's own conversation scope has a standing approval. */
478
+ isAlwaysAllowed(toolName: string) {
479
+ return this.approvalScope.isAlwaysAllowed(toolName);
480
+ }
481
+
482
+ // V6: Adaptive Temperature based on task intent
483
+ determineTemperature(prompt: string) {
484
+ if (!prompt) return 0.1;
485
+ const lower = prompt.toLowerCase();
486
+
487
+ // Creative / Open-ended tasks get higher temp
488
+ if (lower.includes("brainstorm") || lower.includes("write a story") || lower.includes("creative") || lower.includes("poem") || lower.includes("novel") || lower.includes("screenplay")) {
489
+ return 0.5;
490
+ }
491
+ // Web Design / UI tasks get creative-code temp (Anti-Slop: warm enough for diversity, cool enough for valid code)
492
+ if (lower.includes("website") || lower.includes("landing page") || lower.includes("web app") || lower.includes("dashboard") || lower.includes("portfolio") || lower.includes("ui design") || lower.includes("homepage") || lower.includes("frontend")) {
493
+ return 0.4;
494
+ }
495
+ // Conversational / Explanatory tasks get medium temp
496
+ if (lower.includes("explain") || lower.includes("how does") || lower.includes("what is") || lower.includes("teach me")) {
497
+ return 0.3;
498
+ }
499
+ // Code / Technical / Precision tasks get low temp
500
+ return 0.1;
501
+ }
502
+
503
+ /**
504
+ * Load a capability pack into the context window, recording the sequence.
505
+ *
506
+ * Order matters for cost, not just bookkeeping: tool definitions sit at the
507
+ * front of the cached prefix, so appending is nearly free while reordering
508
+ * invalidates the cache for the tools, the system prompt and every message.
509
+ */
510
+ unlockPack(packName: string) {
511
+ if (!packName || this.unlockedPacks.has(packName)) return false;
512
+ this.unlockedPacks.add(packName);
513
+ this.unlockOrder.push(packName);
514
+ return true;
515
+ }
516
+
517
+ /**
518
+ * Build the parts of the system context that are constant for a whole task.
519
+ * Called once per task rather than once per step.
520
+ */
521
+ async buildStaticContext() {
522
+ let lessonsLearned = '';
523
+ this._lessonSimilarity = 0;
524
+ if (this.currentTaskPrompt) {
525
+ try {
526
+ const matches = await cortexDb.search(this.currentTaskPrompt, 2);
527
+ if (matches.length > 0) {
528
+ lessonsLearned = `\n\n🧠 DIGITAL BRAIN (LESSONS LEARNED FROM PAST MISTAKES):\n` + matches.map((m: any) => `- ${m.text}`).join('\n');
529
+ this._lessonSimilarity = matches[0].similarity || 0;
530
+ this.debugLog(`cortex search hit: ${(this._lessonSimilarity * 100).toFixed(0)}% similarity`);
531
+ }
532
+ } catch (e: any) {
533
+ this.debugLog(`cortex retrieval failed: ${e.message}`);
534
+ }
535
+ }
536
+
537
+ // Anti-Slop: Design Context Awareness (what design system is already installed)
538
+ let designContext = '';
539
+ try {
540
+ const detectedDesign = await this.perception.detectDesignContext(process.cwd());
541
+ if (detectedDesign && detectedDesign.length > 0) {
542
+ designContext = `\nDETECTED DESIGN SYSTEM IN WORKSPACE: ${detectedDesign.join(', ')} — USE THIS. Do NOT install a conflicting system.`;
543
+ }
544
+ } catch (e: any) {}
545
+
546
+ // Anti-Slop: Creative Pattern Memory (prevents repeating the same design approach)
547
+ let antiRepeatDirective = '';
548
+ if (this.currentTaskPrompt && isWebIntent(this.currentTaskPrompt)) {
549
+ try {
550
+ const recentPatterns = await cortexDb.getRecentCreativePatterns(5);
551
+ if (recentPatterns.length > 0) {
552
+ antiRepeatDirective = `\n\n🎨 CREATIVE DIVERSITY (DO NOT REPEAT RECENT PATTERNS):\n` +
553
+ recentPatterns.map((p: any) => `- ${p}`).join('\n') +
554
+ `\nChoose a DIFFERENT design approach, color palette, and font combination than the above.`;
555
+ }
556
+ } catch (e: any) {}
557
+ }
558
+
559
+ // Universal skills awareness
560
+ let universalSkillsContext = '';
561
+ try {
562
+ const detectedDomains = detectWorkspaceDomains(process.cwd());
563
+ if (detectedDomains.length > 0) {
564
+ this.debugLog(`detected workspace domains: ${detectedDomains.join(', ')}`);
565
+ for (const domain of detectedDomains) {
566
+ ensureSkillRepo(domain);
567
+ }
568
+ universalSkillsContext = getSkillDomainHeader(detectedDomains);
569
+ }
570
+ } catch (e: any) {
571
+ this.debugLog(`skill domain detection failed: ${e.message}`);
572
+ }
573
+
574
+ // Plan cache lookup. Deterministic and local: no model call, no network.
575
+ // Goes in the per-task STATIC block, which is byte-identical every step and
576
+ // already carries a cache anchor, so a hit costs its own tokens exactly
577
+ // once per task rather than once per step.
578
+ let planHint = '';
579
+ try {
580
+ planHint = renderPlanHint(this._planMatch);
581
+ } catch (e: any) {
582
+ this.debugLog(`plan cache hint skipped: ${e.message}`);
583
+ }
584
+
585
+ return { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint };
586
+ }
587
+
588
+
589
+ rearmAbortController() {
590
+ this.abortController = new AbortController();
591
+ }
592
+
593
+ abort() {
594
+ this.stopRequested = true;
595
+ if (this.abortController) {
596
+ this.abortController.abort();
597
+ }
598
+ }
599
+
600
+ setAutonomyMode(mode: string) {
601
+ const normalized = String(mode || '').trim().toUpperCase();
602
+ if (!['A', 'B', 'C'].includes(normalized)) {
603
+ throw new Error('autonomy mode must be A, B, or C');
604
+ }
605
+ this.autonomyOverride = normalized;
606
+ this.config.autonomyMode = normalized;
607
+ }
608
+
609
+ /**
610
+ * A provider for UTILITY work — condensation, classification, filtering.
611
+ *
612
+ * Same provider, cheaper model. Condensing a dropped transcript is mechanical
613
+ * text work whose output the machine consumes, and paying a flagship rate for
614
+ * it is the clearest waste in the loop: on Anthropic it is $5/$25 against
615
+ * Haiku's $1/$5. Built lazily and cached, because most tasks never compact at
616
+ * all and constructing a second provider they will not use is its own cost.
617
+ *
618
+ * Falls back to the reasoning provider whenever the router declines — an
619
+ * unknown provider, a config override, or a route that would change the
620
+ * training-data posture. Utility work still has to happen.
621
+ *
622
+ * @returns {any}
623
+ */
624
+ utilityProvider() {
625
+ if (this._utilityLlm) return this._utilityLlm;
626
+ try {
627
+ const { config, route } = routedConfig(this.config, 'condense');
628
+ if (!route.routed) {
629
+ this._utilityLlm = this.llm;
630
+ this.debugLog(`utility route: ${route.reason}`);
631
+ } else {
632
+ this._utilityLlm = createProvider(config);
633
+ this.debugLog(`utility route: ${this.config.model} -> ${route.model}`);
634
+ }
635
+ } catch (e: any) {
636
+ this._utilityLlm = this.llm; // a routing failure must never stop a task
637
+ this.debugLog(`utility route failed, staying on the reasoning model: ${e.message}`);
638
+ }
639
+ return this._utilityLlm;
640
+ }
641
+
642
+ initializeProvider() {
643
+ if (!this.config?.provider) return null;
644
+ return createProvider(this.config);
645
+ }
646
+
647
+ /**
648
+ * Tools that only observe. Nothing here writes to disk, mutates process
649
+ * state, spends money, or can require approval — which is what makes running
650
+ * several of them at once safe and order-independent.
651
+ *
652
+ * Deliberately an allowlist. A denylist would silently start prefetching
653
+ * every tool added in the future, including destructive ones.
654
+ */
655
+ static READ_ONLY_TOOLS = new Set([
656
+ 'fs_read', 'fs_list', 'fs_find', 'fs_search',
657
+ 'code_search_ast', 'code_list_symbols', 'code_search_ripgrep', 'codebase_search',
658
+ 'web_fetch', 'web_search', 'pdf_read', 'fs_read_skill',
659
+ 'check_system_specs', 'process_list', 'view_image'
660
+ ]);
661
+
662
+ /** How many reads may be in flight at once. */
663
+ static PREFETCH_CONCURRENCY = 6;
664
+
665
+ /**
666
+ * Start the read-only calls of one assistant turn concurrently.
667
+ *
668
+ * @returns {Map<string, Promise<object|null>>} keyed by tool_call_id. A entry
669
+ * resolves to the tool result, or to null when the call was not eligible,
670
+ * was denied by the sandbox, or threw — in every one of those cases the
671
+ * serial loop executes it normally and keeps its own error handling.
672
+ */
673
+ prefetchReadOnlyCalls(toolCalls: any) {
674
+ const prefetched = new Map();
675
+ if (!Array.isArray(toolCalls) || toolCalls.length < 2) return prefetched;
676
+
677
+ // Mode A promises approval before every tool, including reads. Starting a
678
+ // read here would execute it before the serial approval and hook gates.
679
+ if ((this.config.autonomyMode || 'C') === 'A') return prefetched;
680
+
681
+ const eligible: any[] = [];
682
+ for (const toolCall of toolCalls) {
683
+ const functionName = canonicalToolName(toolCall.function.name);
684
+ if (!AgentLoop.READ_ONLY_TOOLS.has(functionName)) continue;
685
+ // Prefetch begins before the serial dispatch path. If this tool has a
686
+ // PreToolUse hook, running it here would create a temporal pre-trust
687
+ // window where the read happens before the hook can deny it.
688
+ if (hasMatchingHook(this.config.hooks, 'PreToolUse', functionName)) continue;
689
+
690
+ let args;
691
+ try {
692
+ args = typeof toolCall.function.arguments === 'string'
693
+ ? JSON.parse(toolCall.function.arguments || '{}')
694
+ : (toolCall.function.arguments || {});
695
+ } catch (e: any) {
696
+ continue; // malformed arguments are the serial loop's business
697
+ }
698
+
699
+ // The same guard the serial path applies, applied before anything runs.
700
+ let validation;
701
+ try {
702
+ validation = this.sandbox.validate(functionName, args);
703
+ } catch (e: any) {
704
+ continue;
705
+ }
706
+ if (!validation || validation.allowed === false || validation.risk !== 'safe') continue;
707
+
708
+ const tool = resolveTool(functionName);
709
+ if (!tool || typeof tool.execute !== 'function') continue;
710
+
711
+ eligible.push({ toolCall, functionName, args, tool });
712
+ }
713
+
714
+ if (eligible.length < 2) return prefetched;
715
+
716
+ // A bounded worker pool rather than a bare Promise.all: a model can emit a
717
+ // large batch, and opening fifty file handles or fifty sockets at once
718
+ // would trade one problem for another.
719
+ let cursor = 0;
720
+ const resolvers = new Map();
721
+ for (const item of eligible) {
722
+ prefetched.set(item.toolCall.id, new Promise(resolve => resolvers.set(item.toolCall.id, resolve)));
723
+ }
724
+
725
+ const worker = async () => {
726
+ while (cursor < eligible.length) {
727
+ const item = eligible[cursor++];
728
+ const resolve = resolvers.get(item.toolCall.id);
729
+ if (this.stopRequested || this.abortController.signal.aborted) { resolve(null); continue; }
730
+ try {
731
+ resolve(await item.tool.execute(item.args, {
732
+ signal: this.abortController.signal,
733
+ parentLoop: this,
734
+ ...this.sandbox
735
+ }));
736
+ } catch (e: any) {
737
+ resolve(null); // let the serial path fail it, with its own retries
738
+ }
739
+ }
740
+ };
741
+
742
+ const lanes = Math.min(AgentLoop.PREFETCH_CONCURRENCY, eligible.length);
743
+ for (let i = 0; i < lanes; i++) worker();
744
+
745
+ return prefetched;
746
+ }
747
+
748
+ emitEvent(messageObj: AgentLoopEvent) {
749
+ if (this.eventSink && this.eventSink.readyState === 1) {
750
+ this.eventSink.send(JSON.stringify({ taskId: this.taskId, ...messageObj }));
751
+ }
752
+ }
753
+
754
+
755
+ // WHAT BELONGS HERE: things the user would want to know even though they did
756
+ // not ask — a file was written on their behalf, a limit was reached. Not
757
+ // internal telemetry. Converting the old console.log calls to notices fixed
758
+ // the display corruption but kept the noise, and three lines of task-shape and
759
+ // tier sizing after every invocation is exactly the clutter neither reference
760
+ // shows. Diagnostics go to debugLog().
761
+ notice(message: unknown, tone: string = 'muted') {
762
+ this.emitEvent({ type: 'notice', tone, message: String(message) });
763
+ }
764
+
765
+ /**
766
+ * Diagnostics, off by default.
767
+ *
768
+ * These are for whoever is debugging Causyne, not for the person using it.
769
+ * Printed unconditionally they are both noise and a second uncontrolled writer
770
+ * to a terminal the prompt is repainting. Behind CAUSYNE_DEBUG they cost
771
+ * nothing in a normal session, and stderr keeps them out of a piped stdout.
772
+ */
773
+ debugLog(message: string) {
774
+ if (process.env.CAUSYNE_DEBUG !== '1') return;
775
+ process.stderr.write(`[causyne] ${message}\n`);
776
+ }
777
+
778
+
779
+ handleApprovalResponse(toolCallId: string, approved: boolean) {
780
+ if (this.pendingApprovals.has(toolCallId)) {
781
+ const resolve = this.pendingApprovals.get(toolCallId);
782
+ resolve(approved);
783
+ this.pendingApprovals.delete(toolCallId);
784
+ }
785
+ }
786
+
787
+ updateImplementationPlan(update: any) {
788
+ this._implementationPlan = update.plan.map((item: any) => ({ ...item }));
789
+ this.emitEvent({
790
+ type: 'agent_plan',
791
+ explanation: update.explanation || '',
792
+ plan: this._implementationPlan.map((item: any) => ({ status: item.status, text: item.step, id: item.id }))
793
+ });
794
+ auditLog.log({
795
+ event: 'implementation_plan_updated', taskId: this.taskId,
796
+ steps: this._implementationPlan.length,
797
+ completed: this._implementationPlan.filter((item: any) => item.status === 'completed').length
798
+ });
799
+ }
800
+
801
+ async requestDecision(request: any) {
802
+ const fingerprint = createHash('sha256')
803
+ .update(JSON.stringify({ kind: request.kind, question: request.question, options: request.options.map((option: any) => option.id) }))
804
+ .digest('hex');
805
+ const remembered = this._decisionAnswers.get(fingerprint);
806
+ if (remembered) return remembered;
807
+
808
+ this.emitEvent({ type: 'decision_request', request });
809
+ auditLog.log({ event: 'decision_requested', taskId: this.taskId, kind: request.kind, optionCount: request.options.length });
810
+ const answer = await this.waitForDecision(request);
811
+ if (!answer || typeof answer.label !== 'string' || !answer.label.trim()) {
812
+ this.emitEvent({ type: 'decision_result', request, answer: null });
813
+ return null;
814
+ }
815
+ const normalized = {
816
+ requestId: request.id,
817
+ optionId: typeof answer.optionId === 'string' ? answer.optionId : null,
818
+ label: answer.label.trim(),
819
+ custom: answer.custom === true
820
+ };
821
+ this._decisionAnswers.set(fingerprint, normalized);
822
+ if (request.kind === 'architecture') this._decisionResolved = true;
823
+ this.emitEvent({ type: 'decision_result', request, answer: normalized });
824
+ auditLog.log({ event: 'decision_answered', taskId: this.taskId, kind: request.kind, custom: normalized.custom });
825
+ return normalized;
826
+ }
827
+
828
+ mutationCheckpoint(functionName: string, args: any = {}) {
829
+ if (!isMutatingToolCall(functionName, args)) return null;
830
+ if (this._decisionRequirement.required && !this._decisionResolved) {
831
+ return 'ARCHITECTURE_DECISION_REQUIRED: Before changing the system, call request_decision with kind "architecture", 2-4 concrete options, their consequences, and a clear reason. Do not ask about routine details; this checkpoint exists because the current request crosses a durable architecture boundary.';
832
+ }
833
+ if (this._implementationPlanRequired && this._implementationPlan.length === 0) {
834
+ return 'IMPLEMENTATION_PLAN_REQUIRED: Call update_plan with atomic, verifiable steps and exactly one in_progress step before mutating this complex task.';
835
+ }
836
+ return null;
837
+ }
838
+
839
+ updateTierLimits() {
840
+ this.config = loadConfig();
841
+ if (this.autonomyOverride) this.config.autonomyMode = this.autonomyOverride;
842
+ if (typeof this.initializeProvider === 'function') {
843
+ this.llm = this.initializeProvider();
844
+ this._utilityLlm = null; // the route is derived from the model; re-derive it
845
+ }
846
+ if (this.tokenTracker) {
847
+ this.tokenTracker.config = this.config;
848
+ this.tokenTracker.budget = this.config.tokenBudget || { enabled: false };
849
+ }
850
+
851
+ // verified entitlement). Developer emulator mode is a hardened, secret-gated
852
+ // override for local development on a Fast-tier emulator — see devMode.js.
853
+ const devMode = isDevEmulator(this.config);
854
+ this.activeTier = devMode ? 'super_max' : (this.config.tier || 'premium');
855
+ if (this.config.maxStepsPerTask) {
856
+ this.maxSteps = this.config.maxStepsPerTask;
857
+ } else if (this.activeTier === 'super_max') {
858
+ this.maxSteps = 600;
859
+ } else if (this.activeTier === 'max') {
860
+ this.maxSteps = 400;
861
+ } else {
862
+ this.maxSteps = 300;
863
+ }
864
+ if (Number.isInteger(this.maxStepsCeiling) && this.maxStepsCeiling > 0) {
865
+ this.maxSteps = Math.min(this.maxSteps, this.maxStepsCeiling);
866
+ }
867
+ if (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0 && this.tokenTracker) {
868
+ this.tokenTracker.budget = {
869
+ ...this.tokenTracker.budget,
870
+ enabled: true,
871
+ hardStop: true,
872
+ maxTokensPerTask: this.taskTokenLimit
873
+ };
874
+ }
875
+ this.maxCircuitBreaker = this.maxSteps;
876
+ }
877
+
878
+ async run() {
879
+ this.stopRequested = false;
880
+ // A task that was stopped must not poison the next one — see
881
+ // rearmAbortController(). This has to happen before any tool can run.
882
+ this.rearmAbortController();
883
+ // Refresh tier limits on every task run
884
+ this.updateTierLimits();
885
+ if (!this.llm) {
886
+ throw new Error("API Key Required. Causyne is a 100% Sovereign BYOK Engine. Please configure your API Provider and Key in Settings.");
887
+ }
888
+
889
+ // 1. PERCEIVE — runs once per task so the agent starts with real workspace
890
+ // awareness instead of burning steps rediscovering it. The result used to be
891
+ // assigned to a local variable and thrown away.
892
+ auditLog.log({ event: 'task_start', taskId: this.taskId, request: this.userPrompt });
893
+ this.workspaceRoot = process.cwd();
894
+ coldObserver.beginTask(this.taskId);
895
+ this.emitEvent({ type: 'status', message: 'Analyzing workspace...' });
896
+
897
+ // P2: open the undo group for this task. This snapshots the CONVERSATION as
898
+ // well as the workspace tree, because restoring files while chat_history
899
+ // still claims the edits happened leaves the agent believing in a disk state
900
+ // that no longer exists. Fail-open — never blocks the task.
901
+ await beginCheckpointTask({
902
+ taskId: this.taskId,
903
+ prompt: this.userPrompt,
904
+ // The working directory FIRST, always.
905
+ //
906
+ // This passed sandbox.workspacePaths, which is the broad default SCOPE —
907
+ // the places the agent is permitted to touch, not the place it is working.
908
+ // beginTask() snapshots the first three, so on a default install it
909
+ // captured /Users/Shared and /home (5.6 MB of files nobody was editing)
910
+ // and never captured the project the user was actually in. Permission and
911
+ // location are different questions; undo needs the location.
912
+ // beginTask() de-duplicates and takes the first three.
913
+ // The PROJECT, not the process's working directory.
914
+ //
915
+
916
+ // started inside a project. Started from the home directory — which is
917
+ // simply what happens when someone opens a terminal and types the command
918
+ // — cwd is $HOME, the snapshot blew past MAX_TREE_FILES and was recorded
919
+ // as `too_many_files`, and the permission-scope fallbacks then captured
920
+ // /Users/Shared and /home: 5.6 MB of files nobody has ever edited. Every
921
+ // task produced a checkpoint containing nothing worth restoring, which is
922
+ // why undo appeared to do nothing no matter where it was invoked.
923
+ //
924
+ // resolveProjectRoot walks up for a real project marker and refuses to
925
+ // return $HOME or a system root, so the checkpoint covers the code being
926
+ // worked on or honestly covers nothing at all.
927
+ workspaceRoots: [
928
+ resolveProjectRoot(process.cwd()),
929
+ process.cwd(),
930
+ ...(this.sandbox.grantAllAccess ? [] : (this.sandbox.workspacePaths || []))
931
+ ].filter(Boolean)
932
+ });
933
+
934
+ try {
935
+ this.workspaceContext = await this.perception.buildContext(process.cwd());
936
+ } catch (perceptionError: any) {
937
+ this.debugLog(`workspace scan failed: ${perceptionError.message}`);
938
+ this.workspaceContext = null;
939
+ }
940
+
941
+ // 2. ANALYSE TASK SHAPE & PRE-WARM CAPABILITY PACKS.
942
+ // A game request gets the full game toolset from step one with no discovery
943
+ // round trip, while a "rename my files" request never pays the 7,282 tokens
944
+ // those 21 schemas cost. The shape analysis additionally tells the model the
945
+ // ORDER to work in, which saves whole exploratory steps.
946
+ this.gameGuardFired = false;
947
+ this.webGuardFired = false;
948
+ this.webArtifacts = new Set();
949
+ this.slopGateFired = false;
950
+ this.coldObserverGuardFired = false;
951
+ this.staticContext = null;
952
+ // Plan cache: the procedure THIS task follows, and the template (if any)
953
+ // that was offered to it. Both reset per task — a plan is a property of one
954
+ // request, not of the session.
955
+ this._planSteps = [];
956
+ this._offeredPlanId = null;
957
+ this._planSimilarity = 0;
958
+ this._planMatch = null;
959
+ this._lessonSimilarity = 0;
960
+ this._lastToolResult = null;
961
+ this._paradigmShiftPending = false;
962
+ this._implementationPlan = [];
963
+ this._decisionAnswers = new Map();
964
+ this._decisionRequirement = assessDecisionRequirement(this.userPrompt || '');
965
+ this._decisionResolved = !this._decisionRequirement.required;
966
+ this._implementationPlanRequired = false;
967
+ if (this.vfeTracker) this.vfeTracker.reset();
968
+
969
+ if (this.userPrompt) {
970
+ this.taskShape = analyzeTask(this.userPrompt, this.workspaceContext);
971
+ this._implementationPlanRequired = requiresImplementationPlan(
972
+ this.userPrompt,
973
+ this.taskShape?.archetype || '',
974
+ this.taskShape?.confidence || ''
975
+ );
976
+ // request_decision is comparatively large and most tasks never need it.
977
+ // On providers without server-side schema deferral, expose it from the
978
+ // first model call only when the deterministic task policy found an
979
+ // unresolved durable choice. This keeps the resident prompt within its
980
+ // measured budget without making the checkpoint undiscoverable.
981
+ if (this._decisionRequirement.required) this.unlockedTools.add('request_decision');
982
+
983
+ // Scored routing, with the regex router as a safety net so a pack can
984
+ // never be missed just because it scored below threshold.
985
+ const scored = packsFromShape(this.taskShape);
986
+ const fallback = routePacks(this.userPrompt, this.workspaceContext);
987
+ for (const pack of [...scored, ...fallback]) {
988
+ this.unlockPack(pack);
989
+ }
990
+
991
+ // Reuse a known route before the first model call. Exact keyword-set
992
+ // matches are always eligible; fuzzy reuse requires at least medium task
993
+ // classification confidence because APC's threshold study shows that
994
+ // aggressive fuzzy hits trade accuracy for speed.
995
+ try {
996
+ this._planMatch = lookupPlan({
997
+ prompt: this.userPrompt,
998
+ archetype: this.taskShape ? this.taskShape.archetype : '',
999
+ allowFuzzy: this.taskShape?.confidence !== 'low'
1000
+ });
1001
+ if (this._planMatch) {
1002
+ this._offeredPlanId = this._planMatch.template.id;
1003
+ this._planSimilarity = this._planMatch.similarity;
1004
+ for (const step of this._planMatch.template.steps || []) {
1005
+ if (!step.ok || !resolveTool(step.tool)) continue;
1006
+ this.unlockedTools.add(step.tool);
1007
+ const pack = packForTool(step.tool);
1008
+ if (pack) this.unlockPack(pack);
1009
+ }
1010
+ this.debugLog(
1011
+ `plan cache ${this._planMatch.matchType || 'fuzzy'} hit `
1012
+ + `${(this._planMatch.similarity * 100).toFixed(0)}% `
1013
+ + `(${this._planMatch.template.steps.length} steps, `
1014
+ + `${this._planMatch.telemetry?.lookupMs?.toFixed(2) || '0.00'} ms)`
1015
+ );
1016
+ }
1017
+ } catch (e: any) {
1018
+ this.debugLog(`plan cache lookup skipped: ${e.message}`);
1019
+ }
1020
+
1021
+ this.debugLog(`task shape: ${this.taskShape.archetype} (${this.taskShape.confidence} confidence)`);
1022
+ }
1023
+
1024
+ if (!this.isInitialized) {
1025
+ const activeTier = this.activeTier;
1026
+ const charPoolLimit = resolveCharPool(activeTier, this.config.maxCharPool);
1027
+ const devTag = isDevEmulator(this.config) ? ' (dev emulator)' : '';
1028
+ // Was a console.log carrying a hardcoded \x1b[1m\x1b[36m, which ignored
1029
+ // NO_COLOR outright. The renderer paints this through the theme.
1030
+ // Internal sizing, and already implied by the header's `tier` field.
1031
+ this.debugLog(
1032
+ `tier ${activeTier}${devTag} | ${this.maxSteps} steps | ${charPoolLimit} char context`
1033
+ );
1034
+ this.isInitialized = true;
1035
+ }
1036
+
1037
+ this.taskTemperature = this.determineTemperature(this.userPrompt);
1038
+ if (this.unlockedPacks.size > 0) {
1039
+ this.debugLog(`capability packs pre-warmed: ${[...this.unlockedPacks].join(', ')}`);
1040
+ }
1041
+
1042
+ if (this.userPrompt) {
1043
+ // 1b. RESOLVE @ MENTIONS FOR REFERENCED FILES, DIRECTORIES & SUBPROJECTS
1044
+ try {
1045
+ const subprojects = this.workspaceContext?.subprojects || [];
1046
+ const mentionResult = await resolveMentionedContext(this.userPrompt, {
1047
+ cwd: process.cwd(),
1048
+ subprojects
1049
+ });
1050
+
1051
+ if (mentionResult.detectedSubproject) {
1052
+ this.activeSubproject = mentionResult.detectedSubproject;
1053
+ this.notice(`Focused on subproject '${mentionResult.detectedSubproject}'`);
1054
+ } else if (subprojects.length > 0) {
1055
+ const lowerPrompt = this.userPrompt.toLowerCase();
1056
+ for (const sp of subprojects) {
1057
+ if (lowerPrompt.includes(sp.toLowerCase())) {
1058
+ this.activeSubproject = sp;
1059
+ this.notice(`Focused on subproject '${sp}'`);
1060
+ break;
1061
+ }
1062
+ }
1063
+ }
1064
+
1065
+ if (mentionResult.referencedContext) {
1066
+ this.userPrompt += mentionResult.referencedContext;
1067
+ this.notice(`Loaded ${mentionResult.mentions.length} referenced @ mention(s) into context`);
1068
+ }
1069
+ } catch (mentionErr: any) {
1070
+ this.debugLog(`mention resolution error: ${mentionErr.message}`);
1071
+ }
1072
+
1073
+ this.currentTaskPrompt = this.userPrompt; // Save for notification later
1074
+
1075
+ // V5: Multimodal Attachments Support
1076
+ if (this.attachments && this.attachments.length > 0) {
1077
+ let contentArray: any[] = [{ type: 'text', text: this.userPrompt }];
1078
+
1079
+ for (const att of this.attachments) {
1080
+ if (att.type === 'image') {
1081
+ contentArray.push({
1082
+ type: 'image_url',
1083
+ image_url: { url: `data:${att.mimeType};base64,${att.base64}` }
1084
+ });
1085
+ } else if (att.type === 'audio') {
1086
+
1087
+ // be hardcoded to 'mp3' while the recorder produced AAC/m4a, so every
1088
+ // clip was mislabelled and the provider failed on decode. att.mimeType
1089
+ // has always been on the wire; it is now actually read.
1090
+ const audioFormat = audioFormatForMimeType(att.mimeType);
1091
+
1092
+
1093
+ // cap during reassembly; this is the final, vendor-specific ceiling,
1094
+ // reported as a Causyne message rather than an opaque upstream 400.
1095
+ const audioBytes = Math.round((att.base64?.length || 0) * 0.75);
1096
+ const byteCeiling = this.llm?.maxAudioBytes;
1097
+ if (byteCeiling && audioBytes > byteCeiling) {
1098
+ contentArray[0].text +=
1099
+ `\n\n[SYSTEM NOTIFICATION: The user's voice clip (${Math.round(audioBytes / 1024)} KB) exceeds the ${Math.round(byteCeiling / 1024)} KB limit of the selected model and was not attached. Ask the user to record a shorter clip.]`;
1100
+ this.notice(`voice clip dropped: ${audioBytes} B over the ${byteCeiling} B provider limit`);
1101
+ } else if (!this.llm?.supportsAudio) {
1102
+
1103
+ // model that cannot hear — a stale capability advertisement. Say so
1104
+ // in-band; prepareMessages would otherwise strip it further down
1105
+ // and the user would never learn why nothing was heard.
1106
+ // Before giving up: the provider may ship a dedicated
1107
+ // speech-to-text model on this same key. Meta does, and it is the
1108
+ // whole answer to Muse Spark 1.3 being both the recommended model
1109
+ // and the one that cannot hear.
1110
+ let transcript = null;
1111
+ let transcribeError = null;
1112
+ if (typeof this.llm?.transcribeAudio === 'function') {
1113
+ try {
1114
+ transcript = await this.llm.transcribeAudio(att.base64, att.mimeType);
1115
+ } catch (e: any) {
1116
+ transcribeError = e.message;
1117
+ }
1118
+ }
1119
+
1120
+ if (transcript) {
1121
+ contentArray[0].text +=
1122
+ `\n\n[VOICE TRANSCRIPT: The user spoke rather than typed. The selected model cannot take audio directly, so the clip was transcribed by this provider's speech-to-text model. Treat the following as the user's own words: "${transcript}"]`;
1123
+ this.notice(`voice clip transcribed (${transcript.length} chars) — the chat model cannot hear`, 'accent');
1124
+ } else {
1125
+ // Name the way out when the provider knows one. A refusal the
1126
+ // user cannot act on is worse than the limitation it reports.
1127
+ const alternative = typeof this.llm?.audioAlternative === 'function'
1128
+ ? this.llm.audioAlternative()
1129
+ : null;
1130
+ const route = alternative
1131
+ ? `Ask them to switch to ${alternative}, which accepts audio on this same provider and key, or to use the on-device transcription instead.`
1132
+ : 'Ask them to switch to an audio-capable model, or to use the on-device transcription instead.';
1133
+ contentArray[0].text +=
1134
+ `\n\n[SYSTEM NOTIFICATION: The user sent a voice recording but the selected model cannot process audio. ${route}]`;
1135
+ this.notice(transcribeError
1136
+ ? `voice clip dropped: transcription failed — ${transcribeError}`
1137
+ : alternative
1138
+ ? `voice clip dropped: ${this.config.model} cannot hear — ${alternative} can`
1139
+ : 'voice clip dropped: selected model does not support audio input',
1140
+ transcribeError ? 'warn' : 'muted');
1141
+ }
1142
+ } else {
1143
+ contentArray.push({
1144
+ type: 'input_audio',
1145
+ input_audio: {
1146
+ data: att.base64,
1147
+ format: audioFormat
1148
+ }
1149
+ });
1150
+ }
1151
+ } else if (att.type === 'document') {
1152
+ const fs = await import('fs');
1153
+ const path = await import('path');
1154
+ // Ensure unique name to prevent overwriting
1155
+ const safeName = att.name.replace(/[^a-zA-Z0-9.\-_]/g, '_');
1156
+ const writePath = path.join(process.cwd(), safeName);
1157
+ fs.writeFileSync(writePath, Buffer.from(att.base64, 'base64'));
1158
+
1159
+ contentArray[0].text += `\n\n[SYSTEM NOTIFICATION: The user attached a document named '${safeName}'. It has been saved to your workspace at ./${safeName}. Please use your file reading tools to examine its contents.]`;
1160
+ this.notice(`saved attached document to ${writePath}`);
1161
+ }
1162
+ }
1163
+ this.messages.push({ role: 'user', content: contentArray });
1164
+ } else {
1165
+ this.messages.push({ role: 'user', content: this.userPrompt });
1166
+ }
1167
+
1168
+ this.userPrompt = null; // Clear so we don't push it again
1169
+ this.attachments = null; // Clear attachments
1170
+ }
1171
+
1172
+ this.stepsCompleted = 0;
1173
+ // Fresh per task. A digest from a previous task would point at a step
1174
+ // number the model can no longer see, which is worse than paying twice.
1175
+ this._observationDigests = new Map();
1176
+ this.consecutiveCommands = 0;
1177
+ this.circuitBreakerUnlocked = false;
1178
+ this.tokenTracker.resetTask();
1179
+
1180
+ // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
1181
+ while (!this.stopRequested) {
1182
+ if (this.stopRequested) {
1183
+ this.emitEvent({ type: 'error', message: 'Task killed by user.' });
1184
+ auditLog.log({ event: 'task_killed', taskId: this.taskId });
1185
+ break;
1186
+ }
1187
+ this.emitEvent({ type: 'status', message: 'Thinking...' });
1188
+
1189
+ try {
1190
+ // --- V8 MEMORY ARCHITECTURE: DECAY → WINDOW → REAL COMPACTION ---
1191
+ // The window is no longer only a view over an ever-growing array. Old
1192
+ // tool payloads decay into stubs, and anything amputated is physically
1193
+ // replaced by a summary, so memory, disk and CPU all stay bounded.
1194
+
1195
+ const activeTier = isDevEmulator(this.config) ? 'super_max' : (this.config.tier || 'premium');
1196
+ const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool);
1197
+
1198
+ // 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
1199
+ // Stage 2 (Snip >15K tokens / 60K chars) + Stage 1 (Budget Reduction >70%) +
1200
+ // Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
1201
+ const compaction = applyProgressiveCompaction(this.messages, MAX_CHAR_POOL, {
1202
+ budgetKeepRecent: this.config.keepRecentToolResults ?? 8,
1203
+ collapseKeepRecent: 2
1204
+ });
1205
+ if (compaction.totalReclaimed > 0) {
1206
+ this.debugLog(`progressive compaction reclaimed ${(compaction.totalReclaimed / 1024).toFixed(1)} KB [${compaction.stagesFired.join(', ')}]`);
1207
+ auditLog.log({
1208
+ event: 'context_compaction', taskId: this.taskId,
1209
+ kind: 'progressive', stages: compaction.stagesFired,
1210
+ reclaimedChars: compaction.totalReclaimed,
1211
+ finalChars: compaction.finalChars,
1212
+ limitChars: MAX_CHAR_POOL
1213
+ });
1214
+ }
1215
+
1216
+ const { window: slidingWindow, splitIndex } = buildWindow(this.messages, MAX_CHAR_POOL);
1217
+
1218
+ // What the context window actually holds right now.
1219
+ //
1220
+ // The footer's context meter was being fed `usedTokens` — the CUMULATIVE
1221
+ // token spend of the whole task — and divided by a CHARACTER pool. Two
1222
+ // unit errors compounding: after 16 steps it read 290,069 against
1223
+ // 120,000 and, because the meter clamped at 99, displayed "290K (99%)"
1224
+ // while the real window sat around a quarter full. A meter pinned at 99%
1225
+ // for most of a run answers no question at all.
1226
+ //
1227
+ // Measured, not extrapolated: this is the same array the request is
1228
+ // built from, one line after it is built.
1229
+ this._contextChars = measureMessages(slidingWindow);
1230
+ this._contextLimitChars = MAX_CHAR_POOL;
1231
+
1232
+ // Real compaction: physically collapse the amputated range so the array
1233
+ // stops growing. Index 0 (the Root Anchor / original user intent) is
1234
+ // never compacted away.
1235
+ if (splitIndex >= 1) {
1236
+ const dropped = this.messages.slice(1, splitIndex + 1);
1237
+ if (dropped.length > 0) {
1238
+ const compactSummary = buildStructuralSummary(dropped) || describeDroppedMessages(dropped);
1239
+ const removed = compactInPlace(this.messages, splitIndex, compactSummary);
1240
+ this._lastCompactionIndex = null;
1241
+ this.debugLog(`compacted ${removed} messages out of the live context`);
1242
+ auditLog.log({
1243
+ event: 'context_compaction', taskId: this.taskId,
1244
+ kind: 'summary', removedMessages: removed,
1245
+ retainedSummaryChars: compactSummary.length,
1246
+ limitChars: MAX_CHAR_POOL
1247
+ });
1248
+ this.notice(`Context compacted: ${removed} earlier messages condensed into a reviewable summary.`);
1249
+
1250
+ // V5 Cortex tiered condensation. Tier 1 (structural, free) always
1251
+ // runs so the Digital Brain keeps learning on every provider. Tier 2
1252
+ // (semantic, billed) is capped per task and fully tracked.
1253
+ condenseAndSave(dropped, this.utilityProvider(), this.tokenTracker, {
1254
+ enableLlmPass: this.config.enableCortexCondenser !== false,
1255
+ maxLlmPasses: this.config.maxCortexCondenserPasses ?? 3,
1256
+ passesUsed: this._cortexPassesUsed
1257
+ }).then((outcome: any) => {
1258
+ if (outcome.semantic) this._cortexPassesUsed++;
1259
+ }).catch(() => {});
1260
+ }
1261
+ }
1262
+
1263
+ // Resolve the active toolset before assembling the prompt: the task
1264
+ // brief only cites tools the model can actually see right now.
1265
+ // Providers with native schema deferral (Anthropic: `defer_loading` +
1266
+ // `tool_search_tool_regex`) keep the whole core in context for free —
1267
+ // the API holds the schemas server-side and expands them on demand,
1268
+ // with no discovery round trip. Every OTHER provider was serialising
1269
+ // all 24 core schemas into every request. There, ship the small resident
1270
+ // set and let `tool_search` — the same mechanism that already
1271
+ // unlocks packs — fetch the rest.
1272
+ const residentOnly = this.llm.supportsToolSearch?.() !== true;
1273
+ let dynamicTools = await getDynamicTools(this.config.autonomyMode, this.llm.supportsVision, {
1274
+ unlockedPacks: this.unlockedPacks,
1275
+ unlockedTools: this.unlockedTools,
1276
+ unlockOrder: this.unlockOrder,
1277
+ grantAllTools: this.config.grantAllTools === true,
1278
+ allowedTools: this.sandbox.allowedTools,
1279
+ deniedTools: this.config.deniedTools,
1280
+ residentOnly
1281
+ });
1282
+ // A delegated subagent runs with a declared toolScope. Enforcing it
1283
+ // here — the one place the catalogue is assembled — is what makes the
1284
+ // scope real; the previous implementation accepted the argument and
1285
+ // ignored it entirely (finding D-7).
1286
+ if (this.toolScope instanceof Set && this.toolScope.size > 0) {
1287
+ dynamicTools = dynamicTools.filter((t: any) => this.toolScope.has(t.name));
1288
+ }
1289
+ const dynamicToolNames = dynamicTools.map((t: any) => t.name);
1290
+
1291
+ // Dynamically inject the absolute latest System context
1292
+ const autonomyMode = this.config.autonomyMode || 'C';
1293
+ const allowedPaths = this.sandbox.grantAllAccess
1294
+ ? "/ (ALL ACCESS GRANTED - You can read/write anywhere EXCEPT system protected folders like /etc or /System)"
1295
+ : (this.sandbox.workspacePaths ? this.sandbox.workspacePaths.join(', ') : process.cwd());
1296
+ const providerPrompt = getProviderSpecificPrompt(this.config.provider);
1297
+ const memoryContext = getMemoryContextString();
1298
+
1299
+ // --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
1300
+ // Cortex retrieval, design detection, creative-pattern lookup and the
1301
+ // workspace domain scan are all constant for the duration of a task, but
1302
+ // used to run on every single iteration: a SQLite query, several
1303
+ // directory scans and a skills-index rebuild per step. They also churned
1304
+ // the prompt prefix whenever a result shifted, costing cache hits.
1305
+ if (!this.staticContext) {
1306
+ this.staticContext = await this.buildStaticContext();
1307
+ }
1308
+ const { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint } = this.staticContext;
1309
+
1310
+ // --- WORKSPACE AWARENESS ---
1311
+ // perception.buildContext() output used to be computed and discarded,
1312
+ // leaving the agent blind and forcing it to rediscover the project with
1313
+ // ls/cat on every task.
1314
+ let workspaceSummary = '';
1315
+ if (this.workspaceContext) {
1316
+ const ctx = this.workspaceContext;
1317
+ const facts = [
1318
+ ctx.cwd && `Working directory: ${ctx.cwd}`,
1319
+ this.activeSubproject && `Active project focus: ${this.activeSubproject}`,
1320
+ ctx.projectName && `Workspace project: ${ctx.projectName}`,
1321
+ ctx.os && `OS: ${ctx.os}`,
1322
+ ctx.framework && `Framework: ${ctx.framework}`,
1323
+ ctx.projectType && `Project type: ${ctx.projectType}`,
1324
+ ctx.packageManager && `Package manager: ${ctx.packageManager}`,
1325
+ ctx.gitBranch && `Git branch: ${ctx.gitBranch}`,
1326
+ ctx.gitStatus && `Git status: ${ctx.gitStatus}`,
1327
+ Array.isArray(ctx.subprojects) && ctx.subprojects.length > 0 && `Subprojects in workspace: ${ctx.subprojects.join(', ')}`,
1328
+ Array.isArray(ctx.keyFiles) && ctx.keyFiles.length > 0 && `Key files: ${ctx.keyFiles.slice(0, 25).join(', ')}`
1329
+ ].filter(Boolean);
1330
+ if (facts.length > 0) {
1331
+ workspaceSummary = `\n\n📂 WORKSPACE CONTEXT (already scanned for you — do NOT waste steps rediscovering this):\n${facts.join('\n')}`;
1332
+ }
1333
+ }
1334
+
1335
+ // --- PROMPT ASSEMBLY, ORDERED STABLE → VOLATILE ---
1336
+ // Every provider's prompt cache binds on an identical prefix. Anthropic
1337
+ // marks it explicitly with cache_control (up to 4 breakpoints); OpenAI,
1338
+ // DeepSeek and Gemini match the longest stable prefix automatically. So
1339
+ // each block that is constant within a task carries its own cache anchor,
1340
+ // and the ONLY bytes that can change between steps live in a single
1341
+ // volatile block kept dead last. Previously just [1] was anchored, so the
1342
+ // pack catalogue and the whole workspace/memory/skills context were
1343
+ // re-billed on every step even though they never changed mid-task.
1344
+ const activePlaybooks = [...this.unlockedPacks]
1345
+ .map(pack => PACK_PLAYBOOKS[pack])
1346
+ .filter(Boolean)
1347
+ .join('\n\n');
1348
+
1349
+ // The task brief turns "here are 28 tools" into "here is the order to
1350
+ // use them in", which is where whole exploratory steps get saved.
1351
+ const taskBrief = this.taskShape
1352
+ ? buildTaskBrief(this.taskShape, dynamicToolNames)
1353
+ : '';
1354
+
1355
+ // Uncertainty gate. Every input is already in hand — no sampling, no
1356
+ // second model, no network. Returns '' for a confident step, and that
1357
+ // empty string is the point: reflecting on every step is the waste the
1358
+ // gating literature exists to prevent.
1359
+ let uncertaintyDirective = '';
1360
+ let uncertaintyTemperatureDelta = 0;
1361
+ try {
1362
+ const lastAssistant = [...this.messages].reverse()
1363
+ .find((m) => m.role === 'assistant' && typeof m.content === 'string');
1364
+ const vfeStatus = this.vfeTracker ? this.vfeTracker.getStatus() : { isPlateau: false };
1365
+ const isVfePlateau = Boolean(this._paradigmShiftPending || vfeStatus.isPlateau);
1366
+
1367
+ const verdict = assessStep({
1368
+ consecutiveFailures: this.consecutiveFailures,
1369
+ lastResult: this._lastToolResult,
1370
+ recentTools: (this._planSteps || []).map((step: any) => step.tool),
1371
+ planSimilarity: this._planSimilarity,
1372
+ lessonSimilarity: this._lessonSimilarity,
1373
+ vfePlateau: isVfePlateau,
1374
+ assistantText: lastAssistant ? lastAssistant.content : ''
1375
+ });
1376
+ uncertaintyDirective = verdict.directive;
1377
+ uncertaintyTemperatureDelta = verdict.temperatureDelta || 0;
1378
+ if (isVfePlateau) {
1379
+ this._paradigmShiftPending = false;
1380
+ }
1381
+ if (verdict.directive) {
1382
+ this.debugLog(`uncertainty ${verdict.uncertainty.toFixed(2)} (${verdict.level}): ${verdict.signals.join(', ')}`);
1383
+ auditLog.log({
1384
+ event: 'uncertainty_gate', taskId: this.taskId, step: this.stepsCompleted,
1385
+ level: verdict.level, score: Number(verdict.uncertainty.toFixed(3)), signals: verdict.signals
1386
+ });
1387
+ }
1388
+ } catch (e: any) {
1389
+ this.debugLog(`uncertainty gate skipped: ${e.message}`);
1390
+ }
1391
+
1392
+ const systemMessages = [
1393
+ // [1] stable for the entire task — the primary cache anchor.
1394
+ { role: 'system', content: SYSTEM_PROMPT, cacheAnchor: true },
1395
+ // [2] changes only when a capability pack unlocks (append-only), so it
1396
+ // is stable within a task and gets its own breakpoint.
1397
+ {
1398
+ role: 'system',
1399
+ content: `${taskBrief ? taskBrief + '\n\n' : ''}${getPackCatalogue(this.unlockedPacks)}${activePlaybooks ? '\n\n' + activePlaybooks : ''}`,
1400
+ cacheAnchor: true
1401
+ },
1402
+ // [3] per-task STATIC context — provider activation, detected design,
1403
+ // the one-time workspace scan, Cortex lessons, creative-diversity and
1404
+ // the skills index. All from this.staticContext (computed once) so it
1405
+ // is byte-identical every step; cached.
1406
+ {
1407
+ role: 'system',
1408
+ content: `${providerPrompt}${designContext}${workspaceSummary}${lessonsLearned}${planHint ? '\n' + planHint + '\n' : ''}${antiRepeatDirective}\n${universalSkillsContext}`,
1409
+ cacheAnchor: true
1410
+ },
1411
+ // [4] THE INVOKED SKILL, when the user named one.
1412
+ //
1413
+ // This is what makes `/skills <id> <instruction>` mean anything. Before
1414
+ // it existed the command printed the skill to the terminal and called
1415
+ // `continue` — the body never entered a request, the trailing
1416
+ // instruction was dropped on the floor, and no API call was made at
1417
+ // all. "Activating" a skill was a document viewer.
1418
+ //
1419
+ // Its own message rather than appended to [3]: [3] is the per-task
1420
+ // static anchor and appending here would invalidate that cache every
1421
+ // time a different skill is invoked. This one is stable for the task,
1422
+ // so it anchors too.
1423
+ ...(skillSystemMessage(this.activeSkill) || []),
1424
+ // [5] VOLATILE tail — the only bytes that may differ between steps:
1425
+ // autonomy/workspace paths (change via config) and persistent memory
1426
+ // (grows via memory_write mid-task). Kept LAST and UNcached so a change
1427
+ // here never invalidates the cached prefix in [1]-[3].
1428
+ {
1429
+ role: 'system',
1430
+ content: `${uncertaintyDirective ? uncertaintyDirective + '\n\n' : ''}${describeSession(this.taskId)}CURRENT AUTONOMY MODE: ${autonomyMode}\nALLOWED WORKSPACE PATHS: ${allowedPaths}\n(You MUST NOT write files outside these paths!)\n\n🧠 PERSISTENT MEMORY (FACTS LEARNED ABOUT THE USER):\n${memoryContext}`
1431
+ }
1432
+ ];
1433
+
1434
+ // Dev-only visibility into what fills each step's prompt. Set
1435
+ // CAUSYNE_TOKEN_DEBUG=1 to see the cached prefix ([1]-[3]) vs the volatile
1436
+ // tail ([4]) and confirm the cache is doing its job (pair it with the
1437
+ // "Prompt cache hit" line logged after the call).
1438
+ if (process.env.CAUSYNE_TOKEN_DEBUG === '1') {
1439
+ const chars = (m: any) => (typeof m?.content === 'string' ? m.content.length : JSON.stringify(m?.content || '').length);
1440
+ const windowChars = slidingWindow.reduce((sum: number, m: any) => sum + chars(m), 0);
1441
+ this.debugLog(
1442
+ `[token] sys1_base=${chars(systemMessages[0])} sys2_packs=${chars(systemMessages[1])} `
1443
+ + `sys3_static(cached)=${chars(systemMessages[2])} sys4_volatile=${chars(systemMessages[3])} `
1444
+ + `tools=${JSON.stringify(dynamicTools).length} window=${windowChars} (chars)`
1445
+ );
1446
+ }
1447
+
1448
+ // --- SOVEREIGN ROOT ANCHOR PRESERVATION ---
1449
+ // Ensure the original User Blueprint / Root Intent (`this.messages[0]`) is NEVER amputated
1450
+ // by the sliding window, regardless of how many steps or tool outputs accumulate.
1451
+ const rootAnchor = [];
1452
+ // The `slidingWindow.length > 0` guard is GONE on purpose. It meant an
1453
+ // empty window skipped the anchor too, and a request of nothing but
1454
+ // system blocks is a 400 on every provider. The window can no longer be
1455
+ // empty (contextManager.buildWindow), but the anchor must not depend on
1456
+ // that staying true.
1457
+ if (this.messages.length > 0 && slidingWindow[0] !== this.messages[0] && this.messages[0].role === 'user') {
1458
+ rootAnchor.push(this.messages[0]);
1459
+ }
1460
+
1461
+ // Final Assembly for the LLM. sanitizeSequences guarantees every
1462
+ // assistant tool_calls block is followed by matching tool results and
1463
+ // drops orphans that would otherwise 400 the provider.
1464
+ let prunedMessages = sanitizeSequences([...systemMessages, ...rootAnchor, ...slidingWindow]);
1465
+
1466
+ // THE INVARIANT, ENFORCED AT THE LAST POSSIBLE MOMENT.
1467
+ //
1468
+ // Every provider rejects a request whose messages carry no `user` or
1469
+ // `tool` turn. Two separate paths above can produce one — an empty
1470
+ // window, and sanitizeSequences dropping orphaned tool results — and
1471
+ // relying on either to be correct forever is how a 340,000-token run
1472
+ // died at step 13 with nothing to show for it. Checked here because
1473
+ // this is the last place the shape is still ours to fix.
1474
+ if (!prunedMessages.some((m: any) => m.role === 'user' || m.role === 'tool')) {
1475
+ const root = this.messages.find((m: any) => m.role === 'user');
1476
+ prunedMessages = [
1477
+ ...prunedMessages,
1478
+ root || { role: 'user', content: 'Continue the task from where you left off.' }
1479
+ ];
1480
+ this.debugLog('request had no user/tool message; re-anchored before sending');
1481
+ }
1482
+
1483
+ // BUDGET CEILING, CHECKED BEFORE SPENDING RATHER THAN AFTER.
1484
+ //
1485
+ // trackUsage() below stops the loop once the ceiling has ALREADY been
1486
+ // passed, so a run always overshot by one step — with ~9,000-token
1487
+ // steps a 299,000 ceiling landed near 308,000. Asking first is what
1488
+ // makes a ceiling mean the number the user typed.
1489
+ const affordability = this.tokenTracker.canAffordAnotherStep();
1490
+ if (!affordability.allowed) {
1491
+ this.emitEvent({ type: 'budget_warning', message: affordability.reason });
1492
+ this.emitEvent({ type: 'notice', message: 'Stopped before the token ceiling. Nothing was truncated mid-step.' });
1493
+ // A plan that was offered and did NOT carry the task through loses
1494
+ // rank, so a stale template stops being suggested forever. Only the
1495
+ // denominator moves here — recordPlan() is what awards a win.
1496
+ if (this._offeredPlanId) {
1497
+ try { recordMiss(this._offeredPlanId); } catch (e: any) { /* never block a stop */ }
1498
+ }
1499
+ auditLog.log({
1500
+ event: 'task_stopped_on_budget', taskId: this.taskId,
1501
+ used: affordability.used, limit: affordability.limit, projected: affordability.projected
1502
+ });
1503
+ break;
1504
+ }
1505
+
1506
+ // 2. PLAN (Call LLM). dynamicTools was resolved above so the task brief
1507
+ // could reference the tools actually in context.
1508
+ let hasStreamedChunk = false;
1509
+ let reasoningAccumulated = '';
1510
+ let thoughtStartedAt = 0;
1511
+
1512
+ this.emitEvent({ type: 'status', message: 'Thinking…' });
1513
+ this.emitEvent({ type: 'agent_activity', activity: 'Thinking…' });
1514
+
1515
+ const response = await this.llm.chat(prunedMessages, {
1516
+ tools: dynamicTools,
1517
+ // IARS couples escalation to a wider search. Bounded so a stuck task
1518
+ // cannot climb into randomness across repeated escalations.
1519
+ temperature: Math.min(1, this.taskTemperature + uncertaintyTemperatureDelta),
1520
+ coreToolCount: dynamicTools.filter((t: any) => isCoreTool(t.name)).length,
1521
+ signal: this.abortController?.signal,
1522
+ onReasoningChunk: (chunk: string) => {
1523
+ if (!thoughtStartedAt) thoughtStartedAt = Date.now();
1524
+ reasoningAccumulated += chunk;
1525
+ this.emitEvent({
1526
+ type: 'agent_reasoning',
1527
+ content: reasoningAccumulated,
1528
+ delta: chunk,
1529
+ streaming: true,
1530
+ elapsedMs: Date.now() - thoughtStartedAt
1531
+ });
1532
+ },
1533
+ onChunk: (_chunk: string) => {
1534
+ if (!hasStreamedChunk) {
1535
+ hasStreamedChunk = true;
1536
+ this.emitEvent({ type: 'status', message: 'Responding…' });
1537
+ this.emitEvent({ type: 'agent_activity', activity: 'Responding…' });
1538
+ }
1539
+ }
1540
+ });
1541
+
1542
+ // The call came back. Whatever went wrong before is no longer
1543
+ // consecutive — without this reset, one failure at step 2 and another
1544
+ // at step 200 would count toward the same ceiling and stop a task that
1545
+ // was working perfectly well.
1546
+ this.consecutiveFailures = 0;
1547
+ this.lastFailureType = null;
1548
+
1549
+ // Track tokens. usage carries cachedPromptTokens / cacheWriteTokens so
1550
+ // the cost estimate reflects the real cache-discounted bill.
1551
+ const tracking = await this.tokenTracker.trackUsage(
1552
+ response.usage.promptTokens,
1553
+ response.usage.completionTokens,
1554
+ (msg: string) => this.emitEvent({ type: 'budget_warning', message: msg }),
1555
+ response.usage
1556
+ );
1557
+
1558
+ const cachedTokens = response.usage.cachedPromptTokens || 0;
1559
+ if (cachedTokens > 0) {
1560
+ this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
1561
+ }
1562
+
1563
+
1564
+ //
1565
+
1566
+ // ALWAYS read (AgentViewModel: `optInt("dailyTokens", optInt("usedTokens",
1567
+
1568
+
1569
+ // — which this frame set to the TASK total. The card therefore drew task
1570
+ // tokens against `maxTokensPerDay` and read 29% while the daily limiter
1571
+ // fired at 1,001,877 / 1,000,000. The contract existed on one side only.
1572
+ //
1573
+ // Context is reported in characters against the character pool, the unit
1574
+ // the window is actually budgeted in. The renderer converts once, using
1575
+ // the project's own CHAR_POOLS convention, instead of comparing a token
1576
+ // count to a character limit.
1577
+ this.emitEvent({
1578
+ type: 'usage_update',
1579
+ usedTokens: tracking.dailyTokens || 0,
1580
+ dailyTokens: tracking.dailyTokens || 0,
1581
+ dailyCostUsd: tracking.dailyCostUsd || 0,
1582
+ dailyLimit: tracking.dailyLimit || 0,
1583
+ taskTokens: tracking.taskTokens || 0,
1584
+ taskCostUsd: tracking.taskCostUsd || 0,
1585
+ taskLimit: tracking.taskLimit || 0,
1586
+ costUsd: tracking.costUsd || 0,
1587
+ lifetimeTokens: tracking.lifetimeTokens || 0,
1588
+ lifetimeCostUsd: tracking.lifetimeCostUsd || 0,
1589
+ contextChars: this._contextChars || 0,
1590
+ contextLimitChars: this._contextLimitChars || 0,
1591
+ cachedTokens
1592
+ });
1593
+
1594
+ if (!tracking.allowed) {
1595
+ this.emitEvent({ type: 'error', message: tracking.reason });
1596
+ break;
1597
+ }
1598
+
1599
+ // Add assistant response to history. This is the ONLY place the turn is
1600
+ // recorded — the completion and guard branches below used to push it a
1601
+ // second time, duplicating every finished turn in the history.
1602
+ const hasToolCalls = Boolean(response.toolCalls && response.toolCalls.length > 0);
1603
+ const assistantMsg: any = {
1604
+ role: 'assistant',
1605
+ // An assistant message with neither text nor tool calls is rejected by
1606
+ // some providers, so a terminal turn always carries something.
1607
+ content: response.content || (hasToolCalls ? '' : 'Task completed.')
1608
+ };
1609
+ if (hasToolCalls) {
1610
+ assistantMsg.tool_calls = response.toolCalls;
1611
+ }
1612
+ if (response.reasoningContent) {
1613
+ assistantMsg.reasoning_content = response.reasoningContent;
1614
+ } else if (reasoningAccumulated) {
1615
+ assistantMsg.reasoning_content = reasoningAccumulated;
1616
+ }
1617
+ const finalReasoning = response.reasoningContent || reasoningAccumulated;
1618
+ if (finalReasoning) {
1619
+ this.emitEvent({
1620
+ type: 'agent_reasoning',
1621
+ content: finalReasoning,
1622
+ streaming: false,
1623
+ elapsedMs: thoughtStartedAt ? Date.now() - thoughtStartedAt : 0
1624
+ });
1625
+ }
1626
+ // Kept verbatim on the turn. A thinking-enabled model that gets its own
1627
+ // thinking blocks back is continuing a thought; one that does not is
1628
+ // starting over, and with tool_use in the same turn the API can reject
1629
+ // the sequence outright.
1630
+ if (response.thinkingBlocks) {
1631
+ assistantMsg.thinking_blocks = response.thinkingBlocks;
1632
+ }
1633
+ this.messages.push(assistantMsg);
1634
+
1635
+ if (response.content) {
1636
+ this.emitEvent({ type: 'agent_message', content: response.content });
1637
+ }
1638
+
1639
+ // If no tool calls, check if the agent is just thinking/planning or actually done
1640
+ if (!response.toolCalls || response.toolCalls.length === 0) {
1641
+ const contentText = response.content || '';
1642
+ const lower = contentText.toLowerCase();
1643
+ const thinkingKeywords = ['let me ', "i'll ", 'i will ', 'now i ', 'next, i ', 'first, i ', 'checking ', 'trying to ', 'let us ', 'going to '];
1644
+ const isThinking = thinkingKeywords.some(kw => lower.includes(kw));
1645
+
1646
+ if (isThinking && this.consecutiveThinkingSteps < 3) {
1647
+ this.consecutiveThinkingSteps++;
1648
+ this.emitEvent({ type: 'status', message: 'Agent planning next steps...' });
1649
+ this.emitEvent({ type: 'agent_activity', activity: 'Planning next actionable steps…' });
1650
+ // assistantMsg was already pushed above — pushing it again here
1651
+ // duplicated the whole turn in history on every nudge.
1652
+ this.messages.push({
1653
+ role: 'system',
1654
+ content: '[SYSTEM NOTICE: You provided reasoning/planning without calling any tools. Please invoke the next appropriate tool now to continue progressing on the task.]'
1655
+ });
1656
+ this.memoryManager.saveHistory(this.messages);
1657
+ continue;
1658
+ }
1659
+
1660
+ if (this.stepsCompleted === 0 && this.consecutiveThinkingSteps < 2) {
1661
+ if (lower.includes('turn completed') || lower.includes('no output produced') || !contentText.trim()) {
1662
+ this.consecutiveThinkingSteps++;
1663
+ this.emitEvent({ type: 'status', message: 'Nudging agent to execute actionable steps...' });
1664
+ this.emitEvent({ type: 'agent_activity', activity: 'Nudging agent to invoke tools…' });
1665
+ this.messages.push({
1666
+ role: 'system',
1667
+ content: '[SYSTEM NOTICE: An action or task was requested, but no tools were called. Please invoke the appropriate tool by outputting: <tool_call>{"name": "tool_name", "arguments": {...}}</tool_call> to execute the task.]'
1668
+ });
1669
+ this.memoryManager.saveHistory(this.messages);
1670
+ continue;
1671
+ }
1672
+ }
1673
+
1674
+ // --- COMPLETION GUARDS ---
1675
+ // Two hard rules learned the expensive way:
1676
+ // 1. Match on word boundaries. Substring matching made 'ui' fire on
1677
+ // "build"/"quick"/"requirements" and 'race' fire on "trace",
1678
+ // dragging ordinary scripting tasks into game/web enforcement.
1679
+ // 2. Fire at most once per task. These used to be gated on
1680
+ // consecutiveThinkingSteps, which resets on every tool call, so
1681
+ // a guard could block completion indefinitely and burn the whole
1682
+ // step budget on an already-finished task.
1683
+ const taskPrompt = this.currentTaskPrompt || this.userPrompt || '';
1684
+ const isGameTask = isGameIntent(taskPrompt);
1685
+
1686
+ this.gameToolStats = this.gameToolStats || { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
1687
+
1688
+ if (isGameTask && !this.gameGuardFired) {
1689
+ const buildingRealGame = this.gameCascadeState.currentStage > 1 || this.stepsCompleted > 0;
1690
+ const needsVerification = buildingRealGame && !this.gameCascadeState.verificationPassed && this.gameCascadeState.currentStage >= 7;
1691
+ // Production-depth enforcement is opt-in. It is right for
1692
+ // "build me a full RPG" and wrong for "fix the jump height in my game".
1693
+ const needsDepth = this.config.enforceGameDepth === true && this.stepsCompleted < 50;
1694
+
1695
+ if (needsVerification || needsDepth) {
1696
+ this.gameGuardFired = true;
1697
+ this.emitEvent({ type: 'status', message: '⚡ Sovereign Game Guard: Enforcing Production Depth & Quality Gate...' });
1698
+
1699
+ const guardMsg = needsDepth && !needsVerification
1700
+ ? `[SOVEREIGN DEPTH BLOCK: You are building a Full Production Game but only took ${this.stepsCompleted} steps. A full production game requires 100+ steps. Expand the game with more levels, richer UI, complex enemy AI, or more assets before finishing. This check fires once — if the task genuinely is complete, say so plainly and finish.]`
1701
+ : `[SOVEREIGN QUALITY GATE: You built a game but declared completion without verifying it. Run \`game_web_runtime_inspector\` and \`game_canvas_audit\` to confirm runtime stability (FPS >= 30, no missing sprites) before exiting. This check fires once — if verification is genuinely not applicable, say so plainly and finish.]`;
1702
+
1703
+ this.messages.push({ role: 'system', content: guardMsg });
1704
+ this.memoryManager.saveHistory(this.messages);
1705
+ continue;
1706
+ }
1707
+ }
1708
+
1709
+ // P6 — ANTI-SLOP GATE (Vision §7, ENFORCED)
1710
+ //
1711
+ // The visual guard below makes the agent LOOK at its work, but the
1712
+ // agent was the only judge of what it saw — and a model that just
1713
+ // emitted a purple gradient hero does not reliably call it generic.
1714
+ // This reads the HTML/CSS actually written and scores it. Weighted and
1715
+ // threshold-based, never a single tripwire: a guard with false
1716
+ // positives gets switched off (the ZM-09 lesson).
1717
+ if (!this.slopGateFired && this.webArtifacts.size > 0) {
1718
+ this.slopGateFired = true; // fires at most once per task, like the others
1719
+ try {
1720
+ const files = [];
1721
+ for (const artifactPath of this.webArtifacts) {
1722
+ try {
1723
+ files.push({ path: artifactPath, content: fsSync.readFileSync(artifactPath, 'utf8') });
1724
+ } catch (e: any) { /* deleted or moved since: nothing to judge */ }
1725
+ }
1726
+
1727
+ const result = analyzeFiles(files);
1728
+ if (result.verdict === 'slop') {
1729
+ const recent = Array.isArray(this.staticContext?.recentMovements) ? this.staticContext.recentMovements : [];
1730
+ const brief = formatMovementBrief(suggestMovements(recent, 3));
1731
+
1732
+ auditLog.log({
1733
+ event: 'anti_slop_block', taskId: this.taskId,
1734
+ score: result.score, signals: result.findings.map((f: any) => f.id)
1735
+ });
1736
+ this.emitEvent({ type: 'status', message: `⚡ Anti-Slop Gate: design scored ${result.score} — rebuilding.` });
1737
+ this.messages.push({ role: 'system', content: formatFindings(result, brief) });
1738
+ this.memoryManager.saveHistory(this.messages);
1739
+ continue;
1740
+ }
1741
+
1742
+ if (result.findings.length > 0) {
1743
+ auditLog.log({
1744
+ event: 'anti_slop_pass', taskId: this.taskId,
1745
+ score: result.score, verdict: result.verdict,
1746
+ signals: result.findings.map((f: any) => f.id)
1747
+ });
1748
+ }
1749
+ } catch (e: any) {
1750
+ // A quality gate must never be the reason a task fails.
1751
+ this.debugLog(`anti-slop gate skipped: ${e.message}`);
1752
+ }
1753
+ }
1754
+
1755
+ // Web Visual Validation Guard (Anti-Slop / Transcendence)
1756
+ const isWebTask = isWebIntent(taskPrompt);
1757
+
1758
+ if (isWebTask && !this.webGuardFired && this.stepsCompleted > 0) {
1759
+ const hasVision = this.llm.supportsVision !== false;
1760
+ // Finding D-6: this guard used to demand `screenshot` /
1761
+ // `vision_inspect_ui` unconditionally. Both need the browser and
1762
+ // capture packages, which are provisioned only after the user
1763
+ // consents — so on a fresh install the guard was ordering the agent
1764
+ // to use a tool that could not run. Ask for the capability once;
1765
+ // if it was declined, fall through to the path that needs nothing.
1766
+ let visionReady = false;
1767
+ let visionDeclined = false;
1768
+ let browserReady = false;
1769
+ let browserDeclined = false;
1770
+ try {
1771
+ const { groupStatus, isGroupDeclined } = await import('./provisioning/capabilityProvisioner.js');
1772
+ visionReady = groupStatus('vision').state === 'ready';
1773
+ visionDeclined = isGroupDeclined('vision');
1774
+ browserReady = groupStatus('browser').state === 'ready';
1775
+ browserDeclined = isGroupDeclined('browser');
1776
+ } catch (e: any) { /* treat as not ready */ }
1777
+ let webGuardMsg = '';
1778
+
1779
+ if (!browserReady && !browserDeclined) {
1780
+ webGuardMsg = `[ANTI-SLOP CHECK: You are building a Web/UI project and must inspect it before finishing, but the dedicated browser capability is not enabled yet. Call \`manage_local_dependencies\` with action "grant_capability" and group "browser" to request the Causyne Browser runtime. If the user declines, read the final compiled HTML/CSS instead. This check fires once.]`;
1781
+ } else if (hasVision && !visionReady && !visionDeclined) {
1782
+ webGuardMsg = `[ANTI-SLOP CHECK: The browser is available, but desktop screen capture is not enabled. Call \`manage_local_dependencies\` with action "grant_capability" and group "vision" to request it, or use \`browser_act\` snapshots and its workspace-scoped screenshot action. This check fires once.]`;
1783
+ } else if (hasVision && visionReady && !this.webVerificationState.screenshotTaken) {
1784
+ webGuardMsg = `[ANTI-SLOP CHECK: You are building a Web/UI project but attempted to finish without VISUALLY verifying your work. Use \`screenshot\` or \`vision_inspect_ui\` to look at the UI in a browser. A human looks at their work to avoid slop. This check fires once — if there is genuinely nothing visual to inspect, say so plainly and finish.]`;
1785
+ } else if ((!hasVision || visionDeclined) && browserReady && !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken) {
1786
+ webGuardMsg = `[TRANSCENDENCE CHECK: You are building a Web/UI project. As a vision-disabled model you cannot screenshot, but you MUST use \`browser_act\` to inspect the DOM, or read the final compiled HTML/CSS, to verify semantic correctness before finishing. This check fires once.]`;
1787
+ }
1788
+
1789
+ if (webGuardMsg) {
1790
+ this.webGuardFired = true;
1791
+ // The verification tools live in the web pack; make sure they are
1792
+ // actually in context before demanding the agent use them.
1793
+ this.unlockPack('web');
1794
+ this.emitEvent({ type: 'status', message: '⚡ Anti-Slop Guard: Forcing visual/semantic verification...' });
1795
+ this.messages.push({ role: 'system', content: webGuardMsg });
1796
+ this.memoryManager.saveHistory(this.messages);
1797
+ continue;
1798
+ }
1799
+ }
1800
+
1801
+ // Cold Observer: Overconfidence & Loop Verification Check
1802
+ if (!this.coldObserverGuardFired) {
1803
+ try {
1804
+ const coldAudit = await coldObserver.auditTurnVerification({
1805
+ taskId: this.taskId,
1806
+ userPrompt: this.currentTaskPrompt || this.userPrompt || '',
1807
+ agentClaim: response.content || '',
1808
+ toolHistory: [],
1809
+ stepsCompleted: this.stepsCompleted
1810
+ });
1811
+
1812
+ if (coldAudit.overconfident) {
1813
+ this.coldObserverGuardFired = true;
1814
+ this.emitEvent({ type: 'status', message: `Cold Observer: ${coldAudit.discrepancy}` });
1815
+ this.messages.push({
1816
+ role: 'system',
1817
+ content: coldAudit.coldDirective
1818
+ });
1819
+ this.memoryManager.saveHistory(this.messages);
1820
+ continue;
1821
+ }
1822
+ } catch (_err: any) {
1823
+ // Cold observer fail-open
1824
+ }
1825
+ }
1826
+
1827
+ this.emitEvent({ type: 'status', message: 'Task completed.' });
1828
+ this.memoryManager.saveHistory(this.messages); // Save final state
1829
+
1830
+
1831
+
1832
+ // The task worked. Keep the route so the next one like it does not
1833
+ // have to rediscover it. Deterministic: we already watched every step
1834
+ // run, so asking a model to summarise it would be paying for a worse
1835
+ // copy of a fact we hold.
1836
+ try {
1837
+ const stored = recordPlan({
1838
+ prompt: this.currentTaskPrompt || this.userPrompt,
1839
+ archetype: this.taskShape ? this.taskShape.archetype : '',
1840
+ steps: this._planSteps || []
1841
+ });
1842
+ if (stored) this.debugLog(`plan cached: ${stored.steps.length} steps, ${stored.wins}/${stored.uses} wins`);
1843
+ } catch (e: any) {
1844
+ this.debugLog(`plan cache write skipped: ${e.message}`);
1845
+ }
1846
+
1847
+ auditLog.log({ event: 'task_complete', taskId: this.taskId, steps: this.stepsCompleted });
1848
+ this.emitEvent({ type: 'task_complete', taskId: this.taskId });
1849
+ break;
1850
+ }
1851
+
1852
+ this.consecutiveThinkingSteps = 0; // Reset thinking counter when tools are called
1853
+
1854
+ // 3a. PREFETCH — run the independent read-only calls of this batch
1855
+ // concurrently (finding D-8).
1856
+ //
1857
+ // Every competitive agent batches independent reads; this loop executed
1858
+ // them strictly one after another, so six `fs_read`s cost six full
1859
+ // round trips of tool latency.
1860
+ //
1861
+ // The serial loop below is deliberately left EXACTLY as it was. Nothing
1862
+ // about ordering, approval gates, step counting, streaming, retries or
1863
+ // error classification changes — the only difference is that a
1864
+ // read-only result may already be sitting in this map by the time the
1865
+ // loop reaches it. Restructuring the 400-line body into a batch would
1866
+ // have been the obvious approach and a far worse one: it is dense with
1867
+ // `break`s, approval waits and circuit breakers, and a subtle reordering
1868
+ // there is exactly the class of silent defect this whole remediation
1869
+ // exists to clean up.
1870
+ //
1871
+ // Safety rules that make this sound:
1872
+ // * Only tools on the read-only allowlist are eligible. Nothing that
1873
+ // writes, deletes, executes or asks for approval is ever prefetched.
1874
+ // * The sandbox is consulted FIRST, with the same call the serial path
1875
+ // makes, so a denied path is never read behind the guard's back.
1876
+ // * Only a SUCCESSFUL prefetch is consumed. A failure is discarded and
1877
+ // the serial path executes normally, so the retry-with-backoff and
1878
+ // error-classification logic keeps its exact behaviour.
1879
+ const prefetched = this.prefetchReadOnlyCalls(response.toolCalls);
1880
+
1881
+ // 3. ACT (Execute tool calls)
1882
+ for (const toolCall of response.toolCalls) {
1883
+ // Canonicalise once, here. Every downstream comparison — the sandbox's
1884
+ // risk classification, the approval gates, the game cascade lists —
1885
+ // matches on this string, so if it is not the catalogue name those
1886
+ // checks silently never fire.
1887
+ const functionName = canonicalToolName(toolCall.function.name);
1888
+ const tool = resolveTool(functionName);
1889
+ const toolSchema = tool?.schema?.parameters || tool?.schema?.input_schema;
1890
+ const repair = selfRepairToolCall(toolCall, toolSchema, {
1891
+ cwd: this.workspaceRoot || process.cwd()
1892
+ });
1893
+
1894
+ if (repair.error) {
1895
+ this.messages.push({
1896
+ role: 'tool',
1897
+ tool_call_id: toolCall.id,
1898
+ name: functionName,
1899
+ content: JSON.stringify({
1900
+ success: false,
1901
+ error: `Invalid JSON in arguments: ${repair.error}`,
1902
+ selfRepairGuidance: {
1903
+ tool: functionName,
1904
+ instruction: 'Ensure arguments are passed as a valid JSON object without unescaped control characters or trailing commas.'
1905
+ }
1906
+ })
1907
+ });
1908
+ continue;
1909
+ }
1910
+
1911
+ let args: any = repair.args;
1912
+ if (repair.repaired && repair.repairs.length > 0) {
1913
+ this.debugLog(`[TOOL SELF-REPAIR] Healed tool call '${functionName}': ${repair.repairs.join(', ')}`);
1914
+ }
1915
+
1916
+ this.emitEvent({ type: 'step_start', tool: functionName, args: args, toolCallId: toolCall.id });
1917
+ this.consecutiveCommands++;
1918
+
1919
+ if (functionName === 'screenshot' || functionName === 'vision_inspect_ui') {
1920
+ this.webVerificationState.screenshotTaken = true;
1921
+ }
1922
+ if (functionName === 'browser_act') {
1923
+ this.webVerificationState.browserActUsed = true;
1924
+ }
1925
+
1926
+ // Sovereign Game Pre-Flight Interceptor (v1.3.13)
1927
+ const isGameTaskExec = isGameIntent(this.currentTaskPrompt || this.userPrompt || '');
1928
+
1929
+ const ALL_GAME_TOOLS_LIST = [
1930
+ 'godot_act', 'game_asset_fetch', 'game_build_html5',
1931
+ 'game_lore_forge', 'game_dialogue_tree_gen', 'game_quest_arc_builder',
1932
+ 'game_animation_rig', 'game_ai_behavior_tree', 'game_cinematic_sequencer',
1933
+ 'game_asset_harvest', 'game_audio_synth', 'game_vfx_emitter_gen',
1934
+ 'game_shader_forge', 'game_scene_build', 'game_entity_spawner',
1935
+ 'game_tilemap_gen', 'game_ui_hud_builder', 'game_economy_balancer',
1936
+ 'game_data_forge', 'check_system_specs', 'game_web_runtime_inspector', 'game_canvas_audit'
1937
+ ];
1938
+
1939
+ if (ALL_GAME_TOOLS_LIST.includes(functionName)) {
1940
+ // Stage progression
1941
+ if (['check_system_specs', 'godot_act'].includes(functionName)) this.gameCascadeState.currentStage = Math.max(this.gameCascadeState.currentStage, 2);
1942
+ if (['game_lore_forge', 'game_dialogue_tree_gen', 'game_quest_arc_builder'].includes(functionName)) this.gameCascadeState.currentStage = Math.max(this.gameCascadeState.currentStage, 3);
1943
+ if (['game_animation_rig', 'game_ai_behavior_tree', 'game_cinematic_sequencer'].includes(functionName)) this.gameCascadeState.currentStage = Math.max(this.gameCascadeState.currentStage, 4);
1944
+ if (['game_asset_harvest', 'game_audio_synth', 'game_vfx_emitter_gen'].includes(functionName)) this.gameCascadeState.currentStage = Math.max(this.gameCascadeState.currentStage, 5);
1945
+ if (['game_shader_forge', 'game_scene_build', 'game_entity_spawner'].includes(functionName)) this.gameCascadeState.currentStage = Math.max(this.gameCascadeState.currentStage, 6);
1946
+ if (['game_tilemap_gen', 'game_ui_hud_builder', 'game_economy_balancer', 'game_build_html5'].includes(functionName)) this.gameCascadeState.currentStage = Math.max(this.gameCascadeState.currentStage, 7);
1947
+
1948
+ if (functionName === 'game_web_runtime_inspector' || functionName === 'game_canvas_audit') {
1949
+ this.gameCascadeState.verificationPassed = true;
1950
+ }
1951
+ }
1952
+
1953
+ if (isGameTaskExec && ['fs_write', 'sysRun', 'terminal_persistent_shell', 'game_build_html5'].includes(functionName) && this.gameCascadeState.currentStage < 7) {
1954
+ const isGameBuildHtml5 = functionName === 'game_build_html5';
1955
+ const isCustomScriptBlock = isGameBuildHtml5 && args.template === 'custom' && args.customScript && args.customScript.length > 2000;
1956
+ const targetPath = (args.path || args.filepath || args.targetFile || args.command || '').toLowerCase();
1957
+
1958
+ // BUGFIX: Only block actual game file extensions to prevent false positives when creating directories (e.g., mkdir /Desktop/RacerGame)
1959
+ const isGameFileOrDir = targetPath.includes('.html'); // Removed .gd and .tscn to allow Godot to function
1960
+ const isEchoingToFile = targetPath.includes('echo') && targetPath.includes('>') && isGameFileOrDir;
1961
+
1962
+ if ((['fs_write'].includes(functionName) && isGameFileOrDir) || isEchoingToFile || isCustomScriptBlock) {
1963
+ const interceptMsg = `[SOVEREIGN CASCADE VIOLATION: You attempted to skip from Stage ${this.gameCascadeState.currentStage} to Stage 7 without completing Stages 3, 4, 5, and 6 modularly. DO NOT write monolithic 20 KB custom scripts!]`;
1964
+ this.emitEvent({ type: 'step_error', tool: functionName, error: 'Sovereign Game Intercept: Cascade violation detected.', toolCallId: toolCall.id });
1965
+ this.messages.push({
1966
+ role: 'tool',
1967
+ tool_call_id: toolCall.id,
1968
+ name: functionName,
1969
+ content: JSON.stringify({ success: false, error: "Sovereign Cascade Violation", CRITICAL_INSTRUCTION: interceptMsg })
1970
+ });
1971
+ continue;
1972
+ }
1973
+ }
1974
+
1975
+ if (functionName === 'game_build_html5' && args.template === 'custom' && args.customScript) {
1976
+ const scr = args.customScript;
1977
+ if (scr.includes('c.drw ?') && !scr.includes('drw(')) {
1978
+ this.messages.push({
1979
+ role: 'tool', tool_call_id: toolCall.id, name: functionName,
1980
+ content: JSON.stringify({ success: false, error: 'AST SANITIZER: Detected ternary check for c.drw but no actual drw() method definition found! Fix and retry.' })
1981
+ });
1982
+ continue;
1983
+ }
1984
+ if (scr.includes('ctx.translate(-cam.x, -cam.y)') && (scr.includes('c.x - cam.x') || scr.includes('c.y - cam.y'))) {
1985
+ this.messages.push({
1986
+ role: 'tool', tool_call_id: toolCall.id, name: functionName,
1987
+ content: JSON.stringify({ success: false, error: 'AST SANITIZER: Detected double translation! You are translating context by cam and then manually subtracting cam again inside drawing calls!' })
1988
+ });
1989
+ continue;
1990
+ }
1991
+ }
1992
+
1993
+ // 4-Layer Security Sandbox Validation
1994
+ // 2. Sandbox Security Validation (CRITICAL FIX: Prevent Infinite Loop on Block)
1995
+ const validation = this.sandbox.validate(functionName, args);
1996
+ if (!validation.allowed) {
1997
+ this.consecutiveBlockedActions++;
1998
+
1999
+ // Hard Circuit Breaker (Transcendence Context Consciousness)
2000
+ if (this.consecutiveBlockedActions >= 4) {
2001
+ const fatalMsg = `FATAL ERROR: Infinite Token Drain Detected. Agent repeatedly attempted blocked/forbidden actions 4 times in a row. Forcibly aborting task to save tokens.`;
2002
+ this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
2003
+ auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
2004
+
2005
+ // Save memory of failure for RLTF
2006
+ cortexDb.saveMemory(
2007
+ this.currentTaskPrompt || 'Unknown task',
2008
+ 'Agent stubbornly repeated blocked actions causing an infinite loop.',
2009
+ `Do NOT repeat ${functionName} with these exact arguments, as it is permanently blocked by Sandbox. Ensure you respect ALLOWED WORKSPACE PATHS.`
2010
+ ).catch(() => {});
2011
+
2012
+ this.abort();
2013
+ break;
2014
+ }
2015
+
2016
+ auditLog.log({ event: 'tool_blocked', taskId: this.taskId, tool: functionName, args, reason: validation.reason });
2017
+ coldObserver.recordToolOutcome(this.taskId, functionName, args, {
2018
+ success: false,
2019
+ error: validation.reason
2020
+ });
2021
+ this.emitEvent({ type: 'step_error', tool: functionName, error: validation.reason, toolCallId: toolCall.id });
2022
+
2023
+ // Feed error back to LLM with absolute command to stop repeating
2024
+ this.messages.push({
2025
+ role: 'tool',
2026
+ tool_call_id: toolCall.id,
2027
+ name: functionName,
2028
+ content: JSON.stringify({
2029
+ success: false,
2030
+ error: validation.reason,
2031
+ CRITICAL_INSTRUCTION: "DO NOT RETRY THIS EXACT ACTION. The Sandbox blocked it. Ensure you only write to paths inside ALLOWED WORKSPACE PATHS, or use a different approach. Repeating this will drain tokens."
2032
+ })
2033
+ });
2034
+ continue;
2035
+ }
2036
+
2037
+ this.consecutiveBlockedActions = 0; // Reset counter on allowed action
2038
+
2039
+ // Resolve and validate before asking the user for approval. Unknown or
2040
+ // malformed calls should self-correct without creating approval fatigue.
2041
+ if (!tool || typeof tool.execute !== 'function') {
2042
+ this.messages.push({
2043
+ role: 'tool',
2044
+ tool_call_id: toolCall.id,
2045
+ name: functionName,
2046
+ content: JSON.stringify({
2047
+ success: false,
2048
+ error: `Tool "${functionName}" does not exist. Call tool_search with a description of the capability you need to discover the correct tool.`
2049
+ })
2050
+ });
2051
+ continue;
2052
+ }
2053
+
2054
+ if (!isCoreTool(functionName) && !this.unlockedTools.has(functionName)) {
2055
+ const pack = packForTool(functionName);
2056
+ if (this.unlockPack(pack)) {
2057
+ this.debugLog(`unlocked capability pack "${pack}" for ${functionName}`);
2058
+ }
2059
+ this.unlockedTools.add(functionName);
2060
+ }
2061
+
2062
+ const validationErrors = this.validateToolArgs(functionName, args);
2063
+ if (validationErrors) {
2064
+ const diagnostic = generateSelfRepairDiagnostic(
2065
+ functionName,
2066
+ args,
2067
+ validationErrors,
2068
+ tool?.schema?.parameters || tool?.schema?.input_schema
2069
+ );
2070
+ this.messages.push({
2071
+ role: 'tool',
2072
+ tool_call_id: toolCall.id,
2073
+ name: functionName,
2074
+ content: JSON.stringify(diagnostic)
2075
+ });
2076
+ continue;
2077
+ }
2078
+
2079
+ const checkpointError = this.mutationCheckpoint(functionName, args);
2080
+ if (checkpointError) {
2081
+ this.messages.push({
2082
+ role: 'tool',
2083
+ tool_call_id: toolCall.id,
2084
+ name: functionName,
2085
+ content: JSON.stringify({
2086
+ success: false,
2087
+ error: checkpointError
2088
+ })
2089
+ });
2090
+ continue;
2091
+ }
2092
+
2093
+ // A policy hook runs after the built-in sandbox but before any user
2094
+ // approval prompt, so a deterministic denial never asks the user to
2095
+ // approve work that will be rejected anyway.
2096
+ const preHook = await this.runPreToolUse(functionName, args, toolCall.id);
2097
+ if (preHook && preHook.denied) {
2098
+ auditLog.log({
2099
+ event: 'hook_denied', taskId: this.taskId, hookEvent: 'PreToolUse',
2100
+ tool: functionName, reason: preHook.reason || 'hook denied'
2101
+ });
2102
+ coldObserver.recordToolOutcome(this.taskId, functionName, args, {
2103
+ success: false,
2104
+ error: `PreToolUse hook denied "${functionName}".`
2105
+ });
2106
+ this.messages.push({
2107
+ role: 'tool',
2108
+ tool_call_id: toolCall.id,
2109
+ name: functionName,
2110
+ content: JSON.stringify({
2111
+ success: false,
2112
+ error: `PreToolUse hook denied "${functionName}".`,
2113
+ hookFeedback: (preHook.messages || []).join('\n') || undefined
2114
+ })
2115
+ });
2116
+ continue;
2117
+ }
2118
+
2119
+ // Approval flow for dangerous actions (Mode A/B) or ALWAYS for heavy AI downloads
2120
+ // The schema name is manage_local_dependencies. Comparing against the
2121
+ // old alias meant this consent gate never fired and multi-GB model
2122
+ // downloads ran unannounced.
2123
+ const isHeavyAiDownload = functionName === 'manage_local_dependencies' &&
2124
+ ['pipInst', 'fetchBin', 'fetchMod'].includes(args.action);
2125
+
2126
+ // Cold Observer: Assess blast radius and mutation risk
2127
+ try {
2128
+ const coldMutation = await coldObserver.evaluateMutation(functionName, args, {
2129
+ workspaceRoot: this.workspaceRoot
2130
+ });
2131
+ if (coldMutation.veto) {
2132
+ this.emitEvent({
2133
+ type: 'status',
2134
+ message: `Cold Observer Veto: Action blocked (${coldMutation.reason})`
2135
+ });
2136
+ coldObserver.recordToolOutcome(this.taskId, functionName, args, {
2137
+ success: false,
2138
+ error: `[COLD OBSERVER VETO]: ${coldMutation.reason}`
2139
+ });
2140
+ this.messages.push({
2141
+ role: 'tool',
2142
+ tool_call_id: toolCall.id,
2143
+ name: functionName,
2144
+ content: JSON.stringify({
2145
+ success: false,
2146
+ error: `[COLD OBSERVER VETO]: ${coldMutation.reason}. Modify your approach to avoid project damage.`
2147
+ })
2148
+ });
2149
+ continue;
2150
+ }
2151
+ if (coldMutation.requiresConfirmation) {
2152
+ validation.risk = 'dangerous';
2153
+ }
2154
+ } catch (_err: any) {
2155
+ // Cold observer mutation assessment fail-open
2156
+ }
2157
+
2158
+ // A standing approval from "Allow always" lifts the gate for this
2159
+ // tool until the process restarts. It is checked HERE rather than
2160
+
2161
+ // asking and then auto-answering would still interrupt the user,
2162
+ // which is the entire thing they were trying to stop.
2163
+ //
2164
+ // Nothing else is bypassed: the sandbox has already run above, so a
2165
+ // FORBIDDEN command is still refused and a path outside the workspace
2166
+ // is still blocked. This waives the QUESTION, not the guard.
2167
+ const standingApproval = this.isAlwaysAllowed(functionName);
2168
+ if (standingApproval) {
2169
+ auditLog.log({
2170
+ event: 'approval_auto_granted', taskId: this.taskId,
2171
+ tool: functionName, risk: validation.risk, reason: 'allow_always'
2172
+ });
2173
+ }
2174
+
2175
+ if (!standingApproval && (
2176
+ validation.risk === 'extreme' ||
2177
+ isHeavyAiDownload ||
2178
+ (this.config.autonomyMode !== 'C' && validation.risk === 'dangerous') ||
2179
+ this.config.autonomyMode === 'A')) {
2180
+
2181
+ // Wait for local approval
2182
+ this.emitEvent({ type: 'approval_request', toolCallId: toolCall.id, tool: functionName, args, risk: validation.risk });
2183
+
2184
+ const approved = await this.waitForApproval(toolCall.id);
2185
+
2186
+ if (!approved) {
2187
+ coldObserver.recordToolOutcome(this.taskId, functionName, args, {
2188
+ success: false,
2189
+ error: 'User denied this action'
2190
+ });
2191
+ this.messages.push({
2192
+ role: 'tool',
2193
+ tool_call_id: toolCall.id,
2194
+ name: functionName,
2195
+ content: JSON.stringify({ success: false, error: 'User denied this action' })
2196
+ });
2197
+ continue;
2198
+ }
2199
+ }
2200
+
2201
+ // P2: snapshot the files this call is about to change, before it runs.
2202
+ // Only the mutating fs tools match; everything else returns immediately.
2203
+ // Fail-open by contract — this can never block or fail a tool call.
2204
+ const restorePoints = captureBeforeMutation(functionName, args, {
2205
+ taskId: this.taskId,
2206
+ step: this.stepsCompleted
2207
+ });
2208
+
2209
+ // Say that a restore point exists.
2210
+ //
2211
+ // The ids came back and were dropped on the floor, so checkpointing
2212
+ // ran on every mutating call and the user was never told — /undo was
2213
+ // there the whole time with nothing pointing at it. On the Stage this
2214
+ // also marks the rail, which is what makes scrolling back double as
2215
+ // finding somewhere to roll back TO.
2216
+ if (restorePoints.length > 0) {
2217
+ this.emitEvent({
2218
+ type: 'checkpoint',
2219
+ taskId: this.taskId,
2220
+ count: restorePoints.length,
2221
+ tool: functionName,
2222
+ path: args.path || args.file_path || null,
2223
+ step: this.stepsCompleted
2224
+ });
2225
+ }
2226
+
2227
+ // P6: remember which rendered surfaces this task touched, so the
2228
+ // anti-slop gate can read the finished result back off disk rather
2229
+ // than trusting the model's own account of what it built.
2230
+ if (['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
2231
+ const written = args.path || args.file_path;
2232
+ if (typeof written === 'string' && isScannableFile(written)) {
2233
+ this.webArtifacts.add(written.replace(/^~\//, os.homedir() + '/'));
2234
+ }
2235
+ }
2236
+
2237
+ // V5: Execute with Error Recovery Loop (3-attempt retry with exponential backoff)
2238
+ const retryKey = `${functionName}:${JSON.stringify(args).substring(0, 100)}`;
2239
+ let result;
2240
+ let duration;
2241
+ const MAX_RETRIES = 3;
2242
+ const currentRetries = this._toolRetryCount.get(retryKey) || 0;
2243
+
2244
+ try {
2245
+ const wasRetried = currentRetries > 0;
2246
+ const startTime = Date.now();
2247
+ // A concurrent read from the prefetch pass above, if it succeeded.
2248
+ const ready = prefetched.get(toolCall.id);
2249
+ const early = ready ? await ready : null;
2250
+ result = (early && early.success)
2251
+ ? early
2252
+ : await tool.execute(args, { signal: this.abortController.signal, parentLoop: this, ...this.sandbox });
2253
+ duration = Date.now() - startTime;
2254
+
2255
+ // Success: reset retry count for this operation
2256
+ this._toolRetryCount.delete(retryKey);
2257
+
2258
+ // V5 Cortex RLTF: Save the successful recovery as a permanent neural memory
2259
+ if (wasRetried) {
2260
+ cortexDb.saveMemory(
2261
+ this.currentTaskPrompt || `Task using ${functionName}`,
2262
+ `Failed ${currentRetries} times previously.`,
2263
+ `Successfully recovered and executed ${functionName} with arguments: ${JSON.stringify(args).substring(0, 200)}`
2264
+ ).catch((e: any) => this.debugLog(`cortex save failed: ${e.message}`));
2265
+ }
2266
+
2267
+ } catch (toolError: any) {
2268
+ duration = 0;
2269
+ const errorType = this.classifyError(toolError);
2270
+
2271
+ if (currentRetries < MAX_RETRIES && errorType !== 'fatal') {
2272
+ this._toolRetryCount.set(retryKey, currentRetries + 1);
2273
+ const backoffMs = Math.pow(2, currentRetries) * 1000; // 1s, 2s, 4s
2274
+
2275
+ this.emitEvent({
2276
+ type: 'step_error',
2277
+ tool: functionName,
2278
+ error: `${errorType}: ${toolError.message} (retry ${currentRetries + 1}/${MAX_RETRIES} in ${backoffMs/1000}s)`,
2279
+ toolCallId: toolCall.id
2280
+ });
2281
+
2282
+ auditLog.log({
2283
+ event: 'tool_retry',
2284
+ taskId: this.taskId,
2285
+ tool: functionName,
2286
+ attempt: currentRetries + 1,
2287
+ errorType,
2288
+ error: toolError.message
2289
+ });
2290
+
2291
+ // Wait before retry (the LLM will see the error and can adjust)
2292
+ await new Promise(resolve => setTimeout(resolve, backoffMs));
2293
+
2294
+ // Feed the classified error back so LLM can adjust its approach
2295
+ this.messages.push({
2296
+ role: 'tool',
2297
+ tool_call_id: toolCall.id,
2298
+ name: functionName,
2299
+ content: JSON.stringify({
2300
+ success: false,
2301
+ error: toolError.message,
2302
+ errorType: errorType,
2303
+ retryHint: this.getRetryHint(errorType),
2304
+ retriesLeft: MAX_RETRIES - currentRetries - 1
2305
+ })
2306
+ });
2307
+ continue;
2308
+ } else {
2309
+ // Max retries exceeded or fatal error: give up on this tool call
2310
+ this._toolRetryCount.delete(retryKey);
2311
+ this.emitEvent({
2312
+ type: 'step_error',
2313
+ tool: functionName,
2314
+ error: `Failed after ${MAX_RETRIES} attempts: ${toolError.message}`,
2315
+ toolCallId: toolCall.id
2316
+ });
2317
+ coldObserver.recordToolOutcome(this.taskId, functionName, args, {
2318
+ success: false,
2319
+ error: `PERMANENT FAILURE after ${MAX_RETRIES} retries: ${toolError.message}`
2320
+ });
2321
+
2322
+ this.messages.push({
2323
+ role: 'tool',
2324
+ tool_call_id: toolCall.id,
2325
+ name: functionName,
2326
+ content: JSON.stringify({
2327
+ success: false,
2328
+ error: `PERMANENT FAILURE after ${MAX_RETRIES} retries: ${toolError.message}. Do NOT retry this exact operation. Try a completely different approach or ask the user for help.`,
2329
+ errorType: errorType
2330
+ })
2331
+ });
2332
+ continue;
2333
+ }
2334
+ }
2335
+
2336
+ auditLog.log({
2337
+ event: 'tool_exec',
2338
+ taskId: this.taskId,
2339
+ tool: functionName,
2340
+ success: result.success,
2341
+ duration_ms: duration
2342
+ });
2343
+
2344
+ // Stage 3 seam: PostToolUse hook. A no-op that always allows today; when
2345
+ // hooks are configured it can mark a completed call failed (e.g. a
2346
+ // formatter rejecting a write) so the model sees it. Neutral until then.
2347
+ const postHook = await this.runPostToolUse(functionName, args, result);
2348
+ if (postHook && postHook.denied) {
2349
+ result = {
2350
+ ...result,
2351
+ success: false,
2352
+ error: postHook.reason || `PostToolUse hook rejected "${functionName}".`,
2353
+ hookFeedback: (postHook.messages || []).join('\n') || undefined
2354
+ };
2355
+ }
2356
+
2357
+ // The journal is the observer's own record of what actually ran. It
2358
+ // is written only after post-hook review, so a formatter that rejects
2359
+ // a write is remembered as a failure rather than a success.
2360
+ coldObserver.recordToolOutcome(this.taskId, functionName, args, result);
2361
+
2362
+ // PROGRESSIVE DISCLOSURE: honour unlock signals from tool_search.
2363
+ // The control fields are stripped before the result reaches the LLM.
2364
+ if (result && (result._unlock_tools || result._unlock_packs)) {
2365
+ for (const packName of result._unlock_packs || []) {
2366
+ this.unlockPack(packName);
2367
+ }
2368
+ for (const toolName of result._unlock_tools || []) {
2369
+ this.unlockedTools.add(toolName);
2370
+ }
2371
+ delete result._unlock_tools;
2372
+ delete result._unlock_packs;
2373
+ this.debugLog(`capability packs loaded: ${[...this.unlockedPacks].join(', ') || 'core only'}`);
2374
+ }
2375
+
2376
+ // Buffer output for disconnect resilience
2377
+ await this.taskBuffer.appendOutput(this.taskId, { tool: functionName, result });
2378
+
2379
+ this.emitEvent({ type: 'step_complete', tool: functionName, result: result._is_image_marker ? '[IMAGE DATA]' : result, toolCallId: toolCall.id });
2380
+ this.stepsCompleted++;
2381
+
2382
+ // The procedure, as it actually ran. Tool name plus a whitelisted
2383
+ // action token only — planCache.toStep() reads no paths, arguments or
2384
+ // command lines, so what is cached is a route and never a transcript.
2385
+ try {
2386
+ if (Array.isArray(this._planSteps)) {
2387
+ const stepSuccess = Boolean(result && result.success !== false && !result.error);
2388
+ this._planSteps.push(toStep(
2389
+ functionName,
2390
+ args,
2391
+ stepSuccess,
2392
+ result
2393
+ ));
2394
+ this._lastToolResult = result;
2395
+
2396
+ // Active Inference: Record step prediction error into VFE rolling tracker
2397
+ if (this.vfeTracker) {
2398
+ const isThrash = isThrashing((this._planSteps || []).map((s) => s.tool), functionName);
2399
+ const vfeOutcome = this.vfeTracker.recordStep({
2400
+ tool: functionName,
2401
+ success: stepSuccess,
2402
+ result,
2403
+ consecutiveFailures: this.consecutiveFailures,
2404
+ isThrashing: isThrash
2405
+ });
2406
+ if (vfeOutcome.paradigmShift) {
2407
+ this.debugLog(`[ACTIVE INFERENCE] VFE plateau detected: mean=${vfeOutcome.mean}, var=${vfeOutcome.variance}. Triggering paradigm shift.`);
2408
+ this._paradigmShiftPending = true;
2409
+ }
2410
+ }
2411
+ }
2412
+ } catch (e: any) { /* a plan is never worth failing a step for */ }
2413
+
2414
+ const ALL_GAME_TOOLS = [
2415
+ 'godot_act', 'game_asset_fetch', 'game_build_html5',
2416
+ 'game_lore_forge', 'game_dialogue_tree_gen', 'game_quest_arc_builder',
2417
+ 'game_animation_rig', 'game_ai_behavior_tree', 'game_cinematic_sequencer',
2418
+ 'game_asset_harvest', 'game_audio_synth', 'game_vfx_emitter_gen',
2419
+ 'game_shader_forge', 'game_scene_build', 'game_entity_spawner',
2420
+ 'game_tilemap_gen', 'game_ui_hud_builder', 'game_economy_balancer',
2421
+ 'game_data_forge', 'check_system_specs', 'game_web_runtime_inspector', 'game_canvas_audit'
2422
+ ];
2423
+ if (ALL_GAME_TOOLS.includes(functionName)) {
2424
+ // this.hasUsedGameTools is deprecated by this.gameCascadeState
2425
+ this.gameToolStats = this.gameToolStats || { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
2426
+ this.gameToolStats[functionName] = (this.gameToolStats[functionName] || 0) + 1;
2427
+ if (functionName === 'godot_act' && args && args.action) {
2428
+ this.gameToolStats.last_godot_action = args.action;
2429
+ }
2430
+ }
2431
+
2432
+ // Sovereign 100-Step Circuit Breaker Checkpoint Gate
2433
+ if (this.consecutiveCommands === 100 && !this.circuitBreakerUnlocked) {
2434
+ this.emitEvent({
2435
+ type: 'approval_request',
2436
+ toolCallId: 'circuit_breaker_100_' + this.stepsCompleted,
2437
+ tool: 'circuit_breaker_checkpoint',
2438
+ args: {
2439
+ consecutiveCommands: this.consecutiveCommands,
2440
+ stepsCompleted: this.stepsCompleted,
2441
+ activeTier: this.activeTier,
2442
+ maxTierSteps: this.maxSteps,
2443
+ message: `⚡ Circuit Breaker Checkpoint (100 steps reached). Approve to unlock and continue using your remaining ${this.activeTier.toUpperCase()} tier budget (up to ${this.maxSteps} steps total)?`
2444
+ },
2445
+ risk: 'info'
2446
+ });
2447
+
2448
+ const approved = await this.waitForApproval('circuit_breaker_100_' + this.stepsCompleted);
2449
+ if (!approved) {
2450
+ this.stopRequested = true;
2451
+ this.emitEvent({ type: 'status', message: 'Task stopped at 100-step circuit breaker checkpoint by user.' });
2452
+ break;
2453
+ }
2454
+ this.circuitBreakerUnlocked = true;
2455
+ this.emitEvent({ type: 'status', message: `⚡ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
2456
+ }
2457
+
2458
+ // Sovereign Tier Budget Extension Checkpoint Gate
2459
+ if (this.stepsCompleted >= this.maxSteps) {
2460
+ const extensionBatch = (this.activeTier === 'super_max') ? 600 : ((this.activeTier === 'max') ? 400 : 300);
2461
+ this.emitEvent({
2462
+ type: 'approval_request',
2463
+ toolCallId: 'tier_extension_' + this.stepsCompleted,
2464
+ tool: 'tier_budget_extension',
2465
+ args: {
2466
+ stepsCompleted: this.stepsCompleted,
2467
+ activeTier: this.activeTier,
2468
+ currentMaxSteps: this.maxSteps,
2469
+ message: `⚡ Tier Limit Reached (${this.stepsCompleted} / ${this.maxSteps} steps). The agent needs more steps to fulfill your intent. Approve to unlock another +${extensionBatch} steps for your ${this.activeTier.toUpperCase()} tier?`
2470
+ },
2471
+ risk: 'info'
2472
+ });
2473
+
2474
+ const approved = await this.waitForApproval('tier_extension_' + this.stepsCompleted);
2475
+ if (!approved) {
2476
+ this.stopRequested = true;
2477
+ this.emitEvent({ type: 'status', message: `Task stopped at ${this.maxSteps}-step tier limit by user.` });
2478
+ break;
2479
+ }
2480
+ this.maxSteps += extensionBatch;
2481
+ this.maxCircuitBreaker = this.maxSteps;
2482
+ this.emitEvent({ type: 'status', message: `⚡ Tier budget extended (+${extensionBatch} steps unlocked, new limit: ${this.maxSteps}). Resuming task...` });
2483
+ }
2484
+
2485
+ // Feed result back to LLM (4. OBSERVE)
2486
+ if (result && result._is_image_marker) {
2487
+ if (!this.llm.supportsVision) {
2488
+ // Fallback for blind models
2489
+ this.messages.push({
2490
+ role: 'tool',
2491
+ tool_call_id: toolCall.id,
2492
+ name: functionName,
2493
+ content: "[ERROR: The current LLM model you are using does not support Vision/Image capabilities. You cannot view images. Please rely on text tools or metadata instead.]"
2494
+ });
2495
+ } else {
2496
+ // Provider-specific format.
2497
+ //
2498
+ // This used to read `this.llm.constructor.name.includes('OpenAI')`.
2499
+ // Constructor names are not a stable provider identifier and can
2500
+ // change during packaging. Each provider declares its wire shape
2501
+ // explicitly.
2502
+ const imageContent = this.llm.imagePayloadFormat === 'openai' ? {
2503
+ type: "image_url",
2504
+ image_url: { url: `data:${result.mimeType};base64,${result.base64}` }
2505
+ } : {
2506
+ type: "image",
2507
+ source: {
2508
+ type: "base64",
2509
+ media_type: result.mimeType,
2510
+ data: result.base64
2511
+ }
2512
+ };
2513
+
2514
+ // We MUST push the tool return FIRST so tool_calls is immediately followed by tool messages
2515
+ this.messages.push({
2516
+ role: 'tool',
2517
+ tool_call_id: toolCall.id,
2518
+ name: functionName,
2519
+ content: `Image successfully captured: ${result.filename || 'image'}. Passing to vision observation.`
2520
+ });
2521
+
2522
+ // Then push the user observation message containing the image data block
2523
+ this.messages.push({
2524
+ role: 'user',
2525
+ content: [
2526
+ imageContent,
2527
+ {
2528
+ type: "text",
2529
+ text: `Image successfully loaded into vision context: ${result.filename || ''}`
2530
+ }
2531
+ ]
2532
+ });
2533
+ }
2534
+ } else {
2535
+ // SOVEREIGN CONTEXT WINDOW PROTECTION.
2536
+ // The previous implementation spread `...result` and only shortened
2537
+ // `output`, so tools that return their payload under a different key
2538
+ // (browser_act and blender_act return `log`) leaked the full
2539
+ // untruncated blob into history — and gained a redundant `output`
2540
+ // field on top. Truncate whichever string field is actually large.
2541
+ let resultString = JSON.stringify(result);
2542
+ // Per tool, not one number for all of them. A build log and a
2543
+ // source file are not equally worth their space in the window.
2544
+ const MAX_RESULT_CHARS = resultCapFor(functionName);
2545
+ let spill = null;
2546
+
2547
+ if (resultString.length > MAX_RESULT_CHARS) {
2548
+ // A1: spill the WHOLE result to disk before shortening it. The
2549
+ // previous code threw the overflow away, so the only way back to
2550
+ // it was re-running the tool — a second full execution and a
2551
+ // second full-size result in the window. Now the bytes survive
2552
+ // behind a path and recovery is one bounded read.
2553
+ // The raw result, not JSON.stringify(result): JSON escapes every
2554
+ // newline, which would land a large payload on a single line and
2555
+ // make the fs_read/ripgrep recovery route we advertise useless.
2556
+ spill = spillToolResult(result, {
2557
+ taskId: this.taskId,
2558
+ step: this.stepsCompleted,
2559
+ tool: functionName
2560
+ });
2561
+ const TRUNCATION_NOTICE = buildSpillNotice(spill);
2562
+
2563
+ const truncatedResult: any = {};
2564
+ // Budget shared across every oversized string field on the result.
2565
+ let budget = MAX_RESULT_CHARS - 2000;
2566
+
2567
+ for (const [key, value] of Object.entries(result)) {
2568
+ if (typeof value === 'string' && value.length > 500) {
2569
+ const allowance = Math.max(0, Math.min(value.length, budget));
2570
+ budget -= allowance;
2571
+ truncatedResult[key] = allowance < value.length
2572
+ ? value.substring(0, allowance) + TRUNCATION_NOTICE
2573
+ : value;
2574
+ } else if (value !== null && typeof value === 'object') {
2575
+ const serialized = JSON.stringify(value);
2576
+ if (serialized.length > budget) {
2577
+ truncatedResult[key] = spill
2578
+ ? `[${key} omitted here: ${(serialized.length / 1024).toFixed(1)} KB. The complete result is saved at ${spill.path} — read or search that file rather than re-running.]`
2579
+ : `[${key} omitted: ${(serialized.length / 1024).toFixed(1)} KB. Re-run with narrower arguments if you need it.]`;
2580
+ } else {
2581
+ budget -= serialized.length;
2582
+ truncatedResult[key] = value;
2583
+ }
2584
+ } else {
2585
+ truncatedResult[key] = value;
2586
+ }
2587
+ }
2588
+
2589
+ resultString = JSON.stringify(truncatedResult);
2590
+ }
2591
+
2592
+ // B5 — OBSERVATION COMPACTION.
2593
+ //
2594
+ // ARC Prize measured the same GPT-6 Astra weights at 62.7% under a
2595
+ // note-passing harness and 99.9% under one that compacts and reuses
2596
+ // prior work — with 49% FEWER tokens. Re-reading a file the agent
2597
+ // already read, or re-listing an unchanged directory, pays full
2598
+ // price for bytes that are verbatim identical to bytes already in
2599
+ // the window.
2600
+ //
2601
+ // Replacing the repeat with a pointer is not a loss of information:
2602
+ // "identical to step N" is strictly MORE informative than the bytes
2603
+ // alone, because it tells the model the thing did not change —
2604
+ // which after an edit is exactly the question it is asking.
2605
+ //
2606
+ // Only payloads worth the trade are folded. A small `{"success":true}`
2607
+ // ack costs less than the pointer that would replace it, and every
2608
+ // Plan updates would otherwise collide with unrelated plan updates.
2609
+ const OBSERVATION_FOLD_FLOOR = 600;
2610
+ if (resultString.length >= OBSERVATION_FOLD_FLOOR) {
2611
+ const digest = createHash('sha256').update(resultString).digest('hex');
2612
+ const seenAt = this._observationDigests.get(digest);
2613
+ if (seenAt !== undefined) {
2614
+ resultString = JSON.stringify({
2615
+ success: true,
2616
+ unchanged: true,
2617
+ output: `Identical to the result of step ${seenAt} — nothing has changed since. `
2618
+ + `That earlier result is still in your context; re-read it there rather than asking again.`
2619
+ });
2620
+ } else {
2621
+ this._observationDigests.set(digest, this.stepsCompleted + 1);
2622
+ }
2623
+ }
2624
+
2625
+ this.messages.push({
2626
+ role: 'tool',
2627
+ tool_call_id: toolCall.id,
2628
+ name: functionName,
2629
+ content: resultString,
2630
+ // Internal bookkeeping only: stripped before any provider call
2631
+ // (providers/base.js INTERNAL_MESSAGE_FIELDS). It lets the decay
2632
+ // stub keep pointing at the spill after the payload is gone.
2633
+ ...(spill ? { spillPath: spill.path } : {})
2634
+ });
2635
+ }
2636
+
2637
+ // Save state continuously after each tool loop
2638
+ this.memoryManager.saveHistory(this.messages);
2639
+ }
2640
+
2641
+ } catch (e: any) {
2642
+ // A real failure. It reaches the user as an `error` frame further down
2643
+ // this same catch; the stack is a diagnostic and stays behind the flag.
2644
+ this.debugLog(`agent loop error: ${e && e.stack ? e.stack : e}`);
2645
+ const errorType = this.classifyError(e);
2646
+
2647
+ if (e.message.includes('NO_BACKEND_URL:')) {
2648
+ this.emitEvent({ type: 'warning', message: e.message.replace('NO_BACKEND_URL: ', '') });
2649
+ break;
2650
+ }
2651
+
2652
+ // V5: Only break on fatal errors. Transient errors get fed back to LLM.
2653
+ if (errorType === 'fatal' || errorType === 'auth_error' || errorType === 'invalid_request_error') {
2654
+ this.emitEvent({ type: 'error', message: e.message });
2655
+ auditLog.log({ event: 'task_error', taskId: this.taskId, error: e.message, errorType });
2656
+
2657
+ break;
2658
+ } else {
2659
+ // A transient error. "Transient" only means the loop MAY continue —
2660
+ // it does not mean it should continue forever.
2661
+ //
2662
+ // This used to retry immediately, with no backoff and no cap, until
2663
+ // the step budget ran out. A sleeping laptop or a wifi blip therefore
2664
+ // produced up to 300 attempts against a dead endpoint, each one
2665
+ // waiting out a full connect timeout, while the status line said
2666
+ // "Thinking" and the only signal was `network_error: fetch failed`
2667
+ // repeated in red. From the outside it is indistinguishable from
2668
+ // working, and it burns the user's step budget doing nothing.
2669
+ const repeated = this.lastFailureType === errorType;
2670
+ this.consecutiveFailures = repeated ? this.consecutiveFailures + 1 : 1;
2671
+ this.lastFailureType = errorType;
2672
+
2673
+ const isNetwork = errorType === NETWORK_ERROR_TYPE;
2674
+ const detail = isNetwork ? explainNetworkError(e, this.config) : e.message;
2675
+ auditLog.log({ event: 'loop_error_recovered', taskId: this.taskId, error: e.message, errorType });
2676
+
2677
+ if (this.consecutiveFailures >= AgentLoop.MAX_CONSECUTIVE_FAILURES) {
2678
+ // Nothing is changing between attempts. Stop and say why, rather
2679
+ // than spinning until the budget is gone.
2680
+ this.emitEvent({
2681
+ type: 'error',
2682
+ message: `${detail}\n\nStopped after ${this.consecutiveFailures} attempts. `
2683
+ + 'Nothing changed between them, so retrying further would only spend your budget.'
2684
+ });
2685
+
2686
+ break;
2687
+ }
2688
+
2689
+ this.emitEvent({
2690
+ type: 'step_error',
2691
+ tool: 'agent_loop',
2692
+ error: `${detail}\n retrying (${this.consecutiveFailures} of `
2693
+ + `${AgentLoop.MAX_CONSECUTIVE_FAILURES})`
2694
+ });
2695
+
2696
+ // Back off before trying again. Hammering a failing endpoint as fast
2697
+ // as the loop can spin turns a one-second blip into a burst of
2698
+ // failures and gives the endpoint no chance to recover.
2699
+ await this.backoff(this.consecutiveFailures);
2700
+
2701
+ // Only tell the MODEL about errors the model can act on. It cannot
2702
+ // fix DNS or a firewall, and a system message per attempt grows the
2703
+ // context — and the bill — for nothing.
2704
+ if (!isNetwork) {
2705
+ this.messages.push({
2706
+ role: 'system',
2707
+ content: `[SYSTEM ERROR RECOVERED: A ${errorType} error occurred: "${e.message}". `
2708
+ + 'The loop has recovered. You may continue or try a different approach.]'
2709
+ });
2710
+ }
2711
+ }
2712
+ }
2713
+ }
2714
+
2715
+ this.emitEvent({ type: 'task_complete', taskId: this.taskId });
2716
+ }
2717
+
2718
+ async waitForApproval(toolCallId: string) {
2719
+
2720
+ return new Promise((resolve) => {
2721
+ this.pendingApprovals.set(toolCallId, resolve);
2722
+
2723
+ // Safety timeout: If user doesn't respond in 1 hour, auto-deny.
2724
+ setTimeout(() => {
2725
+ if (this.pendingApprovals.has(toolCallId)) {
2726
+ this.handleApprovalResponse(toolCallId, false);
2727
+ }
2728
+ }, 3600000);
2729
+ });
2730
+ }
2731
+
2732
+ /**
2733
+ * Wait before retrying, and stay interruptible while waiting.
2734
+ *
2735
+ * Exponential, capped. Without the abort check a user pressing esc during a
2736
+ * backoff would wait out the full delay before anything responded.
2737
+ */
2738
+ async backoff(attempt: number) {
2739
+ const delay = Math.min(8000, 500 * Math.pow(2, Math.max(0, attempt - 1)));
2740
+ await new Promise<void>((resolve) => {
2741
+ const timer = setTimeout(resolve, delay);
2742
+ if (timer.unref) timer.unref();
2743
+ const signal = this.abortController && this.abortController.signal;
2744
+ if (signal) {
2745
+ signal.addEventListener('abort', () => { clearTimeout(timer); resolve(); }, { once: true });
2746
+ }
2747
+ });
2748
+ }
2749
+
2750
+ // V5: Classify errors for intelligent retry decisions
2751
+ classifyError(error: any) {
2752
+ const msg = (error.message || '').toLowerCase();
2753
+
2754
+ if (msg.includes('syntax') || msg.includes('unexpected token') || msg.includes('invalid json')) {
2755
+ return 'syntax_error';
2756
+ }
2757
+ if (msg.includes('enoent') || msg.includes('no such file') || msg.includes('not found') || msg.includes('does not exist')) {
2758
+ return 'path_not_found';
2759
+ }
2760
+ if (msg.includes('econnrefused') || msg.includes('econnreset') || msg.includes('etimedout') || msg.includes('fetch failed') || msg.includes('network')) {
2761
+ return "network_error";
2762
+ }
2763
+ if (msg.includes('rate limit') || msg.includes('429') || msg.includes('too many requests') || msg.includes('quota')) {
2764
+ return 'rate_limit';
2765
+ }
2766
+ if (msg.includes('eacces') || msg.includes('permission denied') || msg.includes('eperm')) {
2767
+ return 'permission_denied';
2768
+ }
2769
+ if (msg.includes('401') || msg.includes('403') || msg.includes('unauthorized') || msg.includes('api key')) {
2770
+ return 'auth_error';
2771
+ }
2772
+ if (msg.includes('400') || msg.includes('invalid_parameter') || msg.includes('invalid_request') || msg.includes('required property') || msg.includes('bad request')) {
2773
+ return 'invalid_request_error';
2774
+ }
2775
+ if (msg.includes('kill') || msg.includes('abort') || msg.includes('signal') || msg.includes('fatal')) {
2776
+ return 'fatal';
2777
+ }
2778
+
2779
+ return 'unknown_error';
2780
+ }
2781
+
2782
+ // V5: Provide actionable retry hints per error type
2783
+ getRetryHint(errorType: string) {
2784
+ const hints: Record<string, string> = {
2785
+ 'syntax_error': 'Check your command syntax or JSON structure. Ensure quotes are balanced.',
2786
+ 'path_not_found': 'The file or directory does not exist. Use fs.list to verify the path first, or create it with fs.write/mkdir.',
2787
+ ["network_error"]: "Network connectivity issue. Wait a moment and retry. If persistent, check if the URL is correct.",
2788
+ 'rate_limit': 'API rate limit hit. Wait 5-10 seconds before retrying.',
2789
+ 'permission_denied': 'Permission denied. Check if the path is within allowed workspace paths. Try a different directory.',
2790
+ 'auth_error': 'Authentication failed. Do NOT retry — the API key may be invalid.',
2791
+ 'invalid_request_error': 'API request format error (400 Bad Request). Do NOT retry — check model parameter compliance.',
2792
+ 'unknown_error': 'An unexpected error occurred. Try a different approach entirely.'
2793
+ };
2794
+ return hints[errorType] || hints['unknown_error'];
2795
+ }
2796
+
2797
+ async runPreToolUse(toolName: string, args: any, toolCallId: string) {
2798
+ return runConfiguredHooks({
2799
+ hooks: this.config?.hooks,
2800
+ event: 'PreToolUse',
2801
+ toolName,
2802
+ args,
2803
+ taskId: this.taskId,
2804
+ toolCallId,
2805
+ workspacePaths: this.sandbox?.workspacePaths
2806
+ });
2807
+ }
2808
+
2809
+ async runPostToolUse(toolName: string, args: any, result: any) {
2810
+ return runConfiguredHooks({
2811
+ hooks: this.config?.hooks,
2812
+ event: 'PostToolUse',
2813
+ toolName,
2814
+ args,
2815
+ result,
2816
+ taskId: this.taskId,
2817
+ workspacePaths: this.sandbox?.workspacePaths
2818
+ });
2819
+ }
2820
+
2821
+ // V5: Validate tool call arguments before execution
2822
+
2823
+ validateToolArgs(toolName: string, args: any) {
2824
+ // Check for common LLM mistakes
2825
+
2826
+ // 1. File operations must have absolute paths
2827
+ const pathFields = ['path', 'source', 'destination'];
2828
+ for (const field of pathFields) {
2829
+ if (args[field] && typeof args[field] === 'string') {
2830
+ // Auto-fix relative paths by prepending cwd
2831
+ if (!args[field].startsWith('/') && !args[field].startsWith('~')) {
2832
+ args[field] = `${process.cwd()}/${args[field]}`;
2833
+ }
2834
+ }
2835
+ }
2836
+
2837
+ // 2. Terminal commands must have a command string
2838
+ if ((toolName === 'sysRun' || toolName === 'sysRunBg') && !args.command) {
2839
+ return 'Missing required "command" argument';
2840
+ }
2841
+
2842
+ // 3. File write must have a path AND content.
2843
+ //
2844
+ // These branches were dead: canonicalToolName() (called on every tool name
2845
+ // before this runs) normalises '.'→'_', so `toolName` is 'fs_write', never
2846
+ // 'fs.write'. The old 'fs.write' / 'codebase.search' / 'web.search' literals
2847
+ // could never match, so the model's missing-argument mistakes reached the
2848
+ // tool as runtime exceptions instead of a corrective message. Matched on the
2849
+ // canonical names now, and fs_write's `content` is actually checked (the old
2850
+ // comment said "must have content" but the code only looked at `path`).
2851
+ if (toolName === 'fs_write' && !args.path) {
2852
+ return 'Missing required "path" argument';
2853
+ }
2854
+ if (toolName === 'fs_write' && args.content === undefined) {
2855
+ return 'Missing required "content" argument';
2856
+ }
2857
+
2858
+ // 4. Search must have a query
2859
+ if ((toolName === 'codebase_search' || toolName === 'web_search') && !args.query) {
2860
+ return 'Missing required "query" argument';
2861
+ }
2862
+
2863
+ return null; // No validation errors
2864
+ }
2865
+ }