ft-scout 9.4.7 → 9.4.9

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 (107) hide show
  1. package/.firebase/hosting.d2Vi.cache +8 -8
  2. package/.scoutrules +13 -0
  3. package/AUTONOMOUS_FEATURES.md +15 -10
  4. package/README.md +591 -482
  5. package/bin/src/commands/agent.d.ts.map +1 -1
  6. package/bin/src/commands/agent.js +17 -49
  7. package/bin/src/commands/agent.js.map +1 -1
  8. package/bin/src/commands/authCommand.d.ts.map +1 -1
  9. package/bin/src/commands/authCommand.js +4 -10
  10. package/bin/src/commands/authCommand.js.map +1 -1
  11. package/bin/src/commands/benchmark.d.ts.map +1 -1
  12. package/bin/src/commands/benchmark.js +0 -5
  13. package/bin/src/commands/benchmark.js.map +1 -1
  14. package/bin/src/commands/init.d.ts.map +1 -1
  15. package/bin/src/commands/init.js +28 -49
  16. package/bin/src/commands/init.js.map +1 -1
  17. package/bin/src/commands/login.d.ts.map +1 -1
  18. package/bin/src/commands/login.js +2 -17
  19. package/bin/src/commands/login.js.map +1 -1
  20. package/bin/src/commands/plan.d.ts.map +1 -1
  21. package/bin/src/commands/plan.js +36 -6
  22. package/bin/src/commands/plan.js.map +1 -1
  23. package/bin/src/commands/web.d.ts.map +1 -1
  24. package/bin/src/commands/web.js +8 -26
  25. package/bin/src/commands/web.js.map +1 -1
  26. package/bin/src/engine/agentEngine.d.ts.map +1 -1
  27. package/bin/src/engine/agentEngine.js +433 -388
  28. package/bin/src/engine/agentEngine.js.map +1 -1
  29. package/bin/src/engine/computer/computerController.d.ts.map +1 -1
  30. package/bin/src/engine/computer/computerController.js +46 -0
  31. package/bin/src/engine/computer/computerController.js.map +1 -1
  32. package/bin/src/engine/llm.d.ts.map +1 -1
  33. package/bin/src/engine/llm.js +21 -51
  34. package/bin/src/engine/llm.js.map +1 -1
  35. package/bin/src/engine/runtime/agentRuntime.d.ts.map +1 -1
  36. package/bin/src/engine/runtime/agentRuntime.js +325 -215
  37. package/bin/src/engine/runtime/agentRuntime.js.map +1 -1
  38. package/bin/src/engine/toolRegistry.js +1 -1
  39. package/bin/src/engine/toolRegistry.js.map +1 -1
  40. package/bin/src/engine/voiceEngine.d.ts.map +1 -1
  41. package/bin/src/engine/voiceEngine.js +28 -252
  42. package/bin/src/engine/voiceEngine.js.map +1 -1
  43. package/bin/src/engine/workspace/agentWorkspace.d.ts.map +1 -1
  44. package/bin/src/engine/workspace/agentWorkspace.js +22 -9
  45. package/bin/src/engine/workspace/agentWorkspace.js.map +1 -1
  46. package/bin/src/index.js +30 -10
  47. package/bin/src/index.js.map +1 -1
  48. package/bin/src/mcp/client.d.ts.map +1 -1
  49. package/bin/src/mcp/client.js +8 -4
  50. package/bin/src/mcp/client.js.map +1 -1
  51. package/bin/src/mcp/discovery.d.ts.map +1 -1
  52. package/bin/src/mcp/discovery.js +13 -6
  53. package/bin/src/mcp/discovery.js.map +1 -1
  54. package/bin/src/mcp/health.d.ts.map +1 -1
  55. package/bin/src/mcp/health.js +3 -2
  56. package/bin/src/mcp/health.js.map +1 -1
  57. package/bin/src/mcp/manager.d.ts.map +1 -1
  58. package/bin/src/mcp/manager.js +22 -7
  59. package/bin/src/mcp/manager.js.map +1 -1
  60. package/bin/src/mcp/persistence.d.ts.map +1 -1
  61. package/bin/src/mcp/persistence.js +50 -15
  62. package/bin/src/mcp/persistence.js.map +1 -1
  63. package/bin/src/mcp/recovery.d.ts.map +1 -1
  64. package/bin/src/mcp/recovery.js +1 -1
  65. package/bin/src/mcp/recovery.js.map +1 -1
  66. package/bin/src/mcp/telemetry.d.ts.map +1 -1
  67. package/bin/src/mcp/telemetry.js +13 -6
  68. package/bin/src/mcp/telemetry.js.map +1 -1
  69. package/bin/src/mcp/transport.d.ts.map +1 -1
  70. package/bin/src/mcp/transport.js +68 -29
  71. package/bin/src/mcp/transport.js.map +1 -1
  72. package/bin/src/mcp/types.d.ts.map +1 -1
  73. package/bin/src/server/server.d.ts.map +1 -1
  74. package/bin/src/server/server.js +35 -1
  75. package/bin/src/server/server.js.map +1 -1
  76. package/bin/src/utils/admin.d.ts.map +1 -1
  77. package/bin/src/utils/admin.js +63 -0
  78. package/bin/src/utils/admin.js.map +1 -1
  79. package/bin/src/utils/auth.d.ts.map +1 -1
  80. package/bin/src/utils/auth.js +10 -5
  81. package/bin/src/utils/auth.js.map +1 -1
  82. package/bin/src/utils/branding.js +1 -1
  83. package/bin/src/utils/claudeUI.d.ts.map +1 -0
  84. package/bin/src/utils/claudeUI.js +404 -0
  85. package/bin/src/utils/claudeUI.js.map +1 -0
  86. package/bin/src/utils/interruptHandler.d.ts.map +1 -0
  87. package/bin/src/utils/interruptHandler.js +121 -0
  88. package/bin/src/utils/interruptHandler.js.map +1 -0
  89. package/bin/src/utils/payment.d.ts.map +1 -1
  90. package/bin/src/utils/payment.js +1 -1
  91. package/bin/src/utils/payment.js.map +1 -1
  92. package/bin/src/utils/pricing.d.ts.map +1 -1
  93. package/bin/src/utils/pricing.js +109 -46
  94. package/bin/src/utils/pricing.js.map +1 -1
  95. package/bin/src/utils/qrBridge.d.ts.map +1 -1
  96. package/bin/src/utils/qrBridge.js +17 -17
  97. package/bin/src/utils/qrBridge.js.map +1 -1
  98. package/bin/src/utils/rules.d.ts.map +1 -0
  99. package/bin/src/utils/rules.js +105 -0
  100. package/bin/src/utils/rules.js.map +1 -0
  101. package/bin/src/utils/updateCheck.d.ts.map +1 -1
  102. package/bin/src/utils/updateCheck.js +12 -1
  103. package/bin/src/utils/updateCheck.js.map +1 -1
  104. package/firebase.json +1 -1
  105. package/package.json +1 -1
  106. package/web/app.js +108 -51
  107. package/web/styles.css +3 -3
@@ -20,6 +20,9 @@ import { robustSnippetReplace, buildDirectoryTree } from '../agentEngine.js';
20
20
  import { loadAuthConfig, isProOrHigher } from '../../utils/auth.js';
21
21
  import { getMCPManager } from '../../mcp/index.js';
22
22
  import { compress, LEVEL_FAST } from 'codrop';
23
+ import { renderStepHeader, renderThoughtBox, renderToolCall, renderToolResult, renderTaskCompletedCard, } from '../../utils/claudeUI.js';
24
+ import { loadWorkspaceRules } from '../../utils/rules.js';
25
+ import { InterruptManager } from '../../utils/interruptHandler.js';
23
26
  export class AgentRuntime {
24
27
  cwd;
25
28
  autoApprove;
@@ -54,10 +57,9 @@ export class AgentRuntime {
54
57
  this.mockMode = Boolean(options?.mockMode);
55
58
  this.language = options?.language;
56
59
  this.userTier = (options?.tier || (options?.mockMode ? 'pro' : loadAuthConfig().currentTier) || 'free').toLowerCase();
57
- // Free tier is bounded to basic direct actions (max 5 steps). Full autonomous multi-step loops require Pro/Enterprise (unlimited steps).
58
- const isPaid = this.mockMode || this.userTier === 'pro' || this.userTier === 'enterprise';
60
+ // All tiers have unlimited execution steps by default (unless user explicitly limits via options.maxSteps)
59
61
  const requestedSteps = options?.maxSteps;
60
- this.maxSteps = isPaid ? (requestedSteps || Infinity) : Math.min(requestedSteps || 5, 5);
62
+ this.maxSteps = (requestedSteps && requestedSteps > 0) ? requestedSteps : Infinity;
61
63
  this.workspace = new AgentWorkspace(options?.taskId, '', this.cwd);
62
64
  this.computerController = options?.computerController || (this.mockMode ? new MockComputerController() : new SystemComputerController(this.cwd));
63
65
  this.browserController = options?.browserController || new SemanticBrowserController(this.cwd);
@@ -136,6 +138,8 @@ export class AgentRuntime {
136
138
  buildSystemPrompt() {
137
139
  const filesList = getDirectoryFiles(this.cwd).slice(0, 100);
138
140
  const workspaceState = this.workspace.compactWorkspaceForPrompt();
141
+ const workspaceRules = loadWorkspaceRules(this.cwd);
142
+ const rulesSection = workspaceRules.found ? `\n${workspaceRules.formattedPrompt}\n` : '';
139
143
  const tierNotice = !this.isProOrEnterprise()
140
144
  ? `\nTIER RESTRICTION (FREE DEVELOPER TIER):
141
145
  - You are operating under the Free Developer Tier.
@@ -156,7 +160,7 @@ Current Year: ${new Date().getFullYear()}
156
160
  ${tierNotice}
157
161
 
158
162
  ${workspaceState}
159
-
163
+ ${rulesSection}
160
164
  Available Workspace Files (sample):
161
165
  ${filesList.join('\n')}
162
166
 
@@ -227,253 +231,344 @@ Action Rules:
227
231
  this.historyMessages.push({ role: 'user', content: userGoal });
228
232
  let step = 0;
229
233
  let finalSummary = '';
230
- while (step < this.maxSteps) {
231
- if (this.isCancelled) {
232
- return {
233
- success: false,
234
- summary: `Task cancelled: ${this.cancelReason || 'User abort'}`,
235
- taskId,
236
- stepsTaken: step,
237
- modifiedFiles: Array.from(this.modifiedFiles),
238
- status: 'cancelled',
239
- };
240
- }
241
- step++;
242
- this.currentStep = step;
243
- this.workspace.startStep(step);
244
- // Context Compaction check: If history is long, compact middle turns using workspace state
245
- if (this.historyMessages.length > 10) {
246
- this.historyMessages = this.workspace.compactHistoryMessages(this.historyMessages, 6);
247
- }
248
- const isPaid = this.isProOrEnterprise();
249
- const stepSpinner = spinner();
250
- const stepText = isPaid && !Number.isFinite(this.maxSteps)
251
- ? `Scout Operating (Step ${step})`
252
- : `Scout Operating (Step ${step}/${this.maxSteps})`;
253
- stepSpinner.start(chalk.cyan(stepText));
254
- try {
255
- let response;
256
- const mcpRouting = getMCPManager().routeTools(userGoal);
257
- const mcpToolDefs = mcpRouting.tools.map((mt) => {
258
- let desc = mt.description;
259
- if (mt.originalName === 'execute_blender_code') {
260
- desc = 'Execute Python (bpy) code inside Blender. Use this to procedurally create, model, texture, color, and render 3D meshes, anime/game characters, clothing, hair, materials, cel-shading, lights, cameras, and scenes directly.';
261
- }
262
- else if (mt.originalName === 'generate_3d') {
263
- desc = 'Cloud AI text-to-3d generator (requires external API key). If keys are not set, use execute_blender_code to model directly.';
234
+ const interruptManager = new InterruptManager({
235
+ getStepInfo: () => ({
236
+ step: this.currentStep || 1,
237
+ maxSteps: this.maxSteps,
238
+ goal: userGoal,
239
+ modifiedFilesCount: this.modifiedFiles.size,
240
+ }),
241
+ onPause: () => {
242
+ this.workspace.setStatus('paused');
243
+ },
244
+ onResume: () => {
245
+ this.workspace.setStatus('running');
246
+ },
247
+ onFeedback: (feedback) => {
248
+ this.historyMessages.push({
249
+ role: 'user',
250
+ content: `[USER STEERING FEEDBACK (INTERRUPTED AT STEP ${this.currentStep})]:\n"${feedback}"\n\nPlease adapt your execution plan accordingly and follow these user steering instructions immediately.`,
251
+ });
252
+ },
253
+ onRevert: () => {
254
+ if (this.backups.length === 0)
255
+ return false;
256
+ for (const b of this.backups) {
257
+ try {
258
+ fs.writeFileSync(b.filePath, b.originalContent, 'utf-8');
264
259
  }
260
+ catch { }
261
+ }
262
+ this.modifiedFiles.clear();
263
+ return true;
264
+ },
265
+ onAbort: (reason) => {
266
+ this.isCancelled = true;
267
+ this.cancelReason = reason;
268
+ },
269
+ });
270
+ interruptManager.attach();
271
+ try {
272
+ while (step < this.maxSteps) {
273
+ if (this.isCancelled) {
265
274
  return {
266
- name: mt.originalName,
267
- description: `[MCP: ${mt.serverName}] ${desc.length > 250 ? desc.slice(0, 247) + '...' : desc}`,
268
- parameters: {
269
- type: 'object',
270
- properties: mt.inputSchema.properties || {},
271
- required: mt.inputSchema.required || [],
272
- },
273
- source: 'mcp',
274
- mcpServerId: mt.serverId,
275
- mcpServerName: mt.serverName,
275
+ success: false,
276
+ summary: `Task cancelled: ${this.cancelReason || 'User abort'}`,
277
+ taskId,
278
+ stepsTaken: step,
279
+ modifiedFiles: Array.from(this.modifiedFiles),
280
+ status: 'cancelled',
276
281
  };
277
- });
278
- const goalLower = (userGoal || '').toLowerCase();
279
- const needsBrowser = goalLower.includes('browser') || goalLower.includes('website') || goalLower.includes('webpage') || goalLower.includes('http') || goalLower.includes('url') || goalLower.includes('scrape') || goalLower.includes('chrome');
280
- const needsComputer = goalLower.includes('computer') || goalLower.includes('desktop') || goalLower.includes('mouse') || goalLower.includes('coordinate') || goalLower.includes('drag') || goalLower.includes('double click');
281
- let baseTools = this.toolRegistry.getToolsForTier(this.userTier);
282
- if (mcpToolDefs.length > 0 && !needsBrowser && !needsComputer) {
283
- 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']);
284
- baseTools = baseTools.filter((t) => ESSENTIAL_BASE_TOOLS.has(t.name));
285
282
  }
286
- else if (!needsBrowser) {
287
- baseTools = baseTools.filter((t) => !t.name.startsWith('browser_'));
283
+ step++;
284
+ this.currentStep = step;
285
+ this.workspace.startStep(step);
286
+ // Context Compaction check: If history is long, compact middle turns using workspace state
287
+ if (this.historyMessages.length > 10) {
288
+ this.historyMessages = this.workspace.compactHistoryMessages(this.historyMessages, 6);
288
289
  }
289
- const tierTools = [...baseTools, ...mcpToolDefs];
290
+ const isPaid = this.isProOrEnterprise();
291
+ renderStepHeader({
292
+ step,
293
+ maxSteps: this.maxSteps,
294
+ startTimeMs: this.workspace.getData().createdAt ? new Date(this.workspace.getData().createdAt).getTime() : Date.now(),
295
+ tokensConsumed: 0,
296
+ userTier: this.userTier,
297
+ });
298
+ const stepSpinner = spinner();
299
+ const stepText = !Number.isFinite(this.maxSteps)
300
+ ? `Scout Operating (Step ${step})`
301
+ : `Scout Operating (Step ${step}/${this.maxSteps})`;
302
+ stepSpinner.start(chalk.cyan(stepText));
290
303
  try {
291
- response = await callOpenAIWithRetry(async (model) => {
292
- return await openai.chat.completions.create({
293
- model,
294
- messages: sanitizeMessages(this.historyMessages),
295
- tools: tierTools.map((t) => ({ type: 'function', function: t })),
296
- tool_choice: 'auto',
297
- temperature: 0.1,
298
- });
299
- });
300
- }
301
- catch (err) {
302
- const errStr = String(err?.message || err || '').toLowerCase();
303
- if (errStr.includes('tool') || errStr.includes('400') || errStr.includes('not supported')) {
304
- const fallbackMsg = {
305
- role: 'user',
306
- content: `Format your tool call as a JSON code block:\n\`\`\`json\n{ "tool": "tool_name", "args": { ... } }\n\`\`\`\nAvailable tools: ${tierTools.map((t) => t.name).join(', ')}`,
304
+ let response;
305
+ const mcpRouting = getMCPManager().routeTools(userGoal);
306
+ const goalLower = (userGoal || '').toLowerCase();
307
+ const needsBrowser = goalLower.includes('browser') || goalLower.includes('website') || goalLower.includes('webpage') || goalLower.includes('http') || goalLower.includes('url') || goalLower.includes('scrape') || goalLower.includes('chrome');
308
+ const needsComputer = goalLower.includes('computer') || goalLower.includes('desktop') || goalLower.includes('mouse') || goalLower.includes('coordinate') || goalLower.includes('drag') || goalLower.includes('double click');
309
+ let baseTools = this.toolRegistry.getToolsForTier(this.userTier);
310
+ if (mcpRouting.tools.length > 0 && !needsBrowser && !needsComputer) {
311
+ 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']);
312
+ baseTools = baseTools.filter((t) => ESSENTIAL_BASE_TOOLS.has(t.name));
313
+ }
314
+ else if (!needsBrowser) {
315
+ baseTools = baseTools.filter((t) => !t.name.startsWith('browser_'));
316
+ }
317
+ const baseToolNames = new Set(baseTools.map((t) => t.name));
318
+ const mcpNameCounts = new Map();
319
+ for (const mt of mcpRouting.tools) {
320
+ mcpNameCounts.set(mt.originalName, (mcpNameCounts.get(mt.originalName) || 0) + 1);
321
+ }
322
+ const mcpToolDefs = mcpRouting.tools.map((mt) => {
323
+ let desc = mt.description;
324
+ if (mt.originalName === 'execute_blender_code') {
325
+ desc = 'Execute Python (bpy) code inside Blender. Use this to procedurally create, model, texture, color, and render 3D meshes, anime/game characters, clothing, hair, materials, cel-shading, lights, cameras, and scenes directly.';
326
+ }
327
+ else if (mt.originalName === 'generate_3d') {
328
+ desc = 'Cloud AI text-to-3d generator (requires external API key). If keys are not set, use execute_blender_code to model directly.';
329
+ }
330
+ // Disambiguate if tool name collides with a base tool or another MCP tool
331
+ const hasCollision = (mcpNameCounts.get(mt.originalName) || 0) > 1 || baseToolNames.has(mt.originalName);
332
+ const exposedName = hasCollision ? mt.qualifiedName : mt.originalName;
333
+ // Ensure required keys strictly match properties for valid OpenAI function calling schema
334
+ const props = (mt.inputSchema.properties || {});
335
+ const propKeys = new Set(Object.keys(props));
336
+ const cleanRequired = (mt.inputSchema.required || []).filter((r) => propKeys.has(r));
337
+ return {
338
+ name: exposedName,
339
+ description: `[MCP: ${mt.serverName}] ${desc.length > 250 ? desc.slice(0, 247) + '...' : desc}`,
340
+ parameters: {
341
+ type: 'object',
342
+ properties: props,
343
+ required: cleanRequired,
344
+ },
345
+ source: 'mcp',
346
+ mcpServerId: mt.serverId,
347
+ mcpServerName: mt.serverName,
307
348
  };
349
+ });
350
+ const tierTools = [...baseTools, ...mcpToolDefs];
351
+ try {
308
352
  response = await callOpenAIWithRetry(async (model) => {
309
353
  return await openai.chat.completions.create({
310
354
  model,
311
- messages: sanitizeMessages([...this.historyMessages, fallbackMsg]),
355
+ messages: sanitizeMessages(this.historyMessages),
356
+ tools: tierTools.map((t) => ({ type: 'function', function: t })),
357
+ tool_choice: 'auto',
312
358
  temperature: 0.1,
313
359
  });
314
360
  });
315
361
  }
316
- else {
317
- throw err;
318
- }
319
- }
320
- const choice = response.choices[0];
321
- if (!choice) {
322
- stepSpinner.stop(chalk.yellow('No response from model. Retrying step...'));
323
- continue;
324
- }
325
- const msg = sanitizeMessage(choice.message);
326
- this.historyMessages.push(msg);
327
- if (msg.content && msg.content.trim()) {
328
- safeNote(renderMarkdown(msg.content), `Scout Step ${step}`);
329
- }
330
- let toolCallsToExecute = [];
331
- if (msg.tool_calls && msg.tool_calls.length > 0) {
332
- for (const tc of msg.tool_calls) {
333
- if (tc.type === 'function' && tc.function) {
334
- try {
335
- toolCallsToExecute.push({
336
- name: tc.function.name,
337
- args: JSON.parse(tc.function.arguments || '{}'),
338
- id: tc.id,
362
+ catch (err) {
363
+ const errStr = String(err?.message || err || '').toLowerCase();
364
+ if (errStr.includes('tool') || errStr.includes('400') || errStr.includes('not supported')) {
365
+ const fallbackMsg = {
366
+ role: 'user',
367
+ content: `Format your tool call as a JSON code block:\n\`\`\`json\n{ "tool": "tool_name", "args": { ... } }\n\`\`\`\nAvailable tools: ${tierTools.map((t) => t.name).join(', ')}`,
368
+ };
369
+ response = await callOpenAIWithRetry(async (model) => {
370
+ return await openai.chat.completions.create({
371
+ model,
372
+ messages: sanitizeMessages([...this.historyMessages, fallbackMsg]),
373
+ temperature: 0.1,
339
374
  });
340
- }
341
- catch {
342
- toolCallsToExecute.push({ name: tc.function.name, args: {}, id: tc.id });
343
- }
375
+ });
376
+ }
377
+ else {
378
+ throw err;
344
379
  }
345
380
  }
346
- }
347
- else if (msg.content) {
348
- const parsed = this.extractJsonToolCall(msg.content);
349
- if (parsed) {
350
- toolCallsToExecute.push({ name: parsed.tool, args: parsed.args });
381
+ const choice = response.choices[0];
382
+ if (!choice) {
383
+ stepSpinner.stop(chalk.yellow('No response from model. Retrying step...'));
384
+ continue;
351
385
  }
352
- }
353
- stepSpinner.stop(chalk.green(`Step ${step}: Executing ${toolCallsToExecute.length} action(s).`));
354
- for (const tc of toolCallsToExecute) {
355
- if (this.isCancelled)
356
- break;
357
- const toolResult = await this.dispatchTool(tc.name, tc.args);
358
- // Build the tool result message with correct role
359
- const rawContent = typeof toolResult.result === 'string' ? toolResult.result : JSON.stringify(toolResult.result);
360
- let cappedContent = rawContent;
361
- if (rawContent.length > 800) {
362
- try {
363
- const origBytes = Buffer.byteLength(rawContent, 'utf-8');
364
- const cdp = compress(Buffer.from(rawContent, 'utf-8'), LEVEL_FAST);
365
- const ratio = (origBytes / Math.max(1, cdp.length)).toFixed(1);
366
- cappedContent = rawContent.slice(0, 800) + `\n... [Codrop: ${origBytes}B compressed to ${cdp.length}B (${ratio}x ratio) for LLM context]`;
367
- }
368
- catch {
369
- cappedContent = rawContent.slice(0, 800) + '\n... [output truncated for token efficiency]';
370
- }
386
+ const msg = sanitizeMessage(choice.message);
387
+ this.historyMessages.push(msg);
388
+ if (msg.content && msg.content.trim()) {
389
+ renderThoughtBox(msg.content, step);
371
390
  }
372
- if (tc.id) {
373
- // Native tool call: use 'tool' role with matching tool_call_id
374
- this.historyMessages.push({
375
- role: 'tool',
376
- tool_call_id: tc.id,
377
- content: cappedContent,
378
- });
391
+ let toolCallsToExecute = [];
392
+ if (msg.tool_calls && msg.tool_calls.length > 0) {
393
+ for (const tc of msg.tool_calls) {
394
+ if (tc.type === 'function' && tc.function) {
395
+ try {
396
+ toolCallsToExecute.push({
397
+ name: tc.function.name,
398
+ args: JSON.parse(tc.function.arguments || '{}'),
399
+ id: tc.id,
400
+ });
401
+ }
402
+ catch {
403
+ toolCallsToExecute.push({ name: tc.function.name, args: {}, id: tc.id });
404
+ }
405
+ }
406
+ }
379
407
  }
380
- else {
381
- // JSON-extracted tool call (no tc.id): use 'user' role
382
- this.historyMessages.push({
383
- role: 'user',
384
- content: `Tool Execution Result (${tc.name}):\n${cappedContent}`,
385
- });
408
+ else if (msg.content) {
409
+ const parsed = this.extractJsonToolCall(msg.content);
410
+ if (parsed) {
411
+ toolCallsToExecute.push({ name: parsed.tool, args: parsed.args });
412
+ }
386
413
  }
387
- // If the tool returned screenshot data, append a vision message so the model can see the screen
388
- if (toolResult.screenshotBase64) {
389
- this.pruneOldScreenshots();
390
- this.historyMessages.push({
391
- role: 'user',
392
- content: [
393
- { type: 'text', text: `[Screenshot after ${tc.name}]: ${toolResult.screenshotSummary || 'Current screen state.'}` },
394
- { type: 'image_url', image_url: { url: `data:image/png;base64,${toolResult.screenshotBase64}`, detail: 'low' } },
395
- ],
414
+ stepSpinner.stop(chalk.green(`Step ${step}: Executing ${toolCallsToExecute.length} action(s).`));
415
+ for (const tc of toolCallsToExecute) {
416
+ if (this.isCancelled)
417
+ break;
418
+ renderToolCall({ name: tc.name, args: tc.args, step });
419
+ const toolStartTime = Date.now();
420
+ const toolResult = await this.dispatchTool(tc.name, tc.args);
421
+ const durationMs = Date.now() - toolStartTime;
422
+ renderToolResult({
423
+ name: tc.name,
424
+ args: tc.args,
425
+ result: typeof toolResult.result === 'string' ? toolResult.result : JSON.stringify(toolResult.result),
426
+ durationMs,
427
+ success: !String(toolResult.result).includes('[PLAN RESTRICTION') && !String(toolResult.result).includes('[ACTION BLOCKED'),
396
428
  });
397
- }
398
- // Automatic immediate completion for simple app actions (open/close/switch window)
399
- const simpleAppCheck = checkSimpleAppAction(userGoal);
400
- if (simpleAppCheck.isSimple && (tc.name === 'computer_open_app' || tc.name === 'computer_close_app' || tc.name === 'computer_switch_window')) {
401
- let callSucceeded = false;
402
- try {
403
- const parsed = typeof toolResult.result === 'string' ? JSON.parse(toolResult.result) : toolResult.result;
404
- callSucceeded = parsed?.success !== false;
429
+ // Build the tool result message with correct role
430
+ const rawContent = typeof toolResult.result === 'string' ? toolResult.result : JSON.stringify(toolResult.result);
431
+ let cappedContent = rawContent;
432
+ if (rawContent.length > 800) {
433
+ try {
434
+ const origBytes = Buffer.byteLength(rawContent, 'utf-8');
435
+ const cdp = compress(Buffer.from(rawContent, 'utf-8'), LEVEL_FAST);
436
+ const ratio = (origBytes / Math.max(1, cdp.length)).toFixed(1);
437
+ cappedContent = rawContent.slice(0, 800) + `\n... [Codrop: ${origBytes}B compressed to ${cdp.length}B (${ratio}x ratio) for LLM context]`;
438
+ }
439
+ catch {
440
+ cappedContent = rawContent.slice(0, 800) + '\n... [output truncated for token efficiency]';
441
+ }
442
+ }
443
+ if (tc.id) {
444
+ // Native tool call: use 'tool' role with matching tool_call_id
445
+ this.historyMessages.push({
446
+ role: 'tool',
447
+ tool_call_id: tc.id,
448
+ content: cappedContent,
449
+ });
405
450
  }
406
- catch {
407
- const str = String(toolResult.result || '').toLowerCase();
408
- callSucceeded = !str.includes('failed') && !str.includes('error');
451
+ else {
452
+ // JSON-extracted tool call (no tc.id): use 'user' role
453
+ this.historyMessages.push({
454
+ role: 'user',
455
+ content: `Tool Execution Result (${tc.name}):\n${cappedContent}`,
456
+ });
457
+ }
458
+ // If the tool returned screenshot data, append a vision message so the model can see the screen
459
+ if (toolResult.screenshotBase64) {
460
+ this.pruneOldScreenshots();
461
+ this.historyMessages.push({
462
+ role: 'user',
463
+ content: [
464
+ { type: 'text', text: `[Screenshot after ${tc.name}]: ${toolResult.screenshotSummary || 'Current screen state.'}` },
465
+ { type: 'image_url', image_url: { url: `data:image/png;base64,${toolResult.screenshotBase64}`, detail: 'low' } },
466
+ ],
467
+ });
409
468
  }
410
- if (callSucceeded) {
411
- const appName = simpleAppCheck.appName || 'application';
412
- const actionVerb = simpleAppCheck.action === 'close' ? 'closed' : (simpleAppCheck.action === 'switch' ? 'focused' : 'launched');
413
- finalSummary = `I've ${actionVerb} ${appName} for you. It's ready on your screen!`;
414
- safeNote(chalk.green(` ${finalSummary}`), 'Task Completed');
469
+ // Automatic immediate completion for simple app actions (open/close/switch window)
470
+ const simpleAppCheck = checkSimpleAppAction(userGoal);
471
+ if (simpleAppCheck.isSimple && (tc.name === 'computer_open_app' || tc.name === 'computer_close_app' || tc.name === 'computer_switch_window')) {
472
+ let callSucceeded = false;
473
+ try {
474
+ const parsed = typeof toolResult.result === 'string' ? JSON.parse(toolResult.result) : toolResult.result;
475
+ callSucceeded = parsed?.success !== false;
476
+ }
477
+ catch {
478
+ const str = String(toolResult.result || '').toLowerCase();
479
+ callSucceeded = !str.includes('failed') && !str.includes('error');
480
+ }
481
+ if (callSucceeded) {
482
+ const appName = simpleAppCheck.appName || 'application';
483
+ const actionVerb = simpleAppCheck.action === 'close' ? 'closed' : (simpleAppCheck.action === 'switch' ? 'focused' : 'launched');
484
+ finalSummary = `I've ${actionVerb} ${appName} for you. It's ready on your screen!`;
485
+ renderTaskCompletedCard({
486
+ objective: userGoal,
487
+ summary: finalSummary,
488
+ modifiedFiles: [],
489
+ steps: step,
490
+ maxSteps: this.maxSteps,
491
+ totalTokens: 0,
492
+ totalToolCalls: step,
493
+ elapsedSecs: Math.round((Date.now() - (this.workspace.getData().createdAt ? new Date(this.workspace.getData().createdAt).getTime() : Date.now())) / 1000),
494
+ userTier: this.userTier,
495
+ });
496
+ this.workspace.setStatus('completed');
497
+ this.workspace.completeStep(step, finalSummary);
498
+ saveAgentSession({
499
+ goal: userGoal,
500
+ summary: finalSummary,
501
+ modifiedFiles: [],
502
+ });
503
+ return {
504
+ success: true,
505
+ summary: finalSummary,
506
+ taskId,
507
+ stepsTaken: step,
508
+ modifiedFiles: [],
509
+ status: 'completed',
510
+ };
511
+ }
512
+ }
513
+ if (tc.name === 'task_completed') {
514
+ finalSummary = tc.args.summary || toolResult.result;
515
+ if (this.modifiedFiles.size > 0) {
516
+ const filesList = getDirectoryFiles(this.cwd);
517
+ await verifyAndSelfHealFiles(Array.from(this.modifiedFiles), this.cwd, path.basename(this.cwd), filesList, { maxRetries: 3 });
518
+ }
519
+ renderTaskCompletedCard({
520
+ objective: userGoal,
521
+ summary: finalSummary,
522
+ modifiedFiles: Array.from(this.modifiedFiles),
523
+ steps: step,
524
+ maxSteps: this.maxSteps,
525
+ totalTokens: 0,
526
+ totalToolCalls: step,
527
+ elapsedSecs: Math.round((Date.now() - (this.workspace.getData().createdAt ? new Date(this.workspace.getData().createdAt).getTime() : Date.now())) / 1000),
528
+ userTier: this.userTier,
529
+ });
415
530
  this.workspace.setStatus('completed');
416
531
  this.workspace.completeStep(step, finalSummary);
417
532
  saveAgentSession({
418
533
  goal: userGoal,
419
534
  summary: finalSummary,
420
- modifiedFiles: [],
535
+ modifiedFiles: Array.from(this.modifiedFiles),
421
536
  });
422
537
  return {
423
538
  success: true,
424
539
  summary: finalSummary,
425
540
  taskId,
426
541
  stepsTaken: step,
427
- modifiedFiles: [],
542
+ modifiedFiles: Array.from(this.modifiedFiles),
428
543
  status: 'completed',
429
544
  };
430
545
  }
431
546
  }
432
- if (tc.name === 'task_completed') {
433
- finalSummary = tc.args.summary || toolResult.result;
434
- if (this.modifiedFiles.size > 0) {
435
- const filesList = getDirectoryFiles(this.cwd);
436
- await verifyAndSelfHealFiles(Array.from(this.modifiedFiles), this.cwd, path.basename(this.cwd), filesList, { maxRetries: 3 });
437
- }
438
- this.workspace.setStatus('completed');
439
- this.workspace.completeStep(step, finalSummary);
440
- saveAgentSession({
441
- goal: userGoal,
442
- summary: finalSummary,
443
- modifiedFiles: Array.from(this.modifiedFiles),
444
- });
445
- return {
446
- success: true,
447
- summary: finalSummary,
448
- taskId,
449
- stepsTaken: step,
450
- modifiedFiles: Array.from(this.modifiedFiles),
451
- status: 'completed',
452
- };
453
- }
547
+ }
548
+ catch (err) {
549
+ stepSpinner.stop(chalk.red(`Step ${step} error: ${err?.message || String(err)}`));
550
+ this.workspace.recordError(err?.message || String(err), 'runtime', undefined, false);
551
+ this.historyMessages.push({
552
+ role: 'user',
553
+ content: `System Error encountered on step ${step}: ${err?.message || String(err)}. Diagnose and adapt action.`,
554
+ });
454
555
  }
455
556
  }
456
- catch (err) {
457
- stepSpinner.stop(chalk.red(`Step ${step} error: ${err?.message || String(err)}`));
458
- this.workspace.recordError(err?.message || String(err), 'runtime', undefined, false);
459
- this.historyMessages.push({
460
- role: 'user',
461
- content: `System Error encountered on step ${step}: ${err?.message || String(err)}. Diagnose and adapt action.`,
462
- });
463
- }
557
+ this.workspace.setStatus('failed');
558
+ return {
559
+ success: false,
560
+ summary: Number.isFinite(this.maxSteps)
561
+ ? `Reached max iteration steps limit (${this.maxSteps}). Modified files: ${Array.from(this.modifiedFiles).join(', ')}`
562
+ : `Task ended after ${step} iteration steps. Modified files: ${Array.from(this.modifiedFiles).join(', ')}`,
563
+ taskId,
564
+ stepsTaken: step,
565
+ modifiedFiles: Array.from(this.modifiedFiles),
566
+ status: 'failed',
567
+ };
568
+ }
569
+ finally {
570
+ interruptManager.detach();
464
571
  }
465
- this.workspace.setStatus('failed');
466
- const isPaid = this.isProOrEnterprise();
467
- return {
468
- success: false,
469
- summary: isPaid
470
- ? `Task ended after ${step} iteration steps. Modified files: ${Array.from(this.modifiedFiles).join(', ')}`
471
- : `Reached max iteration steps limit (${this.maxSteps}). Modified files: ${Array.from(this.modifiedFiles).join(', ')}`,
472
- taskId,
473
- stepsTaken: step,
474
- modifiedFiles: Array.from(this.modifiedFiles),
475
- status: 'failed',
476
- };
477
572
  }
478
573
  async executeTool(name, args) {
479
574
  return await this.dispatchTool(name, args);
@@ -608,6 +703,9 @@ Action Rules:
608
703
  else if (action === 'diagnostic') {
609
704
  name = 'computer_diagnostic';
610
705
  }
706
+ else if (action === 'wait') {
707
+ name = 'computer_wait';
708
+ }
611
709
  }
612
710
  switch (name) {
613
711
  case 'computer_screenshot': {
@@ -879,6 +977,15 @@ Action Rules:
879
977
  const diag = await this.computerController.runDiagnostic();
880
978
  return { result: JSON.stringify(diag, null, 2) };
881
979
  }
980
+ case 'computer': {
981
+ return {
982
+ result: JSON.stringify({
983
+ success: false,
984
+ error: 'InvalidComputerAction',
985
+ message: `Unknown computer action: "${args?.action}". Supported actions: click, right_click, double_click, move, mouse_down, mouse_up, drag, scroll, screenshot, type, key_press, hotkey, open_app, close_app, switch_window, inspect_ui, diagnostic, wait.`
986
+ }, null, 2)
987
+ };
988
+ }
882
989
  default:
883
990
  return { result: `Unknown computer tool: "${name}"` };
884
991
  }
@@ -1234,8 +1341,7 @@ Action Rules:
1234
1341
  }
1235
1342
  case 'speak_text': {
1236
1343
  const txt = String(args.text || '');
1237
- speakText(txt, { async: true });
1238
- return { result: `Spoke: "${txt}"` };
1344
+ return { result: `[TTS DISABLED]: Text-to-speech audio synthesis has been disabled. Text displayed: "${txt}"` };
1239
1345
  }
1240
1346
  case 'task_completed': {
1241
1347
  const summary = String(args.summary || 'Completed');
@@ -1254,7 +1360,6 @@ Action Rules:
1254
1360
  };
1255
1361
  }
1256
1362
  }
1257
- speakText(summary, { async: true });
1258
1363
  return { result: summary };
1259
1364
  }
1260
1365
  default: {
@@ -1263,17 +1368,22 @@ Action Rules:
1263
1368
  if (mcpTarget) {
1264
1369
  const mcpRes = await mcpManager.executeTool(name, args);
1265
1370
  const isSuccess = mcpRes.status === 'success';
1371
+ const resObj = (typeof mcpRes.result === 'object' && mcpRes.result !== null)
1372
+ ? mcpRes.result
1373
+ : null;
1266
1374
  const outputStr = typeof mcpRes.result === 'string'
1267
1375
  ? mcpRes.result
1268
- : (mcpRes.result?.text ? String(mcpRes.result.text) : JSON.stringify(mcpRes.result ?? { status: mcpRes.status, error: mcpRes.error }));
1376
+ : (resObj && 'text' in resObj && typeof resObj.text === 'string'
1377
+ ? resObj.text
1378
+ : JSON.stringify(mcpRes.result ?? { status: mcpRes.status, error: mcpRes.error }));
1269
1379
  this.workspace.addObservation({
1270
1380
  tool: name,
1271
1381
  resultSummary: mcpRes.outputSummary || outputStr,
1272
1382
  verified: isSuccess,
1273
1383
  });
1274
1384
  // Track modified files if returned
1275
- if (isSuccess && typeof mcpRes.result === 'object' && mcpRes.result !== null) {
1276
- const possiblePath = mcpRes.result.path || mcpRes.result.filePath || mcpRes.result.file || args.destPath || args.path || args.outputPath;
1385
+ if (isSuccess && resObj) {
1386
+ const possiblePath = resObj.path || resObj.filePath || resObj.file || args.destPath || args.path || args.outputPath;
1277
1387
  if (typeof possiblePath === 'string' && fs.existsSync(path.resolve(this.cwd, possiblePath))) {
1278
1388
  this.modifiedFiles.add(path.relative(this.cwd, path.resolve(this.cwd, possiblePath)).replace(/\\/g, '/'));
1279
1389
  }