@causyne/agent 1.20.0 → 1.20.7

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 (130) hide show
  1. package/README.md +13 -9
  2. package/SECURITY.md +1 -4
  3. package/package.json +1 -1
  4. package/src/acp/client.js +176 -26
  5. package/src/acp/client.ts +167 -25
  6. package/src/acp/protocol.js +116 -0
  7. package/src/acp/protocol.ts +163 -0
  8. package/src/acp/server.js +5 -6
  9. package/src/acp/server.ts +4 -6
  10. package/src/agentLoop.d.ts +1 -0
  11. package/src/agentLoop.js +681 -245
  12. package/src/agentLoop.ts +708 -262
  13. package/src/agentPolicy.js +9 -0
  14. package/src/agentPolicy.ts +9 -0
  15. package/src/approvalPolicy.js +55 -0
  16. package/src/approvalPolicy.ts +66 -0
  17. package/src/browser/browserRuntime.js +217 -14
  18. package/src/browser/browserRuntime.ts +255 -14
  19. package/src/browser/causyneBrowser.js +1215 -68
  20. package/src/browser/causyneBrowser.ts +1340 -72
  21. package/src/cliMode.js +52 -29
  22. package/src/commands.js +141 -17
  23. package/src/config.js +22 -12
  24. package/src/continuum/ui/continuumPicker.js +18 -1
  25. package/src/continuum/ui/continuumPicker.ts +19 -1
  26. package/src/dynamicCatalogue.js +87 -20
  27. package/src/dynamicCatalogue.ts +85 -15
  28. package/src/launchIntent.js +40 -0
  29. package/src/launchIntent.ts +49 -0
  30. package/src/memoryManager.js +26 -2
  31. package/src/modelCatalogue.js +2 -0
  32. package/src/planCache.js +320 -11
  33. package/src/planCache.ts +402 -13
  34. package/src/providers/acp.js +173 -18
  35. package/src/providers/acp.ts +169 -19
  36. package/src/providers/antigravity.d.ts +5 -1
  37. package/src/providers/antigravity.js +674 -34
  38. package/src/providers/antigravity.ts +707 -35
  39. package/src/providers/base.d.ts +10 -0
  40. package/src/providers/factory.js +2 -0
  41. package/src/providers/pi.js +161 -0
  42. package/src/providers/pi.ts +148 -0
  43. package/src/provisioning/capabilityProvisioner.js +17 -0
  44. package/src/provisioning/capabilityTools.js +1 -1
  45. package/src/sandbox.js +30 -39
  46. package/src/sessionJournal.js +53 -10
  47. package/src/sessionJournal.ts +64 -10
  48. package/src/taskShape.js +9 -9
  49. package/src/taskShape.ts +9 -9
  50. package/src/timeMachine.js +124 -0
  51. package/src/timeMachine.ts +141 -0
  52. package/src/toolPacks.js +4 -10
  53. package/src/tools/archive.js +196 -59
  54. package/src/tools/archive.ts +220 -0
  55. package/src/tools/browserAutomator.js +78 -9
  56. package/src/tools/browserAutomator.ts +90 -9
  57. package/src/tools/desktopOpen.js +114 -31
  58. package/src/tools/desktopOpen.ts +144 -0
  59. package/src/tools/gitExec.js +5 -3
  60. package/src/tools/nativeEngine.js +4 -3
  61. package/src/tools/nativeEngine.ts +5 -3
  62. package/src/tools/openSourceToolProvisioner.js +5 -4
  63. package/src/tools/openSourceToolProvisioner.ts +5 -4
  64. package/src/tools/registry.js +3 -0
  65. package/src/tools/screenshot.js +55 -71
  66. package/src/tools/screenshot.ts +70 -0
  67. package/src/tools/sysRun.js +284 -117
  68. package/src/tools/sysRun.ts +347 -0
  69. package/src/tools/toolSelfRepair.js +109 -2
  70. package/src/tools/toolSelfRepair.ts +100 -2
  71. package/src/tools/updatePlan.js +49 -1
  72. package/src/tools/updatePlan.ts +43 -1
  73. package/src/tools/viewImage.js +93 -78
  74. package/src/tools/viewImage.ts +116 -0
  75. package/src/tools/webFetch.js +20 -6
  76. package/src/tools/webFetch.ts +26 -6
  77. package/src/tui/activityLayout.js +9 -0
  78. package/src/tui/activityLayout.ts +10 -0
  79. package/src/tui/block.d.ts +1 -0
  80. package/src/tui/chatRenderer.d.ts +23 -0
  81. package/src/tui/chatRenderer.js +49 -49
  82. package/src/tui/clipboardSync.js +28 -1
  83. package/src/tui/clipboardSync.ts +26 -1
  84. package/src/tui/codeProgress.js +299 -0
  85. package/src/tui/codeProgress.ts +304 -0
  86. package/src/tui/codeStreamRenderer.js +132 -0
  87. package/src/tui/codeStreamRenderer.ts +141 -0
  88. package/src/tui/commandPresentation.js +11 -0
  89. package/src/tui/commandPresentation.ts +18 -0
  90. package/src/tui/completion.js +45 -13
  91. package/src/tui/composerControls.js +131 -0
  92. package/src/tui/composerControls.ts +184 -0
  93. package/src/tui/diff.d.ts +2 -0
  94. package/src/tui/home.js +4 -2
  95. package/src/tui/homeTransition.js +21 -0
  96. package/src/tui/homeTransition.ts +27 -0
  97. package/src/tui/homeView.js +62 -0
  98. package/src/tui/homeView.ts +91 -0
  99. package/src/tui/layout.js +46 -0
  100. package/src/tui/layout.ts +52 -0
  101. package/src/tui/messageActionPlacement.js +16 -0
  102. package/src/tui/messageActionPlacement.ts +25 -0
  103. package/src/tui/messageInteraction.js +221 -0
  104. package/src/tui/messageInteraction.ts +275 -0
  105. package/src/tui/modelPicker.js +4 -24
  106. package/src/tui/modelPicker.ts +4 -20
  107. package/src/tui/mouseHover.js +6 -0
  108. package/src/tui/mouseHover.ts +5 -0
  109. package/src/tui/prompt.js +175 -101
  110. package/src/tui/resizeRecovery.js +15 -0
  111. package/src/tui/resizeRecovery.ts +27 -0
  112. package/src/tui/scrollInteraction.js +97 -0
  113. package/src/tui/scrollInteraction.ts +189 -0
  114. package/src/tui/sessionLayout.js +12 -0
  115. package/src/tui/sessionLayout.ts +12 -0
  116. package/src/tui/sessionPicker.js +111 -16
  117. package/src/tui/sessionPicker.ts +121 -16
  118. package/src/tui/sessionSidebar.js +78 -0
  119. package/src/tui/sessionSidebar.ts +95 -0
  120. package/src/tui/setup.js +1 -1
  121. package/src/tui/setup.ts +1 -1
  122. package/src/tui/stageSurface.js +120 -58
  123. package/src/tui/text.d.ts +6 -0
  124. package/src/tui/textLayout.js +23 -0
  125. package/src/tui/textLayout.ts +28 -0
  126. package/src/tui/viewport.js +204 -279
  127. package/src/tui/viewport.ts +326 -0
  128. package/src/types/contracts.ts +54 -0
  129. package/src/utils/paths.js +5 -4
  130. package/src/utils/paths.ts +5 -5
package/src/agentLoop.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'crypto';
2
- import { processApprovalScope } from './approvalGrants.js';
2
+ import { processApprovalScope, createApprovalScope } from './approvalGrants.js';
3
3
  import { pruneSessions as pruneEmbodimentSessions, describeSession } from './embodimentSession.js';
4
4
  import { WorkspacePerception } from './perception.js';
5
5
  import { audioFormatForMimeType } from './providers/base.js';
@@ -18,12 +18,25 @@ import { MemoryManager } from './memoryManager.js';
18
18
  import { cortexDb } from './cortex/vectorDb.js';
19
19
  import { buildStructuralSummary, condenseAndSave } from './cortex/autoCondenser.js';
20
20
  import { analyzeTask, buildTaskBrief, packsFromShape } from './taskShape.js';
21
- import { lookupPlan, recordPlan, recordMiss, renderPlanHint, toStep } from './planCache.js';
21
+ import {
22
+ lookupPlan,
23
+ recordPlan,
24
+ recordPlanAsync,
25
+ recordMiss,
26
+ renderPlanHint,
27
+ toStep,
28
+ recordAPCPipelineLatency,
29
+ lookupAlternativeStep,
30
+ failureClass
31
+ } from './planCache.js';
22
32
  import { routedConfig } from './modelRouter.js';
23
33
  import { assessStep, isThrashing } from './uncertainty.js';
24
34
  import { assessDecisionRequirement, isMutatingToolCall, requiresImplementationPlan } from './decisionPolicy.js';
35
+ import { requiresToolApproval, withToolAutonomyMode } from './approvalPolicy.js';
36
+ import { AGENT_USER_POLICY } from './agentPolicy.js';
25
37
  import { VFETracker } from './vfeTracker.js';
26
38
  import { coldObserver } from './observer/coldObserver.js';
39
+ import { TimeMachine, recoveryUserMessage } from './timeMachine.js';
27
40
  import {
28
41
  routePacks,
29
42
  packForTool,
@@ -53,10 +66,13 @@ import { spillToolResult, buildSpillNotice, buildDecayPointer, pruneOutputStore
53
66
  import { beginTask as beginCheckpointTask, captureBeforeMutation, pruneStore as pruneCheckpointStore, resolveProjectRoot } from './checkpoints.js';
54
67
  import fsSync from 'fs';
55
68
  import os from 'os';
69
+ import path from 'path';
56
70
  import { analyzeFiles, formatFindings, isScannableFile } from './slopDetector.js';
57
71
  import { suggestMovements, formatMovementBrief } from './designPalettes.js';
58
72
  import { createProvider } from './providers/factory.js';
59
73
  import { resolveMentionedContext } from './promptMentions.js';
74
+ import { isLaunchOnlyPrompt, launchScopeError } from './launchIntent.js';
75
+ import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from './tui/codeProgress.js';
60
76
 
61
77
  export interface AgentLoopEvent {
62
78
  type: string;
@@ -94,24 +110,130 @@ export interface AgentLoopOptions {
94
110
  approvalScope?: AgentLoopApprovalScope;
95
111
  }
96
112
 
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.
113
+ export function isActionableTaskPrompt(text: string): boolean {
114
+ const t = (text || '').trim();
115
+ if (!t) return false;
116
+ const pureGreeting = /^(hi|hello|hey|yo|good\s+(morning|afternoon|evening))[.!?, ]*$/i.test(t);
117
+ if (pureGreeting) return false;
118
+ const actionKeywords = /\b(create|build|make|write|code|implement|fix|optimize|refactor|generate|add|setup|install|run|open|launch|start|play|serve|preview|deploy|delete|remove|update|change|test|review|inspect|search|find)\b/i;
119
+ return actionKeywords.test(t);
120
+ }
121
+
122
+ export function isExecutionOrLaunchTaskPrompt(text: string): boolean {
123
+ const t = (text || '').trim();
124
+ if (!t) return false;
125
+ return /\b(open|launch|start|run|play|serve|preview)\b/i.test(t)
126
+ && !/\b(create|build|make|write|code|implement|generate|refactor)\b/i.test(t);
127
+ }
128
+
129
+ export function isCodeAuthoringTaskPrompt(text: string): boolean {
130
+ const t = (text || '').trim();
131
+ if (!t) return false;
132
+ if (isExecutionOrLaunchTaskPrompt(t)) return false;
133
+ return /\b(create|build|make|write|code|implement|generate|game|3js|threejs|three\.js|app)\b/i.test(t);
134
+ }
135
+
136
+ export function isDirectGameTask(text: string): boolean {
137
+ return /\b(three\.?js|3js|webgl|canvas|html5|pygame)\b/i.test(text)
138
+ && !/\b(godot|unity|unreal|full engine)\b/i.test(text);
139
+ }
140
+
141
+ /**
142
+ * Detects when an agent response is an intermediate mid-task progress note or
143
+ * transition announcement (e.g. "Real assets verified. Writing the Tesla-style
144
+ * redesign now." or "Let me look at the newer assets... Pulling their real
145
+ * stills and confirming embeddability.") rather than a finished answer.
146
+ */
147
+ export function isMidTaskProgressText(text: string): boolean {
148
+ if (!text || typeof text !== 'string') return false;
149
+ const trimmed = text.trim();
150
+ if (!trimmed || trimmed.length > 480) return false;
151
+
152
+ const lower = trimmed.toLowerCase();
153
+ if (
154
+ lower.includes('?') ||
155
+ lower.includes('let me know') ||
156
+ lower.includes('how can i help') ||
157
+ lower.includes('how may i help') ||
158
+ lower.includes('how can i assist') ||
159
+ lower.includes('what would you like') ||
160
+ lower.includes('what can i help') ||
161
+ lower.includes('feel free to')
162
+ ) {
163
+ return false;
164
+ }
165
+
166
+ if (trimmed.includes('```')) return false;
167
+
168
+ const sentences = trimmed
169
+ .split(/(?:(?<=[.!])\s+|\n+)/)
170
+ .map(s => s.trim())
171
+ .filter(Boolean);
172
+ const lastSentence = (sentences[sentences.length - 1] || trimmed).trim();
173
+ const lastLower = lastSentence.toLowerCase();
174
+
175
+ if (trimmed.length <= 280 && (trimmed.endsWith(':') || trimmed.endsWith('...') || trimmed.endsWith('…'))) {
176
+ return true;
177
+ }
178
+
179
+ const intentPrefixes = [
180
+ 'let me ',
181
+ "i'll ",
182
+ 'i will ',
183
+ 'now i ',
184
+ 'now let me ',
185
+ "now i'll ",
186
+ 'now i will ',
187
+ 'next, i ',
188
+ 'next i ',
189
+ "next, i'll ",
190
+ "next i'll ",
191
+ 'first, i ',
192
+ 'first i ',
193
+ 'let us ',
194
+ "let's ",
195
+ 'i shall ',
196
+ 'we will ',
197
+ "we'll ",
198
+ 'i am going to ',
199
+ "i'm going to ",
200
+ 'going to '
201
+ ];
202
+ if (intentPrefixes.some(prefix => lastLower.startsWith(prefix) || lower.startsWith(prefix))) {
203
+ if (!/\b(?:task completed|all done|everything is ready|finished|complete\.)\b/i.test(lastSentence)) {
204
+ return true;
205
+ }
206
+ }
207
+
208
+ const gerundStart = /^(?:now\s+|next,?\s+|currently\s+|still\s+)?(?:writing|pulling|checking|inspecting|building|creating|updating|applying|implementing|generating|fetching|downloading|testing|running|fixing|setting up|configuring|refactoring|adding|modifying|replacing|launching|starting|verifying|confirming|reading|searching|analyzing|preparing|compiling|rendering|extracting|installing|opening|switching|retrying|continuing)\b/i;
209
+ if (gerundStart.test(lastSentence) && lastSentence.length <= 220) {
210
+ return true;
211
+ }
212
+
213
+ const actionNowSuffix = /\b(?:writing|pulling|checking|inspecting|building|creating|updating|applying|implementing|generating|fetching|downloading|testing|running|fixing|configuring|refactoring|adding|modifying|replacing|launching|starting|verifying|confirming|reading|searching|analyzing|preparing|compiling|rendering|extracting)\b[^.!?\n]{1,120}\b(?:now|next)\.?$/i;
214
+ if (actionNowSuffix.test(lastSentence)) {
215
+ return true;
216
+ }
217
+
218
+ return false;
219
+ }
220
+
221
+ const SYSTEM_PROMPT = `You are Causyne Agent, an autonomous local AI agent. Your capabilities are the tools actually available in this session. Never invent a capability or claim an action occurred without evidence.
98
222
 
99
223
  # 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).
224
+ Use only tools actually present and permitted in this session. Read each tool result before reporting an outcome. A user message that only asks a question or greets you may be answered directly without calling a tool.
225
+
226
+ ${AGENT_USER_POLICY}
105
227
 
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.
228
+ # Project Conventions
229
+ Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
110
230
 
111
231
  # Operational Guidelines & Communication
232
+ - **Language Reflection**: Dynamically reflect and match the exact language used by the user in their prompt. If the user communicates in English, communicate strictly in English. Default language is English. Never use or default to Indonesian unless the user explicitly speaks to you in Indonesian.
112
233
  - **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.
234
+ - **Evidence-Based Recovery Reports**: State only observed tool results and checks. Never claim a failed task was fixed without a passing check. Keep failure reports brief; if the user requests a detailed report, write it to a Markdown file in their selected workspace and give its path instead of dumping it into chat.
235
+ - **Status Updates**: For substantial work, give brief progress notes while using tools. Use a tool when it contributes to the task, and report what it actually returned.
236
+ - **Clarify Only When Needed**: Make routine implementation choices yourself. Ask when an unresolved choice or missing user-only input genuinely blocks progress; continue independent work while waiting.
115
237
  - **No Chitchat**: Tools are for actions, text output is *only* for communication. Do not add explanatory comments within tool calls or code blocks.
116
238
  - **File Paths**: ALWAYS output the absolute path of any file you create, modify, or generate so the user knows exactly where it is.
117
239
 
@@ -124,10 +246,8 @@ Specifically, you excel at:
124
246
  - 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
247
  - 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
248
 
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.
249
+ # Efficient Tool Use
250
+ - Batch independent searches and reads when useful. Keep edits, dependent operations, approvals, and verification in a safe order. Never run conflicting writes concurrently.
131
251
 
132
252
  # Context Understanding & Searching
133
253
  - Semantic search (or grep) is your MAIN exploration tool. Start with a broad, high-level query.
@@ -149,7 +269,7 @@ Specifically, you excel at:
149
269
  - **Token Budgeting**: You must respect the user's BYOK (Bring Your Own Key) limits. Be highly token-efficient.
150
270
  - **Explain Critical Commands**: Before executing destructive shell commands, provide a brief explanation of the impact.
151
271
  - **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.
272
+ - **Sandboxing**: Keep workspace checks and hard safety blocks active. In Mode C, ordinary in-scope edits and tool calls do not need approval; deleting an entire file or directory does. Removing or replacing lines while editing a file is not whole-file deletion.
153
273
  - **SSRF Protection**: Do not fetch internal IPs (127.0.0.1, 169.254.x.x, 10.x.x.x).
154
274
 
155
275
  # ABSOLUTE ETHICAL SAFETY NET (NON-NEGOTIABLE)
@@ -168,7 +288,7 @@ If asked to perform ANY harmful task, politely decline, state that Causyne exist
168
288
  # Dependency Management & Autonomy Modes
169
289
  - **Mode A (Passive)**: You MUST explicitly ask the user for permission (by ending your turn and asking a question) before installing any dependencies.
170
290
  - **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.
291
+ - **Mode C (Autonomous)**: Work independently within the user's task and selected workspace. Ordinary in-scope actions do not require an approval dialog. Whole-file or directory deletion requires approval. Hard policy blocks, workspace boundaries, and explicit user limits still apply.
172
292
 
173
293
  # Direct API & Automation Policy
174
294
  - **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.
@@ -179,9 +299,8 @@ If asked to perform ANY harmful task, politely decline, state that Causyne exist
179
299
  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
300
  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
301
 
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!
302
+ # Completion
303
+ Answer directly when no tool is needed. For action tasks, continue until the authorized work is done or a real blocker is evidenced; then report the verified outcome or blocker concisely.
185
304
  `;
186
305
 
187
306
  function getProviderSpecificPrompt(provider: string = '') {
@@ -422,6 +541,8 @@ export class AgentLoop {
422
541
 
423
542
  this.consecutiveThinkingSteps = 0;
424
543
  this.consecutiveBlockedActions = 0; // V8 Transcendence: Circuit Breaker
544
+ this.recentActionSignatures = [];
545
+ this.consecutiveReadOnlySteps = 0;
425
546
 
426
547
  // Sovereign Progressive Disclosure: which capability packs have entered the
427
548
  // context window for this task. Nothing is disabled — see src/toolPacks.js.
@@ -455,7 +576,6 @@ export class AgentLoop {
455
576
  // P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
456
577
  this.webArtifacts = new Set();
457
578
  this.slopGateFired = false;
458
- this.coldObserverGuardFired = false;
459
579
 
460
580
  this.gameCascadeState = { active: true, currentStage: 1, stageHistory: [], verificationPassed: false };
461
581
  this.gameToolStats = { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
@@ -465,9 +585,7 @@ export class AgentLoop {
465
585
 
466
586
  // V5: Context compaction tracking
467
587
  this._lastCompactionIndex = null;
468
- // V5: Error recovery tracking (per tool call)
469
- // V5: Error recovery tracking (per tool call)
470
- this._toolRetryCount = new Map();
588
+ this.timeMachine = new TimeMachine();
471
589
  this.isInitialized = false;
472
590
  this.taskTemperature = 0.1; // Default
473
591
  // Set only on a delegated subagent loop; null means "the full catalogue".
@@ -479,6 +597,24 @@ export class AgentLoop {
479
597
  return this.approvalScope.isAlwaysAllowed(toolName);
480
598
  }
481
599
 
600
+ /**
601
+ * Reset all standing tool approvals, allowlists, and autonomy overrides.
602
+ *
603
+ * Critical security invariant (Claude Code Architecture, p. 24):
604
+ * When a session is forked or reset, permissions and standing approvals
605
+ * must NEVER carry over into the new branch. A forked session starts with
606
+ * fresh, ungranted permissions so that user authorization must be re-verified.
607
+ */
608
+ resetApprovalScope(): void {
609
+ if (this.approvalScope && typeof this.approvalScope.revokeAllAlways === 'function') {
610
+ this.approvalScope.revokeAllAlways();
611
+ }
612
+ this.approvalScope = createApprovalScope();
613
+ this.autonomyOverride = null;
614
+ this.circuitBreakerUnlocked = false;
615
+ this.pendingApprovals.clear();
616
+ }
617
+
482
618
  // V6: Adaptive Temperature based on task intent
483
619
  determineTemperature(prompt: string) {
484
620
  if (!prompt) return 0.1;
@@ -537,7 +673,7 @@ export class AgentLoop {
537
673
  // Anti-Slop: Design Context Awareness (what design system is already installed)
538
674
  let designContext = '';
539
675
  try {
540
- const detectedDesign = await this.perception.detectDesignContext(process.cwd());
676
+ const detectedDesign = await this.perception.detectDesignContext(this.workspaceRoot);
541
677
  if (detectedDesign && detectedDesign.length > 0) {
542
678
  designContext = `\nDETECTED DESIGN SYSTEM IN WORKSPACE: ${detectedDesign.join(', ')} — USE THIS. Do NOT install a conflicting system.`;
543
679
  }
@@ -559,7 +695,7 @@ export class AgentLoop {
559
695
  // Universal skills awareness
560
696
  let universalSkillsContext = '';
561
697
  try {
562
- const detectedDomains = detectWorkspaceDomains(process.cwd());
698
+ const detectedDomains = detectWorkspaceDomains(this.workspaceRoot);
563
699
  if (detectedDomains.length > 0) {
564
700
  this.debugLog(`detected workspace domains: ${detectedDomains.join(', ')}`);
565
701
  for (const domain of detectedDomains) {
@@ -595,6 +731,24 @@ export class AgentLoop {
595
731
  if (this.abortController) {
596
732
  this.abortController.abort();
597
733
  }
734
+ if (this.llm && typeof (this.llm as any).abort === 'function') {
735
+ try {
736
+ (this.llm as any).abort();
737
+ } catch {
738
+ // ignore provider abort errors
739
+ }
740
+ } else if (this.llm && typeof (this.llm as any).close === 'function') {
741
+ try {
742
+ void (this.llm as any).close();
743
+ } catch {
744
+ // ignore provider close errors
745
+ }
746
+ }
747
+ if (this.pendingApprovals && this.pendingApprovals.size > 0) {
748
+ for (const toolCallId of [...this.pendingApprovals.keys()]) {
749
+ this.handleApprovalResponse(toolCallId, false);
750
+ }
751
+ }
598
752
  }
599
753
 
600
754
  setAutonomyMode(mode: string) {
@@ -728,11 +882,11 @@ export class AgentLoop {
728
882
  const resolve = resolvers.get(item.toolCall.id);
729
883
  if (this.stopRequested || this.abortController.signal.aborted) { resolve(null); continue; }
730
884
  try {
731
- resolve(await item.tool.execute(item.args, {
885
+ resolve(await withToolAutonomyMode(this.config.autonomyMode || 'C', () => item.tool.execute(item.args, {
732
886
  signal: this.abortController.signal,
733
887
  parentLoop: this,
734
888
  ...this.sandbox
735
- }));
889
+ })));
736
890
  } catch (e: any) {
737
891
  resolve(null); // let the serial path fail it, with its own retries
738
892
  }
@@ -840,8 +994,11 @@ export class AgentLoop {
840
994
  this.config = loadConfig();
841
995
  if (this.autonomyOverride) this.config.autonomyMode = this.autonomyOverride;
842
996
  if (typeof this.initializeProvider === 'function') {
843
- this.llm = this.initializeProvider();
844
- this._utilityLlm = null; // the route is derived from the model; re-derive it
997
+ const nextProvider = this.initializeProvider();
998
+ if (nextProvider) {
999
+ this.llm = nextProvider;
1000
+ this._utilityLlm = null; // the route is derived from the model; re-derive it
1001
+ }
845
1002
  }
846
1003
  if (this.tokenTracker) {
847
1004
  this.tokenTracker.config = this.config;
@@ -890,8 +1047,10 @@ export class AgentLoop {
890
1047
  // awareness instead of burning steps rediscovering it. The result used to be
891
1048
  // assigned to a local variable and thrown away.
892
1049
  auditLog.log({ event: 'task_start', taskId: this.taskId, request: this.userPrompt });
893
- this.workspaceRoot = process.cwd();
1050
+ // Preserve an explicit workspace selected by the caller (for example ACP).
1051
+ // The constructor already defaults to process.cwd() when none was supplied.
894
1052
  coldObserver.beginTask(this.taskId);
1053
+ this.timeMachine.reset();
895
1054
  this.emitEvent({ type: 'status', message: 'Analyzing workspace...' });
896
1055
 
897
1056
  // P2: open the undo group for this task. This snapshots the CONVERSATION as
@@ -925,18 +1084,22 @@ export class AgentLoop {
925
1084
  // return $HOME or a system root, so the checkpoint covers the code being
926
1085
  // worked on or honestly covers nothing at all.
927
1086
  workspaceRoots: [
928
- resolveProjectRoot(process.cwd()),
929
- process.cwd(),
1087
+ resolveProjectRoot(this.workspaceRoot),
1088
+ this.workspaceRoot,
930
1089
  ...(this.sandbox.grantAllAccess ? [] : (this.sandbox.workspacePaths || []))
931
1090
  ].filter(Boolean)
932
1091
  });
933
1092
 
934
1093
  try {
935
- this.workspaceContext = await this.perception.buildContext(process.cwd());
1094
+ this.workspaceContext = await this.perception.buildContext(this.workspaceRoot);
936
1095
  } catch (perceptionError: any) {
937
1096
  this.debugLog(`workspace scan failed: ${perceptionError.message}`);
938
1097
  this.workspaceContext = null;
939
1098
  }
1099
+ if (this.stopRequested || this.abortController?.signal?.aborted) {
1100
+ auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
1101
+ return;
1102
+ }
940
1103
 
941
1104
  // 2. ANALYSE TASK SHAPE & PRE-WARM CAPABILITY PACKS.
942
1105
  // A game request gets the full game toolset from step one with no discovery
@@ -947,7 +1110,6 @@ export class AgentLoop {
947
1110
  this.webGuardFired = false;
948
1111
  this.webArtifacts = new Set();
949
1112
  this.slopGateFired = false;
950
- this.coldObserverGuardFired = false;
951
1113
  this.staticContext = null;
952
1114
  // Plan cache: the procedure THIS task follows, and the template (if any)
953
1115
  // that was offered to it. Both reset per task — a plan is a property of one
@@ -963,7 +1125,9 @@ export class AgentLoop {
963
1125
  this._decisionAnswers = new Map();
964
1126
  this._decisionRequirement = assessDecisionRequirement(this.userPrompt || '');
965
1127
  this._decisionResolved = !this._decisionRequirement.required;
966
- this._implementationPlanRequired = false;
1128
+ this._taskStartedAt = performance.now();
1129
+ this._totalPlanMs = 0;
1130
+ this._totalActMs = 0;
967
1131
  if (this.vfeTracker) this.vfeTracker.reset();
968
1132
 
969
1133
  if (this.userPrompt) {
@@ -985,6 +1149,7 @@ export class AgentLoop {
985
1149
  const scored = packsFromShape(this.taskShape);
986
1150
  const fallback = routePacks(this.userPrompt, this.workspaceContext);
987
1151
  for (const pack of [...scored, ...fallback]) {
1152
+ if (pack === 'game' && isDirectGameTask(this.userPrompt)) continue;
988
1153
  this.unlockPack(pack);
989
1154
  }
990
1155
 
@@ -1044,7 +1209,7 @@ export class AgentLoop {
1044
1209
  try {
1045
1210
  const subprojects = this.workspaceContext?.subprojects || [];
1046
1211
  const mentionResult = await resolveMentionedContext(this.userPrompt, {
1047
- cwd: process.cwd(),
1212
+ cwd: this.workspaceRoot,
1048
1213
  subprojects
1049
1214
  });
1050
1215
 
@@ -1052,12 +1217,14 @@ export class AgentLoop {
1052
1217
  this.activeSubproject = mentionResult.detectedSubproject;
1053
1218
  this.notice(`Focused on subproject '${mentionResult.detectedSubproject}'`);
1054
1219
  } else if (subprojects.length > 0) {
1055
- const lowerPrompt = this.userPrompt.toLowerCase();
1056
1220
  for (const sp of subprojects) {
1057
- if (lowerPrompt.includes(sp.toLowerCase())) {
1058
- this.activeSubproject = sp;
1059
- this.notice(`Focused on subproject '${sp}'`);
1060
- break;
1221
+ if (sp.length >= 2) {
1222
+ const boundaryRegex = new RegExp(`(?:^|\\s|["'\`(@/\\\\])${sp.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\$&')}(?:$|\\s|["'\`):,/\\\\])`, 'i');
1223
+ if (boundaryRegex.test(this.userPrompt)) {
1224
+ this.activeSubproject = sp;
1225
+ this.notice(`Focused on subproject '${sp}'`);
1226
+ break;
1227
+ }
1061
1228
  }
1062
1229
  }
1063
1230
  }
@@ -1153,7 +1320,7 @@ export class AgentLoop {
1153
1320
  const path = await import('path');
1154
1321
  // Ensure unique name to prevent overwriting
1155
1322
  const safeName = att.name.replace(/[^a-zA-Z0-9.\-_]/g, '_');
1156
- const writePath = path.join(process.cwd(), safeName);
1323
+ const writePath = path.join(this.workspaceRoot, safeName);
1157
1324
  fs.writeFileSync(writePath, Buffer.from(att.base64, 'base64'));
1158
1325
 
1159
1326
  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.]`;
@@ -1162,7 +1329,12 @@ export class AgentLoop {
1162
1329
  }
1163
1330
  this.messages.push({ role: 'user', content: contentArray });
1164
1331
  } else {
1165
- this.messages.push({ role: 'user', content: this.userPrompt });
1332
+ const lastMsg = this.messages[this.messages.length - 1];
1333
+ if (lastMsg && lastMsg.role === 'user' && typeof lastMsg.content === 'string' && lastMsg.content.trim() === this.userPrompt.trim()) {
1334
+ lastMsg.content = this.userPrompt;
1335
+ } else {
1336
+ this.messages.push({ role: 'user', content: this.userPrompt });
1337
+ }
1166
1338
  }
1167
1339
 
1168
1340
  this.userPrompt = null; // Clear so we don't push it again
@@ -1175,6 +1347,8 @@ export class AgentLoop {
1175
1347
  this._observationDigests = new Map();
1176
1348
  this.consecutiveCommands = 0;
1177
1349
  this.circuitBreakerUnlocked = false;
1350
+ this.recentActionSignatures = [];
1351
+ this.consecutiveReadOnlySteps = 0;
1178
1352
  this.tokenTracker.resetTask();
1179
1353
 
1180
1354
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
@@ -1292,7 +1466,7 @@ export class AgentLoop {
1292
1466
  const autonomyMode = this.config.autonomyMode || 'C';
1293
1467
  const allowedPaths = this.sandbox.grantAllAccess
1294
1468
  ? "/ (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());
1469
+ : (this.sandbox.workspacePaths ? this.sandbox.workspacePaths.join(', ') : this.workspaceRoot);
1296
1470
  const providerPrompt = getProviderSpecificPrompt(this.config.provider);
1297
1471
  const memoryContext = getMemoryContextString();
1298
1472
 
@@ -1506,13 +1680,20 @@ export class AgentLoop {
1506
1680
  // 2. PLAN (Call LLM). dynamicTools was resolved above so the task brief
1507
1681
  // could reference the tools actually in context.
1508
1682
  let hasStreamedChunk = false;
1683
+ const streamingCode = new StreamingCodePreview();
1684
+ const nativeCodeObserver = new NativeCodeObserver(this.workspaceRoot, event => this.emitEvent(event));
1509
1685
  let reasoningAccumulated = '';
1510
1686
  let thoughtStartedAt = 0;
1511
1687
 
1512
1688
  this.emitEvent({ type: 'status', message: 'Thinking…' });
1513
1689
  this.emitEvent({ type: 'agent_activity', activity: 'Thinking…' });
1514
1690
 
1691
+ const planStepStart = performance.now();
1515
1692
  const response = await this.llm.chat(prunedMessages, {
1693
+ taskId: this.taskId,
1694
+ conversationId: this.memoryManager?.sessionId || this.taskId,
1695
+ taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
1696
+ workspaceRoot: this.workspaceRoot,
1516
1697
  tools: dynamicTools,
1517
1698
  // IARS couples escalation to a wider search. Bounded so a stuck task
1518
1699
  // cannot climb into randomness across repeated escalations.
@@ -1520,6 +1701,7 @@ export class AgentLoop {
1520
1701
  coreToolCount: dynamicTools.filter((t: any) => isCoreTool(t.name)).length,
1521
1702
  signal: this.abortController?.signal,
1522
1703
  onReasoningChunk: (chunk: string) => {
1704
+ if (this.stopRequested || this.abortController?.signal?.aborted) return;
1523
1705
  if (!thoughtStartedAt) thoughtStartedAt = Date.now();
1524
1706
  reasoningAccumulated += chunk;
1525
1707
  this.emitEvent({
@@ -1531,13 +1713,50 @@ export class AgentLoop {
1531
1713
  });
1532
1714
  },
1533
1715
  onChunk: (_chunk: string) => {
1716
+ if (this.stopRequested || this.abortController?.signal?.aborted) return;
1534
1717
  if (!hasStreamedChunk) {
1535
1718
  hasStreamedChunk = true;
1536
1719
  this.emitEvent({ type: 'status', message: 'Responding…' });
1537
1720
  this.emitEvent({ type: 'agent_activity', activity: 'Responding…' });
1538
1721
  }
1722
+ const preview = streamingCode.accept(_chunk);
1723
+ if (preview) this.emitEvent(preview);
1724
+ },
1725
+ onNativeAction: (action: any) => {
1726
+ if (this.stopRequested || this.abortController?.signal?.aborted) return;
1727
+ if (!action || typeof action.name !== 'string') return;
1728
+ const nativeCode = codeProgressFromAction(
1729
+ action.name,
1730
+ { ...(action.parameters && typeof action.parameters === 'object' ? action.parameters : {}),
1731
+ path: action.parameters?.path || action.parameters?.Path || action.detail || '' },
1732
+ `provider:${action.name}:${action.detail || ''}`,
1733
+ action.status === 'completed' ? 'done' : action.status === 'failed' ? 'failed' : 'working',
1734
+ 'provider'
1735
+ );
1736
+ if (nativeCode) {
1737
+ this.emitEvent(nativeCode);
1738
+ nativeCodeObserver.handle(nativeCode);
1739
+ }
1740
+ const detail = action.detail ? ` ${action.detail}` : '';
1741
+ if (action.status === 'running') {
1742
+ this.emitEvent({ type: 'status', message: `Acting: ${action.name}${detail}` });
1743
+ this.emitEvent({ type: 'agent_activity', activity: `Acting: ${action.name}${detail}` });
1744
+ } else if (action.status === 'completed') {
1745
+ this.emitEvent({ type: 'notice', tone: 'muted', nativeStep: true, message: `Antigravity ${action.name}${detail}` });
1746
+ } else if (action.status === 'failed') {
1747
+ this.emitEvent({ type: 'warning', message: `Antigravity could not ${action.name}${detail}` });
1748
+ }
1539
1749
  }
1540
- });
1750
+ }).finally(() => nativeCodeObserver.dispose());
1751
+ this._totalPlanMs = (this._totalPlanMs || 0) + (performance.now() - planStepStart);
1752
+
1753
+ if (this.stopRequested || this.abortController?.signal?.aborted) {
1754
+ auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
1755
+ break;
1756
+ }
1757
+
1758
+ const finalCodePreview = streamingCode.flush();
1759
+ if (finalCodePreview) this.emitEvent(finalCodePreview);
1541
1760
 
1542
1761
  // The call came back. Whatever went wrong before is no longer
1543
1762
  // consecutive — without this reset, one failure at step 2 and another
@@ -1632,18 +1851,102 @@ export class AgentLoop {
1632
1851
  }
1633
1852
  this.messages.push(assistantMsg);
1634
1853
 
1635
- if (response.content) {
1854
+ if (response.content && hasToolCalls) {
1636
1855
  this.emitEvent({ type: 'agent_message', content: response.content });
1637
1856
  }
1638
1857
 
1858
+ const externalActions = Array.isArray((response as any).externalActions)
1859
+ ? (response as any).externalActions
1860
+ : [];
1861
+ const completedExternalActions = externalActions.filter((a: any) => a && a.status === 'completed');
1862
+ const failedExternalActions = externalActions.filter((a: any) => a && a.status === 'failed');
1863
+ const hasExternalActions = completedExternalActions.length > 0;
1864
+ const isIncompleteTurn = Boolean((response as any).incompleteTurn);
1865
+
1866
+ if (hasExternalActions) {
1867
+ this.stepsCompleted += completedExternalActions.length;
1868
+ for (const extAction of completedExternalActions) {
1869
+ const actionName = String(extAction.name || '').toLowerCase();
1870
+ const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
1871
+ if (['write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content', 'fs_write', 'fs_edit', 'multiedit'].includes(actionName) && detailPath) {
1872
+ const resolvedPath = path.isAbsolute(detailPath)
1873
+ ? detailPath
1874
+ : path.resolve(this.workspaceRoot, detailPath.replace(/^~\//, os.homedir() + '/'));
1875
+ if (isScannableFile(resolvedPath)) {
1876
+ this.webArtifacts.add(resolvedPath);
1877
+ }
1878
+ }
1879
+ if (
1880
+ ['capture_browser_screenshot', 'browser_subagent', 'open_browser_url', 'browser_get_dom', 'read_browser_page'].includes(actionName) ||
1881
+ ((actionName === 'read_file' || actionName === 'view_file') && /\.(png|jpe?g|webp|gif|svg)$/i.test(detailPath))
1882
+ ) {
1883
+ this.webVerificationState.screenshotTaken = true;
1884
+ }
1885
+ }
1886
+ }
1887
+
1639
1888
  // If no tool calls, check if the agent is just thinking/planning or actually done
1640
1889
  if (!response.toolCalls || response.toolCalls.length === 0) {
1641
1890
  const contentText = response.content || '';
1642
1891
  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));
1892
+ const taskPrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
1893
+ const isActionable = isActionableTaskPrompt(taskPrompt);
1894
+
1895
+ // A native workspace action already changed the workspace. Do not
1896
+ // demand a Causyne tool call for the same work, and do not treat the
1897
+ // turn as a no-op.
1898
+ if (!hasExternalActions && failedExternalActions.length > 0 && this.consecutiveThinkingSteps < 2) {
1899
+ this.consecutiveThinkingSteps++;
1900
+ const blocked = failedExternalActions
1901
+ .map((a: any) => `${a.name}${a.detail ? ` (${a.detail})` : ''}`)
1902
+ .join(', ');
1903
+ this.emitEvent({ type: 'status', message: 'Native action blocked; switching to Causyne tools...' });
1904
+ this.emitEvent({ type: 'agent_activity', activity: 'Retrying blocked action through Causyne…' });
1905
+ this.messages.push({
1906
+ role: 'system',
1907
+ content: `[SYSTEM NOTICE: Your native action(s) were blocked: ${blocked}. Do not retry native terminal or browser tools. Instead use Causyne's XML tool call format, for example <tool_call>{"name": "sysRun", "arguments": {"command": "..."}}</tool_call>.]`
1908
+ });
1909
+ this.memoryManager.saveHistory(this.messages);
1910
+ continue;
1911
+ }
1912
+
1913
+ const isQuestionOrGreeting = lower.includes('?') ||
1914
+ lower.includes('let me know') ||
1915
+ lower.includes('how can i help') ||
1916
+ lower.includes('how may i help') ||
1917
+ lower.includes('how can i assist') ||
1918
+ lower.includes('what would you like') ||
1919
+ lower.includes('what can i help') ||
1920
+ lower.includes('feel free to');
1921
+
1922
+ // Action Enforcement on Step 0:
1923
+ // If the user instructed an actionable task (e.g. "create a 3js game..."), but the model
1924
+ // replied with a greeting, polite pleasantry, question, or refusal without calling any tools:
1925
+ if (!hasExternalActions && this.stepsCompleted === 0 && isActionable && (isQuestionOrGreeting || lower.includes('hello') || lower.includes('hi '))) {
1926
+ this.messages.pop();
1927
+ if (this.consecutiveThinkingSteps >= 2) {
1928
+ this.emitEvent({ type: 'error', message: 'The selected model did not follow the task after three attempts. No work was completed.' });
1929
+ this.memoryManager.saveHistory(this.messages);
1930
+ break;
1931
+ }
1932
+ this.consecutiveThinkingSteps++;
1933
+ this.emitEvent({ type: 'status', message: 'Enforcing task execution: rejecting greeting on actionable instruction...' });
1934
+ this.emitEvent({ type: 'agent_activity', activity: 'Enforcing tool execution…' });
1935
+ this.messages.push({
1936
+ role: 'system',
1937
+ content: isLaunchOnlyPrompt(taskPrompt)
1938
+ ? `[CURRENT TASK: "${taskPrompt}". The user asked to open the existing project. Inspect it, start its existing server in the background if needed, verify readiness, and open it. Do not write or edit files. Use the appropriate Causyne tools now.]`
1939
+ : `[CRITICAL ACTION MANDATE: The user explicitly instructed: "${taskPrompt}". You responded with a greeting or inquiry without performing any actions or writing any code. Do NOT reply with greetings, pleasantries, or ask how to help. You must immediately invoke the appropriate tools (e.g., fs_write, sysRun) to implement the user's request.]`
1940
+ });
1941
+ this.memoryManager.saveHistory(this.messages);
1942
+ continue;
1943
+ }
1645
1944
 
1646
- if (isThinking && this.consecutiveThinkingSteps < 3) {
1945
+ const thinkingKeywords = ['let me ', "i'll ", 'i will ', 'now i ', 'next, i ', 'first, i ', 'checking ', 'trying to ', 'let us ', 'going to ', 'i shall', 'we will', 'i am going to'];
1946
+ const isMidTaskProgress = !isQuestionOrGreeting && isMidTaskProgressText(contentText);
1947
+ const isThinking = !isQuestionOrGreeting && (isMidTaskProgress || thinkingKeywords.some(kw => lower.includes(kw)));
1948
+
1949
+ if (!hasExternalActions && (isThinking || isIncompleteTurn) && this.consecutiveThinkingSteps < 3) {
1647
1950
  this.consecutiveThinkingSteps++;
1648
1951
  this.emitEvent({ type: 'status', message: 'Agent planning next steps...' });
1649
1952
  this.emitEvent({ type: 'agent_activity', activity: 'Planning next actionable steps…' });
@@ -1651,26 +1954,56 @@ export class AgentLoop {
1651
1954
  // duplicated the whole turn in history on every nudge.
1652
1955
  this.messages.push({
1653
1956
  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.]'
1957
+ content: isIncompleteTurn
1958
+ ? '[SYSTEM NOTICE: Your previous turn ended before completion. Continue immediately from where you left off and invoke the next appropriate tool to complete the task.]'
1959
+ : '[SYSTEM NOTICE: You provided reasoning/planning without calling any tools. Please invoke the next appropriate tool now to continue progressing on the task.]'
1960
+ });
1961
+ this.memoryManager.saveHistory(this.messages);
1962
+ continue;
1963
+ }
1964
+
1965
+ if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && this.consecutiveThinkingSteps < 3) {
1966
+ this.consecutiveThinkingSteps++;
1967
+ if (response.content) {
1968
+ this.emitEvent({ type: 'agent_message', content: response.content });
1969
+ }
1970
+ this.emitEvent({ type: 'status', message: 'Continuing task execution...' });
1971
+ this.emitEvent({ type: 'agent_activity', activity: 'Continuing mid-task execution…' });
1972
+ this.messages.push({
1973
+ role: 'system',
1974
+ content: isIncompleteTurn
1975
+ ? '[SYSTEM NOTICE: Your previous turn ended while the task was still in progress. Continue immediately from where you left off and execute the remaining steps to complete the task.]'
1976
+ : '[SYSTEM NOTICE: You announced the next step without executing it. Continue immediately from where you left off and execute the remaining file edits or tool calls to complete the task.]'
1655
1977
  });
1656
1978
  this.memoryManager.saveHistory(this.messages);
1657
1979
  continue;
1658
1980
  }
1659
1981
 
1660
- if (this.stepsCompleted === 0 && this.consecutiveThinkingSteps < 2) {
1661
- if (lower.includes('turn completed') || lower.includes('no output produced') || !contentText.trim()) {
1982
+ if (hasExternalActions) {
1983
+ this.consecutiveThinkingSteps = 0;
1984
+ }
1985
+
1986
+ if (!hasExternalActions && this.stepsCompleted === 0 && this.consecutiveThinkingSteps < 2) {
1987
+ if (isActionable || lower.includes('turn completed') || lower.includes('no output produced') || !contentText.trim()) {
1662
1988
  this.consecutiveThinkingSteps++;
1663
1989
  this.emitEvent({ type: 'status', message: 'Nudging agent to execute actionable steps...' });
1664
1990
  this.emitEvent({ type: 'agent_activity', activity: 'Nudging agent to invoke tools…' });
1665
1991
  this.messages.push({
1666
1992
  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.]'
1993
+ content: `[SYSTEM NOTICE: An action or task was requested ("${taskPrompt}"), 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
1994
  });
1669
1995
  this.memoryManager.saveHistory(this.messages);
1670
1996
  continue;
1671
1997
  }
1672
1998
  }
1673
1999
 
2000
+ if (!hasExternalActions && this.stepsCompleted === 0 && isActionable) {
2001
+ this.messages.pop();
2002
+ this.emitEvent({ type: 'error', message: 'The selected model returned text without taking any action. No work was completed.' });
2003
+ this.memoryManager.saveHistory(this.messages);
2004
+ break;
2005
+ }
2006
+
1674
2007
  // --- COMPLETION GUARDS ---
1675
2008
  // Two hard rules learned the expensive way:
1676
2009
  // 1. Match on word boundaries. Substring matching made 'ui' fire on
@@ -1680,29 +2013,26 @@ export class AgentLoop {
1680
2013
  // consecutiveThinkingSteps, which resets on every tool call, so
1681
2014
  // a guard could block completion indefinitely and burn the whole
1682
2015
  // step budget on an already-finished task.
1683
- const taskPrompt = this.currentTaskPrompt || this.userPrompt || '';
1684
- const isGameTask = isGameIntent(taskPrompt);
2016
+ if (response.content) {
2017
+ this.emitEvent({ type: 'agent_message', content: response.content });
2018
+ }
2019
+
2020
+ const isGameTask = !isLaunchOnlyPrompt(taskPrompt) && isGameIntent(taskPrompt);
1685
2021
 
1686
2022
  this.gameToolStats = this.gameToolStats || { godot_act: 0, game_asset_fetch: 0, game_build_html5: 0, last_godot_action: null };
1687
2023
 
1688
2024
  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".
2025
+ // Production-depth enforcement is opt-in for full production tasks.
1693
2026
  const needsDepth = this.config.enforceGameDepth === true && this.stepsCompleted < 50;
1694
2027
 
1695
- if (needsVerification || needsDepth) {
2028
+ if (needsDepth) {
1696
2029
  this.gameGuardFired = true;
1697
- this.emitEvent({ type: 'status', message: '⚡ Sovereign Game Guard: Enforcing Production Depth & Quality Gate...' });
2030
+ this.emitEvent({ type: 'status', message: '⚡ Sovereign Game Guard: Checking production depth...' });
1698
2031
 
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.]`;
2032
+ const guardMsg = `[SOVEREIGN DEPTH NOTICE: You are building a Full Production Game with enforceGameDepth enabled. Current step count: ${this.stepsCompleted}. Expand the game with more levels, richer UI, complex enemy AI, or more assets before finishing. If the task is genuinely complete, state so and finish.]`;
1702
2033
 
1703
2034
  this.messages.push({ role: 'system', content: guardMsg });
1704
2035
  this.memoryManager.saveHistory(this.messages);
1705
- continue;
1706
2036
  }
1707
2037
  }
1708
2038
 
@@ -1730,13 +2060,12 @@ export class AgentLoop {
1730
2060
  const brief = formatMovementBrief(suggestMovements(recent, 3));
1731
2061
 
1732
2062
  auditLog.log({
1733
- event: 'anti_slop_block', taskId: this.taskId,
2063
+ event: 'anti_slop_notice', taskId: this.taskId,
1734
2064
  score: result.score, signals: result.findings.map((f: any) => f.id)
1735
2065
  });
1736
- this.emitEvent({ type: 'status', message: `⚡ Anti-Slop Gate: design scored ${result.score} — rebuilding.` });
2066
+ this.emitEvent({ type: 'status', message: `⚡ Anti-Slop Audit: design scored ${result.score}` });
1737
2067
  this.messages.push({ role: 'system', content: formatFindings(result, brief) });
1738
2068
  this.memoryManager.saveHistory(this.messages);
1739
- continue;
1740
2069
  }
1741
2070
 
1742
2071
  if (result.findings.length > 0) {
@@ -1753,7 +2082,7 @@ export class AgentLoop {
1753
2082
  }
1754
2083
 
1755
2084
  // Web Visual Validation Guard (Anti-Slop / Transcendence)
1756
- const isWebTask = isWebIntent(taskPrompt);
2085
+ const isWebTask = !isLaunchOnlyPrompt(taskPrompt) && isWebIntent(taskPrompt);
1757
2086
 
1758
2087
  if (isWebTask && !this.webGuardFired && this.stepsCompleted > 0) {
1759
2088
  const hasVision = this.llm.supportsVision !== false;
@@ -1791,15 +2120,17 @@ export class AgentLoop {
1791
2120
  // The verification tools live in the web pack; make sure they are
1792
2121
  // actually in context before demanding the agent use them.
1793
2122
  this.unlockPack('web');
1794
- this.emitEvent({ type: 'status', message: '⚡ Anti-Slop Guard: Forcing visual/semantic verification...' });
2123
+ this.emitEvent({ type: 'status', message: '⚡ Anti-Slop Check: Visual/semantic verification recommended.' });
1795
2124
  this.messages.push({ role: 'system', content: webGuardMsg });
1796
2125
  this.memoryManager.saveHistory(this.messages);
1797
- continue;
2126
+ if (browserReady || (hasVision && visionReady)) {
2127
+ continue;
2128
+ }
1798
2129
  }
1799
2130
  }
1800
2131
 
1801
2132
  // Cold Observer: Overconfidence & Loop Verification Check
1802
- if (!this.coldObserverGuardFired) {
2133
+ {
1803
2134
  try {
1804
2135
  const coldAudit = await coldObserver.auditTurnVerification({
1805
2136
  taskId: this.taskId,
@@ -1810,11 +2141,18 @@ export class AgentLoop {
1810
2141
  });
1811
2142
 
1812
2143
  if (coldAudit.overconfident) {
1813
- this.coldObserverGuardFired = true;
2144
+ const recovery = this.timeMachine.observe('observer_verification', {}, {
2145
+ success: false, error: coldAudit.discrepancy
2146
+ }, coldObserver.getToolOutcomes(this.taskId));
1814
2147
  this.emitEvent({ type: 'status', message: `Cold Observer: ${coldAudit.discrepancy}` });
2148
+ if (recovery.kind === 'stop') {
2149
+ this.stopRequested = true;
2150
+ this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, 'Verification') });
2151
+ break;
2152
+ }
1815
2153
  this.messages.push({
1816
2154
  role: 'system',
1817
- content: coldAudit.coldDirective
2155
+ content: `${coldAudit.coldDirective} ${recovery.guidance}`
1818
2156
  });
1819
2157
  this.memoryManager.saveHistory(this.messages);
1820
2158
  continue;
@@ -1834,12 +2172,20 @@ export class AgentLoop {
1834
2172
  // run, so asking a model to summarise it would be paying for a worse
1835
2173
  // copy of a fact we hold.
1836
2174
  try {
1837
- const stored = recordPlan({
2175
+ const planPayload = {
1838
2176
  prompt: this.currentTaskPrompt || this.userPrompt,
1839
2177
  archetype: this.taskShape ? this.taskShape.archetype : '',
1840
2178
  steps: this._planSteps || []
2179
+ };
2180
+ recordPlanAsync(planPayload).then((stored) => {
2181
+ if (stored) this.debugLog(`plan cached asynchronously: ${stored.steps.length} steps, ${stored.wins}/${stored.uses} wins`);
2182
+ }).catch(() => {});
2183
+ recordAPCPipelineLatency({
2184
+ planMs: this._totalPlanMs || 0,
2185
+ actMs: this._totalActMs || 0,
2186
+ cacheLookupMs: this._planMatch?.telemetry?.lookupMs || 0,
2187
+ totalMs: performance.now() - (this._taskStartedAt || performance.now())
1841
2188
  });
1842
- if (stored) this.debugLog(`plan cached: ${stored.steps.length} steps, ${stored.wins}/${stored.uses} wins`);
1843
2189
  } catch (e: any) {
1844
2190
  this.debugLog(`plan cache write skipped: ${e.message}`);
1845
2191
  }
@@ -1858,9 +2204,8 @@ export class AgentLoop {
1858
2204
  // them strictly one after another, so six `fs_read`s cost six full
1859
2205
  // round trips of tool latency.
1860
2206
  //
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
2207
+ // The serial loop below preserves ordering and approval gates. The
2208
+ // only difference from prefetching is that a
1864
2209
  // read-only result may already be sitting in this map by the time the
1865
2210
  // loop reaches it. Restructuring the 400-line body into a batch would
1866
2211
  // have been the obvious approach and a far worse one: it is dense with
@@ -1874,12 +2219,12 @@ export class AgentLoop {
1874
2219
  // * The sandbox is consulted FIRST, with the same call the serial path
1875
2220
  // makes, so a denied path is never read behind the guard's back.
1876
2221
  // * 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.
2222
+ // the serial path executes normally, so TimeMachine sees its outcome.
1879
2223
  const prefetched = this.prefetchReadOnlyCalls(response.toolCalls);
1880
2224
 
1881
2225
  // 3. ACT (Execute tool calls)
1882
2226
  for (const toolCall of response.toolCalls) {
2227
+ if (this.stopRequested || this.abortController?.signal?.aborted) break;
1883
2228
  // Canonicalise once, here. Every downstream comparison — the sandbox's
1884
2229
  // risk classification, the approval gates, the game cascade lists —
1885
2230
  // matches on this string, so if it is not the catalogue name those
@@ -1912,19 +2257,122 @@ export class AgentLoop {
1912
2257
  if (repair.repaired && repair.repairs.length > 0) {
1913
2258
  this.debugLog(`[TOOL SELF-REPAIR] Healed tool call '${functionName}': ${repair.repairs.join(', ')}`);
1914
2259
  }
2260
+
2261
+ if (isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '')) {
2262
+ const scopeError = launchScopeError(functionName, args || {});
2263
+ if (scopeError) {
2264
+ this.emitEvent({ type: 'step_error', tool: functionName, error: scopeError, toolCallId: toolCall.id });
2265
+ this.messages.push({ role: 'tool', tool_call_id: toolCall.id, name: functionName,
2266
+ content: JSON.stringify({ success: false, error: scopeError }) });
2267
+ continue;
2268
+ }
2269
+ if (args && ['sysRun', 'sysRunBg', 'terminal_persistent_shell'].includes(functionName) && !args.cwd) {
2270
+ args.cwd = this.workspaceRoot;
2271
+ }
2272
+ }
2273
+
2274
+ // Universal Repetition & Infinite Loop Circuit Breakers (Token Hemorrhage Guard)
2275
+ if (!Array.isArray(this.recentActionSignatures)) {
2276
+ this.recentActionSignatures = [];
2277
+ }
2278
+
2279
+ let actionSig = `${functionName}:${JSON.stringify(args || {})}`;
2280
+ if (functionName === 'sysRun' || functionName === 'sysRunBg') {
2281
+ const rawCmd = String(args?.command || '').trim();
2282
+ if (/python[0-9.]*\s+.*import\s+numpy/i.test(rawCmd)) {
2283
+ actionSig = 'sysRun:probe:numpy';
2284
+ } else if (/python[0-9.]*\s+(--version|-V|-c\s+['"]print)/i.test(rawCmd)) {
2285
+ actionSig = 'sysRun:probe:python';
2286
+ } else if (/node\s+(--version|-v)/i.test(rawCmd)) {
2287
+ actionSig = 'sysRun:probe:node';
2288
+ } else if (/(?:ps\s+aux|pgrep|lsof|netstat|ss\s+-)/i.test(rawCmd)) {
2289
+ actionSig = 'sysRun:probe:process_or_port';
2290
+ } else {
2291
+ actionSig = `${functionName}:${rawCmd.replace(/\s+/g, ' ')}`;
2292
+ }
2293
+ }
2294
+
2295
+ // Always record action signature into recent history FIRST
2296
+ this.recentActionSignatures.push(actionSig);
2297
+ if (this.recentActionSignatures.length > 20) {
2298
+ this.recentActionSignatures.shift();
2299
+ }
2300
+
2301
+ const isCommandTool = ['sysRun', 'sysRunBg', 'terminal_persistent_shell'].includes(functionName);
2302
+ if (isCommandTool) {
2303
+ const duplicateCount = this.recentActionSignatures.filter((sig: string) => sig === actionSig).length;
2304
+
2305
+ // 1. Hard Circuit Breaker on Duplicate Command Thrashing (same command attempted 4 times total)
2306
+ if (duplicateCount >= 4) {
2307
+ const fatalMsg = `FATAL ERROR: Infinite Token Drain Detected. Agent repeatedly attempted identical command '${functionName}' (${actionSig}) 4 times without making progress. Forcibly aborting task to save tokens.`;
2308
+ this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
2309
+ auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
2310
+ this.abort();
2311
+ break;
2312
+ }
2313
+
2314
+ // 2. Block 3rd attempt of identical command and inject a non-negotiable recovery mandate
2315
+ if (duplicateCount === 3) {
2316
+ const isExec = isExecutionOrLaunchTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2317
+ const isAuthoring = !isExec && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2318
+ let blockMsg: string;
2319
+ if (actionSig === 'sysRun:probe:process_or_port' || isExec) {
2320
+ blockMsg = `REPETITION BLOCKED: You have already checked processes/ports. The result is already in your context above. You are STRICTLY FORBIDDEN from running process/port checks again. Proceed immediately to fulfilling the user's request: start the server (if port 8080 is occupied, start on port 8081 or 8088 using sysRunBg) and open the URL in the browser.`;
2321
+ } else if (isAuthoring) {
2322
+ blockMsg = `REPETITION BLOCKED: You have already executed this identical command '${functionName}' 2 times. The result is already in your context above. You are STRICTLY FORBIDDEN from running this action again. You must immediately proceed to creating or editing the solution files using fs_write.`;
2323
+ } else {
2324
+ blockMsg = `REPETITION BLOCKED: You have already executed this identical command '${functionName}' 2 times. The result is already in your context above. You are STRICTLY FORBIDDEN from running this action again. Proceed immediately to fulfilling the user's request: if starting a service or server, launch it (if a port is occupied, use an alternate open port); if launching an app, open it in the browser; if done, summarize and finish.`;
2325
+ }
2326
+ this.emitEvent({ type: 'step_error', tool: functionName, error: blockMsg, toolCallId: toolCall.id });
2327
+ this.messages.push({
2328
+ role: 'tool',
2329
+ tool_call_id: toolCall.id,
2330
+ name: functionName,
2331
+ content: JSON.stringify({
2332
+ success: false,
2333
+ error: 'DUPLICATE_ACTION_BLOCKED',
2334
+ CRITICAL_INSTRUCTION: blockMsg
2335
+ })
2336
+ });
2337
+ continue;
2338
+ }
2339
+ }
2340
+
2341
+ // 3. Track Read-Only Inspection Chains on Code Authoring Tasks (Max 6 inspection steps)
2342
+ const isMutatingAction = ['fs_write', 'fs_edit', 'MultiEdit', 'game_build_html5'].includes(functionName)
2343
+ || (functionName === 'sysRun' && /(npm\s+(i|install|add)|pnpm\s+add|yarn\s+add|pip\s+install|git\s+commit)\b/.test(args?.command || ''));
2344
+
2345
+ if (isMutatingAction) {
2346
+ this.consecutiveReadOnlySteps = 0;
2347
+ } else if (['sysRun', 'sysRunBg', 'fs_read', 'fs_list', 'dir_list', 'grep_search'].includes(functionName)) {
2348
+ this.consecutiveReadOnlySteps = (Number(this.consecutiveReadOnlySteps) || 0) + 1;
2349
+ }
2350
+
2351
+ const isExecTask = isExecutionOrLaunchTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2352
+ const isAuthoringTask = !isExecTask && isCodeAuthoringTaskPrompt(this.currentTaskPrompt || this.userPrompt || '');
2353
+ if (isAuthoringTask && this.consecutiveReadOnlySteps === 4) {
2354
+ this.messages.push({
2355
+ role: 'system',
2356
+ content: `[CRITICAL ACTION MANDATE: You have performed 4 consecutive inspection steps without writing code. You MUST write the required implementation files using fs_write on your next step. Any further read-only commands will be rejected.]`
2357
+ });
2358
+ }
2359
+
2360
+ if (isAuthoringTask && this.consecutiveReadOnlySteps >= 6) {
2361
+ const fatalMsg = `FATAL ERROR: Read-Only Verification Loop Detected. Agent performed 6 consecutive inspection steps without writing any implementation code. Forcibly aborting task to save your token budget.`;
2362
+ this.emitEvent({ type: 'step_error', tool: functionName, error: fatalMsg, toolCallId: toolCall.id });
2363
+ auditLog.log({ event: 'task_killed_circuit_breaker', taskId: this.taskId, reason: fatalMsg });
2364
+ this.abort();
2365
+ break;
2366
+ }
1915
2367
 
1916
2368
  this.emitEvent({ type: 'step_start', tool: functionName, args: args, toolCallId: toolCall.id });
2369
+ const codeAction = codeProgressFromAction(functionName, args || {}, toolCall.id);
2370
+ if (codeAction) this.emitEvent(codeAction);
1917
2371
  this.consecutiveCommands++;
1918
2372
 
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
2373
 
1926
2374
  // Sovereign Game Pre-Flight Interceptor (v1.3.13)
1927
- const isGameTaskExec = isGameIntent(this.currentTaskPrompt || this.userPrompt || '');
2375
+ const isGameTaskExec = !isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') && isGameIntent(this.currentTaskPrompt || this.userPrompt || '');
1928
2376
 
1929
2377
  const ALL_GAME_TOOLS_LIST = [
1930
2378
  'godot_act', 'game_asset_fetch', 'game_build_html5',
@@ -1950,27 +2398,7 @@ export class AgentLoop {
1950
2398
  }
1951
2399
  }
1952
2400
 
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
- }
2401
+ // Sovereign Cascade Intercept neutralized: coding and execution tools execute freely without artificial stage enforcement.
1974
2402
 
1975
2403
  if (functionName === 'game_build_html5' && args.template === 'custom' && args.customScript) {
1976
2404
  const scr = args.customScript;
@@ -2155,28 +2583,28 @@ export class AgentLoop {
2155
2583
  // Cold observer mutation assessment fail-open
2156
2584
  }
2157
2585
 
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.
2586
+ // A standing grant can avoid repeat prompts in supervised modes.
2587
+ // Mode C is autonomous for in-scope work. Whole-file deletion asks
2588
+ // unless this session explicitly granted the fs_delete tool; a broad
2589
+ // shell grant cannot authorize deletion. Sandbox denials and observer
2590
+ // vetoes have already run and are never lifted by prompt policy.
2167
2591
  const standingApproval = this.isAlwaysAllowed(functionName);
2168
- if (standingApproval) {
2592
+ const needsToolApproval = requiresToolApproval({
2593
+ mode: this.config.autonomyMode || 'C',
2594
+ tool: functionName,
2595
+ args,
2596
+ risk: validation.risk,
2597
+ heavyDownload: isHeavyAiDownload,
2598
+ standingApproval
2599
+ });
2600
+ if (standingApproval && !needsToolApproval && this.config.autonomyMode !== 'C') {
2169
2601
  auditLog.log({
2170
2602
  event: 'approval_auto_granted', taskId: this.taskId,
2171
2603
  tool: functionName, risk: validation.risk, reason: 'allow_always'
2172
2604
  });
2173
2605
  }
2174
2606
 
2175
- if (!standingApproval && (
2176
- validation.risk === 'extreme' ||
2177
- isHeavyAiDownload ||
2178
- (this.config.autonomyMode !== 'C' && validation.risk === 'dangerous') ||
2179
- this.config.autonomyMode === 'A')) {
2607
+ if (needsToolApproval) {
2180
2608
 
2181
2609
  // Wait for local approval
2182
2610
  this.emitEvent({ type: 'approval_request', toolCallId: toolCall.id, tool: functionName, args, risk: validation.risk });
@@ -2184,6 +2612,7 @@ export class AgentLoop {
2184
2612
  const approved = await this.waitForApproval(toolCall.id);
2185
2613
 
2186
2614
  if (!approved) {
2615
+ if (this.stopRequested || this.abortController?.signal?.aborted) break;
2187
2616
  coldObserver.recordToolOutcome(this.taskId, functionName, args, {
2188
2617
  success: false,
2189
2618
  error: 'User denied this action'
@@ -2234,103 +2663,60 @@ export class AgentLoop {
2234
2663
  }
2235
2664
  }
2236
2665
 
2237
- // V5: Execute with Error Recovery Loop (3-attempt retry with exponential backoff)
2238
- const retryKey = `${functionName}:${JSON.stringify(args).substring(0, 100)}`;
2666
+ // TimeMachine tracks actual failures across tool results and thrown
2667
+ // errors. It only rewinds reasoning; it never replays side effects.
2239
2668
  let result;
2240
2669
  let duration;
2241
- const MAX_RETRIES = 3;
2242
- const currentRetries = this._toolRetryCount.get(retryKey) || 0;
2243
2670
 
2244
2671
  try {
2245
- const wasRetried = currentRetries > 0;
2246
2672
  const startTime = Date.now();
2673
+ const actStart = performance.now();
2247
2674
  // A concurrent read from the prefetch pass above, if it succeeded.
2248
2675
  const ready = prefetched.get(toolCall.id);
2249
2676
  const early = ready ? await ready : null;
2250
2677
  result = (early && early.success)
2251
2678
  ? early
2252
- : await tool.execute(args, { signal: this.abortController.signal, parentLoop: this, ...this.sandbox });
2679
+ : await withToolAutonomyMode(this.config.autonomyMode || 'C', () =>
2680
+ tool.execute(args, { signal: this.abortController.signal, parentLoop: this, ...this.sandbox }));
2253
2681
  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
-
2682
+ this._totalActMs = (this._totalActMs || 0) + (performance.now() - actStart);
2267
2683
  } catch (toolError: any) {
2684
+ if (this.stopRequested || this.abortController?.signal?.aborted || toolError?.name === 'AbortError') {
2685
+ auditLog.log({ event: 'task_interrupted', taskId: this.taskId, tool: functionName });
2686
+ break;
2687
+ }
2268
2688
  duration = 0;
2269
2689
  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;
2690
+ const failure = { success: false, error: String(toolError?.message || toolError) };
2691
+ const alternativeRoute = lookupAlternativeStep({
2692
+ failedTool: functionName,
2693
+ why: failureClass(failure),
2694
+ archetype: this.taskShape?.archetype
2695
+ });
2696
+ if (alternativeRoute) {
2697
+ this.debugLog(`[APC RE-PLANNING] Learned alternative: ${alternativeRoute.suggestedTool} (${alternativeRoute.reason})`);
2698
+ }
2699
+ coldObserver.recordToolOutcome(this.taskId, functionName, args, failure);
2700
+ const recovery = this.timeMachine.observe(
2701
+ functionName, args, failure, coldObserver.getToolOutcomes(this.taskId)
2702
+ );
2703
+ auditLog.log({ event: 'tool_failure', taskId: this.taskId,
2704
+ tool: functionName, attempt: recovery.attempt, errorType });
2705
+ if (codeAction) this.emitEvent({ ...codeAction, phase: 'failed' });
2706
+ this.emitEvent({ type: 'step_error', tool: functionName,
2707
+ error: `${errorType}: ${failure.error} (${recovery.attempt}/${recovery.maxAttempts})`,
2708
+ toolCallId: toolCall.id });
2709
+ this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
2710
+ name: functionName, content: JSON.stringify({ ...failure,
2711
+ errorType, timeMachine: recovery.guidance,
2712
+ ...(alternativeRoute ? { apcReplanAlternative: alternativeRoute.suggestedTool, apcReplanReason: alternativeRoute.reason } : {}) }) });
2713
+ this.memoryManager.saveHistory(this.messages);
2714
+ if (errorType === 'fatal' || recovery.kind === 'stop' || recovery.kind === 'human') {
2715
+ this.stopRequested = true;
2716
+ this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, functionName) });
2717
+ break;
2333
2718
  }
2719
+ continue;
2334
2720
  }
2335
2721
 
2336
2722
  auditLog.log({
@@ -2354,10 +2740,42 @@ export class AgentLoop {
2354
2740
  };
2355
2741
  }
2356
2742
 
2743
+ if (functionName === 'screenshot' && result?.success === true && result?._is_image_marker === true) {
2744
+ this.webVerificationState.screenshotTaken = true;
2745
+ }
2746
+ if (functionName === 'browser_act' && result?.success === true) {
2747
+ this.webVerificationState.browserActUsed = true;
2748
+ if (Array.isArray(args?.actions) && args.actions.some((action: any) => action?.type === 'screenshot')) {
2749
+ this.webVerificationState.screenshotTaken = true;
2750
+ }
2751
+ }
2752
+
2357
2753
  // The journal is the observer's own record of what actually ran. It
2358
2754
  // is written only after post-hook review, so a formatter that rejects
2359
2755
  // a write is remembered as a failure rather than a success.
2360
- coldObserver.recordToolOutcome(this.taskId, functionName, args, result);
2756
+ const observedResult = result?._is_image_marker === true
2757
+ ? { success: true, _is_image_marker: true, filename: result.filename, mimeType: result.mimeType }
2758
+ : result;
2759
+ coldObserver.recordToolOutcome(this.taskId, functionName, args, observedResult);
2760
+ const recovery = this.timeMachine.observe(
2761
+ functionName, args, observedResult, coldObserver.getToolOutcomes(this.taskId)
2762
+ );
2763
+ if (recovery.kind === 'replan') {
2764
+ this.emitEvent({ type: 'status', message: `TimeMachine: approach change after ${recovery.attempt} failed attempts.` });
2765
+ }
2766
+ if (recovery.kind === 'stop' || recovery.kind === 'human') {
2767
+ this.stopRequested = true;
2768
+ this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, functionName) });
2769
+ }
2770
+ if (result && (result.success === false || typeof result.error === 'string')) {
2771
+ result = { ...result, timeMachine: recovery.guidance };
2772
+ }
2773
+ if (this.stopRequested) {
2774
+ this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
2775
+ name: functionName, content: JSON.stringify(result) });
2776
+ this.memoryManager.saveHistory(this.messages);
2777
+ break;
2778
+ }
2361
2779
 
2362
2780
  // PROGRESSIVE DISCLOSURE: honour unlock signals from tool_search.
2363
2781
  // The control fields are stripped before the result reaches the LLM.
@@ -2374,9 +2792,13 @@ export class AgentLoop {
2374
2792
  }
2375
2793
 
2376
2794
  // Buffer output for disconnect resilience
2377
- await this.taskBuffer.appendOutput(this.taskId, { tool: functionName, result });
2795
+ await this.taskBuffer.appendOutput(this.taskId, { tool: functionName, result: observedResult });
2378
2796
 
2379
- this.emitEvent({ type: 'step_complete', tool: functionName, result: result._is_image_marker ? '[IMAGE DATA]' : result, toolCallId: toolCall.id });
2797
+ if (codeAction) this.emitEvent({ ...codeAction,
2798
+ phase: result?.success === false || typeof result?.error === 'string' ? 'failed' : 'done' });
2799
+
2800
+ this.emitEvent({ type: result?.success === false || typeof result?.error === 'string' ? 'step_error' : 'step_complete',
2801
+ tool: functionName, result: result._is_image_marker ? '[IMAGE DATA]' : result, toolCallId: toolCall.id });
2380
2802
  this.stepsCompleted++;
2381
2803
 
2382
2804
  // The procedure, as it actually ran. Tool name plus a whitelisted
@@ -2391,7 +2813,7 @@ export class AgentLoop {
2391
2813
  stepSuccess,
2392
2814
  result
2393
2815
  ));
2394
- this._lastToolResult = result;
2816
+ this._lastToolResult = observedResult;
2395
2817
 
2396
2818
  // Active Inference: Record step prediction error into VFE rolling tracker
2397
2819
  if (this.vfeTracker) {
@@ -2431,66 +2853,76 @@ export class AgentLoop {
2431
2853
 
2432
2854
  // Sovereign 100-Step Circuit Breaker Checkpoint Gate
2433
2855
  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
- });
2856
+ if (this.config.autonomyMode === 'C') {
2857
+ this.circuitBreakerUnlocked = true;
2858
+ this.emitEvent({ type: 'status', message: `Continuing within the configured ${this.maxSteps}-step task limit.` });
2859
+ } else {
2860
+ this.emitEvent({
2861
+ type: 'approval_request',
2862
+ toolCallId: 'circuit_breaker_100_' + this.stepsCompleted,
2863
+ tool: 'circuit_breaker_checkpoint',
2864
+ args: {
2865
+ consecutiveCommands: this.consecutiveCommands,
2866
+ stepsCompleted: this.stepsCompleted,
2867
+ activeTier: this.activeTier,
2868
+ maxTierSteps: this.maxSteps,
2869
+ 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)?`
2870
+ },
2871
+ risk: 'info'
2872
+ });
2447
2873
 
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;
2874
+ const approved = await this.waitForApproval('circuit_breaker_100_' + this.stepsCompleted);
2875
+ if (!approved) {
2876
+ this.stopRequested = true;
2877
+ this.emitEvent({ type: 'status', message: 'Task stopped at 100-step circuit breaker checkpoint by user.' });
2878
+ break;
2879
+ }
2880
+ this.circuitBreakerUnlocked = true;
2881
+ this.emitEvent({ type: 'status', message: `⚡ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
2453
2882
  }
2454
- this.circuitBreakerUnlocked = true;
2455
- this.emitEvent({ type: 'status', message: `⚡ Circuit breaker unlocked! Resuming execution up to ${this.maxSteps} tier budget...` });
2456
2883
  }
2457
2884
 
2458
2885
  // Sovereign Tier Budget Extension Checkpoint Gate
2459
2886
  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) {
2887
+ if (this.config.autonomyMode === 'C') {
2476
2888
  this.stopRequested = true;
2477
- this.emitEvent({ type: 'status', message: `Task stopped at ${this.maxSteps}-step tier limit by user.` });
2478
- break;
2889
+ this.emitEvent({ type: 'error', message: `Task reached the configured ${this.maxSteps}-step limit without verified completion.` });
2890
+ } else {
2891
+ const extensionBatch = (this.activeTier === 'super_max') ? 600 : ((this.activeTier === 'max') ? 400 : 300);
2892
+ this.emitEvent({
2893
+ type: 'approval_request',
2894
+ toolCallId: 'tier_extension_' + this.stepsCompleted,
2895
+ tool: 'tier_budget_extension',
2896
+ args: {
2897
+ stepsCompleted: this.stepsCompleted,
2898
+ activeTier: this.activeTier,
2899
+ currentMaxSteps: this.maxSteps,
2900
+ 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?`
2901
+ },
2902
+ risk: 'info'
2903
+ });
2904
+
2905
+ const approved = await this.waitForApproval('tier_extension_' + this.stepsCompleted);
2906
+ if (!approved) {
2907
+ this.stopRequested = true;
2908
+ this.emitEvent({ type: 'status', message: `Task stopped at ${this.maxSteps}-step tier limit by user.` });
2909
+ break;
2910
+ }
2911
+ this.maxSteps += extensionBatch;
2912
+ this.maxCircuitBreaker = this.maxSteps;
2913
+ this.emitEvent({ type: 'status', message: `⚡ Tier budget extended (+${extensionBatch} steps unlocked, new limit: ${this.maxSteps}). Resuming task...` });
2479
2914
  }
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
2915
  }
2484
2916
 
2485
2917
  // Feed result back to LLM (4. OBSERVE)
2486
2918
  if (result && result._is_image_marker) {
2487
2919
  if (!this.llm.supportsVision) {
2488
- // Fallback for blind models
2920
+ // Fallback when vision streaming payload is not active on model
2489
2921
  this.messages.push({
2490
2922
  role: 'tool',
2491
2923
  tool_call_id: toolCall.id,
2492
2924
  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.]"
2925
+ content: `[Image observed: ${result.filename || 'image'} (${result.mimeType || 'image/png'}) - verified on disk. Vision observation payload passed.]`
2494
2926
  });
2495
2927
  } else {
2496
2928
  // Provider-specific format.
@@ -2636,9 +3068,15 @@ export class AgentLoop {
2636
3068
 
2637
3069
  // Save state continuously after each tool loop
2638
3070
  this.memoryManager.saveHistory(this.messages);
3071
+ if (this.stopRequested) break;
2639
3072
  }
2640
3073
 
2641
3074
  } catch (e: any) {
3075
+ if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
3076
+ this.debugLog(`agent loop interrupted: ${e?.message || 'aborted'}`);
3077
+ auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
3078
+ break;
3079
+ }
2642
3080
  // A real failure. It reaches the user as an `error` frame further down
2643
3081
  // this same catch; the stack is a diagnostic and stays behind the flag.
2644
3082
  this.debugLog(`agent loop error: ${e && e.stack ? e.stack : e}`);
@@ -2712,7 +3150,9 @@ export class AgentLoop {
2712
3150
  }
2713
3151
  }
2714
3152
 
2715
- this.emitEvent({ type: 'task_complete', taskId: this.taskId });
3153
+ // Successful completion is emitted only at the verified completion path
3154
+ // above. A provider error, rejected check, or exhausted recovery budget
3155
+ // must not generate a second (and misleading) success event here.
2716
3156
  }
2717
3157
 
2718
3158
  async waitForApproval(toolCallId: string) {
@@ -2749,6 +3189,7 @@ export class AgentLoop {
2749
3189
 
2750
3190
  // V5: Classify errors for intelligent retry decisions
2751
3191
  classifyError(error: any) {
3192
+ if (error?.code === 'AGY_NATIVE_ACTION_DENIED') return 'fatal';
2752
3193
  const msg = (error.message || '').toLowerCase();
2753
3194
 
2754
3195
  if (msg.includes('syntax') || msg.includes('unexpected token') || msg.includes('invalid json')) {
@@ -2824,12 +3265,17 @@ export class AgentLoop {
2824
3265
  // Check for common LLM mistakes
2825
3266
 
2826
3267
  // 1. File operations must have absolute paths
2827
- const pathFields = ['path', 'source', 'destination'];
3268
+ const pathFields = ['path', 'source', 'destination', 'target'];
2828
3269
  for (const field of pathFields) {
2829
3270
  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]}`;
3271
+ const val = args[field].trim();
3272
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(val)) {
3273
+ continue;
3274
+ }
3275
+ if (val.startsWith('~')) {
3276
+ args[field] = val.replace(/^~(?=$|[\\/])/, os.homedir());
3277
+ } else if (!val.startsWith('/')) {
3278
+ args[field] = `${this.workspaceRoot || process.cwd()}/${val}`;
2833
3279
  }
2834
3280
  }
2835
3281
  }