ft-scout 9.5.5 → 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.
Files changed (99) hide show
  1. package/README.md +1 -1
  2. package/bin/src/engine/agent/computerUseLoop.d.ts +107 -0
  3. package/bin/src/engine/agent/computerUseLoop.js +413 -0
  4. package/bin/src/engine/agent/index.d.ts +2 -0
  5. package/bin/src/engine/agent/index.js +2 -0
  6. package/bin/src/engine/agent/recovery/index.d.ts +4 -0
  7. package/bin/src/engine/agent/recovery/index.js +4 -0
  8. package/bin/src/engine/agent/recovery/loopDetector.d.ts +26 -0
  9. package/bin/src/engine/agent/recovery/loopDetector.js +126 -0
  10. package/bin/src/engine/agent/recovery/recoveryManager.d.ts +43 -0
  11. package/bin/src/engine/agent/recovery/recoveryManager.js +271 -0
  12. package/bin/src/engine/agent/recovery/types.d.ts +48 -0
  13. package/bin/src/engine/agent/recovery/types.js +4 -0
  14. package/bin/src/engine/agent/verification/index.d.ts +3 -0
  15. package/bin/src/engine/agent/verification/index.js +3 -0
  16. package/bin/src/engine/agent/verification/stateChangeVerifier.d.ts +22 -0
  17. package/bin/src/engine/agent/verification/stateChangeVerifier.js +282 -0
  18. package/bin/src/engine/agent/verification/types.d.ts +28 -0
  19. package/bin/src/engine/agent/verification/types.js +4 -0
  20. package/bin/src/engine/agentEngine.d.ts +3 -1
  21. package/bin/src/engine/agentEngine.js +370 -56
  22. package/bin/src/engine/agentState.d.ts +41 -1
  23. package/bin/src/engine/agentState.js +45 -0
  24. package/bin/src/engine/browser/actions/actionEngine.d.ts +41 -0
  25. package/bin/src/engine/browser/actions/actionEngine.js +707 -0
  26. package/bin/src/engine/browser/actions/index.d.ts +4 -0
  27. package/bin/src/engine/browser/actions/index.js +4 -0
  28. package/bin/src/engine/browser/actions/reliability.d.ts +41 -0
  29. package/bin/src/engine/browser/actions/reliability.js +170 -0
  30. package/bin/src/engine/browser/actions/types.d.ts +50 -0
  31. package/bin/src/engine/browser/actions/types.js +2 -0
  32. package/bin/src/engine/browser/browserController.d.ts +18 -0
  33. package/bin/src/engine/browser/browserController.js +44 -12
  34. package/bin/src/engine/browser/index.d.ts +2 -0
  35. package/bin/src/engine/browser/index.js +2 -0
  36. package/bin/src/engine/browser/observer/accessibilityTree.d.ts +14 -0
  37. package/bin/src/engine/browser/observer/accessibilityTree.js +214 -0
  38. package/bin/src/engine/browser/observer/browserObserver.d.ts +29 -0
  39. package/bin/src/engine/browser/observer/browserObserver.js +204 -0
  40. package/bin/src/engine/browser/observer/domExtractor.d.ts +30 -0
  41. package/bin/src/engine/browser/observer/domExtractor.js +407 -0
  42. package/bin/src/engine/browser/observer/index.d.ts +5 -0
  43. package/bin/src/engine/browser/observer/index.js +5 -0
  44. package/bin/src/engine/browser/observer/types.d.ts +163 -0
  45. package/bin/src/engine/browser/observer/types.js +8 -0
  46. package/bin/src/engine/computer/computerController.d.ts +45 -2
  47. package/bin/src/engine/computer/computerController.js +178 -38
  48. package/bin/src/engine/computer/mockComputer.d.ts +7 -2
  49. package/bin/src/engine/computer/mockComputer.js +59 -1
  50. package/bin/src/engine/computer/scoutDriver.cs +310 -63
  51. package/bin/src/engine/llm.js +35 -15
  52. package/bin/src/engine/models/harpProvider.d.ts +32 -0
  53. package/bin/src/engine/models/harpProvider.js +172 -0
  54. package/bin/src/engine/models/index.d.ts +6 -0
  55. package/bin/src/engine/models/index.js +6 -0
  56. package/bin/src/engine/models/localModelProvider.d.ts +11 -0
  57. package/bin/src/engine/models/localModelProvider.js +48 -0
  58. package/bin/src/engine/models/openaiProvider.d.ts +11 -0
  59. package/bin/src/engine/models/openaiProvider.js +50 -0
  60. package/bin/src/engine/models/reasoningOrchestrator.d.ts +17 -0
  61. package/bin/src/engine/models/reasoningOrchestrator.js +75 -0
  62. package/bin/src/engine/models/types.d.ts +63 -0
  63. package/bin/src/engine/models/types.js +2 -0
  64. package/bin/src/engine/production/index.d.ts +3 -0
  65. package/bin/src/engine/production/index.js +3 -0
  66. package/bin/src/engine/production/taskReplay.d.ts +37 -0
  67. package/bin/src/engine/production/taskReplay.js +81 -0
  68. package/bin/src/engine/production/telemetry.d.ts +43 -0
  69. package/bin/src/engine/production/telemetry.js +68 -0
  70. package/bin/src/engine/runtime/agentRuntime.d.ts +1 -1
  71. package/bin/src/engine/runtime/agentRuntime.js +33 -7
  72. package/bin/src/engine/safety/index.d.ts +3 -0
  73. package/bin/src/engine/safety/index.js +3 -0
  74. package/bin/src/engine/safety/policyEngine.d.ts +40 -0
  75. package/bin/src/engine/safety/policyEngine.js +282 -0
  76. package/bin/src/engine/safety/types.d.ts +24 -0
  77. package/bin/src/engine/safety/types.js +2 -0
  78. package/bin/src/engine/safety.d.ts +1 -0
  79. package/bin/src/engine/safety.js +1 -0
  80. package/bin/src/engine/toolRegistry.d.ts +4 -0
  81. package/bin/src/engine/toolRegistry.js +9 -0
  82. package/bin/src/engine/tools/domainHandlers.d.ts +61 -0
  83. package/bin/src/engine/tools/domainHandlers.js +495 -0
  84. package/bin/src/engine/tools/index.d.ts +4 -0
  85. package/bin/src/engine/tools/index.js +4 -0
  86. package/bin/src/engine/tools/types.d.ts +56 -0
  87. package/bin/src/engine/tools/types.js +2 -0
  88. package/bin/src/engine/tools/unifiedRouter.d.ts +29 -0
  89. package/bin/src/engine/tools/unifiedRouter.js +426 -0
  90. package/bin/src/engine/workspace/agentWorkspace.js +4 -2
  91. package/bin/src/index.js +4 -4
  92. package/bin/src/mcp/client.js +1 -1
  93. package/bin/src/server/server.js +57 -18
  94. package/bin/src/utils/branding.js +1 -1
  95. package/bin/src/utils/claudeUI.d.ts +10 -1
  96. package/bin/src/utils/claudeUI.js +136 -6
  97. package/bin/src/utils/qrBridge.js +1 -1
  98. package/bin/src/utils/support.js +1 -1
  99. package/package.json +2 -2
@@ -24,18 +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
- export { AgentRuntime, AgentWorkspace, inferExecutionIntent, resolveDesktopPath, SystemComputerController, MockComputerController };
30
+ import { ComputerUseAgentLoop } from './agent/index.js';
31
+ export { AgentRuntime, AgentWorkspace, inferExecutionIntent, resolveDesktopPath, SystemComputerController, MockComputerController, ComputerUseAgentLoop };
31
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
+ }
32
74
  export function robustSnippetReplace(origContent, target, replacement) {
33
75
  if (!origContent || !target) {
34
76
  return { success: false, updatedContent: origContent, error: 'Target snippet or original content is empty.' };
35
77
  }
78
+ const isCRLF = origContent.includes('\r\n');
36
79
  const normOrig = origContent.replace(/\r\n/g, '\n');
37
80
  const normTarget = target.replace(/\r\n/g, '\n');
38
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
+ };
39
85
  // 1. Direct exact match
40
86
  if (normOrig.includes(normTarget)) {
41
87
  const occurrences = normOrig.split(normTarget).length - 1;
@@ -46,12 +92,20 @@ export function robustSnippetReplace(origContent, target, replacement) {
46
92
  error: `Target snippet occurs ${occurrences} times. Please include more surrounding code lines in target to make it unique.`
47
93
  };
48
94
  }
49
- 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
+ }
50
104
  }
51
- // 2. Trailing whitespace normalized match
52
105
  const origLines = normOrig.split('\n');
53
106
  const targetLines = normTarget.split('\n');
54
107
  const targetLen = targetLines.length;
108
+ // 3. Trailing whitespace normalized match
55
109
  const strippedTarget = targetLines.map((l) => l.trimEnd()).join('\n');
56
110
  const matches = [];
57
111
  for (let i = 0; i <= origLines.length - targetLen; i++) {
@@ -65,7 +119,7 @@ export function robustSnippetReplace(origContent, target, replacement) {
65
119
  const before = origLines.slice(0, idx);
66
120
  const after = origLines.slice(idx + targetLen);
67
121
  const updatedContent = [...before, normReplacement, ...after].join('\n');
68
- return { success: true, updatedContent };
122
+ return finalize(updatedContent);
69
123
  }
70
124
  if (matches.length > 1) {
71
125
  return {
@@ -74,34 +128,37 @@ export function robustSnippetReplace(origContent, target, replacement) {
74
128
  error: `Target snippet matched ${matches.length} locations when ignoring trailing spaces. Please provide more surrounding code lines in target.`
75
129
  };
76
130
  }
77
- // 3. Fully trimmed lines match (handles leading/trailing indentation differences)
78
- const trimmedTargetLines = targetLines.map((l) => l.trim()).filter(Boolean);
79
- if (trimmedTargetLines.length > 0) {
80
- const trimmedTargetStr = trimmedTargetLines.join('\n');
81
- const trimMatches = [];
82
- for (let i = 0; i <= origLines.length - targetLen; i++) {
83
- const windowLines = origLines.slice(i, i + targetLen).map((l) => l.trim()).filter(Boolean);
84
- if (windowLines.join('\n') === trimmedTargetStr) {
85
- trimMatches.push(i);
86
- }
87
- }
88
- if (trimMatches.length === 1) {
89
- const idx = trimMatches[0];
90
- const before = origLines.slice(0, idx);
91
- const after = origLines.slice(idx + targetLen);
92
- const updatedContent = [...before, normReplacement, ...after].join('\n');
93
- 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);
94
138
  }
95
139
  }
96
- // 4. Fuzzy non-blank lines window match (handles variable blank lines in target snippet)
97
- 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());
98
151
  if (nonBlankTargetLines.length > 0) {
99
- const nonBlankTargetStr = nonBlankTargetLines.map((l) => l.trim()).join('\n');
152
+ const nonBlankTargetStr = nonBlankTargetLines.join('\n');
100
153
  const fuzzyMatches = [];
101
154
  for (let i = 0; i < origLines.length; i++) {
102
- for (let j = i + 1; j <= Math.min(origLines.length, i + targetLen + 6); j++) {
103
- const windowLines = origLines.slice(i, j).filter((l) => l.trim().length > 0);
104
- 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) {
105
162
  fuzzyMatches.push({ startIdx: i, endIdx: j });
106
163
  break;
107
164
  }
@@ -111,14 +168,99 @@ export function robustSnippetReplace(origContent, target, replacement) {
111
168
  const { startIdx, endIdx } = fuzzyMatches[0];
112
169
  const before = origLines.slice(0, startIdx);
113
170
  const after = origLines.slice(endIdx);
114
- const updatedContent = [...before, normReplacement, ...after].join('\n');
115
- 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
+ }
116
246
  }
117
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
+ }
118
260
  return {
119
261
  success: false,
120
262
  updatedContent: origContent,
121
- 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.`
122
264
  };
123
265
  }
124
266
  export const AGENT_TOOLS = [
@@ -680,7 +822,7 @@ CORE ARCHITECTURAL PRINCIPLES:
680
822
  NEVER output a vacuous meta-summary like "Task completed" or "Looked up account" without providing the actual information the user asked for!
681
823
  - For coding/modification tasks: Detail what was changed, created, and tested.
682
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!
683
- 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".
684
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!
685
827
  12. STRICT ACTIVE GOAL ISOLATION & ACCURACY:
686
828
  - You must strictly execute ONLY the current active goal provided in the user prompt.
@@ -702,6 +844,11 @@ CORE ARCHITECTURAL PRINCIPLES:
702
844
  * Primitives: bpy.ops.mesh.primitive_uv_sphere_add, primitive_cylinder_add, primitive_cube_add
703
845
  - Apply cel-shading or toon materials with vibrant anime colors matching the request (e.g. Genshin Impact aesthetic).
704
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>".
705
852
 
706
853
  When returning tool calls, use standard OpenAI function calling format or JSON tool call payload format:
707
854
  \`\`\`json
@@ -1038,6 +1185,16 @@ When returning tool calls, use standard OpenAI function calling format or JSON t
1038
1185
  }
1039
1186
  }
1040
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
+ }
1041
1198
  if (mcpRouting.tools.length > 0 && !needsBrowser && !needsComputer) {
1042
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']);
1043
1200
  baseTools = baseTools.filter((t) => ESSENTIAL_BASE_TOOLS.has(t.name));
@@ -1089,6 +1246,7 @@ When returning tool calls, use standard OpenAI function calling format or JSON t
1089
1246
  temperature: 0.1,
1090
1247
  presence_penalty: 0.1,
1091
1248
  frequency_penalty: 0.1,
1249
+ max_tokens: 4096,
1092
1250
  });
1093
1251
  });
1094
1252
  }
@@ -1115,6 +1273,7 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1115
1273
  temperature: 0.1,
1116
1274
  presence_penalty: 0.1,
1117
1275
  frequency_penalty: 0.1,
1276
+ max_tokens: 4096,
1118
1277
  });
1119
1278
  });
1120
1279
  }
@@ -1134,8 +1293,27 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1134
1293
  this.historyMessages.push(msg);
1135
1294
  // Render assistant's thought reasoning text if provided on this turn
1136
1295
  const textContent = msg.content || '';
1137
- if (textContent.trim()) {
1138
- 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);
1139
1317
  }
1140
1318
  // Check native tool calls
1141
1319
  if (msg.tool_calls && msg.tool_calls.length > 0) {
@@ -1315,13 +1493,6 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1315
1493
  continue;
1316
1494
  }
1317
1495
  if (textContent.trim()) {
1318
- let cleanedThought = textContent
1319
- .replace(/[\u0600-\u06FF\u0750-\u077F\uAC00-\uD7AF\u3040-\u30FF\u4E00-\u9FFF\u0D80-\u0DFF]+/g, '')
1320
- .trim();
1321
- if (!cleanedThought || cleanedThought.length < 5) {
1322
- cleanedThought = 'Analyzing codebase files and executing next tool operation...';
1323
- }
1324
- safeNote(renderMarkdown(cleanedThought), ` Scout Agent Thought (Step ${step})`);
1325
1496
  const lowerText = textContent.toLowerCase().trim();
1326
1497
  const isExplicitCompletion = lowerText.includes('task is complete') ||
1327
1498
  lowerText.includes('task complete') ||
@@ -1447,6 +1618,37 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1447
1618
  }
1448
1619
  return null;
1449
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
+ }
1450
1652
  async dispatchToolCall(name, args) {
1451
1653
  this.totalToolCalls++;
1452
1654
  let actionDesc = '';
@@ -1561,9 +1763,25 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1561
1763
  return { result: currentScratch ? `Scratchpad Contents:\n${currentScratch}` : `Scratchpad is currently empty.` };
1562
1764
  }
1563
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);
1564
1782
  // 2. Autonomous Computer & Browser Automation Gating (Pro & Enterprise only)
1565
1783
  if (name === 'computer' || name.startsWith('computer_') || name.startsWith('browser_')) {
1566
- if (!isPaid) {
1784
+ if (!isPaid && !isBasicWindowTool) {
1567
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'.`;
1568
1786
  console.log(chalk.red.bold(`\n⛔ ${blockedMsg}`));
1569
1787
  this.taskStateManager.addObservation(name, blockedMsg, false);
@@ -1688,12 +1906,12 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1688
1906
  }
1689
1907
  // Tier Gating Enforcement
1690
1908
  if (!isPaid) {
1691
- if (name.startsWith('computer_') || name === 'computer') {
1909
+ if ((name.startsWith('computer_') || name === 'computer') && !isBasicWindowTool) {
1692
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.`;
1693
1911
  this.taskStateManager.addObservation(name, upgradeMsg, false);
1694
1912
  return { result: upgradeMsg };
1695
1913
  }
1696
- if (name.startsWith('browser_')) {
1914
+ if (name.startsWith('browser_') && !isBasicWindowTool) {
1697
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.`;
1698
1916
  this.taskStateManager.addObservation(name, upgradeMsg, false);
1699
1917
  return { result: upgradeMsg };
@@ -1715,7 +1933,9 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1715
1933
  const fullPath = path.isAbsolute(targetPath) ? targetPath : path.resolve(this.cwd, targetPath);
1716
1934
  const relPath = path.relative(this.cwd, fullPath).replace(/\\/g, '/');
1717
1935
  const normKey = relPath.toLowerCase();
1718
- 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()))) {
1719
1939
  const readSpin = spinner();
1720
1940
  readSpin.stop(chalk.yellow(` Skipped duplicate read for ${targetPath} (already in context)`));
1721
1941
  return {
@@ -1773,6 +1993,9 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1773
1993
  catch { }
1774
1994
  fs.writeFileSync(fullPath, content, 'utf-8');
1775
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());
1776
1999
  const oldLineCount = origContent !== '__FT_WAS_NEW__' ? origContent.split('\n').length : 0;
1777
2000
  const newLineCount = content.split('\n').length;
1778
2001
  const numberOfLinesChanged = origContent === '__FT_WAS_NEW__' ? newLineCount : Math.abs(newLineCount - oldLineCount) || newLineCount;
@@ -1802,9 +2025,9 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1802
2025
  return { result: `Successfully wrote ${content.length} characters (${numberOfLinesChanged} lines changed) to "${targetPath}". Rationale: ${reason}. Syntax check passed cleanly.` };
1803
2026
  }
1804
2027
  case 'edit_file': {
1805
- const targetPath = String(args.path || '').trim();
1806
- let target = String(args.target || '');
1807
- 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 ?? '');
1808
2031
  const reason = String(args.reason || args.why || args.description || 'Replaced target code snippet with updated implementation.');
1809
2032
  if (replacement.includes('\\n') && !replacement.includes('\n')) {
1810
2033
  replacement = replacement.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
@@ -1832,6 +2055,9 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1832
2055
  catch { }
1833
2056
  fs.writeFileSync(fullPath, replaceRes.updatedContent, 'utf-8');
1834
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());
1835
2061
  const targetLines = target.split('\n').length;
1836
2062
  const replacementLines = replacement.split('\n').length;
1837
2063
  const numberOfLinesChanged = Math.max(targetLines, replacementLines);
@@ -1977,7 +2203,7 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1977
2203
  };
1978
2204
  }
1979
2205
  case 'multi_edit_file': {
1980
- const targetPath = String(args.path || '').trim();
2206
+ const targetPath = String(args.path || args.filePath || args.file || '').trim();
1981
2207
  const edits = Array.isArray(args.edits) ? args.edits : [];
1982
2208
  const reason = String(args.reason || args.description || 'Applied multiple code snippet edits.');
1983
2209
  if (edits.length === 0) {
@@ -1993,8 +2219,8 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1993
2219
  const errors = [];
1994
2220
  for (let i = 0; i < edits.length; i++) {
1995
2221
  const ed = edits[i];
1996
- let target = String(ed.target || '');
1997
- 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 ?? '');
1998
2224
  if (target.includes('\\n') && !target.includes('\n'))
1999
2225
  target = target.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
2000
2226
  if (replacement.includes('\\n') && !replacement.includes('\n'))
@@ -2014,6 +2240,9 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2014
2240
  this.backups.push({ filePath: targetPath, originalContent: origContent });
2015
2241
  fs.writeFileSync(fullPath, currentContent, 'utf-8');
2016
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());
2017
2246
  safeNote(` • File: ${chalk.bold.cyan(targetPath)}\n` +
2018
2247
  ` • Multi-edits applied: ${chalk.bold.green(appliedCount + '/' + edits.length)}\n` +
2019
2248
  ` • Why: ${reason}`, ` Applied ${appliedCount} edits to ${targetPath}`);
@@ -2100,6 +2329,22 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2100
2329
  return { result: res.output };
2101
2330
  }
2102
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
+ }
2103
2348
  const res = await this.browserController.inspect_page();
2104
2349
  this.taskStateManager.addObservation('browser_inspect', res.summary, res.success, res.url);
2105
2350
  return { result: res.summary };
@@ -2143,6 +2388,24 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2143
2388
  return { result: res.output };
2144
2389
  }
2145
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
+ }
2146
2409
  const res = await this.browserController.screenshot();
2147
2410
  this.taskStateManager.addObservation('browser_screenshot', res.output, res.success, res.url);
2148
2411
  return { result: res.output };
@@ -2172,10 +2435,56 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2172
2435
  application: res.activeWindow || 'Desktop',
2173
2436
  });
2174
2437
  }
2175
- if (res.activeWindow) {
2176
- 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 { }
2177
2452
  }
2178
- 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');
2179
2488
  this.taskStateManager.addObservation('computer_screenshot', summary, true);
2180
2489
  return { result: summary };
2181
2490
  }
@@ -2266,7 +2575,8 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2266
2575
  }
2267
2576
  case 'computer_type': {
2268
2577
  const textVal = String(args.text || '');
2269
- 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);
2270
2580
  this.taskStateManager.addObservation('computer_type', res.output, res.success);
2271
2581
  const structuredRes = {
2272
2582
  success: res.success,
@@ -2381,9 +2691,13 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2381
2691
  }
2382
2692
  case 'computer_close_app': {
2383
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
+ }
2384
2699
  const res = await this.computerController.closeApplication(appName);
2385
2700
  this.taskStateManager.addObservation('computer_close_app', res.output, res.success);
2386
- const currentObj = this.taskStateManager.getState()?.objective || '';
2387
2701
  const simpleCheck = checkSimpleAppAction(currentObj);
2388
2702
  const isOnlyClosing = simpleCheck.isSimple && simpleCheck.action === 'close';
2389
2703
  if (isOnlyClosing && res.success) {