ft-scout 1.0.8 → 1.1.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 (243) hide show
  1. package/.firebase/hosting.d2Vi.cache +9 -0
  2. package/.firebaserc +14 -0
  3. package/AUTONOMOUS_FEATURES.md +192 -0
  4. package/README.md +482 -32
  5. package/bin/ft.js +2 -0
  6. package/bin/src/commands/agent.d.ts.map +1 -0
  7. package/bin/src/commands/agent.js +1230 -0
  8. package/bin/src/commands/agent.js.map +1 -0
  9. package/bin/src/commands/audit.d.ts.map +1 -0
  10. package/bin/src/commands/audit.js +104 -0
  11. package/bin/src/commands/audit.js.map +1 -0
  12. package/bin/src/commands/authCommand.d.ts.map +1 -0
  13. package/bin/src/commands/authCommand.js +38 -0
  14. package/bin/src/commands/authCommand.js.map +1 -0
  15. package/bin/src/commands/benchmark.d.ts.map +1 -0
  16. package/bin/src/commands/benchmark.js +135 -0
  17. package/bin/src/commands/benchmark.js.map +1 -0
  18. package/bin/src/commands/brief.d.ts.map +1 -1
  19. package/bin/src/commands/brief.js +28 -19
  20. package/bin/src/commands/brief.js.map +1 -1
  21. package/bin/src/commands/configCommand.d.ts.map +1 -0
  22. package/bin/src/commands/configCommand.js +53 -0
  23. package/bin/src/commands/configCommand.js.map +1 -0
  24. package/bin/src/commands/dashboard.d.ts.map +1 -0
  25. package/bin/src/commands/dashboard.js +41 -0
  26. package/bin/src/commands/dashboard.js.map +1 -0
  27. package/bin/src/commands/history.d.ts.map +1 -0
  28. package/bin/src/commands/history.js +20 -0
  29. package/bin/src/commands/history.js.map +1 -0
  30. package/bin/src/commands/init.d.ts.map +1 -1
  31. package/bin/src/commands/init.js +411 -78
  32. package/bin/src/commands/init.js.map +1 -1
  33. package/bin/src/commands/login.d.ts.map +1 -0
  34. package/bin/src/commands/login.js +190 -0
  35. package/bin/src/commands/login.js.map +1 -0
  36. package/bin/src/commands/logout.d.ts.map +1 -0
  37. package/bin/src/commands/logout.js +15 -0
  38. package/bin/src/commands/logout.js.map +1 -0
  39. package/bin/src/commands/mcp.d.ts.map +1 -0
  40. package/bin/src/commands/mcp.js +393 -0
  41. package/bin/src/commands/mcp.js.map +1 -0
  42. package/bin/src/commands/owners.js +6 -6
  43. package/bin/src/commands/owners.js.map +1 -1
  44. package/bin/src/commands/plan.d.ts.map +1 -0
  45. package/bin/src/commands/plan.js +152 -0
  46. package/bin/src/commands/plan.js.map +1 -0
  47. package/bin/src/commands/quota.d.ts.map +1 -0
  48. package/bin/src/commands/quota.js +32 -0
  49. package/bin/src/commands/quota.js.map +1 -0
  50. package/bin/src/commands/recommend.d.ts.map +1 -0
  51. package/bin/src/commands/recommend.js +46 -0
  52. package/bin/src/commands/recommend.js.map +1 -0
  53. package/bin/src/commands/risky.d.ts.map +1 -1
  54. package/bin/src/commands/risky.js +235 -39
  55. package/bin/src/commands/risky.js.map +1 -1
  56. package/bin/src/commands/setup.d.ts.map +1 -1
  57. package/bin/src/commands/setup.js +411 -16
  58. package/bin/src/commands/setup.js.map +1 -1
  59. package/bin/src/commands/signup.d.ts.map +1 -0
  60. package/bin/src/commands/signup.js +118 -0
  61. package/bin/src/commands/signup.js.map +1 -0
  62. package/bin/src/commands/undo.d.ts.map +1 -0
  63. package/bin/src/commands/undo.js +59 -0
  64. package/bin/src/commands/undo.js.map +1 -0
  65. package/bin/src/commands/web.d.ts.map +1 -0
  66. package/bin/src/commands/web.js +90 -0
  67. package/bin/src/commands/web.js.map +1 -0
  68. package/bin/src/discovery/config.d.ts.map +1 -0
  69. package/bin/src/discovery/config.js +41 -0
  70. package/bin/src/discovery/config.js.map +1 -0
  71. package/bin/src/discovery/display.d.ts.map +1 -0
  72. package/bin/src/discovery/display.js +57 -0
  73. package/bin/src/discovery/display.js.map +1 -0
  74. package/bin/src/discovery/messages.d.ts.map +1 -0
  75. package/bin/src/discovery/messages.js +7 -0
  76. package/bin/src/discovery/messages.js.map +1 -0
  77. package/bin/src/discovery/signals.d.ts.map +1 -0
  78. package/bin/src/discovery/signals.js +33 -0
  79. package/bin/src/discovery/signals.js.map +1 -0
  80. package/bin/src/engine/actionVerifier.d.ts.map +1 -0
  81. package/bin/src/engine/actionVerifier.js +283 -0
  82. package/bin/src/engine/actionVerifier.js.map +1 -0
  83. package/bin/src/engine/agentEngine.d.ts.map +1 -0
  84. package/bin/src/engine/agentEngine.js +2188 -0
  85. package/bin/src/engine/agentEngine.js.map +1 -0
  86. package/bin/src/engine/agentState.d.ts.map +1 -0
  87. package/bin/src/engine/agentState.js +381 -0
  88. package/bin/src/engine/agentState.js.map +1 -0
  89. package/bin/src/engine/browser/browserController.d.ts.map +1 -0
  90. package/bin/src/engine/browser/browserController.js +737 -0
  91. package/bin/src/engine/browser/browserController.js.map +1 -0
  92. package/bin/src/engine/browser/index.d.ts.map +1 -0
  93. package/bin/src/engine/browser/index.js +2 -0
  94. package/bin/src/engine/browser/index.js.map +1 -0
  95. package/bin/src/engine/computer/computerController.d.ts.map +1 -0
  96. package/bin/src/engine/computer/computerController.js +773 -0
  97. package/bin/src/engine/computer/computerController.js.map +1 -0
  98. package/bin/src/engine/computer/computerDiagnostic.d.ts.map +1 -0
  99. package/bin/src/engine/computer/computerDiagnostic.js +71 -0
  100. package/bin/src/engine/computer/computerDiagnostic.js.map +1 -0
  101. package/bin/src/engine/computer/index.d.ts.map +1 -0
  102. package/bin/src/engine/computer/index.js +4 -0
  103. package/bin/src/engine/computer/index.js.map +1 -0
  104. package/bin/src/engine/computer/mockComputer.d.ts.map +1 -0
  105. package/bin/src/engine/computer/mockComputer.js +260 -0
  106. package/bin/src/engine/computer/mockComputer.js.map +1 -0
  107. package/bin/src/engine/computer/scoutDriver.cs +1161 -0
  108. package/bin/src/engine/computer/scout_driver.exe +0 -0
  109. package/bin/src/engine/git.d.ts.map +1 -1
  110. package/bin/src/engine/git.js +71 -0
  111. package/bin/src/engine/git.js.map +1 -1
  112. package/bin/src/engine/llm.d.ts.map +1 -1
  113. package/bin/src/engine/llm.js +1272 -23
  114. package/bin/src/engine/llm.js.map +1 -1
  115. package/bin/src/engine/planner.d.ts.map +1 -0
  116. package/bin/src/engine/planner.js +321 -0
  117. package/bin/src/engine/planner.js.map +1 -0
  118. package/bin/src/engine/runtime/agentRuntime.d.ts.map +1 -0
  119. package/bin/src/engine/runtime/agentRuntime.js +1258 -0
  120. package/bin/src/engine/runtime/agentRuntime.js.map +1 -0
  121. package/bin/src/engine/runtime/index.d.ts.map +1 -0
  122. package/bin/src/engine/runtime/index.js +2 -0
  123. package/bin/src/engine/runtime/index.js.map +1 -0
  124. package/bin/src/engine/safety.d.ts.map +1 -0
  125. package/bin/src/engine/safety.js +316 -0
  126. package/bin/src/engine/safety.js.map +1 -0
  127. package/bin/src/engine/scoutAudioRecorder.cs +215 -0
  128. package/bin/src/engine/scout_audio_recorder.exe +0 -0
  129. package/bin/src/engine/toolRegistry.d.ts.map +1 -0
  130. package/bin/src/engine/toolRegistry.js +521 -0
  131. package/bin/src/engine/toolRegistry.js.map +1 -0
  132. package/bin/src/engine/verifier.d.ts.map +1 -0
  133. package/bin/src/engine/verifier.js +414 -0
  134. package/bin/src/engine/verifier.js.map +1 -0
  135. package/bin/src/engine/voiceEngine.d.ts.map +1 -0
  136. package/bin/src/engine/voiceEngine.js +474 -0
  137. package/bin/src/engine/voiceEngine.js.map +1 -0
  138. package/bin/src/engine/web.d.ts.map +1 -0
  139. package/bin/src/engine/web.js +161 -0
  140. package/bin/src/engine/web.js.map +1 -0
  141. package/bin/src/engine/workspace/agentWorkspace.d.ts.map +1 -0
  142. package/bin/src/engine/workspace/agentWorkspace.js +505 -0
  143. package/bin/src/engine/workspace/agentWorkspace.js.map +1 -0
  144. package/bin/src/engine/workspace/index.d.ts.map +1 -0
  145. package/bin/src/engine/workspace/index.js +2 -0
  146. package/bin/src/engine/workspace/index.js.map +1 -0
  147. package/bin/src/index.js +365 -23
  148. package/bin/src/index.js.map +1 -1
  149. package/bin/src/mcp/client.d.ts.map +1 -0
  150. package/bin/src/mcp/client.js +127 -0
  151. package/bin/src/mcp/client.js.map +1 -0
  152. package/bin/src/mcp/discovery.d.ts.map +1 -0
  153. package/bin/src/mcp/discovery.js +91 -0
  154. package/bin/src/mcp/discovery.js.map +1 -0
  155. package/bin/src/mcp/health.d.ts.map +1 -0
  156. package/bin/src/mcp/health.js +44 -0
  157. package/bin/src/mcp/health.js.map +1 -0
  158. package/bin/src/mcp/index.d.ts.map +1 -0
  159. package/bin/src/mcp/index.js +15 -0
  160. package/bin/src/mcp/index.js.map +1 -0
  161. package/bin/src/mcp/manager.d.ts.map +1 -0
  162. package/bin/src/mcp/manager.js +648 -0
  163. package/bin/src/mcp/manager.js.map +1 -0
  164. package/bin/src/mcp/permissions.d.ts.map +1 -0
  165. package/bin/src/mcp/permissions.js +50 -0
  166. package/bin/src/mcp/permissions.js.map +1 -0
  167. package/bin/src/mcp/persistence.d.ts.map +1 -0
  168. package/bin/src/mcp/persistence.js +171 -0
  169. package/bin/src/mcp/persistence.js.map +1 -0
  170. package/bin/src/mcp/recovery.d.ts.map +1 -0
  171. package/bin/src/mcp/recovery.js +75 -0
  172. package/bin/src/mcp/recovery.js.map +1 -0
  173. package/bin/src/mcp/telemetry.d.ts.map +1 -0
  174. package/bin/src/mcp/telemetry.js +82 -0
  175. package/bin/src/mcp/telemetry.js.map +1 -0
  176. package/bin/src/mcp/toolRouter.d.ts.map +1 -0
  177. package/bin/src/mcp/toolRouter.js +127 -0
  178. package/bin/src/mcp/toolRouter.js.map +1 -0
  179. package/bin/src/mcp/transport.d.ts.map +1 -0
  180. package/bin/src/mcp/transport.js +328 -0
  181. package/bin/src/mcp/transport.js.map +1 -0
  182. package/bin/src/mcp/types.d.ts.map +1 -0
  183. package/bin/src/mcp/types.js +6 -0
  184. package/bin/src/mcp/types.js.map +1 -0
  185. package/bin/src/server/server.d.ts.map +1 -0
  186. package/bin/src/server/server.js +989 -0
  187. package/bin/src/server/server.js.map +1 -0
  188. package/bin/src/utils/admin.d.ts.map +1 -0
  189. package/bin/src/utils/admin.js +231 -0
  190. package/bin/src/utils/admin.js.map +1 -0
  191. package/bin/src/utils/auditLogger.d.ts.map +1 -0
  192. package/bin/src/utils/auditLogger.js +70 -0
  193. package/bin/src/utils/auditLogger.js.map +1 -0
  194. package/bin/src/utils/auth.d.ts.map +1 -0
  195. package/bin/src/utils/auth.js +679 -0
  196. package/bin/src/utils/auth.js.map +1 -0
  197. package/bin/src/utils/branding.d.ts.map +1 -0
  198. package/bin/src/utils/branding.js +14 -0
  199. package/bin/src/utils/branding.js.map +1 -0
  200. package/bin/src/utils/config.d.ts.map +1 -1
  201. package/bin/src/utils/config.js +124 -3
  202. package/bin/src/utils/config.js.map +1 -1
  203. package/bin/src/utils/email.d.ts.map +1 -0
  204. package/bin/src/utils/email.js +267 -0
  205. package/bin/src/utils/email.js.map +1 -0
  206. package/bin/src/utils/firebaseAuth.d.ts.map +1 -0
  207. package/bin/src/utils/firebaseAuth.js +174 -0
  208. package/bin/src/utils/firebaseAuth.js.map +1 -0
  209. package/bin/src/utils/holoseneAuth.d.ts.map +1 -0
  210. package/bin/src/utils/holoseneAuth.js +307 -0
  211. package/bin/src/utils/holoseneAuth.js.map +1 -0
  212. package/bin/src/utils/language.d.ts.map +1 -0
  213. package/bin/src/utils/language.js +181 -0
  214. package/bin/src/utils/language.js.map +1 -0
  215. package/bin/src/utils/markdown.d.ts.map +1 -0
  216. package/bin/src/utils/markdown.js +215 -0
  217. package/bin/src/utils/markdown.js.map +1 -0
  218. package/bin/src/utils/payment.d.ts.map +1 -0
  219. package/bin/src/utils/payment.js +290 -0
  220. package/bin/src/utils/payment.js.map +1 -0
  221. package/bin/src/utils/pricing.d.ts.map +1 -0
  222. package/bin/src/utils/pricing.js +165 -0
  223. package/bin/src/utils/pricing.js.map +1 -0
  224. package/bin/src/utils/razorpay.d.ts.map +1 -0
  225. package/bin/src/utils/razorpay.js +144 -0
  226. package/bin/src/utils/razorpay.js.map +1 -0
  227. package/bin/src/utils/session.d.ts.map +1 -0
  228. package/bin/src/utils/session.js +82 -0
  229. package/bin/src/utils/session.js.map +1 -0
  230. package/bin/src/utils/updateCheck.d.ts.map +1 -0
  231. package/bin/src/utils/updateCheck.js +108 -0
  232. package/bin/src/utils/updateCheck.js.map +1 -0
  233. package/downloads/invoice-2026-03.pdf +1 -0
  234. package/firebase.json +74 -0
  235. package/package.json +49 -46
  236. package/web/ScoutFavicon.png +0 -0
  237. package/web/app.js +3944 -0
  238. package/web/styles.css +3081 -0
  239. package/.ft/context.json +0 -18
  240. package/email-template.html +0 -223
  241. package/email-template.txt +0 -45
  242. package/scripts/send-brevo-campaign.cjs +0 -167
  243. package/scripts/send-email.js +0 -77
@@ -0,0 +1,2188 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { exec } from 'child_process';
4
+ import { promisify } from 'util';
5
+ import chalk from 'chalk';
6
+ import { spinner, confirm, isCancel, text } from '@clack/prompts';
7
+ import { getDirectoryFiles, recordHistoryAction } from '../utils/config.js';
8
+ import { saveAgentSession, getRecentSessionsSummary } from '../utils/session.js';
9
+ import { safeNote, renderMarkdown } from '../utils/markdown.js';
10
+ import { openai, callOpenAIWithRetry, isQuotaExceededError, sanitizeMessage, sanitizeMessages } from './llm.js';
11
+ import { checkFileSyntax, verifyAndSelfHealFiles, executeSmartCommand, extractErrorDiagnostics } from './verifier.js';
12
+ import { speakText, listenSpeechToText, cleanTextForSpeech } from './voiceEngine.js';
13
+ import { TaskStateManager } from './agentState.js';
14
+ import { SemanticBrowserController } from './browser/index.js';
15
+ import { ActionVerifier } from './actionVerifier.js';
16
+ import { ApprovalManager, RiskClassifier } from './safety.js';
17
+ import { TaskPlanner, checkSimpleAppAction } from './planner.js';
18
+ import { UnifiedToolRegistry } from './toolRegistry.js';
19
+ import { SystemComputerController, MockComputerController } from './computer/index.js';
20
+ import { AgentWorkspace, inferExecutionIntent, resolveDesktopPath } from './workspace/index.js';
21
+ import { AgentRuntime } from './runtime/index.js';
22
+ import { loadAuthConfig, isProOrHigher } from '../utils/auth.js';
23
+ import { getMCPManager } from '../mcp/index.js';
24
+ export { AgentRuntime, AgentWorkspace, inferExecutionIntent, resolveDesktopPath, SystemComputerController, MockComputerController };
25
+ const execAsync = promisify(exec);
26
+ export function robustSnippetReplace(origContent, target, replacement) {
27
+ if (!origContent || !target) {
28
+ return { success: false, updatedContent: origContent, error: 'Target snippet or original content is empty.' };
29
+ }
30
+ const normOrig = origContent.replace(/\r\n/g, '\n');
31
+ const normTarget = target.replace(/\r\n/g, '\n');
32
+ const normReplacement = replacement.replace(/\r\n/g, '\n');
33
+ // 1. Direct exact match
34
+ if (normOrig.includes(normTarget)) {
35
+ const occurrences = normOrig.split(normTarget).length - 1;
36
+ if (occurrences > 1) {
37
+ return {
38
+ success: false,
39
+ updatedContent: origContent,
40
+ error: `Target snippet occurs ${occurrences} times. Please include more surrounding code lines in target to make it unique.`
41
+ };
42
+ }
43
+ return { success: true, updatedContent: normOrig.replace(normTarget, () => normReplacement) };
44
+ }
45
+ // 2. Trailing whitespace normalized match
46
+ const origLines = normOrig.split('\n');
47
+ const targetLines = normTarget.split('\n');
48
+ const targetLen = targetLines.length;
49
+ const strippedTarget = targetLines.map((l) => l.trimEnd()).join('\n');
50
+ const matches = [];
51
+ for (let i = 0; i <= origLines.length - targetLen; i++) {
52
+ const windowStr = origLines.slice(i, i + targetLen).map((l) => l.trimEnd()).join('\n');
53
+ if (windowStr === strippedTarget) {
54
+ matches.push(i);
55
+ }
56
+ }
57
+ if (matches.length === 1) {
58
+ const idx = matches[0];
59
+ const before = origLines.slice(0, idx);
60
+ const after = origLines.slice(idx + targetLen);
61
+ const updatedContent = [...before, normReplacement, ...after].join('\n');
62
+ return { success: true, updatedContent };
63
+ }
64
+ if (matches.length > 1) {
65
+ return {
66
+ success: false,
67
+ updatedContent: origContent,
68
+ error: `Target snippet matched ${matches.length} locations when ignoring trailing spaces. Please provide more surrounding code lines in target.`
69
+ };
70
+ }
71
+ // 3. Fully trimmed lines match (handles leading/trailing indentation differences)
72
+ const trimmedTargetLines = targetLines.map((l) => l.trim()).filter(Boolean);
73
+ if (trimmedTargetLines.length > 0) {
74
+ const trimmedTargetStr = trimmedTargetLines.join('\n');
75
+ const trimMatches = [];
76
+ for (let i = 0; i <= origLines.length - targetLen; i++) {
77
+ const windowLines = origLines.slice(i, i + targetLen).map((l) => l.trim()).filter(Boolean);
78
+ if (windowLines.join('\n') === trimmedTargetStr) {
79
+ trimMatches.push(i);
80
+ }
81
+ }
82
+ if (trimMatches.length === 1) {
83
+ const idx = trimMatches[0];
84
+ const before = origLines.slice(0, idx);
85
+ const after = origLines.slice(idx + targetLen);
86
+ const updatedContent = [...before, normReplacement, ...after].join('\n');
87
+ return { success: true, updatedContent };
88
+ }
89
+ }
90
+ // 4. Fuzzy non-blank lines window match (handles variable blank lines in target snippet)
91
+ const nonBlankTargetLines = targetLines.filter((l) => l.trim().length > 0);
92
+ if (nonBlankTargetLines.length > 0) {
93
+ const nonBlankTargetStr = nonBlankTargetLines.map((l) => l.trim()).join('\n');
94
+ const fuzzyMatches = [];
95
+ for (let i = 0; i < origLines.length; i++) {
96
+ for (let j = i + 1; j <= Math.min(origLines.length, i + targetLen + 6); j++) {
97
+ const windowLines = origLines.slice(i, j).filter((l) => l.trim().length > 0);
98
+ if (windowLines.map((l) => l.trim()).join('\n') === nonBlankTargetStr) {
99
+ fuzzyMatches.push({ startIdx: i, endIdx: j });
100
+ break;
101
+ }
102
+ }
103
+ }
104
+ if (fuzzyMatches.length === 1) {
105
+ const { startIdx, endIdx } = fuzzyMatches[0];
106
+ const before = origLines.slice(0, startIdx);
107
+ const after = origLines.slice(endIdx);
108
+ const updatedContent = [...before, normReplacement, ...after].join('\n');
109
+ return { success: true, updatedContent };
110
+ }
111
+ }
112
+ return {
113
+ success: false,
114
+ updatedContent: origContent,
115
+ error: `Target snippet not found in file. Hint: Use write_file with full file content to guarantee edit application, or call read_file to inspect exact current line contents.`
116
+ };
117
+ }
118
+ export const AGENT_TOOLS = [
119
+ {
120
+ name: 'read_file',
121
+ description: 'Read contents of a file in the workspace with optional line numbers range.',
122
+ parameters: {
123
+ type: 'object',
124
+ properties: {
125
+ path: { type: 'string', description: 'Relative path to the target file' },
126
+ startLine: { type: 'number', description: 'Optional 1-based start line' },
127
+ endLine: { type: 'number', description: 'Optional 1-based end line' },
128
+ },
129
+ required: ['path'],
130
+ },
131
+ },
132
+ {
133
+ name: 'write_file',
134
+ description: 'Create a new file or overwrite an existing file with complete new content. Automatically creates all necessary parent directories and folders in one step. ALWAYS use write_file directly to create files and folders instead of shell commands. WARNING: Do NOT use to re-format minified or large files manually as output token limits will truncate file content. Use run_command with formatting tools (e.g. npx prettier --write) instead.',
135
+ parameters: {
136
+ type: 'object',
137
+ properties: {
138
+ path: { type: 'string', description: 'Relative path to the target file' },
139
+ content: { type: 'string', description: 'Complete source code / content string' },
140
+ reason: { type: 'string', description: 'Clear explanation of why this file change is being made and how it fulfills the goal' },
141
+ },
142
+ required: ['path', 'content'],
143
+ },
144
+ },
145
+ {
146
+ name: 'edit_file',
147
+ description: 'Replace an exact target snippet in a file with new replacement code. For reformatting minified files, use run_command with CLI formatters instead.',
148
+ parameters: {
149
+ type: 'object',
150
+ properties: {
151
+ path: { type: 'string', description: 'Relative path to the target file' },
152
+ target: { type: 'string', description: 'Exact string snippet to find in the file' },
153
+ replacement: { type: 'string', description: 'New string snippet to replace target with' },
154
+ reason: { type: 'string', description: 'Clear explanation of why this edit is being made and how the fix/change works' },
155
+ },
156
+ required: ['path', 'target', 'replacement'],
157
+ },
158
+ },
159
+ {
160
+ name: 'run_command',
161
+ description: 'Execute a terminal/shell command in the workspace (e.g. npm test, npm run build, git status). WARNING: Do NOT use run_command to create files or folders (e.g. mkdir, touch, echo >)call write_file directly instead!',
162
+ parameters: {
163
+ type: 'object',
164
+ properties: {
165
+ command: { type: 'string', description: 'The terminal command string to execute' },
166
+ },
167
+ required: ['command'],
168
+ },
169
+ },
170
+ {
171
+ name: 'list_dir',
172
+ description: 'List contents of a directory in the workspace.',
173
+ parameters: {
174
+ type: 'object',
175
+ properties: {
176
+ path: { type: 'string', description: 'Relative directory path (default "." for root)' },
177
+ },
178
+ required: [],
179
+ },
180
+ },
181
+ {
182
+ name: 'grep_search',
183
+ description: 'Search for text pattern across all files in the codebase.',
184
+ parameters: {
185
+ type: 'object',
186
+ properties: {
187
+ query: { type: 'string', description: 'Text or substring to search for' },
188
+ },
189
+ required: ['query'],
190
+ },
191
+ },
192
+ {
193
+ name: 'glob_search',
194
+ description: 'Find workspace files matching a glob or file pattern (e.g. *.ts or src/**/*.js).',
195
+ parameters: {
196
+ type: 'object',
197
+ properties: {
198
+ pattern: { type: 'string', description: 'File pattern or extension filter' },
199
+ },
200
+ required: ['pattern'],
201
+ },
202
+ },
203
+ {
204
+ name: 'tree_view',
205
+ description: 'Generate a visual ASCII/Unicode directory tree of a workspace path to visualize folder structures.',
206
+ parameters: {
207
+ type: 'object',
208
+ properties: {
209
+ path: { type: 'string', description: 'Relative path to directory (default "." for workspace root)' },
210
+ maxDepth: { type: 'number', description: 'Maximum depth limit for tree traversal (default 3)' },
211
+ },
212
+ required: [],
213
+ },
214
+ },
215
+ {
216
+ name: 'file_info',
217
+ description: 'Get file statistics including file size, total line count, file extension, and last modification timestamp.',
218
+ parameters: {
219
+ type: 'object',
220
+ properties: {
221
+ path: { type: 'string', description: 'Relative path to the target file' },
222
+ },
223
+ required: ['path'],
224
+ },
225
+ },
226
+ {
227
+ name: 'multi_edit_file',
228
+ description: 'Apply multiple code snippet replacements across a file in a single step to execute complex refactoring efficiently.',
229
+ parameters: {
230
+ type: 'object',
231
+ properties: {
232
+ path: { type: 'string', description: 'Relative path to the target file' },
233
+ edits: {
234
+ type: 'array',
235
+ description: 'Array of target and replacement pairs to apply sequentially',
236
+ items: {
237
+ type: 'object',
238
+ properties: {
239
+ target: { type: 'string', description: 'Exact code snippet to replace' },
240
+ replacement: { type: 'string', description: 'New code replacement snippet' },
241
+ },
242
+ required: ['target', 'replacement'],
243
+ },
244
+ },
245
+ reason: { type: 'string', description: 'Explanation of why these multi-edits are being applied' },
246
+ },
247
+ required: ['path', 'edits'],
248
+ },
249
+ },
250
+ {
251
+ name: 'fetch_url',
252
+ description: 'Fetch content or documentation from an external HTTP/HTTPS URL for API docs, technical references, or specs.',
253
+ parameters: {
254
+ type: 'object',
255
+ properties: {
256
+ url: { type: 'string', description: 'The absolute HTTP or HTTPS URL to fetch' },
257
+ },
258
+ required: ['url'],
259
+ },
260
+ },
261
+ {
262
+ name: 'git_diff',
263
+ description: 'View current uncommitted git changes across the workspace or for a target file path.',
264
+ parameters: {
265
+ type: 'object',
266
+ properties: {
267
+ path: { type: 'string', description: 'Optional relative file path filter' },
268
+ },
269
+ required: [],
270
+ },
271
+ },
272
+ {
273
+ name: 'ask_user',
274
+ description: 'ONLY use for missing API keys or secret credentials. DO NOT use to ask the user what code to write or to re-confirm their prompttake immediate autonomous tool action instead.',
275
+ parameters: {
276
+ type: 'object',
277
+ properties: {
278
+ question: { type: 'string', description: 'The question or prompt to present to the user' },
279
+ },
280
+ required: ['question'],
281
+ },
282
+ },
283
+ {
284
+ name: 'speak_text',
285
+ description: 'Speak a text phrase out loud using Text-to-Speech (TTS) voice synthesis for voice feedback or audio summaries.',
286
+ parameters: {
287
+ type: 'object',
288
+ properties: {
289
+ text: { type: 'string', description: 'The text content to read aloud' },
290
+ },
291
+ required: ['text'],
292
+ },
293
+ },
294
+ {
295
+ name: 'task_completed',
296
+ description: 'Signal that the user goal has been fully completed with the full answer, results, and summary.',
297
+ parameters: {
298
+ type: 'object',
299
+ properties: {
300
+ summary: {
301
+ type: 'string',
302
+ description: 'The complete answer, findings, and results delivered directly to the user. For lookups or questions, this MUST include all retrieved details, accounts, URLs, or data.',
303
+ },
304
+ },
305
+ required: ['summary'],
306
+ },
307
+ },
308
+ ];
309
+ export function buildDirectoryTree(dirPath, prefix = '', currentDepth = 0, maxDepth = 3) {
310
+ if (currentDepth >= maxDepth)
311
+ return `${prefix}└── ... [depth limit reached]\n`;
312
+ if (!fs.existsSync(dirPath) || !fs.statSync(dirPath).isDirectory())
313
+ return '';
314
+ let result = '';
315
+ let entries = [];
316
+ try {
317
+ entries = fs.readdirSync(dirPath).filter((e) => !['.git', 'node_modules', '.ft', 'dist', 'bin/src/index.js'].includes(e));
318
+ }
319
+ catch {
320
+ return '';
321
+ }
322
+ entries.sort((a, b) => {
323
+ try {
324
+ const aIsDir = fs.statSync(path.join(dirPath, a)).isDirectory();
325
+ const bIsDir = fs.statSync(path.join(dirPath, b)).isDirectory();
326
+ if (aIsDir && !bIsDir)
327
+ return -1;
328
+ if (!aIsDir && bIsDir)
329
+ return 1;
330
+ }
331
+ catch { }
332
+ return a.localeCompare(b);
333
+ });
334
+ entries.forEach((entry, idx) => {
335
+ const isLast = idx === entries.length - 1;
336
+ const connector = isLast ? '└── ' : '├── ';
337
+ const childPath = path.join(dirPath, entry);
338
+ let isDir = false;
339
+ try {
340
+ isDir = fs.statSync(childPath).isDirectory();
341
+ }
342
+ catch { }
343
+ if (isDir) {
344
+ result += `${prefix}${connector}${entry}/\n`;
345
+ const childPrefix = prefix + (isLast ? ' ' : '│ ');
346
+ result += buildDirectoryTree(childPath, childPrefix, currentDepth + 1, maxDepth);
347
+ }
348
+ else {
349
+ result += `${prefix}${connector}${entry}\n`;
350
+ }
351
+ });
352
+ return result;
353
+ }
354
+ export class AgentExecutionLoop {
355
+ cwd;
356
+ historyMessages = [];
357
+ modifiedFiles = new Set();
358
+ backups = [];
359
+ autoApprove;
360
+ maxSteps;
361
+ startTime = Date.now();
362
+ totalToolCalls = 0;
363
+ currentStep = 0;
364
+ readFilesHistory = new Set();
365
+ consecutiveReads = 0;
366
+ consecutiveCommands = 0;
367
+ consecutiveScreenChecks = 0;
368
+ toolCallHistory = [];
369
+ taskStateManager;
370
+ browserController;
371
+ computerController;
372
+ actionVerifier;
373
+ approvalManager;
374
+ taskPlanner;
375
+ toolRegistry;
376
+ mockMode;
377
+ isCancelled = false;
378
+ cancelReason;
379
+ executionIntent;
380
+ userTier;
381
+ currentGoal = '';
382
+ isAudioMode = false;
383
+ constructor(options) {
384
+ this.cwd = process.cwd();
385
+ this.autoApprove = Boolean(options?.autoApprove);
386
+ this.mockMode = Boolean(options?.mockMode);
387
+ this.isAudioMode = Boolean(options?.isAudioMode);
388
+ this.userTier = (options?.tier || loadAuthConfig().currentTier || 'free').toLowerCase();
389
+ // Free tier is bounded to basic direct actions (max 5 steps). Full autonomous multi-step loops require Pro/Enterprise.
390
+ const isPaid = this.mockMode || this.userTier === 'pro' || this.userTier === 'enterprise';
391
+ const requestedSteps = options?.maxSteps || 30;
392
+ this.maxSteps = isPaid ? requestedSteps : Math.min(requestedSteps, 5);
393
+ this.taskStateManager = new TaskStateManager(options?.taskId, '', this.cwd);
394
+ this.computerController = options?.computerController || (this.mockMode ? new MockComputerController() : new SystemComputerController(this.cwd));
395
+ this.browserController = options?.browserController || new SemanticBrowserController(this.cwd);
396
+ this.actionVerifier = new ActionVerifier(this.cwd);
397
+ this.approvalManager = new ApprovalManager(this.autoApprove);
398
+ this.taskPlanner = new TaskPlanner();
399
+ this.toolRegistry = new UnifiedToolRegistry();
400
+ }
401
+ getUserTier() {
402
+ return this.userTier;
403
+ }
404
+ getExecutionIntent() {
405
+ return this.executionIntent;
406
+ }
407
+ getTaskStateManager() {
408
+ return this.taskStateManager;
409
+ }
410
+ getStateManager() {
411
+ return this.taskStateManager;
412
+ }
413
+ getBrowserController() {
414
+ return this.browserController;
415
+ }
416
+ getComputerController() {
417
+ return this.computerController;
418
+ }
419
+ getActionVerifier() {
420
+ return this.actionVerifier;
421
+ }
422
+ getApprovalManager() {
423
+ return this.approvalManager;
424
+ }
425
+ getPlanner() {
426
+ return this.taskPlanner;
427
+ }
428
+ getToolRegistry() {
429
+ return this.toolRegistry;
430
+ }
431
+ cancel(reason = 'User cancelled task') {
432
+ this.isCancelled = true;
433
+ this.cancelReason = reason;
434
+ this.taskStateManager.setStatus('failed');
435
+ this.taskStateManager.recordError(`Task execution cancelled: ${reason}`, 'runtime');
436
+ }
437
+ isTaskCancelled() {
438
+ return this.isCancelled;
439
+ }
440
+ async resumeGoal(taskId) {
441
+ const saved = TaskStateManager.loadTaskState(taskId, this.cwd);
442
+ if (!saved) {
443
+ return { success: false, summary: `Saved task checkpoint "${taskId}" not found.` };
444
+ }
445
+ this.taskStateManager.resumeFromState(saved);
446
+ if (this.mockMode) {
447
+ this.taskStateManager.setStatus('completed');
448
+ return {
449
+ success: true,
450
+ summary: `Resumed and completed task "${taskId}" in mock mode.`,
451
+ };
452
+ }
453
+ return await this.executeGoal(saved.objective);
454
+ }
455
+ getModifiedFiles() {
456
+ return Array.from(this.modifiedFiles);
457
+ }
458
+ getBackups() {
459
+ return this.backups;
460
+ }
461
+ getStats() {
462
+ return {
463
+ totalSteps: this.currentStep,
464
+ totalToolCalls: this.totalToolCalls,
465
+ modifiedFilesCount: this.modifiedFiles.size,
466
+ elapsedMs: Date.now() - this.startTime,
467
+ };
468
+ }
469
+ resetContext() {
470
+ this.historyMessages = [];
471
+ this.modifiedFiles.clear();
472
+ this.readFilesHistory.clear();
473
+ this.backups = [];
474
+ this.startTime = Date.now();
475
+ this.totalToolCalls = 0;
476
+ this.currentStep = 0;
477
+ this.consecutiveReads = 0;
478
+ this.consecutiveCommands = 0;
479
+ this.consecutiveScreenChecks = 0;
480
+ this.toolCallHistory = [];
481
+ this.executionIntent = undefined;
482
+ }
483
+ handleToolConsecutiveTracking(fnName, args, step) {
484
+ const argsKey = JSON.stringify(args || {});
485
+ this.toolCallHistory.push({ fnName, argsKey });
486
+ if (this.toolCallHistory.length > 10) {
487
+ this.toolCallHistory.shift();
488
+ }
489
+ // 1. Direct duplicate call check: Same tool + exact same arguments executed consecutively
490
+ const len = this.toolCallHistory.length;
491
+ if (len >= 2) {
492
+ const prev = this.toolCallHistory[len - 2];
493
+ const curr = this.toolCallHistory[len - 1];
494
+ if (prev && curr && prev.fnName === curr.fnName && prev.argsKey === curr.argsKey && !['task_completed', 'ask_user'].includes(fnName)) {
495
+ this.historyMessages.push({
496
+ role: 'user',
497
+ content: `CRITICAL ACTION LOOP DETECTED (Step ${step}): You called "${fnName}" with the EXACT same arguments as the previous step! Repeating this action will not change the outcome. DO NOT call this tool with these arguments again. Change your strategy immediately: search with different terms, navigate to the correct page, take a concrete input action, or call "task_completed" if done.`,
498
+ });
499
+ }
500
+ }
501
+ // 2. Ping-Pong / Oscillation loop check: A -> B -> A -> B
502
+ if (len >= 4) {
503
+ const a1 = this.toolCallHistory[len - 4];
504
+ const b1 = this.toolCallHistory[len - 3];
505
+ const a2 = this.toolCallHistory[len - 2];
506
+ const b2 = this.toolCallHistory[len - 1];
507
+ if (a1 && b1 && a2 && b2 &&
508
+ a1.fnName === a2.fnName && a1.argsKey === a2.argsKey &&
509
+ b1.fnName === b2.fnName && b1.argsKey === b2.argsKey &&
510
+ (a1.fnName !== b1.fnName || a1.argsKey !== b1.argsKey)) {
511
+ this.historyMessages.push({
512
+ role: 'user',
513
+ content: `CRITICAL OSCILLATION LOOP DETECTED (Step ${step}): You are stuck alternating between "${a1.fnName}" and "${b1.fnName}" without progressing! STOP repeating these actions immediately. If the page or app is not responding as expected, adopt an alternative path, use web search, launch the desktop app directly, or conclude with task_completed.`,
514
+ });
515
+ }
516
+ }
517
+ // 3. Screen inspection stagnation tracking
518
+ if (fnName === 'app_action') {
519
+ const act = String(args?.action || '').toLowerCase();
520
+ if (['see_screen', 'analyze_screen', 'capture_screen'].includes(act)) {
521
+ this.consecutiveScreenChecks++;
522
+ if (this.consecutiveScreenChecks >= 2) {
523
+ this.historyMessages.push({
524
+ role: 'user',
525
+ content: `URGENT ACTION MANDATE (Step ${step}): You have inspected the screen ${this.consecutiveScreenChecks} times consecutively without taking any physical action! Do not keep calling see_screen. Take a concrete action now: click an element ("click_element"), enter text ("type_text"), open/focus a window, or complete the task.`,
526
+ });
527
+ }
528
+ }
529
+ else {
530
+ this.consecutiveScreenChecks = 0;
531
+ }
532
+ }
533
+ else {
534
+ this.consecutiveScreenChecks = 0;
535
+ }
536
+ if (['read_file', 'list_dir', 'glob_search', 'grep_search', 'tree_view', 'file_info'].includes(fnName)) {
537
+ this.consecutiveReads++;
538
+ this.consecutiveCommands = 0;
539
+ if (this.consecutiveReads >= 2) {
540
+ const actionHint = this.executionIntent?.requiredInteraction === 'computer'
541
+ ? `Take action in the requested application (${this.executionIntent.requiredApplications.join(', ') || 'Notepad'})! Use computer_type, computer_click, or computer_hotkey now.`
542
+ : `You MUST execute write_file or edit_file on this step to write or modify code and satisfy the user goal.`;
543
+ this.historyMessages.push({
544
+ role: 'user',
545
+ content: `URGENT ACTION MANDATE (Step ${step}): You have issued ${this.consecutiveReads} exploration tool calls in a row without making progress! ${actionHint}`,
546
+ });
547
+ }
548
+ }
549
+ else if (fnName === 'run_command') {
550
+ this.consecutiveReads = 0;
551
+ this.consecutiveCommands++;
552
+ if (this.consecutiveCommands >= 2) {
553
+ const actionHint = this.executionIntent?.requiredInteraction === 'computer'
554
+ ? `Continue with computer interaction tools (computer_type, computer_hotkey) in the target application.`
555
+ : `Call 'write_file' or 'edit_file' NOW to write the required source code and files directly to disk!`;
556
+ this.historyMessages.push({
557
+ role: 'user',
558
+ content: `URGENT ACTION MANDATE (Step ${step}): You have executed ${this.consecutiveCommands} shell commands in a row without progress! ${actionHint}`,
559
+ });
560
+ }
561
+ }
562
+ else if (['write_file', 'edit_file', 'multi_edit_file'].includes(fnName)) {
563
+ this.consecutiveReads = 0;
564
+ this.consecutiveCommands = 0;
565
+ }
566
+ }
567
+ systemPrompt() {
568
+ const filesList = getDirectoryFiles(this.cwd).slice(0, 100);
569
+ const intentInfo = this.executionIntent ? `
570
+ Task Execution Intent & Constraints:
571
+ • Required Applications: ${this.executionIntent.requiredApplications.length > 0 ? this.executionIntent.requiredApplications.join(', ') : 'None specified'}
572
+ • Required Interaction Type: ${this.executionIntent.requiredInteraction}
573
+ • Allow Alternative Tools (e.g. direct filesystem): ${this.executionIntent.allowAlternativeTools ? 'YES' : 'NO (STRICT)'}
574
+ • Target Destination: ${this.executionIntent.targetDestination || 'Default'}
575
+ • Target Artifact: ${this.executionIntent.targetArtifactName || 'None'}
576
+ ` : '';
577
+ const isPaid = this.mockMode || this.userTier === 'pro' || this.userTier === 'enterprise';
578
+ const tierDirective = isPaid ? `
579
+ PLAN TIER & CAPABILITIES: ${this.userTier.toUpperCase()} (FULL ACCESS UNLOCKED)
580
+ • Autonomous Computer-Use, Browser Automation, and AI Scratchpad Reasoning are fully ENABLED.
581
+ • Use the 'scratchpad' tool to organize multi-step reasoning, break down complex goals, draft hypotheses, and track working memory across turns.
582
+ ` : `
583
+ PLAN TIER & CAPABILITIES: DEVELOPER FREE (BASIC DEVELOPER OPS ONLY)
584
+ • Scratchpadding and Autonomous Multi-Step Desktop/Browser Control are RESTRICTED to Pro & Enterprise plans.
585
+ • As a Free Tier developer assistant, you ONLY perform basic developer operations:
586
+ 1. Code editing: use edit_file or multi_edit_file to modify existing code.
587
+ 2. Creating new files & folders: use write_file to create new files and parent directories.
588
+ 3. Running commands: use run_command to execute terminal commands, builds, or tests.
589
+ 4. Reading & exploring: use read_file, list_dir, grep_search to inspect files.
590
+ • Do NOT attempt to use scratchpad, computer, or browser tools. Execute the requested file edit, file creation, or command directly and call task_completed immediately.
591
+ `;
592
+ const mcpRouting = getMCPManager().routeTools(this.currentGoal);
593
+ const mcpCapabilitiesSection = mcpRouting.capabilitiesSummary ? `\n${mcpRouting.capabilitiesSummary}\n` : '';
594
+ const recentSessionsMemory = getRecentSessionsSummary(3);
595
+ const sessionHistorySection = recentSessionsMemory ? `\n${recentSessionsMemory}\n` : '';
596
+ return `You are Scout Agent, an elite AI Principal Software Engineer & Autonomous Computer-Use Operator (developed by FrontTerrain).
597
+
598
+ Working Directory: "${this.cwd}"
599
+ Host OS Platform: "${process.platform}"
600
+ Current Date & Time: "${new Date().toISOString()}" (Current Year: ${new Date().getFullYear()})
601
+ ${tierDirective}
602
+ ${intentInfo}
603
+ ${mcpCapabilitiesSection}
604
+ ${sessionHistorySection}
605
+ Workspace Overview (first 100 files):
606
+ ${filesList.join('\n')}
607
+
608
+ CORE ARCHITECTURAL PRINCIPLES:
609
+ 1. USER INTENT > TOOL CONVENIENCE (CRITICAL MANDATE):
610
+ The easiest tool is NOT necessarily the correct tool. Scout optimizes for completing the user's ACTUAL REQUESTED WORKFLOW, not merely producing something that looks like the final artifact.
611
+ - Distinguish OUTCOME requirements (e.g. "Create a file containing X") from EXECUTION requirements (e.g. "Open Notepad, type X, save it as Y on Desktop").
612
+ - When the user explicitly specifies an application (e.g. Notepad, Excel, Chrome, VS Code) or computer interaction method, computer interaction tools (computer_open_app, computer_screenshot, computer_type, computer_hotkey, computer_switch_window, computer_click) MUST be used.
613
+ - NEVER silently substitute direct filesystem API calls (write_file) when computer/application interaction is required, unless the user explicitly permits alternative tools ("using any method you prefer").
614
+ - NEVER assume the repository root is the user's Desktop! If the user requests saving to Desktop, the file MUST be saved to the actual Desktop through the requested workflow.
615
+
616
+ 2. COMPUTER ACTION FAILURE RECOVERY:
617
+ When a computer action fails or encounters a problem:
618
+ DO NOT immediately switch to an unrelated tool (like write_file).
619
+ Instead, follow the bounded computer recovery loop:
620
+ ACTION FAILED ➔ OBSERVE SCREEN (computer_screenshot / computer_inspect_ui) ➔ UNDERSTAND FAILURE (check if application is active/focused) ➔ RETRY / ALTERNATIVE COMPUTER ACTION (switch window, click text area, send hotkey/keystrokes) ➔ OBSERVE ➔ CONTINUE.
621
+ Only after repeated bounded computer recovery attempts fail should you report the failure to the user.
622
+
623
+ 3. ACTIVE APPLICATION TRACKING:
624
+ Before sending keyboard or mouse input (computer_type, computer_click, computer_hotkey), ensure that the expected application (e.g. Notepad) is the active foreground window. If not, use computer_switch_window or computer_open_app to focus it first.
625
+
626
+ 4. REAL-TIME DATE AWARENESS: You are aware of real-time date and time (${new Date().getFullYear()}). Always use the current year (${new Date().getFullYear()}) and date for web searches, documentation, commit messages, and references. NEVER hardcode obsolete past years like 2024.
627
+ 5. HIGH AGENCY & AUTONOMY: You act autonomously through step-by-step tool invocation to solve complex coding tasks, debug issues, build features, create projects from scratch, or operate desktop applications.
628
+ 6. MULTILINGUAL & INTENT COMPREHENSION: Understand user intent in any language (English, Hinglish like "likho", "bnao", "code karo", "fix karo", "samjha do", Hindi, Spanish, etc.).
629
+ 7. FOR CODE & REPO TASKS: When the task is a coding, project refactoring, or repository maintenance task, use direct code modification tools (write_file, edit_file, run_command, read_file, grep_search).
630
+ 8. RUN & VERIFY COMMANDS: Execute shell commands, tests, builds, and formatters using run_command.
631
+ 9. CRITICAL TERMINATION, RESULTS DELIVERY & CONVERSATIONAL VOICE RULE:
632
+ - For ANY lookup, question, status check, external data retrieval, or inquiry (e.g. "Lookup up my github account", "What is X", "Check my PRs"):
633
+ Your 'summary' argument in task_completed (or your direct response) MUST contain the COMPLETE, ACCURATE, AND DETAILED ANSWER with all specific data found (usernames, repository names, statistics, URLs, findings, or explanations).
634
+ NEVER output a vacuous meta-summary like "Task completed" or "Looked up account" without providing the actual information the user asked for!
635
+ - For coding/modification tasks: Detail what was changed, created, and tested.
636
+ - CONVERSATIONAL CO-PILOT TONE: In your 'summary' parameter for task_completed, speak directly and warmly to the developer like an elite human co-pilot (e.g. "Here are your GitHub account details: your username is ..."). Never output dry mechanical robot logs or third-person phrases like "Objective achieved with 1 tool call". Talk directly to the user!
637
+ 10. THOUGHT TRANSPARENCY PROTOCOL: In EVERY step before calling any tools or ending a turn, you MUST provide a clear 1-2 sentence explanation in your text response describing your current reasoning, what file/action you are taking, and why you are taking it.
638
+ 11. APPLICATION LAUNCH & SIMPLE ACTION TERMINATION: When the user's objective is simply to open, launch, close, or focus an application (e.g. "Open Chrome", "Launch Notepad", "Open Calculator"): Immediately after calling computer_open_app or computer_close_app, your goal is 100% complete! You MUST call task_completed on the very next step with your friendly conversational summary. NEVER explore the repository or call list_dir, read_file, grep_search, or edit_file for app launching tasks!
639
+ 12. STRICT ACTIVE GOAL ISOLATION & ACCURACY:
640
+ - You must strictly execute ONLY the current active goal provided in the user prompt.
641
+ - Historical workspace sessions are provided for background context ONLY. NEVER re-run, repeat, or resume past session tasks unless the user explicitly requests it in the current prompt.
642
+ - For lookups, questions, status checks, or external service queries (e.g. GitHub account, MCP tools, web): deliver the concrete results directly and do NOT attempt to edit or rewrite unrelated workspace files.
643
+
644
+ When returning tool calls, use standard OpenAI function calling format or JSON tool call payload format:
645
+ \`\`\`json
646
+ {
647
+ "tool": "tool_name",
648
+ "args": { ... }
649
+ }
650
+ \`\`\`
651
+ `.trim();
652
+ }
653
+ async executeGoal(userGoal) {
654
+ this.resetContext();
655
+ this.currentGoal = userGoal;
656
+ this.taskStateManager.createTaskState(userGoal);
657
+ this.executionIntent = inferExecutionIntent(userGoal);
658
+ this.taskStateManager.setObjective(userGoal);
659
+ if (this.computerController.setExpectedApplication && this.executionIntent.requiredApplications.length > 0) {
660
+ this.computerController.setExpectedApplication(this.executionIntent.requiredApplications[0] ?? null);
661
+ }
662
+ const structuredPlan = this.taskPlanner.createPlan(userGoal);
663
+ this.taskStateManager.setPlan(structuredPlan.steps);
664
+ const mcpRouted = getMCPManager().routeTools(userGoal);
665
+ const mcpNames = mcpRouted.tools.map((t) => t.originalName);
666
+ this.taskStateManager.setAvailableTools([...this.toolRegistry.getToolsForTier(this.userTier).map((t) => t.name), ...mcpNames]);
667
+ if (this.mockMode) {
668
+ for (let i = 1; i <= structuredPlan.steps.length; i++) {
669
+ this.taskStateManager.startStep(i);
670
+ this.taskStateManager.completeStep(i, `Completed step ${i} in mock mode`);
671
+ }
672
+ this.taskStateManager.setStatus('completed');
673
+ return {
674
+ success: true,
675
+ summary: `Mock execution completed successfully for goal: "${userGoal}".`,
676
+ };
677
+ }
678
+ this.historyMessages.push({ role: 'system', content: this.systemPrompt() });
679
+ // Robust Target File Discovery: Only run file discovery if the goal has explicit code editing/modification intent
680
+ const simpleAppCheck = checkSimpleAppAction(userGoal);
681
+ const lowerGoal = userGoal.toLowerCase().trim();
682
+ const hasCodeEditIntent = /\b(edit|modify|fix|update|change|refactor|write|create|implement|patch|delete|remove|add\s+code|add\s+function|debug)\b/i.test(lowerGoal) &&
683
+ !/\b(lookup|look\s*up|who|what|why|where|how|explain|describe|tell|status|check|github|mcp)\b/i.test(lowerGoal);
684
+ const filesList = getDirectoryFiles(this.cwd);
685
+ const matchedFiles = [];
686
+ if (hasCodeEditIntent && !simpleAppCheck.isSimple) {
687
+ const isIgnoredFile = (filePath) => {
688
+ const norm = filePath.replace(/\\/g, '/').toLowerCase();
689
+ const ext = path.extname(norm);
690
+ const ignoredExts = ['.pyc', '.pyo', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.exe', '.bin', '.dll', '.so', '.dylib', '.zip', '.tar', '.gz'];
691
+ return (norm.includes('__pycache__/') ||
692
+ norm.includes('.git/') ||
693
+ norm.includes('node_modules/') ||
694
+ norm.includes('.ft/') ||
695
+ ignoredExts.includes(ext));
696
+ };
697
+ // Match potential paths
698
+ const pathMatches = userGoal.match(/(?:[a-zA-Z]:[\\/][^\s"':;,]+|\.?[\\/][^\s"':;,]+\.[a-zA-Z0-9]+|[a-zA-Z0-9_\-./\\]+\.[a-zA-Z0-9]+)/g) || [];
699
+ for (const rawPath of pathMatches) {
700
+ const cleanP = rawPath.replace(/^["'()]+|["'()]+$/g, '').trim();
701
+ if (!cleanP || cleanP.length < 3)
702
+ continue;
703
+ const fullP = path.isAbsolute(cleanP) ? cleanP : path.resolve(this.cwd, cleanP);
704
+ if (fs.existsSync(fullP) && fs.statSync(fullP).isFile()) {
705
+ const relP = path.relative(this.cwd, fullP).replace(/\\/g, '/');
706
+ if (!isIgnoredFile(relP) && !matchedFiles.includes(relP))
707
+ matchedFiles.push(relP);
708
+ }
709
+ else {
710
+ // Check if any file in filesList matches or ends with the extracted relative path or filename
711
+ const normToken = cleanP.replace(/\\/g, '/').toLowerCase();
712
+ const baseName = path.basename(normToken);
713
+ for (const f of filesList) {
714
+ if (isIgnoredFile(f))
715
+ continue;
716
+ const normF = f.replace(/\\/g, '/').toLowerCase();
717
+ if (normF === normToken || normF.endsWith('/' + normToken) || (baseName.includes('.') && normF.endsWith('/' + baseName))) {
718
+ if (!matchedFiles.includes(f))
719
+ matchedFiles.push(f);
720
+ }
721
+ }
722
+ }
723
+ }
724
+ // Keyword fallback only if explicit path wasn't matched and code edit intent exists
725
+ if (matchedFiles.length === 0) {
726
+ const stopWords = new Set([
727
+ 'the', 'a', 'an', 'in', 'is', 'for', 'to', 'of', 'and', 'or', 'on', 'at', 'by', 'from',
728
+ 'with', 'this', 'that', 'it', 'code', 'file', 'files', 'fix', 'add', 'make', 'create',
729
+ 'update', 'change', 'modify', 'edit', 'write', 'implement', 'bro', 'please', 'scout',
730
+ 'agent', 'bug', 'error', 'issue', 'help', 'app', 'project', 'script', 'function',
731
+ 'folder', 'dir', 'directory', 'testing', 'inside', 'open', 'vs', 'vscode', 'py', 'python',
732
+ 'new', 'build', 'run', 'test', 'suite'
733
+ ]);
734
+ const words = userGoal.split(/[\s,;:\/\\]+/).map((w) => w.replace(/["'(),;:!]/g, '').trim());
735
+ const keywords = words.filter((w) => w.length >= 3 && !stopWords.has(w.toLowerCase()));
736
+ for (const f of filesList) {
737
+ if (isIgnoredFile(f))
738
+ continue;
739
+ if (matchedFiles.length >= 3)
740
+ break;
741
+ const normF = f.replace(/\\/g, '/').toLowerCase();
742
+ const baseName = path.basename(normF, path.extname(normF));
743
+ for (const kw of keywords) {
744
+ const kwLower = kw.toLowerCase();
745
+ if (baseName === kwLower || normF.endsWith('/' + kwLower + path.extname(normF))) {
746
+ if (!matchedFiles.includes(f))
747
+ matchedFiles.push(f);
748
+ break;
749
+ }
750
+ }
751
+ }
752
+ }
753
+ // Safely inject high-confidence existing file previews without prompt-hijacking
754
+ for (const file of matchedFiles.slice(0, 3)) {
755
+ const fullP = path.resolve(this.cwd, file);
756
+ if (fs.existsSync(fullP) && fs.statSync(fullP).isFile()) {
757
+ const analyzeSpin = spinner();
758
+ analyzeSpin.start(chalk.cyan(` Auto-discovered target file: ${file}. Analyzing...`));
759
+ try {
760
+ const content = fs.readFileSync(fullP, 'utf-8');
761
+ const lines = content.split('\n');
762
+ analyzeSpin.stop(chalk.green(` Auto-discovered & analyzed ${file} (${lines.length} lines)`));
763
+ const previewSnippet = lines.length <= 250
764
+ ? lines.map((l, i) => `${i + 1} | ${l}`).join('\n')
765
+ : lines.slice(0, 100).map((l, i) => `${i + 1} | ${l}`).join('\n') + `\n... [truncated, file has ${lines.length} lines. Call read_file to view remaining lines]`;
766
+ this.readFilesHistory.add(file);
767
+ this.readFilesHistory.add(file.replace(/\\/g, '/').toLowerCase());
768
+ this.historyMessages.push({
769
+ role: 'user',
770
+ content: `[Reference Workspace Context - Pre-loaded target file "${file}" (${lines.length} lines)]:\n\`\`\`\n${previewSnippet}\n\`\`\`\n(Note: "${file}" is pre-loaded above for your reference. Use this context if relevant to completing the user goal.)`,
771
+ });
772
+ }
773
+ catch {
774
+ analyzeSpin.stop(chalk.yellow(`Could not read file ${file}`));
775
+ }
776
+ }
777
+ }
778
+ }
779
+ if (userGoal && userGoal.trim()) {
780
+ this.historyMessages.push({
781
+ role: 'user',
782
+ content: `USER GOAL: "${userGoal.trim()}"\n\nPlease execute the necessary steps and tools to fulfill this exact goal now.`,
783
+ });
784
+ }
785
+ const estTotalSecs = Math.round(this.maxSteps * 12);
786
+ const estTimeText = estTotalSecs >= 60 ? `~${(estTotalSecs / 60).toFixed(1)}m` : `~${estTotalSecs}s`;
787
+ console.log(chalk.gray(`Estimated completion time: ${estTimeText} (Max ${this.maxSteps} steps)`));
788
+ let step = 0;
789
+ let finalSummary = '';
790
+ const stepDurations = [];
791
+ while (step < this.maxSteps) {
792
+ if (this.isCancelled) {
793
+ return {
794
+ success: false,
795
+ summary: `Task cancelled: ${this.cancelReason || 'User abort'}`,
796
+ };
797
+ }
798
+ step++;
799
+ this.currentStep = step;
800
+ this.taskStateManager.startStep(step);
801
+ const stepStartTime = Date.now();
802
+ const avgStepMs = stepDurations.length > 0
803
+ ? stepDurations.reduce((a, b) => a + b, 0) / stepDurations.length
804
+ : 12000;
805
+ const remainingSteps = (this.maxSteps - step + 1);
806
+ const estSecsLeft = Math.max(5, Math.round((remainingSteps * avgStepMs) / 1000));
807
+ const estLeftStr = estSecsLeft >= 60
808
+ ? `${Math.floor(estSecsLeft / 60)}m ${estSecsLeft % 60}s`
809
+ : `${estSecsLeft}s`;
810
+ const stepSpinner = spinner();
811
+ stepSpinner.start(chalk.cyan(`Scout is Working (Step ${step}/${this.maxSteps} • Est. completion: ~${estLeftStr} left)`));
812
+ try {
813
+ let response;
814
+ const mcpRouting = getMCPManager().routeTools(userGoal);
815
+ const mcpToolDefs = mcpRouting.tools.map((mt) => ({
816
+ name: mt.originalName,
817
+ description: `[MCP: ${mt.serverName}] ${mt.description}`,
818
+ parameters: {
819
+ type: 'object',
820
+ properties: mt.inputSchema.properties || {},
821
+ required: mt.inputSchema.required || [],
822
+ },
823
+ source: 'mcp',
824
+ mcpServerId: mt.serverId,
825
+ mcpServerName: mt.serverName,
826
+ }));
827
+ const activeLoopTools = [...this.toolRegistry.getToolsForTier(this.userTier), ...mcpToolDefs];
828
+ try {
829
+ response = await callOpenAIWithRetry(async (model) => {
830
+ return await openai.chat.completions.create({
831
+ model,
832
+ messages: sanitizeMessages(this.historyMessages),
833
+ tools: activeLoopTools.map((t) => ({ type: 'function', function: t })),
834
+ tool_choice: 'auto',
835
+ temperature: 0.1,
836
+ presence_penalty: 0.1,
837
+ frequency_penalty: 0.1,
838
+ });
839
+ });
840
+ }
841
+ catch (err) {
842
+ const errStr = String(err?.message || err?.error || err || '').toLowerCase();
843
+ if (errStr.includes('tool') || errStr.includes('400') || errStr.includes('not supported') || errStr.includes('reasoning')) {
844
+ // Model doesn't support native function calling inject tool-call formatting hint
845
+ // so extractJsonToolCall can parse the response as a structured tool invocation
846
+ const toolHintMsg = {
847
+ role: 'user',
848
+ content: `IMPORTANT: This model does not support native function/tool calling. You MUST format your tool invocations as a JSON code block in your response like this:
849
+ \`\`\`json
850
+ { "tool": "tool_name", "args": { ... } }
851
+ \`\`\`
852
+ Available tools: read_file, write_file, edit_file, run_command, list_dir, grep_search, glob_search, tree_view, file_info, multi_edit_file, fetch_url, git_diff, ask_user, speak_text, task_completed.
853
+ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what you would do in plain textoutput the JSON tool call directly!`,
854
+ };
855
+ const fallbackMessages = [...this.historyMessages, toolHintMsg];
856
+ response = await callOpenAIWithRetry(async (model) => {
857
+ return await openai.chat.completions.create({
858
+ model,
859
+ messages: sanitizeMessages(fallbackMessages),
860
+ temperature: 0.1,
861
+ presence_penalty: 0.1,
862
+ frequency_penalty: 0.1,
863
+ });
864
+ });
865
+ }
866
+ else {
867
+ throw err;
868
+ }
869
+ }
870
+ const choice = response.choices[0];
871
+ if (!choice) {
872
+ stepSpinner.stop(chalk.yellow('No response from Scout. Retrying step...'));
873
+ continue;
874
+ }
875
+ const msg = sanitizeMessage(choice.message);
876
+ this.historyMessages.push(msg);
877
+ // Render assistant's thought reasoning text if provided on this turn
878
+ const textContent = msg.content || '';
879
+ if (textContent.trim()) {
880
+ safeNote(renderMarkdown(textContent), `Scout Thought (Step ${step})`);
881
+ if (this.isAudioMode) {
882
+ const speechText = cleanTextForSpeech(textContent);
883
+ if (speechText) {
884
+ speakText(speechText.length > 200 ? speechText.slice(0, 200) + '...' : speechText, { async: true });
885
+ }
886
+ }
887
+ }
888
+ // Check native tool calls
889
+ if (msg.tool_calls && msg.tool_calls.length > 0) {
890
+ stepSpinner.stop(chalk.green(`Step ${step}: Scout issued ${msg.tool_calls.length} tool call(s).`));
891
+ for (const tc of msg.tool_calls) {
892
+ if (tc.type === 'function' && tc.function) {
893
+ const fnName = tc.function.name;
894
+ let args = {};
895
+ try {
896
+ args = JSON.parse(tc.function.arguments || '{}');
897
+ }
898
+ catch { }
899
+ if (this.isAudioMode && fnName !== 'task_completed') {
900
+ let actionPhrase = '';
901
+ if (fnName === 'run_command')
902
+ actionPhrase = `Running command ${args.command ? args.command.slice(0, 40) : ''}`;
903
+ else if (fnName === 'read_file')
904
+ actionPhrase = `Reading ${path.basename(args.filePath || '')}`;
905
+ else if (fnName === 'write_file')
906
+ actionPhrase = `Creating ${path.basename(args.filePath || '')}`;
907
+ else if (fnName === 'edit_file')
908
+ actionPhrase = `Editing ${path.basename(args.filePath || '')}`;
909
+ else if (fnName.startsWith('mcp_') || fnName.includes('github'))
910
+ actionPhrase = `Querying ${fnName}`;
911
+ if (actionPhrase)
912
+ speakText(actionPhrase, { async: true });
913
+ }
914
+ const toolResult = await this.dispatchToolCall(fnName, args);
915
+ this.historyMessages.push({
916
+ role: 'user',
917
+ tool_call_id: tc.id,
918
+ content: `Tool Execution Result (${fnName}):\n${toolResult.result}`,
919
+ });
920
+ this.handleToolConsecutiveTracking(fnName, args, step);
921
+ // Automatic immediate completion for simple app actions (open/close/switch window)
922
+ if (simpleAppCheck.isSimple && (fnName === 'computer_open_app' || fnName === 'computer_close_app' || fnName === 'computer_switch_window')) {
923
+ let callSucceeded = false;
924
+ try {
925
+ const parsed = JSON.parse(toolResult.result);
926
+ callSucceeded = parsed.success !== false;
927
+ }
928
+ catch {
929
+ callSucceeded = !toolResult.result.toLowerCase().includes('failed') && !toolResult.result.toLowerCase().includes('error');
930
+ }
931
+ if (callSucceeded) {
932
+ const appName = simpleAppCheck.appName || 'application';
933
+ const actionVerb = simpleAppCheck.action === 'close' ? 'closed' : (simpleAppCheck.action === 'switch' ? 'focused' : 'launched');
934
+ finalSummary = `I've ${actionVerb} ${appName} for you. It's ready on your screen!`;
935
+ safeNote(chalk.green(` ${finalSummary}`), 'Task Completed');
936
+ saveAgentSession({
937
+ goal: userGoal,
938
+ summary: finalSummary,
939
+ modifiedFiles: [],
940
+ });
941
+ return { success: true, summary: finalSummary };
942
+ }
943
+ }
944
+ if (fnName === 'task_completed') {
945
+ finalSummary = args.summary || toolResult.result;
946
+ if (this.modifiedFiles.size > 0) {
947
+ const filesList = getDirectoryFiles(this.cwd);
948
+ const healRes = await verifyAndSelfHealFiles(Array.from(this.modifiedFiles), this.cwd, path.basename(this.cwd), filesList, { maxRetries: 3 });
949
+ if (healRes.verifiedFiles.length > 0) {
950
+ safeNote(chalk.green(` Self-Healing Verification Confirmed: ${healRes.verifiedFiles.length} file(s) syntax & build clean!`), ' Code Verification Clean');
951
+ }
952
+ if (healRes.remainingErrors.length > 0) {
953
+ safeNote(chalk.yellow(`️ Remaining verification issues:\n${healRes.remainingErrors.join('\n')}`), '️ Verification Warning');
954
+ }
955
+ }
956
+ saveAgentSession({
957
+ goal: userGoal,
958
+ summary: finalSummary,
959
+ modifiedFiles: Array.from(this.modifiedFiles),
960
+ });
961
+ return { success: true, summary: finalSummary };
962
+ }
963
+ }
964
+ }
965
+ continue;
966
+ }
967
+ // Check text response or fallback JSON tool call
968
+ stepSpinner.stop(chalk.blue(`Step ${step} thinking complete.`));
969
+ const parsedJsonTool = this.extractJsonToolCall(textContent);
970
+ if (parsedJsonTool) {
971
+ const toolResult = await this.dispatchToolCall(parsedJsonTool.tool, parsedJsonTool.args);
972
+ this.historyMessages.push({
973
+ role: 'user',
974
+ content: `Tool Execution Result (${parsedJsonTool.tool}):\n${toolResult.result}`,
975
+ });
976
+ this.handleToolConsecutiveTracking(parsedJsonTool.tool, parsedJsonTool.args, step);
977
+ // Automatic immediate completion for simple app actions (open/close/switch window)
978
+ if (simpleAppCheck.isSimple && (parsedJsonTool.tool === 'computer_open_app' || parsedJsonTool.tool === 'computer_close_app' || parsedJsonTool.tool === 'computer_switch_window')) {
979
+ let callSucceeded = false;
980
+ try {
981
+ const parsed = JSON.parse(toolResult.result);
982
+ callSucceeded = parsed.success !== false;
983
+ }
984
+ catch {
985
+ callSucceeded = !toolResult.result.toLowerCase().includes('failed') && !toolResult.result.toLowerCase().includes('error');
986
+ }
987
+ if (callSucceeded) {
988
+ const appName = simpleAppCheck.appName || 'application';
989
+ const actionVerb = simpleAppCheck.action === 'close' ? 'closed' : (simpleAppCheck.action === 'switch' ? 'focused' : 'launched');
990
+ finalSummary = `I've ${actionVerb} ${appName} for you. It's ready on your screen!`;
991
+ safeNote(chalk.green(` ${finalSummary}`), 'Task Completed');
992
+ saveAgentSession({
993
+ goal: userGoal,
994
+ summary: finalSummary,
995
+ modifiedFiles: [],
996
+ });
997
+ return { success: true, summary: finalSummary };
998
+ }
999
+ }
1000
+ if (parsedJsonTool.tool === 'task_completed') {
1001
+ finalSummary = parsedJsonTool.args?.summary || toolResult.result;
1002
+ saveAgentSession({
1003
+ goal: userGoal,
1004
+ summary: finalSummary,
1005
+ modifiedFiles: Array.from(this.modifiedFiles),
1006
+ });
1007
+ return { success: true, summary: finalSummary };
1008
+ }
1009
+ continue;
1010
+ }
1011
+ if (textContent.trim()) {
1012
+ let cleanedThought = textContent
1013
+ .replace(/[\u0600-\u06FF\u0750-\u077F\uAC00-\uD7AF\u3040-\u30FF\u4E00-\u9FFF\u0D80-\u0DFF]+/g, '')
1014
+ .trim();
1015
+ if (!cleanedThought || cleanedThought.length < 5) {
1016
+ cleanedThought = 'Analyzing codebase files and executing next tool operation...';
1017
+ }
1018
+ safeNote(renderMarkdown(cleanedThought), ` Scout Agent Thought (Step ${step})`);
1019
+ const lowerText = textContent.toLowerCase();
1020
+ const isExplicitCompletion = lowerText.includes('task is complete') ||
1021
+ lowerText.includes('task complete') ||
1022
+ lowerText.includes('goal completed') ||
1023
+ lowerText.includes('goal is completed') ||
1024
+ lowerText.includes('all tasks completed') ||
1025
+ lowerText.includes('i have completed') ||
1026
+ lowerText.includes('no further changes needed') ||
1027
+ lowerText.includes('the fix is complete') ||
1028
+ lowerText.includes('has been created') ||
1029
+ lowerText.includes('successfully created') ||
1030
+ lowerText.includes('created the file') ||
1031
+ lowerText.includes('file created') ||
1032
+ lowerText.includes('implementation complete') ||
1033
+ lowerText.includes('work is complete');
1034
+ const isInformationalGoal = /^(?:lookup|look\s*up|check|find|who|what|why|where|how|tell|show|explain|display|list|search|query|status|info|get|fetch|describe)\b/i.test(userGoal.trim()) ||
1035
+ !/\b(create|make|write|edit|modify|fix|update|refactor|build|delete|remove|patch|implement)\b/i.test(userGoal.trim());
1036
+ const isAnsweringInformational = isInformationalGoal && textContent.trim().length > 20 && !lowerText.includes('error occurred') && !lowerText.includes('cannot complete');
1037
+ const isSummaryAfterModifications = this.modifiedFiles.size > 0 && !lowerText.includes('?') && textContent.trim().length > 30;
1038
+ const isSummaryAfterToolExecution = this.totalToolCalls > 0 && textContent.trim().length > 30 && !lowerText.includes('calling tool') && !lowerText.includes('next step');
1039
+ // If explicit completion phrase found, OR informational answer provided, OR files were modified, OR tools were executed and assistant is delivering the summary
1040
+ if (isExplicitCompletion || isAnsweringInformational || isSummaryAfterModifications || isSummaryAfterToolExecution) {
1041
+ saveAgentSession({
1042
+ goal: userGoal,
1043
+ summary: textContent,
1044
+ modifiedFiles: Array.from(this.modifiedFiles),
1045
+ });
1046
+ return { success: true, summary: textContent };
1047
+ }
1048
+ }
1049
+ // If assistant responded with text without calling tools, prompt it to execute tools to complete the goal
1050
+ this.historyMessages.push({
1051
+ role: 'user',
1052
+ content: 'You provided a text response but have not called any tools (write_file, edit_file, run_command, task_completed). Please execute necessary tool calls to complete the user goal, or invoke task_completed if finished.',
1053
+ });
1054
+ stepDurations.push(Date.now() - stepStartTime);
1055
+ }
1056
+ catch (err) {
1057
+ stepDurations.push(Date.now() - stepStartTime);
1058
+ if (isQuotaExceededError(err)) {
1059
+ stepSpinner.stop(chalk.red(`Oops! it\'s not you, it\'s us`));
1060
+ safeNote(`${chalk.bold.red(`Something went wrong in (Step ${step}), please try again in a moment`)}\n\n` +
1061
+ `${chalk.yellow('The configured AI provider has reached its API usage limit or rate cap.')}\n` +
1062
+ `${chalk.dim('This is separate from your Scout credit balance shown by `scout quota`.')}\n\n` +
1063
+ `${chalk.bold.cyan(' Please come back and try again in a few hours (or check back later today).')}\n\n` +
1064
+ `${chalk.dim('Scout Agent session has ended gracefully to protect remaining workflow.')}`, '️ API Quota Limit Reached');
1065
+ return {
1066
+ success: false,
1067
+ summary: 'Something went wrong, please try again in a moment.',
1068
+ };
1069
+ }
1070
+ stepSpinner.stop(chalk.red(`Step ${step} execution error: ${err?.message || String(err)}`));
1071
+ this.historyMessages.push({
1072
+ role: 'user',
1073
+ content: `Error in previous turn: ${err?.message || String(err)}. Please try alternative steps or call tools.`,
1074
+ });
1075
+ }
1076
+ // Step limit check: Auto-extend by +15 steps ONLY for Pro & Enterprise (up to 60 max threshold)
1077
+ const isPaid = this.mockMode || this.userTier === 'pro' || this.userTier === 'enterprise';
1078
+ if (step >= this.maxSteps) {
1079
+ if (isPaid && this.maxSteps < 60) {
1080
+ this.maxSteps += 15;
1081
+ safeNote(chalk.bold.yellow(`⚡ Step limit reached while task is in progress. Automatically extending execution by +15 extra steps (New Max Limit: ${this.maxSteps})...`), ' Auto Extra Steps Extension');
1082
+ }
1083
+ else if (!isPaid) {
1084
+ safeNote(chalk.bold.yellow(`⚡ Free Tier limit reached (${this.maxSteps} steps).\nFree developers can perform basic code editing, creating files/folders, and running commands.\nTo unlock unlimited autonomous multi-step loops and scratchpad reasoning, upgrade to Pro at https://scout.frontterrain.com/plans or run 'scout dashboard'.`), ' Free Tier Step Limit');
1085
+ break;
1086
+ }
1087
+ }
1088
+ }
1089
+ return {
1090
+ success: false,
1091
+ summary: `Reached max iteration steps limit (${this.maxSteps}). Modified files: ${Array.from(this.modifiedFiles).join(', ')}`,
1092
+ };
1093
+ }
1094
+ extractJsonToolCall(content) {
1095
+ if (!content)
1096
+ return null;
1097
+ const funcMatch = content.match(/<function=([a-zA-Z0-9_]+)>([\s\S]*?)<\/function>/i);
1098
+ if (funcMatch && funcMatch[1] && funcMatch[2]) {
1099
+ const tool = funcMatch[1].trim();
1100
+ let args = {};
1101
+ try {
1102
+ args = JSON.parse(funcMatch[2].trim());
1103
+ }
1104
+ catch {
1105
+ args = { raw: funcMatch[2].trim() };
1106
+ }
1107
+ return { tool, args };
1108
+ }
1109
+ const knownTools = [
1110
+ 'read_file', 'write_file', 'edit_file', 'run_command', 'list_dir',
1111
+ 'grep_search', 'glob_search', 'tree_view', 'file_info', 'multi_edit_file',
1112
+ 'fetch_url', 'git_diff',
1113
+ 'ask_user', 'speak_text', 'task_completed', 'scratchpad',
1114
+ ];
1115
+ for (const toolName of knownTools) {
1116
+ const tagRegex = new RegExp(`<${toolName}>([\\s\\S]*?)<\\/${toolName}>`, 'i');
1117
+ const match = content.match(tagRegex);
1118
+ if (match && match[1]) {
1119
+ let args = {};
1120
+ try {
1121
+ args = JSON.parse(match[1].trim());
1122
+ }
1123
+ catch {
1124
+ args = { content: match[1].trim() };
1125
+ }
1126
+ return { tool: toolName, args };
1127
+ }
1128
+ }
1129
+ const jsonMatch = content.match(/```json\s*([\s\S]*?)\s*```/) || content.match(/\{[\s\S]*"tool"[\s\S]*\}/);
1130
+ if (jsonMatch) {
1131
+ try {
1132
+ const rawStr = jsonMatch[1] || jsonMatch[0];
1133
+ const obj = JSON.parse(rawStr);
1134
+ if (obj && typeof obj.tool === 'string') {
1135
+ return { tool: obj.tool, args: obj.args || obj.parameters || {} };
1136
+ }
1137
+ }
1138
+ catch { }
1139
+ }
1140
+ return null;
1141
+ }
1142
+ async dispatchToolCall(name, args) {
1143
+ this.totalToolCalls++;
1144
+ let actionDesc = '';
1145
+ if (name === 'read_file')
1146
+ actionDesc = `Reading file: ${args.path || ''}`;
1147
+ else if (name === 'write_file')
1148
+ actionDesc = `Writing/Creating file: ${args.path || ''}`;
1149
+ else if (name === 'edit_file')
1150
+ actionDesc = `Editing file: ${args.path || ''}`;
1151
+ else if (name === 'multi_edit_file')
1152
+ actionDesc = `Multi-editing file: ${args.path || ''}`;
1153
+ else if (name === 'run_command')
1154
+ actionDesc = `Executing command: ${args.command || args.cmd || ''}`;
1155
+ else if (name === 'list_dir')
1156
+ actionDesc = `Listing directory: ${args.path || '.'}`;
1157
+ else if (name === 'tree_view')
1158
+ actionDesc = `Generating directory tree: ${args.path || '.'}`;
1159
+ else if (name === 'file_info')
1160
+ actionDesc = `Inspecting file stats: ${args.path || ''}`;
1161
+ else if (name === 'grep_search')
1162
+ actionDesc = `Searching pattern: "${args.query || args.pattern || ''}"`;
1163
+ else if (name === 'glob_search')
1164
+ actionDesc = `Finding files: "${args.pattern || ''}"`;
1165
+ else if (name === 'fetch_url')
1166
+ actionDesc = `Fetching URL: ${args.url || ''}`;
1167
+ else if (name === 'git_diff')
1168
+ actionDesc = `Retrieving workspace git diff`;
1169
+ else if (name === 'browser_navigate')
1170
+ actionDesc = `Navigating browser: ${args.url || ''}`;
1171
+ else if (name === 'browser_inspect')
1172
+ actionDesc = `Inspecting web page elements`;
1173
+ else if (name === 'browser_click')
1174
+ actionDesc = `Clicking web element: ${args.selectorOrText || ''}`;
1175
+ else if (name === 'browser_type')
1176
+ actionDesc = `Typing in web input: ${args.selectorOrText || ''}`;
1177
+ else if (name === 'browser_download')
1178
+ actionDesc = `Downloading file: ${args.urlOrSelector || ''}`;
1179
+ else if (name === 'browser_content')
1180
+ actionDesc = `Extracting web page content`;
1181
+ else if (name === 'computer_screenshot')
1182
+ actionDesc = `Observing computer screen`;
1183
+ else if (name === 'computer_click')
1184
+ actionDesc = `Clicking screen coordinate: (${args.x}, ${args.y})`;
1185
+ else if (name === 'computer_right_click')
1186
+ actionDesc = `Right clicking coordinate: (${args.x}, ${args.y})`;
1187
+ else if (name === 'computer_double_click')
1188
+ actionDesc = `Double clicking coordinate: (${args.x}, ${args.y})`;
1189
+ else if (name === 'computer_mouse_down')
1190
+ actionDesc = `Mouse down (${args.button || 'left'})`;
1191
+ else if (name === 'computer_mouse_up')
1192
+ actionDesc = `Mouse up (${args.button || 'left'})`;
1193
+ else if (name === 'computer_mouse_move')
1194
+ actionDesc = `Moving mouse to: (${args.x}, ${args.y})`;
1195
+ else if (name === 'computer_drag')
1196
+ actionDesc = `Dragging from (${args.fromX ?? args.startX}, ${args.fromY ?? args.startY}) to (${args.toX ?? args.endX}, ${args.toY ?? args.endY})`;
1197
+ else if (name === 'computer_type')
1198
+ actionDesc = `Typing text: "${String(args.text || '').slice(0, 30)}"`;
1199
+ else if (name === 'computer_key_press')
1200
+ actionDesc = `Pressing key: ${args.key || ''}`;
1201
+ else if (name === 'computer_hotkey')
1202
+ actionDesc = `Executing hotkey: ${(args.keys || []).join('+')}`;
1203
+ else if (name === 'computer_open_app')
1204
+ actionDesc = `Launching application: ${args.appName || args.app || ''}`;
1205
+ else if (name === 'computer_close_app')
1206
+ actionDesc = `Closing application: ${args.appName || args.app || ''}`;
1207
+ else if (name === 'computer_switch_window')
1208
+ actionDesc = `Switching window: ${args.windowTitleOrApp || ''}`;
1209
+ else if (name === 'computer_inspect_ui')
1210
+ actionDesc = `Inspecting visible desktop UI`;
1211
+ else if (name === 'computer_diagnostic')
1212
+ actionDesc = `Running computer control diagnostics`;
1213
+ else if (name === 'computer')
1214
+ actionDesc = `Computer action: ${args.action || 'action'}`;
1215
+ else if (name === 'scratchpad')
1216
+ actionDesc = `Scratchpad (${args.action || 'read'})`;
1217
+ else if (name === 'task_completed')
1218
+ actionDesc = `Task finished`;
1219
+ const badge = chalk.bgCyan.black.bold(` 🛠️ TOOL: ${name} `);
1220
+ const descText = actionDesc ? chalk.yellow.bold(` → ${actionDesc}`) : '';
1221
+ console.log(`\n${badge}${descText} ${chalk.dim(JSON.stringify(args))}`);
1222
+ const isPaid = this.mockMode || this.userTier === 'pro' || this.userTier === 'enterprise';
1223
+ // 1. Scratchpad Feature Gating (Pro & Enterprise only)
1224
+ if (name === 'scratchpad') {
1225
+ if (!isPaid) {
1226
+ const blockedMsg = `[PLAN RESTRICTION: PRO / ENTERPRISE ONLY] The Scratchpad reasoning memory is exclusive to Pro and Enterprise tiers. Free tier developers can perform basic code editing (edit_file), creating files and folders (write_file), and running commands (run_command). To unlock the AI scratchpad, upgrade at https://scout.frontterrain.com/plans or run 'scout dashboard'.`;
1227
+ console.log(chalk.red.bold(`\n⛔ ${blockedMsg}`));
1228
+ this.taskStateManager.addObservation(name, blockedMsg, false);
1229
+ return { result: blockedMsg };
1230
+ }
1231
+ const action = String(args.action || 'read').toLowerCase().trim();
1232
+ const content = String(args.content || '');
1233
+ const ftDir = path.join(this.cwd, '.ft');
1234
+ const scratchPath = path.join(ftDir, 'scratchpad.md');
1235
+ fs.mkdirSync(ftDir, { recursive: true });
1236
+ let currentScratch = '';
1237
+ if (fs.existsSync(scratchPath)) {
1238
+ try {
1239
+ currentScratch = fs.readFileSync(scratchPath, 'utf-8');
1240
+ }
1241
+ catch { }
1242
+ }
1243
+ if (action === 'write') {
1244
+ fs.writeFileSync(scratchPath, content, 'utf-8');
1245
+ this.taskStateManager.addObservation(name, `Scratchpad updated (${content.length} chars)`, true);
1246
+ return { result: `Scratchpad updated successfully:\n${content}` };
1247
+ }
1248
+ else if (action === 'append') {
1249
+ const updated = currentScratch ? `${currentScratch}\n\n---\n<!-- ${new Date().toISOString()} -->\n${content}` : content;
1250
+ fs.writeFileSync(scratchPath, updated, 'utf-8');
1251
+ this.taskStateManager.addObservation(name, `Appended to scratchpad (${content.length} chars)`, true);
1252
+ return { result: `Appended to scratchpad. Current contents:\n${updated}` };
1253
+ }
1254
+ else if (action === 'clear') {
1255
+ fs.writeFileSync(scratchPath, '', 'utf-8');
1256
+ this.taskStateManager.addObservation(name, `Cleared scratchpad`, true);
1257
+ return { result: `Scratchpad cleared.` };
1258
+ }
1259
+ else {
1260
+ this.taskStateManager.addObservation(name, `Read scratchpad (${currentScratch.length} chars)`, true);
1261
+ return { result: currentScratch ? `Scratchpad Contents:\n${currentScratch}` : `Scratchpad is currently empty.` };
1262
+ }
1263
+ }
1264
+ // 2. Autonomous Computer & Browser Automation Gating (Pro & Enterprise only)
1265
+ if (name === 'computer' || name.startsWith('computer_') || name.startsWith('browser_')) {
1266
+ if (!isPaid) {
1267
+ const blockedMsg = `[PLAN RESTRICTION: PRO / ENTERPRISE ONLY] Autonomous Computer-Use & Browser Automation features are exclusive to Pro and Enterprise tiers. Free tier developers can perform basic code editing (edit_file), creating files and folders (write_file), and running commands (run_command) in the workspace. Upgrade to Pro at https://scout.frontterrain.com/plans or run 'scout dashboard'.`;
1268
+ console.log(chalk.red.bold(`\n⛔ ${blockedMsg}`));
1269
+ this.taskStateManager.addObservation(name, blockedMsg, false);
1270
+ return { result: blockedMsg };
1271
+ }
1272
+ }
1273
+ // Safety and human approval classification layer
1274
+ const risk = this.approvalManager.checkAction(name, args);
1275
+ if (risk.requiresApproval && !this.autoApprove) {
1276
+ this.taskStateManager.setPendingAction({
1277
+ id: `act_${Date.now()}`,
1278
+ tool: name,
1279
+ args,
1280
+ riskLevel: risk.level,
1281
+ riskReason: risk.reason,
1282
+ requestedAt: new Date().toISOString(),
1283
+ });
1284
+ const decision = await this.approvalManager.requestApproval(this.taskStateManager.getState().task_id, name, args, risk);
1285
+ this.taskStateManager.setPendingAction(null);
1286
+ if (!decision.approved) {
1287
+ this.taskStateManager.addObservation(name, `[ACTION BLOCKED: User rejected approval: ${decision.reason || 'Not approved'}]`, false);
1288
+ return { result: `[ACTION REJECTED BY USER]: ${decision.reason || 'User did not approve executing this action.'}` };
1289
+ }
1290
+ }
1291
+ // Validate against execution intent (USER INTENT > TOOL CONVENIENCE)
1292
+ const simpleCheckInDispatch = checkSimpleAppAction(this.taskStateManager.getState()?.objective || '');
1293
+ if (simpleCheckInDispatch.isSimple) {
1294
+ if (['list_dir', 'read_file', 'grep_search', 'glob_search', 'file_info', 'tree_view', 'write_file', 'edit_file', 'multi_edit_file'].includes(name)) {
1295
+ const blockedExplorationMsg = `[UNNECESSARY WORKSPACE EXPLORATION BLOCKED]: The user only requested to ${simpleCheckInDispatch.action || 'launch'} ${simpleCheckInDispatch.appName || 'the application'}. Reading repository code or listing files (${name}) is forbidden for this task. You must call task_completed immediately.`;
1296
+ this.taskStateManager.addObservation(name, blockedExplorationMsg, false);
1297
+ return {
1298
+ result: JSON.stringify({
1299
+ success: false,
1300
+ action: name,
1301
+ error: 'UnnecessaryWorkspaceExplorationBlocked',
1302
+ message: blockedExplorationMsg,
1303
+ directive: "Call 'task_completed' NOW with your completion summary."
1304
+ }, null, 2)
1305
+ };
1306
+ }
1307
+ }
1308
+ if (this.executionIntent && !this.executionIntent.allowAlternativeTools) {
1309
+ if (this.executionIntent.requiredInteraction === 'computer') {
1310
+ if (['write_file', 'edit_file', 'multi_edit_file'].includes(name)) {
1311
+ const reqApps = this.executionIntent.requiredApplications.join(', ') || 'the requested desktop application';
1312
+ const violationMsg = `[EXECUTION INTENT VIOLATION BLOCKED]: User explicitly required computer/application interaction using ${reqApps}. You cannot silently substitute direct filesystem API calls (${name}). You must use computer interaction tools (computer_open_app, computer_switch_window, computer_click, computer_type, computer_hotkey) to perform this task in ${reqApps}.`;
1313
+ console.log(chalk.red.bold(`\n⛔ ${violationMsg}`));
1314
+ this.taskStateManager.addObservation(name, violationMsg, false);
1315
+ return {
1316
+ result: JSON.stringify({
1317
+ success: false,
1318
+ action: name,
1319
+ error: 'ExecutionIntentViolation',
1320
+ message: violationMsg,
1321
+ recoverable: true,
1322
+ suggestedAction: `Use computer interaction tools with ${reqApps}. Focus the window, type text into the app, and save through the application UI.`
1323
+ }, null, 2)
1324
+ };
1325
+ }
1326
+ }
1327
+ }
1328
+ if (name === 'computer') {
1329
+ const action = String(args.action || 'screenshot').toLowerCase().trim();
1330
+ if (action === 'click' || action === 'left_click') {
1331
+ name = 'computer_click';
1332
+ }
1333
+ else if (action === 'right_click') {
1334
+ name = 'computer_right_click';
1335
+ }
1336
+ else if (action === 'double_click') {
1337
+ name = 'computer_double_click';
1338
+ }
1339
+ else if (action === 'move' || action === 'mouse_move') {
1340
+ name = 'computer_mouse_move';
1341
+ }
1342
+ else if (action === 'mouse_down') {
1343
+ name = 'computer_mouse_down';
1344
+ }
1345
+ else if (action === 'mouse_up') {
1346
+ name = 'computer_mouse_up';
1347
+ }
1348
+ else if (action === 'drag') {
1349
+ name = 'computer_drag';
1350
+ args.fromX = args.startX ?? args.fromX;
1351
+ args.fromY = args.startY ?? args.fromY;
1352
+ args.toX = args.endX ?? args.toX;
1353
+ args.toY = args.endY ?? args.toY;
1354
+ }
1355
+ else if (action === 'scroll') {
1356
+ name = 'computer_scroll';
1357
+ }
1358
+ else if (action === 'screenshot') {
1359
+ name = 'computer_screenshot';
1360
+ }
1361
+ else if (action === 'type') {
1362
+ name = 'computer_type';
1363
+ }
1364
+ else if (action === 'key_press' || action === 'key') {
1365
+ name = 'computer_key_press';
1366
+ }
1367
+ else if (action === 'hotkey') {
1368
+ name = 'computer_hotkey';
1369
+ }
1370
+ else if (action === 'open_app') {
1371
+ name = 'computer_open_app';
1372
+ }
1373
+ else if (action === 'close_app') {
1374
+ name = 'computer_close_app';
1375
+ }
1376
+ else if (action === 'switch_window') {
1377
+ name = 'computer_switch_window';
1378
+ }
1379
+ else if (action === 'inspect_ui') {
1380
+ name = 'computer_inspect_ui';
1381
+ }
1382
+ else if (action === 'diagnostic') {
1383
+ name = 'computer_diagnostic';
1384
+ }
1385
+ }
1386
+ // Tier Gating Enforcement
1387
+ if (!isPaid) {
1388
+ if (name.startsWith('computer_') || name === 'computer') {
1389
+ const upgradeMsg = `[PLAN RESTRICTION]: Autonomous Computer Control tools (${name}) are exclusively available to Pro and Enterprise plan developers. Free tier developers can perform code editing, creating files/folders, and running terminal commands. Upgrade to Pro at https://scout.frontterrain.com to unlock autonomous computer & app control.`;
1390
+ this.taskStateManager.addObservation(name, upgradeMsg, false);
1391
+ return { result: upgradeMsg };
1392
+ }
1393
+ if (name.startsWith('browser_')) {
1394
+ const upgradeMsg = `[PLAN RESTRICTION]: Autonomous Browser Control tools (${name}) are exclusively available to Pro and Enterprise plan developers. Free tier developers can perform code editing, creating files/folders, and running terminal commands. Upgrade to Pro at https://scout.frontterrain.com to unlock browser automation.`;
1395
+ this.taskStateManager.addObservation(name, upgradeMsg, false);
1396
+ return { result: upgradeMsg };
1397
+ }
1398
+ if (name === 'scratchpad') {
1399
+ const upgradeMsg = `[PLAN RESTRICTION]: AI Scratchpad & Autonomous reasoning is an exclusive feature for Pro and Enterprise plan subscribers. Free tier developers can perform code editing, creating files/folders, and running commands. Upgrade to Pro at https://scout.frontterrain.com to unlock the AI Scratchpad.`;
1400
+ this.taskStateManager.addObservation(name, upgradeMsg, false);
1401
+ return { result: upgradeMsg };
1402
+ }
1403
+ }
1404
+ switch (name) {
1405
+ case 'read_file': {
1406
+ const targetPath = String(args.path || '').trim();
1407
+ const fullPath = path.isAbsolute(targetPath) ? targetPath : path.resolve(this.cwd, targetPath);
1408
+ const relPath = path.relative(this.cwd, fullPath).replace(/\\/g, '/');
1409
+ const normKey = relPath.toLowerCase();
1410
+ if (this.readFilesHistory.has(normKey) || this.readFilesHistory.has(targetPath.toLowerCase())) {
1411
+ const readSpin = spinner();
1412
+ readSpin.stop(chalk.yellow(` Skipped duplicate read for ${targetPath} (already in context)`));
1413
+ return {
1414
+ result: `[DUPLICATE READ BLOCKED]: File "${targetPath}" has ALREADY been read in an earlier step! The complete file content is already present in your context history above. DO NOT re-read files! TAKE IMMEDIATE ACTION NOW: Call write_file, edit_file, or run_command to write/update the code to complete the user goal.`
1415
+ };
1416
+ }
1417
+ this.readFilesHistory.add(normKey);
1418
+ this.readFilesHistory.add(targetPath.toLowerCase());
1419
+ const readSpin = spinner();
1420
+ readSpin.start(chalk.cyan(` Analyzing file ${targetPath}...`));
1421
+ if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {
1422
+ readSpin.stop(chalk.red(`Failed to analyze file ${targetPath}: File not found.`));
1423
+ return { result: `Error: File not found at path "${targetPath}"` };
1424
+ }
1425
+ const fileContent = fs.readFileSync(fullPath, 'utf-8');
1426
+ const lines = fileContent.split('\n');
1427
+ const start = Math.max(1, Number(args.startLine) || 1);
1428
+ const end = Math.min(lines.length, Number(args.endLine) || lines.length);
1429
+ readSpin.stop(chalk.green(` Analyzed file ${targetPath} (${lines.length} lines)`));
1430
+ const sliced = lines.slice(start - 1, end).map((l, i) => `${start + i} | ${l}`).join('\n');
1431
+ let minifiedNotice = '';
1432
+ if (lines.length <= 5 && fileContent.length > 500) {
1433
+ minifiedNotice = `\n\n[NOTICE: File appears minified (${lines.length} line(s), ${fileContent.length} chars). If your goal is to format/beautify this file, DO NOT use write_file or edit_file to rewrite it manually (which causes output token truncation and loses content). Instead, use run_command with CLI formatters like \`npx prettier --write "${targetPath}"\` or \`npx html-beautify -r "${targetPath}"\` to format it in-place.]`;
1434
+ }
1435
+ return { result: `File: ${targetPath} (Lines ${start}-${end}/${lines.length}):\n${sliced}${minifiedNotice}` };
1436
+ }
1437
+ case 'write_file': {
1438
+ let targetPath = String(args.path || '').trim();
1439
+ let content = String(args.content || '');
1440
+ const reason = String(args.reason || args.why || args.description || 'Created/updated file content to fulfill user prompt.');
1441
+ if (content.includes('\\n') && !content.includes('\n')) {
1442
+ content = content.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
1443
+ }
1444
+ if (this.executionIntent?.targetDestination === 'Desktop' || targetPath.toLowerCase().includes('desktop')) {
1445
+ const fileName = path.basename(targetPath);
1446
+ targetPath = resolveDesktopPath(fileName);
1447
+ }
1448
+ const fullPath = path.isAbsolute(targetPath) ? targetPath : path.resolve(this.cwd, targetPath);
1449
+ const fileExists = fs.existsSync(fullPath);
1450
+ const actionText = fileExists ? 'Editing file' : 'Creating file';
1451
+ const writeSpin = spinner();
1452
+ writeSpin.start(chalk.yellow(`️ ${actionText} ${targetPath}...`));
1453
+ let origContent = '__FT_WAS_NEW__';
1454
+ if (fileExists) {
1455
+ origContent = fs.readFileSync(fullPath, 'utf-8');
1456
+ this.backups.push({ filePath: targetPath, originalContent: origContent });
1457
+ }
1458
+ else {
1459
+ this.backups.push({ filePath: targetPath, originalContent: '__FT_WAS_NEW__' });
1460
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
1461
+ }
1462
+ fs.writeFileSync(fullPath, content, 'utf-8');
1463
+ this.modifiedFiles.add(targetPath);
1464
+ const oldLineCount = origContent !== '__FT_WAS_NEW__' ? origContent.split('\n').length : 0;
1465
+ const newLineCount = content.split('\n').length;
1466
+ const numberOfLinesChanged = origContent === '__FT_WAS_NEW__' ? newLineCount : Math.abs(newLineCount - oldLineCount) || newLineCount;
1467
+ writeSpin.stop(chalk.green(` ${actionText} ${targetPath}`));
1468
+ safeNote(` • File: ${chalk.bold.cyan(targetPath)}\n` +
1469
+ ` • Changed: ${chalk.bold.yellow(numberOfLinesChanged + ' line(s)')}\n` +
1470
+ ` • Why: ${reason}`, ` Changed ${numberOfLinesChanged} line(s) in ${targetPath}`);
1471
+ const checkSpin = spinner();
1472
+ checkSpin.start(chalk.cyan(` Checking for error: edited ${targetPath}...`));
1473
+ const syntaxCheck = await checkFileSyntax(targetPath, this.cwd);
1474
+ if (!syntaxCheck.valid) {
1475
+ checkSpin.stop(chalk.red(`️ Checking for error: edited ${targetPath} Compiler/Syntax Error!`));
1476
+ this.taskStateManager.recordError(`Syntax error in "${targetPath}": ${syntaxCheck.errors.join('; ')}`, 'write_file');
1477
+ return {
1478
+ result: `Successfully wrote ${content.length} characters (${numberOfLinesChanged} lines changed) to "${targetPath}".\n\n️ AUTOMATED SYNTAX / COMPILER ERROR DETECTED IN "${targetPath}":\n${syntaxCheck.errors.join('\n')}\n\nPLEASE IMMEDIATELY FIX THIS SYNTAX ERROR IN YOUR NEXT TOOL CALL.`
1479
+ };
1480
+ }
1481
+ checkSpin.stop(chalk.green(` Checking for error: edited ${targetPath} Syntax & build clean.`));
1482
+ this.taskStateManager.recordArtifact({
1483
+ filename: path.basename(targetPath),
1484
+ path: targetPath,
1485
+ source: 'write_file',
1486
+ verified: syntaxCheck.valid,
1487
+ sizeBytes: Buffer.byteLength(content, 'utf-8'),
1488
+ });
1489
+ this.taskStateManager.addObservation('write_file', `Wrote ${numberOfLinesChanged} line(s) to ${targetPath}. Syntax clean: ${syntaxCheck.valid}`, syntaxCheck.valid, targetPath);
1490
+ return { result: `Successfully wrote ${content.length} characters (${numberOfLinesChanged} lines changed) to "${targetPath}". Rationale: ${reason}. Syntax check passed cleanly.` };
1491
+ }
1492
+ case 'edit_file': {
1493
+ const targetPath = String(args.path || '').trim();
1494
+ let target = String(args.target || '');
1495
+ let replacement = String(args.replacement || '');
1496
+ const reason = String(args.reason || args.why || args.description || 'Replaced target code snippet with updated implementation.');
1497
+ if (replacement.includes('\\n') && !replacement.includes('\n')) {
1498
+ replacement = replacement.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
1499
+ }
1500
+ if (target.includes('\\n') && !target.includes('\n')) {
1501
+ target = target.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
1502
+ }
1503
+ const fullPath = path.isAbsolute(targetPath) ? targetPath : path.resolve(this.cwd, targetPath);
1504
+ const editSpin = spinner();
1505
+ editSpin.start(chalk.yellow(`️ Editing file ${targetPath}...`));
1506
+ if (!fs.existsSync(fullPath)) {
1507
+ editSpin.stop(chalk.red(`Failed to edit file ${targetPath}: File does not exist.`));
1508
+ return { result: `Error: File "${targetPath}" does not exist.` };
1509
+ }
1510
+ const origContent = fs.readFileSync(fullPath, 'utf-8');
1511
+ const replaceRes = robustSnippetReplace(origContent, target, replacement);
1512
+ if (!replaceRes.success) {
1513
+ editSpin.stop(chalk.yellow(`Edit snippet failed for ${targetPath}.`));
1514
+ return { result: `Error editing "${targetPath}": ${replaceRes.error}` };
1515
+ }
1516
+ this.backups.push({ filePath: targetPath, originalContent: origContent });
1517
+ fs.writeFileSync(fullPath, replaceRes.updatedContent, 'utf-8');
1518
+ this.modifiedFiles.add(targetPath);
1519
+ const targetLines = target.split('\n').length;
1520
+ const replacementLines = replacement.split('\n').length;
1521
+ const numberOfLinesChanged = Math.max(targetLines, replacementLines);
1522
+ editSpin.stop(chalk.green(` Edited file ${targetPath}`));
1523
+ safeNote(` • File: ${chalk.bold.cyan(targetPath)}\n` +
1524
+ ` • Changed: ${chalk.bold.yellow(numberOfLinesChanged + ' line(s)')}\n` +
1525
+ ` • Why: ${reason}`, ` Changed ${numberOfLinesChanged} line(s) in ${targetPath}`);
1526
+ const checkSpin = spinner();
1527
+ checkSpin.start(chalk.cyan(` Checking for error: edited ${targetPath}...`));
1528
+ const syntaxCheck = await checkFileSyntax(targetPath, this.cwd);
1529
+ if (!syntaxCheck.valid) {
1530
+ checkSpin.stop(chalk.red(`️ Checking for error: edited ${targetPath} Compiler/Syntax Error!`));
1531
+ return {
1532
+ result: `Successfully replaced snippet (${numberOfLinesChanged} lines changed) in "${targetPath}".\n\n️ AUTOMATED SYNTAX / COMPILER ERROR DETECTED IN "${targetPath}":\n${syntaxCheck.errors.join('\n')}\n\nPLEASE IMMEDIATELY FIX THIS SYNTAX ERROR IN YOUR NEXT TOOL CALL.`
1533
+ };
1534
+ }
1535
+ checkSpin.stop(chalk.green(` Checking for error: edited ${targetPath} Syntax & build clean.`));
1536
+ return { result: `Successfully replaced target snippet (${numberOfLinesChanged} lines changed) in "${targetPath}". Rationale: ${reason}. Syntax check passed cleanly.` };
1537
+ }
1538
+ case 'run_command': {
1539
+ let cmd = String(args.command || args.cmd || args.script || args.exec || '').trim();
1540
+ if (!cmd) {
1541
+ return { result: 'Error: No command string provided for run_command.' };
1542
+ }
1543
+ // Intercept shell file creation commands in run_command and redirect to write_file
1544
+ if (/(?:^|\s|&&|;)(?:touch|mkdir|md|New-Item|echo\s+.*>|cat\s+.*>|type\s+.*>|printf\s+.*>)/i.test(cmd)) {
1545
+ const matchPath = cmd.match(/(?:touch|mkdir|md|Path|>\s*)\s*['"]?([a-zA-Z0-9_\-./\\]+)['"]?/i);
1546
+ const targetP = matchPath && matchPath[1] ? matchPath[1] : 'target file/folder';
1547
+ return {
1548
+ result: `[REDIRECT TO write_file]: Do NOT use run_command (or shell commands like mkdir/md/touch/echo/New-Item) to create files or folders! Use the 'write_file' tool directly. When you call write_file with path: "${targetP}", Scout automatically creates all necessary parent directories and writes the file content instantly in one step.`
1549
+ };
1550
+ }
1551
+ // Auto-normalize common Unix commands on Windows for agent resilience
1552
+ if (process.platform === 'win32') {
1553
+ if (/^rm\s+-rf\s+/i.test(cmd)) {
1554
+ const target = cmd.replace(/^rm\s+-rf\s+/i, '').trim();
1555
+ cmd = `powershell -Command "Remove-Item -Path '${target}' -Recurse -Force -ErrorAction SilentlyContinue"`;
1556
+ }
1557
+ else if (/^touch\s+/i.test(cmd)) {
1558
+ const target = cmd.replace(/^touch\s+/i, '').trim();
1559
+ cmd = `powershell -Command "New-Item -ItemType File -Path '${target}' -Force"`;
1560
+ }
1561
+ else if (/^cat\s+/i.test(cmd)) {
1562
+ const target = cmd.replace(/^cat\s+/i, '').trim();
1563
+ cmd = `powershell -Command "Get-Content '${target}'"`;
1564
+ }
1565
+ else if (cmd === 'ls' || cmd === 'ls -la' || cmd === 'ls -l') {
1566
+ cmd = 'dir';
1567
+ }
1568
+ else if (cmd === 'clear') {
1569
+ cmd = 'cls';
1570
+ }
1571
+ }
1572
+ const isTestCmd = /\b(?:test|vitest|jest|pytest|mocha|jasmine|cargo test|go test)\b/i.test(cmd);
1573
+ const actionLabel = isTestCmd ? `Running command for testing: \`${cmd}\`` : `Running command: \`${cmd}\``;
1574
+ const runSpin = spinner();
1575
+ runSpin.start(chalk.cyan(` ${actionLabel}...`));
1576
+ const res = await executeSmartCommand(cmd, this.cwd, 3000);
1577
+ if (res.isBackgroundServer) {
1578
+ runSpin.stop(chalk.green(` ${actionLabel} started in background (PID ${res.pid}).`));
1579
+ return {
1580
+ result: `Command started and running in background (PID ${res.pid || 'active'}). Output:\n${res.output.slice(0, 8000)}\n\n[Process is running as background server. Scout Agent can proceed directly to next step.]`
1581
+ };
1582
+ }
1583
+ if (res.exitCode === 0) {
1584
+ runSpin.stop(chalk.green(` ${actionLabel} executed successfully (Exit Code 0).`));
1585
+ return { result: `Command Exit Code 0 Output:\n${res.output.slice(0, 8000)}` };
1586
+ }
1587
+ else {
1588
+ runSpin.stop(chalk.red(` ${actionLabel} failed with code ${res.exitCode}.`));
1589
+ const diag = extractErrorDiagnostics(res.output);
1590
+ const diagSummary = diag.keyErrors.length > 0
1591
+ ? `\n\n️ [SCOUT ERROR DIAGNOSTIC SUMMARY]:\n${diag.keyErrors.join('\n\n')}` +
1592
+ (diag.referencedFiles.length > 0 ? `\n• Referenced Source Files: ${diag.referencedFiles.join(', ')}` : '')
1593
+ : '';
1594
+ return { result: `Command Exit Code ${res.exitCode} Error:\n${res.output.slice(0, 8000)}${diagSummary}` };
1595
+ }
1596
+ }
1597
+ case 'list_dir': {
1598
+ const relDir = String(args.path || '.').trim();
1599
+ const fullDir = path.resolve(this.cwd, relDir);
1600
+ if (!fs.existsSync(fullDir) || !fs.statSync(fullDir).isDirectory()) {
1601
+ return { result: `Directory not found: "${relDir}"` };
1602
+ }
1603
+ const files = fs.readdirSync(fullDir).slice(0, 100);
1604
+ return { result: `Directory entries in "${relDir}":\n${files.join('\n')}` };
1605
+ }
1606
+ case 'grep_search': {
1607
+ const query = String(args.query || '').toLowerCase().trim();
1608
+ const allFiles = getDirectoryFiles(this.cwd);
1609
+ const matches = [];
1610
+ for (const f of allFiles) {
1611
+ if (matches.length >= 25)
1612
+ break;
1613
+ const fullPath = path.resolve(this.cwd, f);
1614
+ try {
1615
+ const text = fs.readFileSync(fullPath, 'utf-8');
1616
+ if (text.toLowerCase().includes(query)) {
1617
+ matches.push(f);
1618
+ }
1619
+ }
1620
+ catch { }
1621
+ }
1622
+ return { result: `Grep search for "${query}" matched in ${matches.length} file(s):\n${matches.join('\n')}` };
1623
+ }
1624
+ case 'glob_search': {
1625
+ const pattern = String(args.pattern || '').toLowerCase().trim();
1626
+ const allFiles = getDirectoryFiles(this.cwd);
1627
+ const matched = allFiles.filter((f) => f.toLowerCase().includes(pattern) || path.basename(f).toLowerCase().endsWith(pattern.replace('*', '')));
1628
+ return { result: `Glob search "${pattern}" matched ${matched.length} file(s):\n${matched.slice(0, 30).join('\n')}` };
1629
+ }
1630
+ case 'tree_view': {
1631
+ const relPath = String(args.path || '.').trim();
1632
+ const maxDepth = Number(args.maxDepth) || 3;
1633
+ const fullDir = path.resolve(this.cwd, relPath);
1634
+ if (!fs.existsSync(fullDir) || !fs.statSync(fullDir).isDirectory()) {
1635
+ return { result: `Directory not found for tree_view: "${relPath}"` };
1636
+ }
1637
+ const treeStr = buildDirectoryTree(fullDir, '', 0, maxDepth);
1638
+ return { result: `Directory Tree for "${relPath}":\n${relPath}/\n${treeStr}` };
1639
+ }
1640
+ case 'file_info': {
1641
+ const targetPath = String(args.path || '').trim();
1642
+ const fullPath = path.isAbsolute(targetPath) ? targetPath : path.resolve(this.cwd, targetPath);
1643
+ if (!fs.existsSync(fullPath)) {
1644
+ return { result: `Error: Path "${targetPath}" does not exist.` };
1645
+ }
1646
+ const stat = fs.statSync(fullPath);
1647
+ if (stat.isDirectory()) {
1648
+ const entries = fs.readdirSync(fullPath);
1649
+ return { result: `Directory Stats: "${targetPath}"\n • Total Entries: ${entries.length}\n • Created: ${stat.birthtime.toISOString()}\n • Modified: ${stat.mtime.toISOString()}` };
1650
+ }
1651
+ const content = fs.readFileSync(fullPath, 'utf-8');
1652
+ const lineCount = content.split('\n').length;
1653
+ const ext = path.extname(targetPath) || 'none';
1654
+ return {
1655
+ result: `File Info: "${targetPath}"\n` +
1656
+ ` • Size: ${(stat.size / 1024).toFixed(2)} KB (${stat.size} bytes)\n` +
1657
+ ` • Total Lines: ${lineCount}\n` +
1658
+ ` • Extension: ${ext}\n` +
1659
+ ` • Last Modified: ${stat.mtime.toISOString()}\n` +
1660
+ ` • Absolute Path: ${fullPath}`
1661
+ };
1662
+ }
1663
+ case 'multi_edit_file': {
1664
+ const targetPath = String(args.path || '').trim();
1665
+ const edits = Array.isArray(args.edits) ? args.edits : [];
1666
+ const reason = String(args.reason || args.description || 'Applied multiple code snippet edits.');
1667
+ if (edits.length === 0) {
1668
+ return { result: `Error: No edits provided for multi_edit_file on "${targetPath}".` };
1669
+ }
1670
+ const fullPath = path.isAbsolute(targetPath) ? targetPath : path.resolve(this.cwd, targetPath);
1671
+ if (!fs.existsSync(fullPath)) {
1672
+ return { result: `Error: File "${targetPath}" does not exist.` };
1673
+ }
1674
+ let currentContent = fs.readFileSync(fullPath, 'utf-8');
1675
+ const origContent = currentContent;
1676
+ let appliedCount = 0;
1677
+ const errors = [];
1678
+ for (let i = 0; i < edits.length; i++) {
1679
+ const ed = edits[i];
1680
+ let target = String(ed.target || '');
1681
+ let replacement = String(ed.replacement || '');
1682
+ if (target.includes('\\n') && !target.includes('\n'))
1683
+ target = target.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
1684
+ if (replacement.includes('\\n') && !replacement.includes('\n'))
1685
+ replacement = replacement.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
1686
+ const replaceRes = robustSnippetReplace(currentContent, target, replacement);
1687
+ if (replaceRes.success) {
1688
+ currentContent = replaceRes.updatedContent;
1689
+ appliedCount++;
1690
+ }
1691
+ else {
1692
+ errors.push(`Edit #${i + 1} failed: ${replaceRes.error}`);
1693
+ }
1694
+ }
1695
+ if (appliedCount === 0) {
1696
+ return { result: `Error: All ${edits.length} multi-edits failed on "${targetPath}":\n${errors.join('\n')}` };
1697
+ }
1698
+ this.backups.push({ filePath: targetPath, originalContent: origContent });
1699
+ fs.writeFileSync(fullPath, currentContent, 'utf-8');
1700
+ this.modifiedFiles.add(targetPath);
1701
+ safeNote(` • File: ${chalk.bold.cyan(targetPath)}\n` +
1702
+ ` • Multi-edits applied: ${chalk.bold.green(appliedCount + '/' + edits.length)}\n` +
1703
+ ` • Why: ${reason}`, ` Applied ${appliedCount} edits to ${targetPath}`);
1704
+ const syntaxCheck = await checkFileSyntax(targetPath, this.cwd);
1705
+ let syntaxNotice = syntaxCheck.valid ? 'Syntax check passed cleanly.' : `\n\n️ AUTOMATED SYNTAX ERROR DETECTED:\n${syntaxCheck.errors.join('\n')}`;
1706
+ return {
1707
+ result: `Successfully applied ${appliedCount}/${edits.length} edit snippet(s) to "${targetPath}". Rationale: ${reason}.${errors.length > 0 ? ` Warnings: ${errors.join('; ')}` : ''} ${syntaxNotice}`
1708
+ };
1709
+ }
1710
+ case 'fetch_url': {
1711
+ const targetUrl = String(args.url || '').trim();
1712
+ if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) {
1713
+ return { result: `Error: Invalid URL scheme. URL must start with http:// or https://` };
1714
+ }
1715
+ const fetchSpin = spinner();
1716
+ fetchSpin.start(chalk.cyan(` Fetching web URL ${targetUrl}...`));
1717
+ try {
1718
+ const resp = await fetch(targetUrl, { headers: { 'User-Agent': 'Scout-CLI-Agent/6.0' } });
1719
+ if (!resp.ok) {
1720
+ fetchSpin.stop(chalk.red(`Failed to fetch URL: HTTP ${resp.status} ${resp.statusText}`));
1721
+ return { result: `HTTP Error ${resp.status}: ${resp.statusText}` };
1722
+ }
1723
+ let bodyText = await resp.text();
1724
+ fetchSpin.stop(chalk.green(` Fetched URL ${targetUrl} (${bodyText.length} chars)`));
1725
+ if (bodyText.includes('<html') || bodyText.includes('<body')) {
1726
+ bodyText = bodyText
1727
+ .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
1728
+ .replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '')
1729
+ .replace(/<[^>]+>/g, ' ')
1730
+ .replace(/\s+/g, ' ')
1731
+ .trim();
1732
+ }
1733
+ const preview = bodyText.slice(0, 6000) + (bodyText.length > 6000 ? `\n... [truncated, ${bodyText.length} total chars]` : '');
1734
+ return { result: `Content fetched from ${targetUrl}:\n\n${preview}` };
1735
+ }
1736
+ catch (err) {
1737
+ fetchSpin.stop(chalk.red(`Fetch error for ${targetUrl}: ${err?.message || String(err)}`));
1738
+ return { result: `Fetch error: ${err?.message || String(err)}` };
1739
+ }
1740
+ }
1741
+ case 'git_diff': {
1742
+ const targetPath = args.path ? String(args.path).trim() : '';
1743
+ try {
1744
+ const { execSync } = await import('child_process');
1745
+ const diffCmd = targetPath ? `git diff -- "${targetPath}"` : 'git diff';
1746
+ const diffOutput = execSync(diffCmd, { encoding: 'utf-8', cwd: this.cwd });
1747
+ if (!diffOutput || !diffOutput.trim()) {
1748
+ return { result: 'No uncommitted git changes found in workspace.' };
1749
+ }
1750
+ return { result: `Git Diff Output:\n${diffOutput.slice(0, 8000)}` };
1751
+ }
1752
+ catch (err) {
1753
+ return { result: `Could not retrieve git diff: ${err?.message || String(err)}` };
1754
+ }
1755
+ }
1756
+ case 'ask_user': {
1757
+ const questionText = String(args.question || args.prompt || 'Please provide input:').trim();
1758
+ const askSpin = spinner();
1759
+ askSpin.stop();
1760
+ safeNote(questionText, ' Scout Agent Question for User');
1761
+ const userInput = await text({
1762
+ message: chalk.cyan.bold('Your response:'),
1763
+ placeholder: 'Type your answer or instruction here...',
1764
+ validate(value) {
1765
+ if (!value || value.trim().length === 0)
1766
+ return 'Input cannot be empty.';
1767
+ },
1768
+ });
1769
+ if (isCancel(userInput)) {
1770
+ return { result: 'User cancelled the input prompt.' };
1771
+ }
1772
+ return { result: `User Answer: "${userInput.trim()}"` };
1773
+ }
1774
+ case 'speak_text': {
1775
+ const phrase = String(args.text || args.phrase || '').trim();
1776
+ if (phrase) {
1777
+ await speakText(phrase, { async: true });
1778
+ return { result: `Spoke text out loud: "${phrase}"` };
1779
+ }
1780
+ return { result: 'No text provided to speak.' };
1781
+ }
1782
+ case 'browser_navigate': {
1783
+ const targetUrl = String(args.url || '').trim();
1784
+ this.taskStateManager.setActiveUrl(targetUrl);
1785
+ this.taskStateManager.setActiveApplication('browser');
1786
+ const res = await this.browserController.navigate(targetUrl);
1787
+ this.taskStateManager.addObservation('browser_navigate', res.output, res.success, targetUrl);
1788
+ return { result: res.output };
1789
+ }
1790
+ case 'browser_inspect': {
1791
+ const res = await this.browserController.inspect_page();
1792
+ this.taskStateManager.addObservation('browser_inspect', res.summary, res.success, res.url);
1793
+ return { result: res.summary };
1794
+ }
1795
+ case 'browser_click': {
1796
+ const target = String(args.selectorOrText || args.target || '').trim();
1797
+ const res = await this.browserController.click(target);
1798
+ this.taskStateManager.addObservation('browser_click', res.output, res.success, target);
1799
+ return { result: res.output };
1800
+ }
1801
+ case 'browser_type': {
1802
+ const target = String(args.selectorOrText || args.target || '').trim();
1803
+ const text = String(args.text || '');
1804
+ const res = await this.browserController.type(target, text);
1805
+ this.taskStateManager.addObservation('browser_type', res.output, res.success, target);
1806
+ return { result: res.output };
1807
+ }
1808
+ case 'browser_download': {
1809
+ const target = String(args.urlOrSelector || args.url || '').trim();
1810
+ const destPath = args.destPath ? String(args.destPath) : undefined;
1811
+ const res = await this.browserController.download_file(target, destPath);
1812
+ if (res.success && res.details?.path) {
1813
+ const vRes = await this.actionVerifier.verifyFileCreated(res.details.path);
1814
+ const artifact = this.taskStateManager.recordArtifact({
1815
+ filename: res.details.filename || path.basename(res.details.path),
1816
+ path: res.details.path,
1817
+ source: target,
1818
+ application: 'browser',
1819
+ verified: vRes.verified,
1820
+ sizeBytes: res.details.sizeBytes,
1821
+ });
1822
+ this.taskStateManager.addObservation('browser_download', `${res.output} (Verified on disk: ${vRes.verified ? 'YES' : 'NO'})`, vRes.verified, target);
1823
+ return { result: `${res.output}\nTracked Artifact ID: ${artifact.id} (${artifact.path})` };
1824
+ }
1825
+ this.taskStateManager.addObservation('browser_download', res.output, false, target);
1826
+ return { result: res.output };
1827
+ }
1828
+ case 'browser_content': {
1829
+ const res = await this.browserController.extract_content(args.selector);
1830
+ this.taskStateManager.addObservation('browser_content', `Extracted content (${res.output.length} chars)`, res.success);
1831
+ return { result: res.output };
1832
+ }
1833
+ case 'browser_screenshot': {
1834
+ const res = await this.browserController.screenshot();
1835
+ this.taskStateManager.addObservation('browser_screenshot', res.output, res.success, res.url);
1836
+ return { result: res.output };
1837
+ }
1838
+ case 'browser_select': {
1839
+ const selector = String(args.selector || args.target || '');
1840
+ const val = String(args.value || args.val || '');
1841
+ const res = await this.browserController.select(selector, val);
1842
+ this.taskStateManager.addObservation('browser_select', res.output, res.success, selector);
1843
+ return { result: res.output };
1844
+ }
1845
+ case 'browser_scroll': {
1846
+ const direction = (args.direction || 'down');
1847
+ const amount = Number(args.amount) || 4;
1848
+ const res = await this.browserController.scroll(direction, amount);
1849
+ this.taskStateManager.addObservation('browser_scroll', res.output, res.success);
1850
+ return { result: res.output };
1851
+ }
1852
+ case 'scratchpad': {
1853
+ const action = String(args.action || 'read').toLowerCase().trim();
1854
+ const scratchpadPath = path.resolve(this.cwd, '.ft', 'scratchpad.md');
1855
+ fs.mkdirSync(path.dirname(scratchpadPath), { recursive: true });
1856
+ if (action === 'read') {
1857
+ const content = fs.existsSync(scratchpadPath) ? fs.readFileSync(scratchpadPath, 'utf-8') : '(Scratchpad is empty)';
1858
+ this.taskStateManager.addObservation('scratchpad', 'Read scratchpad content', true);
1859
+ return { result: `Scratchpad Content:\n${content || '(empty)'}` };
1860
+ }
1861
+ else if (action === 'write') {
1862
+ const newContent = String(args.content || '');
1863
+ fs.writeFileSync(scratchpadPath, newContent, 'utf-8');
1864
+ this.taskStateManager.addObservation('scratchpad', `Wrote scratchpad (${newContent.length} chars)`, true);
1865
+ return { result: `Scratchpad updated (${newContent.length} chars).` };
1866
+ }
1867
+ else if (action === 'append') {
1868
+ const appendContent = String(args.content || '');
1869
+ fs.appendFileSync(scratchpadPath, `\n${appendContent}`, 'utf-8');
1870
+ this.taskStateManager.addObservation('scratchpad', `Appended to scratchpad (${appendContent.length} chars)`, true);
1871
+ return { result: `Appended to scratchpad (${appendContent.length} chars).` };
1872
+ }
1873
+ else if (action === 'clear') {
1874
+ if (fs.existsSync(scratchpadPath))
1875
+ fs.unlinkSync(scratchpadPath);
1876
+ this.taskStateManager.addObservation('scratchpad', 'Cleared scratchpad', true);
1877
+ return { result: 'Scratchpad cleared.' };
1878
+ }
1879
+ return { result: `Unknown scratchpad action: "${action}". Supported: read, write, append, clear.` };
1880
+ }
1881
+ case 'computer_screenshot': {
1882
+ const res = await this.computerController.screenshot();
1883
+ if (res.path) {
1884
+ this.taskStateManager.recordArtifact({
1885
+ filename: path.basename(res.path),
1886
+ path: res.path,
1887
+ type: 'image',
1888
+ description: `Screen observation (${res.width}x${res.height})`,
1889
+ application: res.activeWindow || 'Desktop',
1890
+ });
1891
+ }
1892
+ if (res.activeWindow) {
1893
+ this.taskStateManager.setActiveWindow(res.activeWindow);
1894
+ }
1895
+ const summary = `Screen captured (${res.width}x${res.height}), Active window: "${res.activeWindow || 'Desktop'}"${res.path ? `, Saved: ${res.path}` : ''}`;
1896
+ this.taskStateManager.addObservation('computer_screenshot', summary, true);
1897
+ return { result: summary };
1898
+ }
1899
+ case 'computer_click': {
1900
+ const x = Number(args.x);
1901
+ const y = Number(args.y);
1902
+ const btn = args.button || 'left';
1903
+ const res = await this.computerController.click(x, y, { button: btn, clicks: 1 });
1904
+ this.taskStateManager.addObservation('computer_click', res.output, res.success, `(${x}, ${y})`);
1905
+ const structuredRes = {
1906
+ success: res.success,
1907
+ action: 'click',
1908
+ coordinates: res.coordinates || { x, y },
1909
+ button: btn,
1910
+ output: res.output,
1911
+ ...(res.error ? { error: res.error } : {}),
1912
+ recoverable: res.recoverable ?? true,
1913
+ ...(res.activeWindow ? { activeWindow: res.activeWindow } : {}),
1914
+ };
1915
+ return { result: JSON.stringify(structuredRes, null, 2) };
1916
+ }
1917
+ case 'computer_right_click': {
1918
+ const x = Number(args.x);
1919
+ const y = Number(args.y);
1920
+ const res = await this.computerController.rightClick(x, y);
1921
+ this.taskStateManager.addObservation('computer_right_click', res.output, res.success, `(${x}, ${y})`);
1922
+ const structuredRes = {
1923
+ success: res.success,
1924
+ action: 'right_click',
1925
+ coordinates: res.coordinates || { x, y },
1926
+ button: 'right',
1927
+ output: res.output,
1928
+ ...(res.error ? { error: res.error } : {}),
1929
+ recoverable: res.recoverable ?? true,
1930
+ ...(res.activeWindow ? { activeWindow: res.activeWindow } : {}),
1931
+ };
1932
+ return { result: JSON.stringify(structuredRes, null, 2) };
1933
+ }
1934
+ case 'computer_double_click': {
1935
+ const x = Number(args.x);
1936
+ const y = Number(args.y);
1937
+ const res = await this.computerController.doubleClick(x, y);
1938
+ this.taskStateManager.addObservation('computer_double_click', res.output, res.success, `(${x}, ${y})`);
1939
+ const structuredRes = {
1940
+ success: res.success,
1941
+ action: 'double_click',
1942
+ coordinates: res.coordinates || { x, y },
1943
+ button: 'left',
1944
+ output: res.output,
1945
+ ...(res.error ? { error: res.error } : {}),
1946
+ recoverable: res.recoverable ?? true,
1947
+ };
1948
+ return { result: JSON.stringify(structuredRes, null, 2) };
1949
+ }
1950
+ case 'computer_mouse_down': {
1951
+ const x = args.x !== undefined ? Number(args.x) : undefined;
1952
+ const y = args.y !== undefined ? Number(args.y) : undefined;
1953
+ const btn = args.button || 'left';
1954
+ const res = await this.computerController.mouseDown(x, y, btn);
1955
+ this.taskStateManager.addObservation('computer_mouse_down', res.output, res.success);
1956
+ const structuredRes = {
1957
+ success: res.success,
1958
+ action: 'mouse_down',
1959
+ coordinates: res.coordinates || (x !== undefined && y !== undefined ? { x, y } : undefined),
1960
+ button: btn,
1961
+ output: res.output,
1962
+ ...(res.error ? { error: res.error } : {}),
1963
+ recoverable: res.recoverable ?? true,
1964
+ };
1965
+ return { result: JSON.stringify(structuredRes, null, 2) };
1966
+ }
1967
+ case 'computer_mouse_up': {
1968
+ const x = args.x !== undefined ? Number(args.x) : undefined;
1969
+ const y = args.y !== undefined ? Number(args.y) : undefined;
1970
+ const btn = args.button || 'left';
1971
+ const res = await this.computerController.mouseUp(x, y, btn);
1972
+ this.taskStateManager.addObservation('computer_mouse_up', res.output, res.success);
1973
+ const structuredRes = {
1974
+ success: res.success,
1975
+ action: 'mouse_up',
1976
+ coordinates: res.coordinates || (x !== undefined && y !== undefined ? { x, y } : undefined),
1977
+ button: btn,
1978
+ output: res.output,
1979
+ ...(res.error ? { error: res.error } : {}),
1980
+ recoverable: res.recoverable ?? true,
1981
+ };
1982
+ return { result: JSON.stringify(structuredRes, null, 2) };
1983
+ }
1984
+ case 'computer_type': {
1985
+ const textVal = String(args.text || '');
1986
+ const res = await this.computerController.type(textVal);
1987
+ this.taskStateManager.addObservation('computer_type', res.output, res.success);
1988
+ const structuredRes = {
1989
+ success: res.success,
1990
+ action: 'type',
1991
+ output: res.output,
1992
+ ...(res.error ? { error: res.error } : {}),
1993
+ recoverable: res.recoverable ?? true,
1994
+ ...(res.activeWindow ? { activeWindow: res.activeWindow } : {}),
1995
+ ...(res.expectedWindow ? { expectedWindow: res.expectedWindow } : {}),
1996
+ };
1997
+ return { result: JSON.stringify(structuredRes, null, 2) };
1998
+ }
1999
+ case 'computer_key_press': {
2000
+ const key = String(args.key || '');
2001
+ const res = await this.computerController.keyPress(key);
2002
+ this.taskStateManager.addObservation('computer_key_press', res.output, res.success);
2003
+ const structuredRes = {
2004
+ success: res.success,
2005
+ action: 'key_press',
2006
+ output: res.output,
2007
+ ...(res.error ? { error: res.error } : {}),
2008
+ recoverable: res.recoverable ?? true,
2009
+ };
2010
+ return { result: JSON.stringify(structuredRes, null, 2) };
2011
+ }
2012
+ case 'computer_hotkey': {
2013
+ const keys = Array.isArray(args.keys) ? args.keys.map(String) : [String(args.keys)];
2014
+ const res = await this.computerController.hotkey(keys);
2015
+ this.taskStateManager.addObservation('computer_hotkey', res.output, res.success);
2016
+ const structuredRes = {
2017
+ success: res.success,
2018
+ action: 'hotkey',
2019
+ output: res.output,
2020
+ ...(res.error ? { error: res.error } : {}),
2021
+ recoverable: res.recoverable ?? true,
2022
+ ...(res.activeWindow ? { activeWindow: res.activeWindow } : {}),
2023
+ };
2024
+ return { result: JSON.stringify(structuredRes, null, 2) };
2025
+ }
2026
+ case 'computer_scroll': {
2027
+ const deltaY = Number(args.deltaY || 0);
2028
+ const deltaX = Number(args.deltaX || 0);
2029
+ const res = await this.computerController.scroll(deltaX, deltaY);
2030
+ this.taskStateManager.addObservation('computer_scroll', res.output, res.success);
2031
+ return { result: res.output };
2032
+ }
2033
+ case 'computer_mouse_move': {
2034
+ const x = Number(args.x);
2035
+ const y = Number(args.y);
2036
+ const res = await this.computerController.move(x, y);
2037
+ this.taskStateManager.addObservation('computer_mouse_move', res.output, res.success);
2038
+ const structuredRes = {
2039
+ success: res.success,
2040
+ action: 'move',
2041
+ coordinates: res.coordinates || { x, y },
2042
+ output: res.output,
2043
+ ...(res.error ? { error: res.error } : {}),
2044
+ recoverable: res.recoverable ?? true,
2045
+ ...(res.activeWindow ? { activeWindow: res.activeWindow } : {}),
2046
+ };
2047
+ return { result: JSON.stringify(structuredRes, null, 2) };
2048
+ }
2049
+ case 'computer_drag': {
2050
+ const fromX = Number(args.fromX ?? args.startX ?? 0);
2051
+ const fromY = Number(args.fromY ?? args.startY ?? 0);
2052
+ const toX = Number(args.toX ?? args.endX ?? 0);
2053
+ const toY = Number(args.toY ?? args.endY ?? 0);
2054
+ const res = await this.computerController.drag(fromX, fromY, toX, toY);
2055
+ this.taskStateManager.addObservation('computer_drag', res.output, res.success);
2056
+ const structuredRes = {
2057
+ success: res.success,
2058
+ action: 'drag',
2059
+ from: { x: fromX, y: fromY },
2060
+ to: { x: toX, y: toY },
2061
+ coordinates: res.coordinates || { x: toX, y: toY },
2062
+ output: res.output,
2063
+ ...(res.error ? { error: res.error } : {}),
2064
+ recoverable: res.recoverable ?? true,
2065
+ };
2066
+ return { result: JSON.stringify(structuredRes, null, 2) };
2067
+ }
2068
+ case 'computer_diagnostic': {
2069
+ const diag = await this.computerController.runDiagnostic();
2070
+ return { result: JSON.stringify(diag, null, 2) };
2071
+ }
2072
+ case 'computer_wait': {
2073
+ const ms = Math.min(10000, Math.max(100, Number(args.ms) || 1000));
2074
+ await this.computerController.wait(ms);
2075
+ return { result: `Waited for ${ms}ms` };
2076
+ }
2077
+ case 'computer_open_app': {
2078
+ const appName = String(args.appName || args.app || '');
2079
+ const res = await this.computerController.openApplication(appName, args.args);
2080
+ this.taskStateManager.setActiveApplication(appName);
2081
+ this.taskStateManager.addObservation('computer_open_app', res.output, res.success);
2082
+ const currentObj = this.taskStateManager.getState()?.objective || '';
2083
+ const simpleCheck = checkSimpleAppAction(currentObj);
2084
+ const isOnlyOpening = simpleCheck.isSimple && simpleCheck.action !== 'close';
2085
+ const structuredRes = {
2086
+ success: res.success,
2087
+ action: 'open_app',
2088
+ output: res.output,
2089
+ ...(res.error ? { error: res.error } : {}),
2090
+ recoverable: res.recoverable ?? true,
2091
+ activeWindow: res.activeWindow || appName,
2092
+ expectedWindow: res.expectedWindow || appName,
2093
+ ...(isOnlyOpening && res.success ? {
2094
+ directive: "CRITICAL: The requested application is now opened. Your objective is 100% satisfied. You MUST call 'task_completed' immediately on your next turn. DO NOT call list_dir, read_file, or explore the repository."
2095
+ } : {}),
2096
+ };
2097
+ return { result: JSON.stringify(structuredRes, null, 2) };
2098
+ }
2099
+ case 'computer_close_app': {
2100
+ const appName = String(args.appName || args.app || '');
2101
+ const res = await this.computerController.closeApplication(appName);
2102
+ this.taskStateManager.addObservation('computer_close_app', res.output, res.success);
2103
+ const currentObj = this.taskStateManager.getState()?.objective || '';
2104
+ const simpleCheck = checkSimpleAppAction(currentObj);
2105
+ const isOnlyClosing = simpleCheck.isSimple && simpleCheck.action === 'close';
2106
+ if (isOnlyClosing && res.success) {
2107
+ return { result: `${res.output}\nCRITICAL: Application closed. Objective complete. Call task_completed now.` };
2108
+ }
2109
+ return { result: res.output };
2110
+ }
2111
+ case 'computer_switch_window': {
2112
+ const targetWin = String(args.windowTitleOrApp || args.target || '');
2113
+ const res = await this.computerController.switchWindow(targetWin);
2114
+ if (res.success) {
2115
+ this.taskStateManager.setActiveWindow(targetWin);
2116
+ }
2117
+ this.taskStateManager.addObservation('computer_switch_window', res.output, res.success);
2118
+ const structuredRes = {
2119
+ success: res.success,
2120
+ action: 'switch_window',
2121
+ output: res.output,
2122
+ ...(res.error ? { error: res.error } : {}),
2123
+ recoverable: res.recoverable ?? true,
2124
+ activeWindow: res.activeWindow || targetWin,
2125
+ expectedWindow: res.expectedWindow,
2126
+ };
2127
+ return { result: JSON.stringify(structuredRes, null, 2) };
2128
+ }
2129
+ case 'computer_inspect_ui': {
2130
+ const ui = await this.computerController.inspectUI();
2131
+ this.taskStateManager.setActiveWindow(ui.activeWindow);
2132
+ const outStr = `Active Window: "${ui.activeWindow}"\nVisible Windows: ${ui.windows.map((w) => `"${w}"`).join(', ')}`;
2133
+ this.taskStateManager.addObservation('computer_inspect_ui', outStr, true);
2134
+ const structuredRes = {
2135
+ success: true,
2136
+ action: 'inspect_ui',
2137
+ activeWindow: ui.activeWindow,
2138
+ windows: ui.windows,
2139
+ output: outStr,
2140
+ };
2141
+ return { result: JSON.stringify(structuredRes, null, 2) };
2142
+ }
2143
+ case 'task_completed': {
2144
+ const summaryStr = String(args.summary || 'Task completed successfully.');
2145
+ if (this.executionIntent?.targetDestination === 'Desktop' && this.executionIntent?.targetArtifactName) {
2146
+ const checkRes = await this.actionVerifier.verifyFileCreated(this.executionIntent.targetArtifactName, 1, 'Desktop');
2147
+ if (!checkRes.verified) {
2148
+ return {
2149
+ result: JSON.stringify({
2150
+ success: false,
2151
+ error: 'VerificationFailed',
2152
+ message: `Cannot conclude task as completed: ${checkRes.message}`,
2153
+ recoverable: true,
2154
+ suggestedAction: 'The file was not found on the Desktop (or was placed in a substitute path). Save the file to the user\'s Desktop via the application interface before completing.'
2155
+ }, null, 2)
2156
+ };
2157
+ }
2158
+ }
2159
+ this.taskStateManager.setStatus('completed');
2160
+ this.taskStateManager.completeStep(this.currentStep, summaryStr);
2161
+ return { result: summaryStr };
2162
+ }
2163
+ default: {
2164
+ // Check if this tool is provided by a connected MCP server
2165
+ const mcpManager = getMCPManager();
2166
+ const mcpTarget = mcpManager.findTool(name);
2167
+ if (mcpTarget) {
2168
+ const mcpRes = await mcpManager.executeTool(name, args);
2169
+ const isSuccess = mcpRes.status === 'success';
2170
+ const outputStr = typeof mcpRes.result === 'string'
2171
+ ? mcpRes.result
2172
+ : (mcpRes.result?.text ? String(mcpRes.result.text) : JSON.stringify(mcpRes.result ?? { status: mcpRes.status, error: mcpRes.error }));
2173
+ this.taskStateManager.addObservation(name, mcpRes.outputSummary || outputStr, isSuccess);
2174
+ // Check if MCP result generated or referenced local files/artifacts
2175
+ if (isSuccess && typeof mcpRes.result === 'object' && mcpRes.result !== null) {
2176
+ const possiblePath = mcpRes.result.path || mcpRes.result.filePath || mcpRes.result.file || args.destPath || args.path || args.outputPath;
2177
+ if (typeof possiblePath === 'string' && fs.existsSync(path.resolve(this.cwd, possiblePath))) {
2178
+ this.modifiedFiles.add(path.relative(this.cwd, path.resolve(this.cwd, possiblePath)).replace(/\\/g, '/'));
2179
+ }
2180
+ }
2181
+ return { result: outputStr };
2182
+ }
2183
+ return { result: `Unknown tool call name: "${name}"` };
2184
+ }
2185
+ }
2186
+ }
2187
+ }
2188
+ //# sourceMappingURL=agentEngine.js.map