ft-scout 9.5.6 → 9.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,19 +24,64 @@ import { getMCPManager } from '../mcp/index.js';
24
24
  import { writeTelemetry } from '../utils/qrBridge.js';
25
25
  import { compress, LEVEL_FAST } from 'codrop';
26
26
  import { CheckpointManager } from './checkpoints/checkpointManager.js';
27
- import { renderStepHeader, renderThoughtBox, renderToolCall, renderToolResult, renderTaskCompletedCard, } from '../utils/claudeUI.js';
27
+ import { renderStepHeader, renderThoughtBox, renderToolCall, renderToolResult, renderTaskCompletedCard, ensureCompleteSentence, getActionFriendlyDescription, } from '../utils/claudeUI.js';
28
28
  import { loadWorkspaceRules } from '../utils/rules.js';
29
29
  import { InterruptManager } from '../utils/interruptHandler.js';
30
30
  import { ComputerUseAgentLoop } from './agent/index.js';
31
31
  export { AgentRuntime, AgentWorkspace, inferExecutionIntent, resolveDesktopPath, SystemComputerController, MockComputerController, ComputerUseAgentLoop };
32
32
  const execAsync = promisify(exec);
33
+ function computeSimilarity(s1, s2) {
34
+ if (s1 === s2)
35
+ return 1.0;
36
+ if (!s1 || !s2)
37
+ return 0.0;
38
+ const longer = s1.length > s2.length ? s1 : s2;
39
+ const shorter = s1.length > s2.length ? s2 : s1;
40
+ if (longer.length === 0)
41
+ return 1.0;
42
+ const costs = [];
43
+ for (let i = 0; i <= shorter.length; i++)
44
+ costs[i] = i;
45
+ for (let i = 1; i <= longer.length; i++) {
46
+ costs[0] = i;
47
+ let nw = i - 1;
48
+ for (let j = 1; j <= shorter.length; j++) {
49
+ const cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), longer[i - 1] === shorter[j - 1] ? nw : nw + 1);
50
+ nw = costs[j];
51
+ costs[j] = cj;
52
+ }
53
+ }
54
+ return (longer.length - costs[shorter.length]) / longer.length;
55
+ }
56
+ function adjustIndentation(replacement, matchedOrigBlock, matchedTargetLines) {
57
+ if (matchedOrigBlock.length === 0)
58
+ return replacement;
59
+ const origFirstIndent = matchedOrigBlock[0].match(/^(\s*)/)?.[1] || '';
60
+ const targetFirstIndent = matchedTargetLines[0]?.match(/^(\s*)/)?.[1] || '';
61
+ if (origFirstIndent !== targetFirstIndent) {
62
+ const replLines = replacement.split('\n');
63
+ return replLines.map((line) => {
64
+ if (!line.trim())
65
+ return line;
66
+ if (targetFirstIndent && line.startsWith(targetFirstIndent)) {
67
+ return origFirstIndent + line.slice(targetFirstIndent.length);
68
+ }
69
+ return origFirstIndent + line;
70
+ }).join('\n');
71
+ }
72
+ return replacement;
73
+ }
33
74
  export function robustSnippetReplace(origContent, target, replacement) {
34
75
  if (!origContent || !target) {
35
76
  return { success: false, updatedContent: origContent, error: 'Target snippet or original content is empty.' };
36
77
  }
78
+ const isCRLF = origContent.includes('\r\n');
37
79
  const normOrig = origContent.replace(/\r\n/g, '\n');
38
80
  const normTarget = target.replace(/\r\n/g, '\n');
39
81
  const normReplacement = replacement.replace(/\r\n/g, '\n');
82
+ const finalize = (content) => {
83
+ return { success: true, updatedContent: isCRLF ? content.replace(/\n/g, '\r\n') : content };
84
+ };
40
85
  // 1. Direct exact match
41
86
  if (normOrig.includes(normTarget)) {
42
87
  const occurrences = normOrig.split(normTarget).length - 1;
@@ -47,12 +92,20 @@ export function robustSnippetReplace(origContent, target, replacement) {
47
92
  error: `Target snippet occurs ${occurrences} times. Please include more surrounding code lines in target to make it unique.`
48
93
  };
49
94
  }
50
- return { success: true, updatedContent: normOrig.replace(normTarget, () => normReplacement) };
95
+ return finalize(normOrig.replace(normTarget, () => normReplacement));
96
+ }
97
+ // 2. Trimmed leading/trailing newlines in target
98
+ const trimmedTarget = normTarget.replace(/^\n+|\n+$/g, '');
99
+ if (trimmedTarget && trimmedTarget !== normTarget && normOrig.includes(trimmedTarget)) {
100
+ const occurrences = normOrig.split(trimmedTarget).length - 1;
101
+ if (occurrences === 1) {
102
+ return finalize(normOrig.replace(trimmedTarget, () => normReplacement.replace(/^\n+|\n+$/g, '')));
103
+ }
51
104
  }
52
- // 2. Trailing whitespace normalized match
53
105
  const origLines = normOrig.split('\n');
54
106
  const targetLines = normTarget.split('\n');
55
107
  const targetLen = targetLines.length;
108
+ // 3. Trailing whitespace normalized match
56
109
  const strippedTarget = targetLines.map((l) => l.trimEnd()).join('\n');
57
110
  const matches = [];
58
111
  for (let i = 0; i <= origLines.length - targetLen; i++) {
@@ -66,7 +119,7 @@ export function robustSnippetReplace(origContent, target, replacement) {
66
119
  const before = origLines.slice(0, idx);
67
120
  const after = origLines.slice(idx + targetLen);
68
121
  const updatedContent = [...before, normReplacement, ...after].join('\n');
69
- return { success: true, updatedContent };
122
+ return finalize(updatedContent);
70
123
  }
71
124
  if (matches.length > 1) {
72
125
  return {
@@ -75,34 +128,37 @@ export function robustSnippetReplace(origContent, target, replacement) {
75
128
  error: `Target snippet matched ${matches.length} locations when ignoring trailing spaces. Please provide more surrounding code lines in target.`
76
129
  };
77
130
  }
78
- // 3. Fully trimmed lines match (handles leading/trailing indentation differences)
79
- const trimmedTargetLines = targetLines.map((l) => l.trim()).filter(Boolean);
80
- if (trimmedTargetLines.length > 0) {
81
- const trimmedTargetStr = trimmedTargetLines.join('\n');
82
- const trimMatches = [];
83
- for (let i = 0; i <= origLines.length - targetLen; i++) {
84
- const windowLines = origLines.slice(i, i + targetLen).map((l) => l.trim()).filter(Boolean);
85
- if (windowLines.join('\n') === trimmedTargetStr) {
86
- trimMatches.push(i);
87
- }
88
- }
89
- if (trimMatches.length === 1) {
90
- const idx = trimMatches[0];
91
- const before = origLines.slice(0, idx);
92
- const after = origLines.slice(idx + targetLen);
93
- const updatedContent = [...before, normReplacement, ...after].join('\n');
94
- return { success: true, updatedContent };
131
+ // 4. Fully trimmed lines match with indentation adjustment (handles indentation differences)
132
+ const trimmedTargetLines = targetLines.map((l) => l.trim());
133
+ const trimMatches = [];
134
+ for (let i = 0; i <= origLines.length - targetLen; i++) {
135
+ const windowLines = origLines.slice(i, i + targetLen).map((l) => l.trim());
136
+ if (windowLines.join('\n') === trimmedTargetLines.join('\n')) {
137
+ trimMatches.push(i);
95
138
  }
96
139
  }
97
- // 4. Fuzzy non-blank lines window match (handles variable blank lines in target snippet)
98
- const nonBlankTargetLines = targetLines.filter((l) => l.trim().length > 0);
140
+ if (trimMatches.length === 1) {
141
+ const idx = trimMatches[0];
142
+ const before = origLines.slice(0, idx);
143
+ const after = origLines.slice(idx + targetLen);
144
+ const matchedOrigBlock = origLines.slice(idx, idx + targetLen);
145
+ const adjustedRepl = adjustIndentation(normReplacement, matchedOrigBlock, targetLines);
146
+ const updatedContent = [...before, adjustedRepl, ...after].join('\n');
147
+ return finalize(updatedContent);
148
+ }
149
+ // 5. Non-blank lines window match (handles variable blank lines in target snippet)
150
+ const nonBlankTargetLines = targetLines.filter((l) => l.trim().length > 0).map((l) => l.trim());
99
151
  if (nonBlankTargetLines.length > 0) {
100
- const nonBlankTargetStr = nonBlankTargetLines.map((l) => l.trim()).join('\n');
152
+ const nonBlankTargetStr = nonBlankTargetLines.join('\n');
101
153
  const fuzzyMatches = [];
102
154
  for (let i = 0; i < origLines.length; i++) {
103
- for (let j = i + 1; j <= Math.min(origLines.length, i + targetLen + 6); j++) {
104
- const windowLines = origLines.slice(i, j).filter((l) => l.trim().length > 0);
105
- if (windowLines.map((l) => l.trim()).join('\n') === nonBlankTargetStr) {
155
+ if (origLines[i].trim().length === 0)
156
+ continue;
157
+ for (let j = i + 1; j <= Math.min(origLines.length, i + targetLen + 8); j++) {
158
+ if (origLines[j - 1].trim().length === 0)
159
+ continue;
160
+ const windowLines = origLines.slice(i, j).filter((l) => l.trim().length > 0).map((l) => l.trim());
161
+ if (windowLines.join('\n') === nonBlankTargetStr) {
106
162
  fuzzyMatches.push({ startIdx: i, endIdx: j });
107
163
  break;
108
164
  }
@@ -112,14 +168,99 @@ export function robustSnippetReplace(origContent, target, replacement) {
112
168
  const { startIdx, endIdx } = fuzzyMatches[0];
113
169
  const before = origLines.slice(0, startIdx);
114
170
  const after = origLines.slice(endIdx);
115
- const updatedContent = [...before, normReplacement, ...after].join('\n');
116
- return { success: true, updatedContent };
171
+ const matchedOrigBlock = origLines.slice(startIdx, endIdx);
172
+ const adjustedRepl = adjustIndentation(normReplacement, matchedOrigBlock, targetLines);
173
+ const updatedContent = [...before, adjustedRepl, ...after].join('\n');
174
+ return finalize(updatedContent);
175
+ }
176
+ }
177
+ // 6. Single-line substring or line-level match
178
+ if (targetLen === 1) {
179
+ const trimmedSingleTarget = normTarget.trim();
180
+ const singleLineExactMatches = [];
181
+ for (let i = 0; i < origLines.length; i++) {
182
+ if (origLines[i].trim() === trimmedSingleTarget) {
183
+ singleLineExactMatches.push(i);
184
+ }
185
+ }
186
+ if (singleLineExactMatches.length === 1) {
187
+ const idx = singleLineExactMatches[0];
188
+ const origIndent = origLines[idx].match(/^(\s*)/)?.[1] || '';
189
+ const replLines = normReplacement.split('\n').map((l) => (l.trim() ? origIndent + l.trim() : l)).join('\n');
190
+ const before = origLines.slice(0, idx);
191
+ const after = origLines.slice(idx + 1);
192
+ return finalize([...before, replLines, ...after].join('\n'));
193
+ }
194
+ // Substring inside a single line
195
+ const lineContainsMatches = [];
196
+ for (let i = 0; i < origLines.length; i++) {
197
+ if (origLines[i].includes(trimmedSingleTarget)) {
198
+ lineContainsMatches.push(i);
199
+ }
200
+ }
201
+ if (lineContainsMatches.length === 1) {
202
+ const idx = lineContainsMatches[0];
203
+ const updatedLine = origLines[idx].replace(trimmedSingleTarget, normReplacement.trim());
204
+ const before = origLines.slice(0, idx);
205
+ const after = origLines.slice(idx + 1);
206
+ return finalize([...before, updatedLine, ...after].join('\n'));
207
+ }
208
+ }
209
+ // 7. Quote & punctuation relaxed matching
210
+ const normalizePunctuation = (str) => str.replace(/['"`]/g, '"').replace(/[;,]$/gm, '').trim();
211
+ const relaxedTarget = normalizePunctuation(normTarget);
212
+ if (relaxedTarget) {
213
+ const relaxedMatches = [];
214
+ for (let i = 0; i <= origLines.length - targetLen; i++) {
215
+ const windowStr = normalizePunctuation(origLines.slice(i, i + targetLen).join('\n'));
216
+ if (windowStr === relaxedTarget) {
217
+ relaxedMatches.push({ startIdx: i, endIdx: i + targetLen });
218
+ }
219
+ }
220
+ if (relaxedMatches.length === 1) {
221
+ const { startIdx, endIdx } = relaxedMatches[0];
222
+ const before = origLines.slice(0, startIdx);
223
+ const after = origLines.slice(endIdx);
224
+ const matchedOrigBlock = origLines.slice(startIdx, endIdx);
225
+ const adjustedRepl = adjustIndentation(normReplacement, matchedOrigBlock, targetLines);
226
+ return finalize([...before, adjustedRepl, ...after].join('\n'));
227
+ }
228
+ }
229
+ // 8. High-confidence fuzzy similarity matching (>= 88% similarity)
230
+ let bestSim = 0;
231
+ let bestRange = null;
232
+ let secondBestSim = 0;
233
+ const targetClean = targetLines.map((l) => l.trim()).filter(Boolean).join('\n');
234
+ for (let i = 0; i <= origLines.length - Math.max(1, targetLen - 2); i++) {
235
+ for (let len = Math.max(1, targetLen - 2); len <= Math.min(origLines.length - i, targetLen + 2); len++) {
236
+ const windowClean = origLines.slice(i, i + len).map((l) => l.trim()).filter(Boolean).join('\n');
237
+ const sim = computeSimilarity(windowClean, targetClean);
238
+ if (sim > bestSim) {
239
+ secondBestSim = bestSim;
240
+ bestSim = sim;
241
+ bestRange = { startIdx: i, endIdx: i + len };
242
+ }
243
+ else if (sim > secondBestSim) {
244
+ secondBestSim = sim;
245
+ }
117
246
  }
118
247
  }
248
+ if (bestSim >= 0.88 && secondBestSim < 0.70 && bestRange) {
249
+ const before = origLines.slice(0, bestRange.startIdx);
250
+ const after = origLines.slice(bestRange.endIdx);
251
+ const matchedOrigBlock = origLines.slice(bestRange.startIdx, bestRange.endIdx);
252
+ const adjustedRepl = adjustIndentation(normReplacement, matchedOrigBlock, targetLines);
253
+ return finalize([...before, adjustedRepl, ...after].join('\n'));
254
+ }
255
+ // 9. Informative error message with closest line indicator
256
+ let closestMsg = '';
257
+ if (bestRange && bestSim >= 0.40) {
258
+ closestMsg = ` (Closest match found near line ${bestRange.startIdx + 1} with ${(bestSim * 100).toFixed(0)}% similarity).`;
259
+ }
119
260
  return {
120
261
  success: false,
121
262
  updatedContent: origContent,
122
- 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.`
263
+ error: `Target snippet not found in file${closestMsg} Hint: Use read_file to view current lines and copy the exact snippet, or use write_file with complete file content.`
123
264
  };
124
265
  }
125
266
  export const AGENT_TOOLS = [
@@ -681,7 +822,7 @@ CORE ARCHITECTURAL PRINCIPLES:
681
822
  NEVER output a vacuous meta-summary like "Task completed" or "Looked up account" without providing the actual information the user asked for!
682
823
  - For coding/modification tasks: Detail what was changed, created, and tested.
683
824
  - 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!
684
- 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.
825
+ 10. THOUGHT TRANSPARENCY PROTOCOL: In EVERY step before calling any tools or ending a turn, you MUST provide a clear, grammatically complete 1-2 sentence explanation in your text response describing your current reasoning, what specific action you are taking, and why. Always finish every sentence completely with proper terminal punctuation (period, question mark, or exclamation mark) before outputting tool calls. NEVER leave a sentence half-written, hanging, or ending on a preposition or conjunction like "to", "and", "by", or "using".
685
826
  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!
686
827
  12. STRICT ACTIVE GOAL ISOLATION & ACCURACY:
687
828
  - You must strictly execute ONLY the current active goal provided in the user prompt.
@@ -703,6 +844,11 @@ CORE ARCHITECTURAL PRINCIPLES:
703
844
  * Primitives: bpy.ops.mesh.primitive_uv_sphere_add, primitive_cylinder_add, primitive_cube_add
704
845
  - Apply cel-shading or toon materials with vibrant anime colors matching the request (e.g. Genshin Impact aesthetic).
705
846
  - Position camera and lighting. Immediately after your Blender script creates the 3D model (or after a single quick verification step), you MUST call task_completed with a complete description of the created 3D character and mesh hierarchy. Do NOT run unnecessary repeated polling turns.
847
+ 15. DO NOT CLOSE USER APPLICATIONS UNLESS EXPLICITLY COMMANDED:
848
+ When the user asks to open, create, write, or interact with an application (e.g. "open notepad and write X", "launch Chrome and search Y"):
849
+ NEVER close or kill the application!
850
+ Keep the application open on the user's screen so they can review, edit, or save the document.
851
+ ONLY call computer_close_app if the user explicitly commanded "close <app>", "exit <app>", or "kill <app>".
706
852
 
707
853
  When returning tool calls, use standard OpenAI function calling format or JSON tool call payload format:
708
854
  \`\`\`json
@@ -1039,6 +1185,16 @@ When returning tool calls, use standard OpenAI function calling format or JSON t
1039
1185
  }
1040
1186
  }
1041
1187
  }
1188
+ if (needsBrowser) {
1189
+ const browserTools = this.toolRegistry.getAllTools().filter((t) => t.name.startsWith('browser_'));
1190
+ const existingNames = new Set(baseTools.map((t) => t.name));
1191
+ for (const bt of browserTools) {
1192
+ if (!existingNames.has(bt.name)) {
1193
+ baseTools.push(bt);
1194
+ existingNames.add(bt.name);
1195
+ }
1196
+ }
1197
+ }
1042
1198
  if (mcpRouting.tools.length > 0 && !needsBrowser && !needsComputer) {
1043
1199
  const ESSENTIAL_BASE_TOOLS = new Set(['read_file', 'write_file', 'edit_file', 'run_command', 'list_dir', 'grep_search', 'task_completed', 'ask_user', 'speak_text', 'scratchpad', 'computer_open_app']);
1044
1200
  baseTools = baseTools.filter((t) => ESSENTIAL_BASE_TOOLS.has(t.name));
@@ -1090,6 +1246,7 @@ When returning tool calls, use standard OpenAI function calling format or JSON t
1090
1246
  temperature: 0.1,
1091
1247
  presence_penalty: 0.1,
1092
1248
  frequency_penalty: 0.1,
1249
+ max_tokens: 4096,
1093
1250
  });
1094
1251
  });
1095
1252
  }
@@ -1116,6 +1273,7 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1116
1273
  temperature: 0.1,
1117
1274
  presence_penalty: 0.1,
1118
1275
  frequency_penalty: 0.1,
1276
+ max_tokens: 4096,
1119
1277
  });
1120
1278
  });
1121
1279
  }
@@ -1135,8 +1293,27 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1135
1293
  this.historyMessages.push(msg);
1136
1294
  // Render assistant's thought reasoning text if provided on this turn
1137
1295
  const textContent = msg.content || '';
1138
- if (textContent.trim()) {
1139
- renderThoughtBox(textContent, step);
1296
+ const inferredToolCall = !msg.tool_calls || msg.tool_calls.length === 0 ? this.extractJsonToolCall(textContent) : null;
1297
+ const toolCallsList = (msg.tool_calls && msg.tool_calls.length > 0)
1298
+ ? msg.tool_calls
1299
+ : (inferredToolCall ? [{ tool: inferredToolCall.tool, args: inferredToolCall.args }] : []);
1300
+ const cleanReasoning = this.extractCleanReasoning(msg, choice, toolCallsList);
1301
+ if (cleanReasoning.trim()) {
1302
+ let fallbackDesc;
1303
+ const firstTc = msg.tool_calls?.[0];
1304
+ if (firstTc?.function?.name) {
1305
+ try {
1306
+ const parsedArgs = JSON.parse(firstTc.function.arguments || '{}');
1307
+ fallbackDesc = getActionFriendlyDescription(firstTc.function.name, parsedArgs);
1308
+ }
1309
+ catch {
1310
+ fallbackDesc = getActionFriendlyDescription(firstTc.function.name, {});
1311
+ }
1312
+ }
1313
+ else if (inferredToolCall?.tool) {
1314
+ fallbackDesc = getActionFriendlyDescription(inferredToolCall.tool, inferredToolCall.args || {});
1315
+ }
1316
+ renderThoughtBox(cleanReasoning, step, fallbackDesc);
1140
1317
  }
1141
1318
  // Check native tool calls
1142
1319
  if (msg.tool_calls && msg.tool_calls.length > 0) {
@@ -1316,13 +1493,6 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1316
1493
  continue;
1317
1494
  }
1318
1495
  if (textContent.trim()) {
1319
- let cleanedThought = textContent
1320
- .replace(/[\u0600-\u06FF\u0750-\u077F\uAC00-\uD7AF\u3040-\u30FF\u4E00-\u9FFF\u0D80-\u0DFF]+/g, '')
1321
- .trim();
1322
- if (!cleanedThought || cleanedThought.length < 5) {
1323
- cleanedThought = 'Analyzing codebase files and executing next tool operation...';
1324
- }
1325
- safeNote(renderMarkdown(cleanedThought), ` Scout Agent Thought (Step ${step})`);
1326
1496
  const lowerText = textContent.toLowerCase().trim();
1327
1497
  const isExplicitCompletion = lowerText.includes('task is complete') ||
1328
1498
  lowerText.includes('task complete') ||
@@ -1448,6 +1618,37 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1448
1618
  }
1449
1619
  return null;
1450
1620
  }
1621
+ extractCleanReasoning(msg, rawChoice, toolCalls) {
1622
+ const rawMsg = rawChoice?.message || msg || {};
1623
+ const rawReasoning = rawMsg.reasoning_content || rawMsg.thinking || rawMsg.thought || msg?.reasoning_content || '';
1624
+ let candidate = '';
1625
+ // Check for <think>...</think> blocks in msg.content or rawReasoning
1626
+ const combined = `${rawReasoning}\n${msg?.content || ''}`.trim();
1627
+ const thinkMatch = combined.match(/<think>([\s\S]*?)<\/think>/i);
1628
+ if (thinkMatch && thinkMatch[1] && thinkMatch[1].trim().length > 0) {
1629
+ candidate = thinkMatch[1].trim();
1630
+ }
1631
+ else if (rawReasoning && typeof rawReasoning === 'string' && rawReasoning.trim().length > 0) {
1632
+ candidate = rawReasoning.trim();
1633
+ }
1634
+ else if (typeof msg?.content === 'string' && msg.content.trim().length > 0) {
1635
+ candidate = msg.content.trim();
1636
+ }
1637
+ const firstCall = (toolCalls && toolCalls.length > 0) ? toolCalls[0] : null;
1638
+ let fallbackDesc;
1639
+ if (firstCall) {
1640
+ const fnName = firstCall.function?.name || firstCall.tool || '';
1641
+ let callArgs = {};
1642
+ try {
1643
+ callArgs = typeof firstCall.function?.arguments === 'string'
1644
+ ? JSON.parse(firstCall.function.arguments)
1645
+ : (firstCall.args || {});
1646
+ }
1647
+ catch { }
1648
+ fallbackDesc = getActionFriendlyDescription(fnName, callArgs);
1649
+ }
1650
+ return ensureCompleteSentence(candidate, fallbackDesc);
1651
+ }
1451
1652
  async dispatchToolCall(name, args) {
1452
1653
  this.totalToolCalls++;
1453
1654
  let actionDesc = '';
@@ -1562,9 +1763,25 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1562
1763
  return { result: currentScratch ? `Scratchpad Contents:\n${currentScratch}` : `Scratchpad is currently empty.` };
1563
1764
  }
1564
1765
  }
1766
+ const isBasicWindowTool = [
1767
+ 'computer_open_app',
1768
+ 'computer_close_app',
1769
+ 'computer_screenshot',
1770
+ 'computer_inspect_ui',
1771
+ 'computer_switch_window',
1772
+ 'computer_type',
1773
+ 'computer_click',
1774
+ 'computer_double_click',
1775
+ 'computer_right_click',
1776
+ 'computer_key_press',
1777
+ 'computer_hotkey',
1778
+ 'computer_wait',
1779
+ 'browser_screenshot',
1780
+ 'browser_inspect',
1781
+ ].includes(name);
1565
1782
  // 2. Autonomous Computer & Browser Automation Gating (Pro & Enterprise only)
1566
1783
  if (name === 'computer' || name.startsWith('computer_') || name.startsWith('browser_')) {
1567
- if (!isPaid) {
1784
+ if (!isPaid && !isBasicWindowTool) {
1568
1785
  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'.`;
1569
1786
  console.log(chalk.red.bold(`\n⛔ ${blockedMsg}`));
1570
1787
  this.taskStateManager.addObservation(name, blockedMsg, false);
@@ -1689,12 +1906,12 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1689
1906
  }
1690
1907
  // Tier Gating Enforcement
1691
1908
  if (!isPaid) {
1692
- if (name.startsWith('computer_') || name === 'computer') {
1909
+ if ((name.startsWith('computer_') || name === 'computer') && !isBasicWindowTool) {
1693
1910
  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.`;
1694
1911
  this.taskStateManager.addObservation(name, upgradeMsg, false);
1695
1912
  return { result: upgradeMsg };
1696
1913
  }
1697
- if (name.startsWith('browser_')) {
1914
+ if (name.startsWith('browser_') && !isBasicWindowTool) {
1698
1915
  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.`;
1699
1916
  this.taskStateManager.addObservation(name, upgradeMsg, false);
1700
1917
  return { result: upgradeMsg };
@@ -1716,7 +1933,9 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1716
1933
  const fullPath = path.isAbsolute(targetPath) ? targetPath : path.resolve(this.cwd, targetPath);
1717
1934
  const relPath = path.relative(this.cwd, fullPath).replace(/\\/g, '/');
1718
1935
  const normKey = relPath.toLowerCase();
1719
- if (this.readFilesHistory.has(normKey) || this.readFilesHistory.has(targetPath.toLowerCase())) {
1936
+ const isRangeRead = Boolean(args.startLine || args.endLine);
1937
+ const wasModified = this.modifiedFiles.has(targetPath) || this.modifiedFiles.has(relPath) || this.modifiedFiles.has(normKey);
1938
+ if (!isRangeRead && !wasModified && (this.readFilesHistory.has(normKey) || this.readFilesHistory.has(targetPath.toLowerCase()))) {
1720
1939
  const readSpin = spinner();
1721
1940
  readSpin.stop(chalk.yellow(` Skipped duplicate read for ${targetPath} (already in context)`));
1722
1941
  return {
@@ -1774,6 +1993,9 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1774
1993
  catch { }
1775
1994
  fs.writeFileSync(fullPath, content, 'utf-8');
1776
1995
  this.modifiedFiles.add(targetPath);
1996
+ const relPWrite = path.relative(this.cwd, fullPath).replace(/\\/g, '/').toLowerCase();
1997
+ this.readFilesHistory.delete(relPWrite);
1998
+ this.readFilesHistory.delete(targetPath.toLowerCase());
1777
1999
  const oldLineCount = origContent !== '__FT_WAS_NEW__' ? origContent.split('\n').length : 0;
1778
2000
  const newLineCount = content.split('\n').length;
1779
2001
  const numberOfLinesChanged = origContent === '__FT_WAS_NEW__' ? newLineCount : Math.abs(newLineCount - oldLineCount) || newLineCount;
@@ -1803,9 +2025,9 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1803
2025
  return { result: `Successfully wrote ${content.length} characters (${numberOfLinesChanged} lines changed) to "${targetPath}". Rationale: ${reason}. Syntax check passed cleanly.` };
1804
2026
  }
1805
2027
  case 'edit_file': {
1806
- const targetPath = String(args.path || '').trim();
1807
- let target = String(args.target || '');
1808
- let replacement = String(args.replacement || '');
2028
+ const targetPath = String(args.path || args.filePath || args.file || '').trim();
2029
+ let target = String(args.target ?? args.old_string ?? args.old_str ?? args.oldText ?? args.find ?? args.search ?? '');
2030
+ let replacement = String(args.replacement ?? args.new_string ?? args.new_str ?? args.newText ?? args.replace ?? '');
1809
2031
  const reason = String(args.reason || args.why || args.description || 'Replaced target code snippet with updated implementation.');
1810
2032
  if (replacement.includes('\\n') && !replacement.includes('\n')) {
1811
2033
  replacement = replacement.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
@@ -1833,6 +2055,9 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1833
2055
  catch { }
1834
2056
  fs.writeFileSync(fullPath, replaceRes.updatedContent, 'utf-8');
1835
2057
  this.modifiedFiles.add(targetPath);
2058
+ const relPEdit = path.relative(this.cwd, fullPath).replace(/\\/g, '/').toLowerCase();
2059
+ this.readFilesHistory.delete(relPEdit);
2060
+ this.readFilesHistory.delete(targetPath.toLowerCase());
1836
2061
  const targetLines = target.split('\n').length;
1837
2062
  const replacementLines = replacement.split('\n').length;
1838
2063
  const numberOfLinesChanged = Math.max(targetLines, replacementLines);
@@ -1978,7 +2203,7 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1978
2203
  };
1979
2204
  }
1980
2205
  case 'multi_edit_file': {
1981
- const targetPath = String(args.path || '').trim();
2206
+ const targetPath = String(args.path || args.filePath || args.file || '').trim();
1982
2207
  const edits = Array.isArray(args.edits) ? args.edits : [];
1983
2208
  const reason = String(args.reason || args.description || 'Applied multiple code snippet edits.');
1984
2209
  if (edits.length === 0) {
@@ -1994,8 +2219,8 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1994
2219
  const errors = [];
1995
2220
  for (let i = 0; i < edits.length; i++) {
1996
2221
  const ed = edits[i];
1997
- let target = String(ed.target || '');
1998
- let replacement = String(ed.replacement || '');
2222
+ let target = String(ed.target ?? ed.old_string ?? ed.old_str ?? ed.oldText ?? ed.find ?? ed.search ?? '');
2223
+ let replacement = String(ed.replacement ?? ed.new_string ?? ed.new_str ?? ed.newText ?? ed.replace ?? '');
1999
2224
  if (target.includes('\\n') && !target.includes('\n'))
2000
2225
  target = target.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
2001
2226
  if (replacement.includes('\\n') && !replacement.includes('\n'))
@@ -2015,6 +2240,9 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2015
2240
  this.backups.push({ filePath: targetPath, originalContent: origContent });
2016
2241
  fs.writeFileSync(fullPath, currentContent, 'utf-8');
2017
2242
  this.modifiedFiles.add(targetPath);
2243
+ const relPMulti = path.relative(this.cwd, fullPath).replace(/\\/g, '/').toLowerCase();
2244
+ this.readFilesHistory.delete(relPMulti);
2245
+ this.readFilesHistory.delete(targetPath.toLowerCase());
2018
2246
  safeNote(` • File: ${chalk.bold.cyan(targetPath)}\n` +
2019
2247
  ` • Multi-edits applied: ${chalk.bold.green(appliedCount + '/' + edits.length)}\n` +
2020
2248
  ` • Why: ${reason}`, ` Applied ${appliedCount} edits to ${targetPath}`);
@@ -2101,6 +2329,22 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2101
2329
  return { result: res.output };
2102
2330
  }
2103
2331
  case 'browser_inspect': {
2332
+ const ui = await this.computerController.inspectUI();
2333
+ const hasDesktopBrowser = ui.windows.some(w => /chrome|edge|brave|firefox/i.test(w)) ||
2334
+ (ui.activeWindow && /chrome|edge|brave|firefox/i.test(ui.activeWindow));
2335
+ if (hasDesktopBrowser) {
2336
+ const activeWin = ui.activeWindow || ui.windows.find(w => /chrome|edge|brave|firefox/i.test(w)) || 'Web Browser';
2337
+ const pageTitle = activeWin.replace(/\s*[-—·]\s*(?:Google Chrome|Microsoft Edge|Brave|Mozilla Firefox)\s*$/i, '').trim();
2338
+ const summary = [
2339
+ `[BROWSER WINDOW INSPECTION]:`,
2340
+ `• Active Desktop Browser: "${activeWin}"`,
2341
+ `• Current Page / Tab Title: "${pageTitle}"`,
2342
+ `• Visible Windows: ${ui.windows.map(w => `"${w}"`).join(', ')}`,
2343
+ `• State: Desktop browser is active and responsive. You can interact directly using computer_click, computer_type, computer_hotkey, or computer_screenshot.`
2344
+ ].join('\n');
2345
+ this.taskStateManager.addObservation('browser_inspect', summary, true, activeWin);
2346
+ return { result: summary };
2347
+ }
2104
2348
  const res = await this.browserController.inspect_page();
2105
2349
  this.taskStateManager.addObservation('browser_inspect', res.summary, res.success, res.url);
2106
2350
  return { result: res.summary };
@@ -2144,6 +2388,24 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2144
2388
  return { result: res.output };
2145
2389
  }
2146
2390
  case 'browser_screenshot': {
2391
+ const ui = await this.computerController.inspectUI();
2392
+ const hasDesktopBrowser = ui.windows.some(w => /chrome|edge|brave|firefox/i.test(w)) ||
2393
+ (ui.activeWindow && /chrome|edge|brave|firefox/i.test(ui.activeWindow));
2394
+ if (hasDesktopBrowser) {
2395
+ const res = await this.computerController.screenshot();
2396
+ const activeWin = res.activeWindow || ui.activeWindow || 'Web Browser';
2397
+ const pageTitle = activeWin.replace(/\s*[-—·]\s*(?:Google Chrome|Microsoft Edge|Brave|Mozilla Firefox)\s*$/i, '').trim();
2398
+ const output = [
2399
+ `[BROWSER SCREEN OBSERVATION]:`,
2400
+ `• Active Browser Window: "${activeWin}"`,
2401
+ `• Current Webpage Title: "${pageTitle}"`,
2402
+ `• Viewport Resolution: ${res.width}x${res.height}`,
2403
+ `• Visual State: Web page is rendered on screen and visible. Address bar and interactive content viewport are active.`,
2404
+ `• Screenshot File: ${res.path || 'captured'}`
2405
+ ].join('\n');
2406
+ this.taskStateManager.addObservation('browser_screenshot', output, true, activeWin);
2407
+ return { result: output };
2408
+ }
2147
2409
  const res = await this.browserController.screenshot();
2148
2410
  this.taskStateManager.addObservation('browser_screenshot', res.output, res.success, res.url);
2149
2411
  return { result: res.output };
@@ -2173,10 +2435,56 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2173
2435
  application: res.activeWindow || 'Desktop',
2174
2436
  });
2175
2437
  }
2176
- if (res.activeWindow) {
2177
- this.taskStateManager.setActiveWindow(res.activeWindow);
2438
+ const ui = await this.computerController.inspectUI();
2439
+ const activeWin = res.activeWindow || ui.activeWindow || 'Desktop';
2440
+ if (activeWin) {
2441
+ this.taskStateManager.setActiveWindow(activeWin);
2442
+ }
2443
+ let boundsInfo = '';
2444
+ if (activeWin && activeWin !== 'Desktop' && typeof this.computerController.getWindowBounds === 'function') {
2445
+ try {
2446
+ const bounds = await this.computerController.getWindowBounds(activeWin);
2447
+ if (bounds) {
2448
+ boundsInfo = `Position: (${bounds.x}, ${bounds.y}), Size: ${bounds.width}x${bounds.height}`;
2449
+ }
2450
+ }
2451
+ catch { }
2178
2452
  }
2179
- const summary = `Screen captured (${res.width}x${res.height}), Active window: "${res.activeWindow || 'Desktop'}"${res.path ? `, Saved: ${res.path}` : ''}`;
2453
+ const activeLower = activeWin.toLowerCase();
2454
+ let appType = 'desktop_application';
2455
+ let visualStatus = '';
2456
+ if (activeLower.includes('chrome') || activeLower.includes('edge') || activeLower.includes('brave') || activeLower.includes('firefox')) {
2457
+ appType = 'web_browser';
2458
+ const pageTitle = activeWin.replace(/\s*[-—·]\s*(?:Google Chrome|Microsoft Edge|Brave|Mozilla Firefox)\s*$/i, '').trim();
2459
+ visualStatus = `Web Browser is active displaying page: "${pageTitle}". Browser address bar, tab bar, and web viewport are visible. Ready for typing URL/search (computer_type), navigation hotkeys (e.g. ["Control", "l"] to focus address bar), or clicking links.`;
2460
+ }
2461
+ else if (activeLower.includes('notepad')) {
2462
+ appType = 'text_editor';
2463
+ visualStatus = `Notepad text editor active. Document text editing canvas is visible and focused. Ready for typing content (computer_type) or saving (["Control", "s"]).`;
2464
+ }
2465
+ else if (activeLower.includes('code') || activeLower.includes('visual studio')) {
2466
+ appType = 'code_editor';
2467
+ visualStatus = `Visual Studio Code active. Editor tabs, sidebar, and coding canvas are visible.`;
2468
+ }
2469
+ else if (activeLower.includes('terminal') || activeLower.includes('powershell') || activeLower.includes('cmd') || activeLower.includes('wt')) {
2470
+ appType = 'terminal';
2471
+ visualStatus = `Terminal console active and ready for shell command input.`;
2472
+ }
2473
+ else if (activeWin === 'Desktop') {
2474
+ visualStatus = `Windows desktop visible with taskbar and wallpaper. No single application window is currently foreground-focused.`;
2475
+ }
2476
+ else {
2477
+ visualStatus = `Application "${activeWin}" is foreground-focused and active on screen.`;
2478
+ }
2479
+ const visibleList = ui.windows.filter(w => w && w !== 'Desktop');
2480
+ const summary = [
2481
+ `[VISUAL SCREEN OBSERVATION & LAYOUT]:`,
2482
+ `• Primary Display Resolution: ${res.width}x${res.height}`,
2483
+ `• Active Foreground Window: "${activeWin}" [Type: ${appType}]${boundsInfo ? ` (${boundsInfo})` : ''}`,
2484
+ `• Visible Open Windows: ${visibleList.length > 0 ? visibleList.map(w => `"${w}"`).join(', ') : '["' + activeWin + '"]'}`,
2485
+ `• Visual Perception State: ${visualStatus}`,
2486
+ `• Screenshot Image: ${res.path ? res.path : 'Captured in memory'}`
2487
+ ].join('\n');
2180
2488
  this.taskStateManager.addObservation('computer_screenshot', summary, true);
2181
2489
  return { result: summary };
2182
2490
  }
@@ -2267,7 +2575,8 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2267
2575
  }
2268
2576
  case 'computer_type': {
2269
2577
  const textVal = String(args.text || '');
2270
- const res = await this.computerController.type(textVal);
2578
+ const targetApp = args.targetApp || args.app || args.appName || undefined;
2579
+ const res = await this.computerController.type(textVal, targetApp);
2271
2580
  this.taskStateManager.addObservation('computer_type', res.output, res.success);
2272
2581
  const structuredRes = {
2273
2582
  success: res.success,
@@ -2382,9 +2691,13 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2382
2691
  }
2383
2692
  case 'computer_close_app': {
2384
2693
  const appName = String(args.appName || args.app || '');
2694
+ const currentObj = this.taskStateManager.getState()?.objective || '';
2695
+ const isExplicitClose = /\b(close|exit|quit|kill|terminate|shut|band\s+kar|hatao|band)\b/i.test(currentObj);
2696
+ if (!isExplicitClose) {
2697
+ return { result: `[ACTION BLOCKED]: The user asked to interact with or use "${appName}", NOT close it. Keep "${appName}" open on their screen so they can see and use the results. Call task_completed now if your work is done.` };
2698
+ }
2385
2699
  const res = await this.computerController.closeApplication(appName);
2386
2700
  this.taskStateManager.addObservation('computer_close_app', res.output, res.success);
2387
- const currentObj = this.taskStateManager.getState()?.objective || '';
2388
2701
  const simpleCheck = checkSimpleAppAction(currentObj);
2389
2702
  const isOnlyClosing = simpleCheck.isSimple && simpleCheck.action === 'close';
2390
2703
  if (isOnlyClosing && res.success) {