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
@@ -24,6 +24,9 @@ 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';
28
+ import { loadWorkspaceRules } from '../utils/rules.js';
29
+ import { InterruptManager } from '../utils/interruptHandler.js';
27
30
  export { AgentRuntime, AgentWorkspace, inferExecutionIntent, resolveDesktopPath, SystemComputerController, MockComputerController };
28
31
  const execAsync = promisify(exec);
29
32
  export function robustSnippetReplace(origContent, target, replacement) {
@@ -407,6 +410,7 @@ export class AgentExecutionLoop {
407
410
  userTier;
408
411
  currentGoal = '';
409
412
  isAudioMode = false;
413
+ agentWorkspace;
410
414
  syncTelemetry(status, lastLog) {
411
415
  try {
412
416
  writeTelemetry({
@@ -427,11 +431,11 @@ export class AgentExecutionLoop {
427
431
  this.mockMode = Boolean(options?.mockMode);
428
432
  this.isAudioMode = Boolean(options?.isAudioMode);
429
433
  this.userTier = (options?.tier || loadAuthConfig().currentTier || 'free').toLowerCase();
430
- // Free tier is bounded to basic direct actions (max 5 steps). Full autonomous multi-step loops require Pro/Enterprise (unlimited steps).
431
- const isPaid = this.mockMode || this.userTier === 'pro' || this.userTier === 'enterprise';
434
+ // All tiers have unlimited execution steps by default (unless user explicitly limits via options.maxSteps)
432
435
  const requestedSteps = options?.maxSteps;
433
- this.maxSteps = isPaid ? (requestedSteps || Infinity) : Math.min(requestedSteps || 5, 5);
434
- this.taskStateManager = new TaskStateManager(options?.taskId, '', this.cwd);
436
+ this.maxSteps = (requestedSteps && requestedSteps > 0) ? requestedSteps : Infinity;
437
+ this.agentWorkspace = new AgentWorkspace(options?.taskId, '', this.cwd);
438
+ this.taskStateManager = this.agentWorkspace.getStateManager();
435
439
  this.computerController = options?.computerController || (this.mockMode ? new MockComputerController() : new SystemComputerController(this.cwd));
436
440
  this.browserController = options?.browserController || new SemanticBrowserController(this.cwd);
437
441
  this.actionVerifier = new ActionVerifier(this.cwd);
@@ -443,7 +447,7 @@ export class AgentExecutionLoop {
443
447
  return this.userTier;
444
448
  }
445
449
  isPaidTier() {
446
- return this.mockMode || this.userTier === 'pro' || this.userTier === 'enterprise';
450
+ return this.mockMode || isProOrHigher(this.userTier);
447
451
  }
448
452
  getExecutionIntent() {
449
453
  return this.executionIntent;
@@ -625,19 +629,17 @@ PLAN TIER & CAPABILITIES: ${this.userTier.toUpperCase()} (FULL ACCESS UNLOCKED)
625
629
  • Autonomous Computer-Use, Browser Automation, and AI Scratchpad Reasoning are fully ENABLED.
626
630
  • Use the 'scratchpad' tool to organize multi-step reasoning, break down complex goals, draft hypotheses, and track working memory across turns.
627
631
  ` : `
628
- PLAN TIER & CAPABILITIES: DEVELOPER FREE (BASIC DEVELOPER OPS ONLY)
629
- • Scratchpadding and Autonomous Multi-Step Desktop/Browser Control are RESTRICTED to Pro & Enterprise plans.
630
- • As a Free Tier developer assistant, you ONLY perform basic developer operations:
631
- 1. Code editing: use edit_file or multi_edit_file to modify existing code.
632
- 2. Creating new files & folders: use write_file to create new files and parent directories.
633
- 3. Running commands: use run_command to execute terminal commands, builds, package installs, or tests.
634
- 4. Reading & exploring: use read_file, list_dir, grep_search, and fetch_url to inspect files and fetch remote documentation/specs.
635
- • Do NOT attempt to use scratchpad, computer, or browser tools. Execute the requested file edit, file creation, command, or url fetch directly and call task_completed immediately.
632
+ PLAN TIER & CAPABILITIES: DEVELOPER FREE (UNLIMITED MULTI-STEP CORE CODING)
633
+ • Unlimited execution steps: Take as many iterative steps as needed to solve, test, and verify the task thoroughly.
634
+ • Developer operations enabled: Code editing, file/directory creation, running terminal commands/tests, syntax verification, reading, and exploration.
635
+ • Work systematically: Inspect the code, run relevant builds/tests, verify syntax, and ensure high code quality before completing.
636
636
  `;
637
637
  const mcpRouting = getMCPManager().routeTools(this.currentGoal);
638
638
  const mcpCapabilitiesSection = mcpRouting.capabilitiesSummary ? `\n${mcpRouting.capabilitiesSummary}\n` : '';
639
639
  const recentSessionsMemory = getRecentSessionsSummary(1);
640
640
  const sessionHistorySection = recentSessionsMemory ? `\n${recentSessionsMemory}\n` : '';
641
+ const workspaceRules = loadWorkspaceRules(this.cwd);
642
+ const rulesSection = workspaceRules.found ? `\n${workspaceRules.formattedPrompt}\n` : '';
641
643
  return `You are Scout Agent, an elite AI Principal Software Engineer & Autonomous Computer-Use Operator (developed by FrontTerrain).
642
644
 
643
645
  Working Directory: "${this.cwd}"
@@ -647,6 +649,7 @@ ${tierDirective}
647
649
  ${intentInfo}
648
650
  ${mcpCapabilitiesSection}
649
651
  ${sessionHistorySection}
652
+ ${rulesSection}
650
653
  Workspace Overview (first 100 files):
651
654
  ${filesList.join('\n')}
652
655
 
@@ -738,6 +741,10 @@ When returning tool calls, use standard OpenAI function calling format or JSON t
738
741
  };
739
742
  }
740
743
  this.historyMessages.push({ role: 'system', content: this.systemPrompt() });
744
+ const workspaceRules = loadWorkspaceRules(this.cwd);
745
+ if (workspaceRules.found) {
746
+ console.log(chalk.cyan(`📋 Loaded workspace rules from ${workspaceRules.fileName}`));
747
+ }
741
748
  // Robust Target File Discovery: Only run file discovery if the goal has explicit code editing/modification intent
742
749
  const simpleAppCheck = checkSimpleAppAction(userGoal);
743
750
  const lowerGoal = userGoal.toLowerCase().trim();
@@ -849,11 +856,8 @@ When returning tool calls, use standard OpenAI function calling format or JSON t
849
856
  content: promptContent,
850
857
  });
851
858
  }
852
- const isPaid = this.mockMode || this.userTier === 'pro' || this.userTier === 'enterprise';
853
- if (!isPaid && Number.isFinite(this.maxSteps)) {
854
- const estTotalSecs = Math.round(this.maxSteps * 12);
855
- const estTimeText = estTotalSecs >= 60 ? `~${(estTotalSecs / 60).toFixed(1)}m` : `~${estTotalSecs}s`;
856
- console.log(chalk.gray(`Estimated completion time: ${estTimeText} (Free Tier Max ${this.maxSteps} steps)`));
859
+ if (Number.isFinite(this.maxSteps)) {
860
+ console.log(chalk.gray(`⚡ Execution loop: User-specified limit of ${this.maxSteps} steps active`));
857
861
  }
858
862
  else {
859
863
  console.log(chalk.gray(`⚡ Autonomous execution loop: Unlimited steps active (${this.userTier.toUpperCase()} plan)`));
@@ -861,365 +865,440 @@ When returning tool calls, use standard OpenAI function calling format or JSON t
861
865
  let step = 0;
862
866
  let finalSummary = '';
863
867
  const stepDurations = [];
864
- while (step < this.maxSteps) {
865
- if (this.isCancelled) {
866
- return {
867
- success: false,
868
- summary: `Task cancelled: ${this.cancelReason || 'User abort'}`,
869
- };
870
- }
871
- step++;
872
- this.currentStep = step;
873
- this.taskStateManager.startStep(step);
874
- const stepStartTime = Date.now();
875
- const stepSpinner = spinner();
876
- if (isPaid && !Number.isFinite(this.maxSteps)) {
877
- stepSpinner.start(chalk.cyan(`Scout is Working (Step ${step})`));
878
- }
879
- else {
880
- const avgStepMs = stepDurations.length > 0
881
- ? stepDurations.reduce((a, b) => a + b, 0) / stepDurations.length
882
- : 12000;
883
- const remainingSteps = (this.maxSteps - step + 1);
884
- const estSecsLeft = Math.max(5, Math.round((remainingSteps * avgStepMs) / 1000));
885
- const estLeftStr = estSecsLeft >= 60
886
- ? `${Math.floor(estSecsLeft / 60)}m ${estSecsLeft % 60}s`
887
- : `${estSecsLeft}s`;
888
- stepSpinner.start(chalk.cyan(`Scout is Working (Step ${step}/${this.maxSteps} • Est. completion: ~${estLeftStr} left)`));
889
- }
890
- try {
891
- let response;
892
- const mcpRouting = getMCPManager().routeTools(userGoal);
893
- const mcpToolDefs = mcpRouting.tools.map((mt) => {
894
- let desc = mt.description;
895
- if (mt.originalName === 'execute_blender_code') {
896
- 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.';
897
- }
898
- else if (mt.originalName === 'generate_3d') {
899
- desc = 'Cloud AI text-to-3d generator (requires external API key). If keys are not set, use execute_blender_code to model directly.';
868
+ const interruptManager = new InterruptManager({
869
+ getStepInfo: () => ({
870
+ step: this.currentStep || 1,
871
+ maxSteps: this.maxSteps,
872
+ goal: this.currentGoal,
873
+ modifiedFilesCount: this.modifiedFiles.size,
874
+ }),
875
+ onPause: () => {
876
+ this.syncTelemetry('paused', `scout: execution paused by user at step ${this.currentStep}`);
877
+ },
878
+ onResume: () => {
879
+ this.syncTelemetry('running', `scout: execution resumed at step ${this.currentStep}`);
880
+ },
881
+ onFeedback: (feedback) => {
882
+ this.historyMessages.push({
883
+ role: 'user',
884
+ 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.`,
885
+ });
886
+ },
887
+ onRevert: () => {
888
+ if (this.backups.length === 0)
889
+ return false;
890
+ for (const b of this.backups) {
891
+ try {
892
+ fs.writeFileSync(b.filePath, b.originalContent, 'utf-8');
900
893
  }
894
+ catch { }
895
+ }
896
+ this.modifiedFiles.clear();
897
+ return true;
898
+ },
899
+ onAbort: (reason) => {
900
+ this.isCancelled = true;
901
+ this.cancelReason = reason;
902
+ },
903
+ });
904
+ interruptManager.attach();
905
+ try {
906
+ while (step < this.maxSteps) {
907
+ if (this.isCancelled) {
901
908
  return {
902
- name: mt.originalName,
903
- description: `[MCP: ${mt.serverName}] ${desc.length > 160 ? desc.slice(0, 157) + '...' : desc}`,
904
- parameters: {
905
- type: 'object',
906
- properties: mt.inputSchema.properties || {},
907
- required: mt.inputSchema.required || [],
908
- },
909
- source: 'mcp',
910
- mcpServerId: mt.serverId,
911
- mcpServerName: mt.serverName,
909
+ success: false,
910
+ summary: `Task cancelled: ${this.cancelReason || 'User abort'}`,
912
911
  };
912
+ }
913
+ step++;
914
+ this.currentStep = step;
915
+ this.taskStateManager.startStep(step);
916
+ // Context Compaction check: If history is long, compact middle turns using workspace state (including scratchpad working memory)
917
+ if (this.historyMessages.length > 10) {
918
+ this.historyMessages = this.agentWorkspace.compactHistoryMessages(this.historyMessages, 6);
919
+ }
920
+ const stepStartTime = Date.now();
921
+ renderStepHeader({
922
+ step,
923
+ maxSteps: this.maxSteps,
924
+ startTimeMs: this.startTime,
925
+ tokensConsumed: this.totalTokensConsumed,
926
+ userTier: this.userTier,
913
927
  });
914
- const goalLower = (userGoal || '').toLowerCase();
915
- const needsBrowser = goalLower.includes('browser') || goalLower.includes('website') || goalLower.includes('webpage') || goalLower.includes('http') || goalLower.includes('url') || goalLower.includes('scrape') || goalLower.includes('chrome');
916
- const needsComputer = goalLower.includes('computer') || goalLower.includes('desktop') || goalLower.includes('mouse') || goalLower.includes('coordinate') || goalLower.includes('drag') || goalLower.includes('double click');
917
- let baseTools = this.toolRegistry.getToolsForTier(this.userTier);
918
- if (mcpToolDefs.length > 0 && !needsBrowser && !needsComputer) {
919
- 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']);
920
- baseTools = baseTools.filter((t) => ESSENTIAL_BASE_TOOLS.has(t.name));
928
+ const stepSpinner = spinner();
929
+ if (!Number.isFinite(this.maxSteps)) {
930
+ stepSpinner.start(chalk.cyan(`Scout is Working (Step ${step})`));
921
931
  }
922
- else if (!needsBrowser) {
923
- baseTools = baseTools.filter((t) => !t.name.startsWith('browser_'));
932
+ else {
933
+ stepSpinner.start(chalk.cyan(`Scout is Working (Step ${step}/${this.maxSteps})`));
924
934
  }
925
- const activeLoopTools = [...baseTools, ...mcpToolDefs];
926
935
  try {
927
- response = await callOpenAIWithRetry(async (model) => {
928
- return await openai.chat.completions.create({
929
- model,
930
- messages: sanitizeMessages(this.historyMessages),
931
- tools: activeLoopTools.map((t) => ({ type: 'function', function: t })),
932
- tool_choice: 'auto',
933
- temperature: 0.1,
934
- presence_penalty: 0.1,
935
- frequency_penalty: 0.1,
936
- });
937
- });
938
- }
939
- catch (err) {
940
- const errStr = String(err?.message || err?.error || err || '').toLowerCase();
941
- if (errStr.includes('tool') || errStr.includes('400') || errStr.includes('not supported') || errStr.includes('reasoning')) {
942
- // Model doesn't support native function calling inject tool-call formatting hint
943
- // so extractJsonToolCall can parse the response as a structured tool invocation
944
- const availableToolNames = activeLoopTools.map((t) => t.name).join(', ');
945
- const toolHintMsg = {
946
- role: 'user',
947
- content: `IMPORTANT: This model does not support native function/tool calling. You MUST format your tool invocations as a JSON code block in your response like this:
948
- \`\`\`json
949
- { "tool": "tool_name", "args": { ... } }
950
- \`\`\`
951
- Available tools: ${availableToolNames}
952
- You MUST output exactly ONE JSON code block per tool call. Do NOT describe what you would do in plain text — output the JSON tool call directly!`,
936
+ let response;
937
+ const mcpRouting = getMCPManager().routeTools(userGoal);
938
+ const goalLower = (userGoal || '').toLowerCase();
939
+ const needsBrowser = goalLower.includes('browser') || goalLower.includes('website') || goalLower.includes('webpage') || goalLower.includes('http') || goalLower.includes('url') || goalLower.includes('scrape') || goalLower.includes('chrome');
940
+ const needsComputer = goalLower.includes('computer') || goalLower.includes('desktop') || goalLower.includes('mouse') || goalLower.includes('coordinate') || goalLower.includes('drag') || goalLower.includes('double click');
941
+ let baseTools = this.toolRegistry.getToolsForTier(this.userTier);
942
+ if (mcpRouting.tools.length > 0 && !needsBrowser && !needsComputer) {
943
+ 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']);
944
+ baseTools = baseTools.filter((t) => ESSENTIAL_BASE_TOOLS.has(t.name));
945
+ }
946
+ else if (!needsBrowser) {
947
+ baseTools = baseTools.filter((t) => !t.name.startsWith('browser_'));
948
+ }
949
+ const baseToolNames = new Set(baseTools.map((t) => t.name));
950
+ const mcpNameCounts = new Map();
951
+ for (const mt of mcpRouting.tools) {
952
+ mcpNameCounts.set(mt.originalName, (mcpNameCounts.get(mt.originalName) || 0) + 1);
953
+ }
954
+ const mcpToolDefs = mcpRouting.tools.map((mt) => {
955
+ let desc = mt.description;
956
+ if (mt.originalName === 'execute_blender_code') {
957
+ 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.';
958
+ }
959
+ else if (mt.originalName === 'generate_3d') {
960
+ desc = 'Cloud AI text-to-3d generator (requires external API key). If keys are not set, use execute_blender_code to model directly.';
961
+ }
962
+ // Disambiguate if tool name collides with a base tool or another MCP tool
963
+ const hasCollision = (mcpNameCounts.get(mt.originalName) || 0) > 1 || baseToolNames.has(mt.originalName);
964
+ const exposedName = hasCollision ? mt.qualifiedName : mt.originalName;
965
+ // Ensure required keys strictly match properties for valid OpenAI function calling schema
966
+ const props = (mt.inputSchema.properties || {});
967
+ const propKeys = new Set(Object.keys(props));
968
+ const cleanRequired = (mt.inputSchema.required || []).filter((r) => propKeys.has(r));
969
+ return {
970
+ name: exposedName,
971
+ description: `[MCP: ${mt.serverName}] ${desc.length > 160 ? desc.slice(0, 157) + '...' : desc}`,
972
+ parameters: {
973
+ type: 'object',
974
+ properties: props,
975
+ required: cleanRequired,
976
+ },
977
+ source: 'mcp',
978
+ mcpServerId: mt.serverId,
979
+ mcpServerName: mt.serverName,
953
980
  };
954
- const fallbackMessages = [...this.historyMessages, toolHintMsg];
981
+ });
982
+ const activeLoopTools = [...baseTools, ...mcpToolDefs];
983
+ try {
955
984
  response = await callOpenAIWithRetry(async (model) => {
956
985
  return await openai.chat.completions.create({
957
986
  model,
958
- messages: sanitizeMessages(fallbackMessages),
987
+ messages: sanitizeMessages(this.historyMessages),
988
+ tools: activeLoopTools.map((t) => ({ type: 'function', function: t })),
989
+ tool_choice: 'auto',
959
990
  temperature: 0.1,
960
991
  presence_penalty: 0.1,
961
992
  frequency_penalty: 0.1,
962
993
  });
963
994
  });
964
995
  }
965
- else {
966
- throw err;
967
- }
968
- }
969
- const choice = response.choices[0];
970
- if (!choice) {
971
- stepSpinner.stop(chalk.yellow('No response from Scout. Retrying step...'));
972
- continue;
973
- }
974
- const msg = sanitizeMessage(choice.message);
975
- const tokensThisTurn = response?.usage?.total_tokens || 0;
976
- this.totalTokensConsumed += tokensThisTurn;
977
- this.syncTelemetry('running', `scout: [step ${step}] generated reasoning (${tokensThisTurn} tokens)`);
978
- this.historyMessages.push(msg);
979
- // Render assistant's thought reasoning text if provided on this turn
980
- const textContent = msg.content || '';
981
- if (textContent.trim()) {
982
- safeNote(renderMarkdown(textContent), `Scout Thought (Step ${step})`);
983
- if (this.isAudioMode) {
984
- const speechText = cleanTextForSpeech(textContent);
985
- if (speechText) {
986
- speakText(speechText.length > 200 ? speechText.slice(0, 200) + '...' : speechText, { async: true });
996
+ catch (err) {
997
+ const errStr = String(err?.message || err?.error || err || '').toLowerCase();
998
+ if (errStr.includes('tool') || errStr.includes('400') || errStr.includes('not supported') || errStr.includes('reasoning')) {
999
+ // Model doesn't support native function calling inject tool-call formatting hint
1000
+ // so extractJsonToolCall can parse the response as a structured tool invocation
1001
+ const availableToolNames = activeLoopTools.map((t) => t.name).join(', ');
1002
+ const toolHintMsg = {
1003
+ role: 'user',
1004
+ content: `IMPORTANT: This model does not support native function/tool calling. You MUST format your tool invocations as a JSON code block in your response like this:
1005
+ \`\`\`json
1006
+ { "tool": "tool_name", "args": { ... } }
1007
+ \`\`\`
1008
+ Available tools: ${availableToolNames}
1009
+ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what you would do in plain text — output the JSON tool call directly!`,
1010
+ };
1011
+ const fallbackMessages = [...this.historyMessages, toolHintMsg];
1012
+ response = await callOpenAIWithRetry(async (model) => {
1013
+ return await openai.chat.completions.create({
1014
+ model,
1015
+ messages: sanitizeMessages(fallbackMessages),
1016
+ temperature: 0.1,
1017
+ presence_penalty: 0.1,
1018
+ frequency_penalty: 0.1,
1019
+ });
1020
+ });
1021
+ }
1022
+ else {
1023
+ throw err;
987
1024
  }
988
1025
  }
989
- }
990
- // Check native tool calls
991
- if (msg.tool_calls && msg.tool_calls.length > 0) {
992
- stepSpinner.stop(chalk.green(`Step ${step}: Scout issued ${msg.tool_calls.length} tool call(s).`));
993
- for (const tc of msg.tool_calls) {
994
- if (tc.type === 'function' && tc.function) {
995
- const fnName = tc.function.name;
996
- let args = {};
997
- try {
998
- args = JSON.parse(tc.function.arguments || '{}');
999
- }
1000
- catch { }
1001
- if (this.isAudioMode && fnName !== 'task_completed') {
1002
- let actionPhrase = '';
1003
- if (fnName === 'run_command')
1004
- actionPhrase = `Running command ${args.command ? args.command.slice(0, 40) : ''}`;
1005
- else if (fnName === 'read_file')
1006
- actionPhrase = `Reading ${path.basename(args.filePath || '')}`;
1007
- else if (fnName === 'write_file')
1008
- actionPhrase = `Creating ${path.basename(args.filePath || '')}`;
1009
- else if (fnName === 'edit_file')
1010
- actionPhrase = `Editing ${path.basename(args.filePath || '')}`;
1011
- else if (fnName.startsWith('mcp_') || fnName.includes('github'))
1012
- actionPhrase = `Querying ${fnName}`;
1013
- if (actionPhrase)
1014
- speakText(actionPhrase, { async: true });
1015
- }
1016
- const toolResult = await this.dispatchToolCall(fnName, args);
1017
- this.totalToolCalls++;
1018
- this.syncTelemetry('running', `scout: [step ${step}] executed tool ${fnName}`);
1019
- const toolResStr = String(toolResult.result || '');
1020
- let cappedResult = toolResStr;
1021
- if (toolResStr.length > 800) {
1026
+ const choice = response.choices[0];
1027
+ if (!choice) {
1028
+ stepSpinner.stop(chalk.yellow('No response from Scout. Retrying step...'));
1029
+ continue;
1030
+ }
1031
+ const msg = sanitizeMessage(choice.message);
1032
+ const tokensThisTurn = response?.usage?.total_tokens || 0;
1033
+ this.totalTokensConsumed += tokensThisTurn;
1034
+ this.syncTelemetry('running', `scout: [step ${step}] generated reasoning (${tokensThisTurn} tokens)`);
1035
+ this.historyMessages.push(msg);
1036
+ // Render assistant's thought reasoning text if provided on this turn
1037
+ const textContent = msg.content || '';
1038
+ if (textContent.trim()) {
1039
+ renderThoughtBox(textContent, step);
1040
+ }
1041
+ // Check native tool calls
1042
+ if (msg.tool_calls && msg.tool_calls.length > 0) {
1043
+ stepSpinner.stop(chalk.green(`Step ${step}: Scout issued ${msg.tool_calls.length} tool call(s).`));
1044
+ for (const tc of msg.tool_calls) {
1045
+ if (tc.type === 'function' && tc.function) {
1046
+ const fnName = tc.function.name;
1047
+ let args = {};
1022
1048
  try {
1023
- const origBytes = Buffer.byteLength(toolResStr, 'utf-8');
1024
- const cdp = compress(Buffer.from(toolResStr, 'utf-8'), LEVEL_FAST);
1025
- const ratio = (origBytes / Math.max(1, cdp.length)).toFixed(1);
1026
- cappedResult = toolResStr.slice(0, 800) + `\n... [Codrop: ${origBytes}B compressed to ${cdp.length}B (${ratio}x ratio) for LLM context]`;
1027
- this.syncTelemetry('running', `scout: [codrop] compressed ${fnName} output (${ratio}x ratio)`);
1049
+ args = JSON.parse(tc.function.arguments || '{}');
1028
1050
  }
1029
- catch {
1030
- cappedResult = toolResStr.slice(0, 800) + '\n... [output truncated for token efficiency]';
1031
- }
1032
- }
1033
- this.historyMessages.push({
1034
- role: 'user',
1035
- tool_call_id: tc.id,
1036
- content: `Tool Execution Result (${fnName}):\n${cappedResult}`,
1037
- });
1038
- this.handleToolConsecutiveTracking(fnName, args, step);
1039
- // Automatic immediate completion for simple app actions (open/close/switch window)
1040
- if (simpleAppCheck.isSimple && (fnName === 'computer_open_app' || fnName === 'computer_close_app' || fnName === 'computer_switch_window')) {
1041
- let callSucceeded = false;
1042
- try {
1043
- const parsed = JSON.parse(toolResult.result);
1044
- callSucceeded = parsed.success !== false;
1051
+ catch { }
1052
+ const toolStartTime = Date.now();
1053
+ const toolResult = await this.dispatchToolCall(fnName, args);
1054
+ const durationMs = Date.now() - toolStartTime;
1055
+ renderToolResult({
1056
+ name: fnName,
1057
+ args,
1058
+ result: toolResult.result,
1059
+ durationMs,
1060
+ success: !String(toolResult.result).startsWith('[PLAN RESTRICTION') && !String(toolResult.result).startsWith('[ACTION BLOCKED'),
1061
+ });
1062
+ this.totalToolCalls++;
1063
+ this.syncTelemetry('running', `scout: [step ${step}] executed tool ${fnName}`);
1064
+ const toolResStr = String(toolResult.result || '');
1065
+ let cappedResult = toolResStr;
1066
+ if (toolResStr.length > 800) {
1067
+ try {
1068
+ const origBytes = Buffer.byteLength(toolResStr, 'utf-8');
1069
+ const cdp = compress(Buffer.from(toolResStr, 'utf-8'), LEVEL_FAST);
1070
+ const ratio = (origBytes / Math.max(1, cdp.length)).toFixed(1);
1071
+ cappedResult = toolResStr.slice(0, 800) + `\n... [Codrop: ${origBytes}B compressed to ${cdp.length}B (${ratio}x ratio) for LLM context]`;
1072
+ this.syncTelemetry('running', `scout: [codrop] compressed ${fnName} output (${ratio}x ratio)`);
1073
+ }
1074
+ catch {
1075
+ cappedResult = toolResStr.slice(0, 800) + '\n... [output truncated for token efficiency]';
1076
+ }
1045
1077
  }
1046
- catch {
1047
- callSucceeded = !toolResult.result.toLowerCase().includes('failed') && !toolResult.result.toLowerCase().includes('error');
1078
+ this.historyMessages.push({
1079
+ role: 'user',
1080
+ tool_call_id: tc.id,
1081
+ content: `Tool Execution Result (${fnName}):\n${cappedResult}`,
1082
+ });
1083
+ this.handleToolConsecutiveTracking(fnName, args, step);
1084
+ // Automatic immediate completion for simple app actions (open/close/switch window)
1085
+ if (simpleAppCheck.isSimple && (fnName === 'computer_open_app' || fnName === 'computer_close_app' || fnName === 'computer_switch_window')) {
1086
+ let callSucceeded = false;
1087
+ try {
1088
+ const parsed = JSON.parse(toolResult.result);
1089
+ callSucceeded = parsed.success !== false;
1090
+ }
1091
+ catch {
1092
+ callSucceeded = !toolResult.result.toLowerCase().includes('failed') && !toolResult.result.toLowerCase().includes('error');
1093
+ }
1094
+ if (callSucceeded) {
1095
+ const appName = simpleAppCheck.appName || 'application';
1096
+ const actionVerb = simpleAppCheck.action === 'close' ? 'closed' : (simpleAppCheck.action === 'switch' ? 'focused' : 'launched');
1097
+ finalSummary = `I've ${actionVerb} ${appName} for you. It's ready on your screen!`;
1098
+ renderTaskCompletedCard({
1099
+ objective: userGoal,
1100
+ summary: finalSummary,
1101
+ modifiedFiles: [],
1102
+ steps: step,
1103
+ maxSteps: this.maxSteps,
1104
+ totalTokens: this.totalTokensConsumed,
1105
+ totalToolCalls: this.totalToolCalls,
1106
+ elapsedSecs: Math.round((Date.now() - this.startTime) / 1000),
1107
+ userTier: this.userTier,
1108
+ });
1109
+ saveAgentSession({
1110
+ goal: userGoal,
1111
+ summary: finalSummary,
1112
+ modifiedFiles: [],
1113
+ });
1114
+ this.syncTelemetry('idle', `scout: completed task successfully (${this.modifiedFiles.size} files modified)`);
1115
+ return { success: true, summary: finalSummary };
1116
+ }
1048
1117
  }
1049
- if (callSucceeded) {
1050
- const appName = simpleAppCheck.appName || 'application';
1051
- const actionVerb = simpleAppCheck.action === 'close' ? 'closed' : (simpleAppCheck.action === 'switch' ? 'focused' : 'launched');
1052
- finalSummary = `I've ${actionVerb} ${appName} for you. It's ready on your screen!`;
1053
- safeNote(chalk.green(` ${finalSummary}`), 'Task Completed');
1118
+ if (fnName === 'task_completed') {
1119
+ finalSummary = args.summary || toolResult.result;
1120
+ if (this.modifiedFiles.size > 0) {
1121
+ const filesList = getDirectoryFiles(this.cwd);
1122
+ const healRes = await verifyAndSelfHealFiles(Array.from(this.modifiedFiles), this.cwd, path.basename(this.cwd), filesList, { maxRetries: 3 });
1123
+ if (healRes.verifiedFiles.length > 0) {
1124
+ safeNote(chalk.green(` Self-Healing Verification Confirmed: ${healRes.verifiedFiles.length} file(s) syntax & build clean!`), ' Code Verification Clean');
1125
+ }
1126
+ if (healRes.remainingErrors.length > 0) {
1127
+ safeNote(chalk.yellow(`️ Remaining verification issues:\n${healRes.remainingErrors.join('\n')}`), '️ Verification Warning');
1128
+ }
1129
+ }
1130
+ renderTaskCompletedCard({
1131
+ objective: userGoal,
1132
+ summary: finalSummary,
1133
+ modifiedFiles: Array.from(this.modifiedFiles),
1134
+ steps: step,
1135
+ maxSteps: this.maxSteps,
1136
+ totalTokens: this.totalTokensConsumed,
1137
+ totalToolCalls: this.totalToolCalls,
1138
+ elapsedSecs: Math.round((Date.now() - this.startTime) / 1000),
1139
+ userTier: this.userTier,
1140
+ });
1054
1141
  saveAgentSession({
1055
1142
  goal: userGoal,
1056
1143
  summary: finalSummary,
1057
- modifiedFiles: [],
1144
+ modifiedFiles: Array.from(this.modifiedFiles),
1058
1145
  });
1059
- this.syncTelemetry('idle', `scout: completed task successfully (${this.modifiedFiles.size} files modified)`);
1060
1146
  return { success: true, summary: finalSummary };
1061
1147
  }
1062
1148
  }
1063
- if (fnName === 'task_completed') {
1064
- finalSummary = args.summary || toolResult.result;
1065
- if (this.modifiedFiles.size > 0) {
1066
- const filesList = getDirectoryFiles(this.cwd);
1067
- const healRes = await verifyAndSelfHealFiles(Array.from(this.modifiedFiles), this.cwd, path.basename(this.cwd), filesList, { maxRetries: 3 });
1068
- if (healRes.verifiedFiles.length > 0) {
1069
- safeNote(chalk.green(` Self-Healing Verification Confirmed: ${healRes.verifiedFiles.length} file(s) syntax & build clean!`), ' Code Verification Clean');
1070
- }
1071
- if (healRes.remainingErrors.length > 0) {
1072
- safeNote(chalk.yellow(`️ Remaining verification issues:\n${healRes.remainingErrors.join('\n')}`), '️ Verification Warning');
1073
- }
1074
- }
1149
+ }
1150
+ continue;
1151
+ }
1152
+ // Check text response or fallback JSON tool call
1153
+ stepSpinner.stop(chalk.blue(`Step ${step} thinking complete.`));
1154
+ const parsedJsonTool = this.extractJsonToolCall(textContent);
1155
+ if (parsedJsonTool) {
1156
+ const toolStartTime = Date.now();
1157
+ const toolResult = await this.dispatchToolCall(parsedJsonTool.tool, parsedJsonTool.args);
1158
+ const durationMs = Date.now() - toolStartTime;
1159
+ renderToolResult({
1160
+ name: parsedJsonTool.tool,
1161
+ args: parsedJsonTool.args,
1162
+ result: toolResult.result,
1163
+ durationMs,
1164
+ success: !String(toolResult.result).startsWith('[PLAN RESTRICTION') && !String(toolResult.result).startsWith('[ACTION BLOCKED'),
1165
+ });
1166
+ const jsonResStr = String(toolResult.result || '');
1167
+ let cappedJsonResult = jsonResStr;
1168
+ if (jsonResStr.length > 800) {
1169
+ try {
1170
+ const origBytes = Buffer.byteLength(jsonResStr, 'utf-8');
1171
+ const cdp = compress(Buffer.from(jsonResStr, 'utf-8'), LEVEL_FAST);
1172
+ const ratio = (origBytes / Math.max(1, cdp.length)).toFixed(1);
1173
+ cappedJsonResult = jsonResStr.slice(0, 800) + `\n... [Codrop: ${origBytes}B compressed to ${cdp.length}B (${ratio}x ratio) for LLM context]`;
1174
+ }
1175
+ catch {
1176
+ cappedJsonResult = jsonResStr.slice(0, 800) + '\n... [output truncated for token efficiency]';
1177
+ }
1178
+ }
1179
+ this.historyMessages.push({
1180
+ role: 'user',
1181
+ content: `Tool Execution Result (${parsedJsonTool.tool}):\n${cappedJsonResult}`,
1182
+ });
1183
+ this.handleToolConsecutiveTracking(parsedJsonTool.tool, parsedJsonTool.args, step);
1184
+ // Automatic immediate completion for simple app actions (open/close/switch window)
1185
+ if (simpleAppCheck.isSimple && (parsedJsonTool.tool === 'computer_open_app' || parsedJsonTool.tool === 'computer_close_app' || parsedJsonTool.tool === 'computer_switch_window')) {
1186
+ let callSucceeded = false;
1187
+ try {
1188
+ const parsed = JSON.parse(toolResult.result);
1189
+ callSucceeded = parsed.success !== false;
1190
+ }
1191
+ catch {
1192
+ callSucceeded = !toolResult.result.toLowerCase().includes('failed') && !toolResult.result.toLowerCase().includes('error');
1193
+ }
1194
+ if (callSucceeded) {
1195
+ const appName = simpleAppCheck.appName || 'application';
1196
+ const actionVerb = simpleAppCheck.action === 'close' ? 'closed' : (simpleAppCheck.action === 'switch' ? 'focused' : 'launched');
1197
+ finalSummary = `I've ${actionVerb} ${appName} for you. It's ready on your screen!`;
1198
+ safeNote(chalk.green(` ${finalSummary}`), 'Task Completed');
1075
1199
  saveAgentSession({
1076
1200
  goal: userGoal,
1077
1201
  summary: finalSummary,
1078
- modifiedFiles: Array.from(this.modifiedFiles),
1202
+ modifiedFiles: [],
1079
1203
  });
1080
1204
  return { success: true, summary: finalSummary };
1081
1205
  }
1082
1206
  }
1083
- }
1084
- continue;
1085
- }
1086
- // Check text response or fallback JSON tool call
1087
- stepSpinner.stop(chalk.blue(`Step ${step} thinking complete.`));
1088
- const parsedJsonTool = this.extractJsonToolCall(textContent);
1089
- if (parsedJsonTool) {
1090
- const toolResult = await this.dispatchToolCall(parsedJsonTool.tool, parsedJsonTool.args);
1091
- const jsonResStr = String(toolResult.result || '');
1092
- let cappedJsonResult = jsonResStr;
1093
- if (jsonResStr.length > 800) {
1094
- try {
1095
- const origBytes = Buffer.byteLength(jsonResStr, 'utf-8');
1096
- const cdp = compress(Buffer.from(jsonResStr, 'utf-8'), LEVEL_FAST);
1097
- const ratio = (origBytes / Math.max(1, cdp.length)).toFixed(1);
1098
- cappedJsonResult = jsonResStr.slice(0, 800) + `\n... [Codrop: ${origBytes}B compressed to ${cdp.length}B (${ratio}x ratio) for LLM context]`;
1099
- }
1100
- catch {
1101
- cappedJsonResult = jsonResStr.slice(0, 800) + '\n... [output truncated for token efficiency]';
1102
- }
1103
- }
1104
- this.historyMessages.push({
1105
- role: 'user',
1106
- content: `Tool Execution Result (${parsedJsonTool.tool}):\n${cappedJsonResult}`,
1107
- });
1108
- this.handleToolConsecutiveTracking(parsedJsonTool.tool, parsedJsonTool.args, step);
1109
- // Automatic immediate completion for simple app actions (open/close/switch window)
1110
- if (simpleAppCheck.isSimple && (parsedJsonTool.tool === 'computer_open_app' || parsedJsonTool.tool === 'computer_close_app' || parsedJsonTool.tool === 'computer_switch_window')) {
1111
- let callSucceeded = false;
1112
- try {
1113
- const parsed = JSON.parse(toolResult.result);
1114
- callSucceeded = parsed.success !== false;
1115
- }
1116
- catch {
1117
- callSucceeded = !toolResult.result.toLowerCase().includes('failed') && !toolResult.result.toLowerCase().includes('error');
1118
- }
1119
- if (callSucceeded) {
1120
- const appName = simpleAppCheck.appName || 'application';
1121
- const actionVerb = simpleAppCheck.action === 'close' ? 'closed' : (simpleAppCheck.action === 'switch' ? 'focused' : 'launched');
1122
- finalSummary = `I've ${actionVerb} ${appName} for you. It's ready on your screen!`;
1123
- safeNote(chalk.green(` ${finalSummary}`), 'Task Completed');
1207
+ if (parsedJsonTool.tool === 'task_completed') {
1208
+ finalSummary = parsedJsonTool.args?.summary || toolResult.result;
1124
1209
  saveAgentSession({
1125
1210
  goal: userGoal,
1126
1211
  summary: finalSummary,
1127
- modifiedFiles: [],
1212
+ modifiedFiles: Array.from(this.modifiedFiles),
1128
1213
  });
1129
1214
  return { success: true, summary: finalSummary };
1130
1215
  }
1216
+ continue;
1131
1217
  }
1132
- if (parsedJsonTool.tool === 'task_completed') {
1133
- finalSummary = parsedJsonTool.args?.summary || toolResult.result;
1134
- saveAgentSession({
1135
- goal: userGoal,
1136
- summary: finalSummary,
1137
- modifiedFiles: Array.from(this.modifiedFiles),
1138
- });
1139
- return { success: true, summary: finalSummary };
1218
+ if (textContent.trim()) {
1219
+ let cleanedThought = textContent
1220
+ .replace(/[\u0600-\u06FF\u0750-\u077F\uAC00-\uD7AF\u3040-\u30FF\u4E00-\u9FFF\u0D80-\u0DFF]+/g, '')
1221
+ .trim();
1222
+ if (!cleanedThought || cleanedThought.length < 5) {
1223
+ cleanedThought = 'Analyzing codebase files and executing next tool operation...';
1224
+ }
1225
+ safeNote(renderMarkdown(cleanedThought), ` Scout Agent Thought (Step ${step})`);
1226
+ const lowerText = textContent.toLowerCase().trim();
1227
+ const isExplicitCompletion = lowerText.includes('task is complete') ||
1228
+ lowerText.includes('task complete') ||
1229
+ lowerText.includes('goal completed') ||
1230
+ lowerText.includes('goal is completed') ||
1231
+ lowerText.includes('all tasks completed') ||
1232
+ lowerText.includes('i have completed') ||
1233
+ lowerText.includes('no further changes needed') ||
1234
+ lowerText.includes('the fix is complete') ||
1235
+ lowerText.includes('has been created') ||
1236
+ lowerText.includes('successfully created') ||
1237
+ lowerText.includes('created the file') ||
1238
+ lowerText.includes('file created') ||
1239
+ lowerText.includes('implementation complete') ||
1240
+ lowerText.includes('setup is complete') ||
1241
+ lowerText.includes('setup complete') ||
1242
+ lowerText.includes('instructions have been executed') ||
1243
+ lowerText.includes('work is complete');
1244
+ const isIntermediateThought = /^(?:the\s+user\s+wants|i\s+will|i'll|let\s+me|i\s+need\s+to|i\s+am\s+going\s+to|first|starting|next|looking\s+at|checking|we\s+need\s+to|we\s+will)\b/i.test(lowerText);
1245
+ const hasActionDirective = /\b(execute|run|setup|set\s+up|install|configure|create|make|write|edit|modify|fix|update|refactor|build|delete|remove|patch|implement|apply|download|save|deploy)\b/i.test(userGoal);
1246
+ const isInformationalGoal = !hasActionDirective && (/^(?:lookup|look\s*up|check|find|who|what|why|where|how|tell|show|explain|display|list|search|query|status|info|describe)\b/i.test(userGoal.trim()) ||
1247
+ !/\b(create|make|write|edit|modify|fix|update|refactor|build|delete|remove|patch|implement|execute|run|setup|set\s+up|install)\b/i.test(userGoal.trim()));
1248
+ const isAnsweringInformational = !isIntermediateThought && isInformationalGoal && textContent.trim().length > 20 && !lowerText.includes('error occurred') && !lowerText.includes('cannot complete');
1249
+ const isSummaryAfterModifications = !isIntermediateThought && this.modifiedFiles.size > 0 && !lowerText.includes('?') && textContent.trim().length > 30;
1250
+ if (isExplicitCompletion || isAnsweringInformational || isSummaryAfterModifications) {
1251
+ saveAgentSession({
1252
+ goal: userGoal,
1253
+ summary: textContent,
1254
+ modifiedFiles: Array.from(this.modifiedFiles),
1255
+ });
1256
+ return { success: true, summary: textContent };
1257
+ }
1140
1258
  }
1141
- continue;
1259
+ // If assistant responded with text without calling tools, prompt it to execute tools to complete the goal
1260
+ this.historyMessages.push({
1261
+ role: 'user',
1262
+ content: 'You provided a text response but have not called any tools (write_file, edit_file, run_command, task_completed). Please execute necessary tool calls to complete the user goal, or invoke task_completed if finished.',
1263
+ });
1264
+ stepDurations.push(Date.now() - stepStartTime);
1142
1265
  }
1143
- if (textContent.trim()) {
1144
- let cleanedThought = textContent
1145
- .replace(/[\u0600-\u06FF\u0750-\u077F\uAC00-\uD7AF\u3040-\u30FF\u4E00-\u9FFF\u0D80-\u0DFF]+/g, '')
1146
- .trim();
1147
- if (!cleanedThought || cleanedThought.length < 5) {
1148
- cleanedThought = 'Analyzing codebase files and executing next tool operation...';
1149
- }
1150
- safeNote(renderMarkdown(cleanedThought), ` Scout Agent Thought (Step ${step})`);
1151
- const lowerText = textContent.toLowerCase().trim();
1152
- const isExplicitCompletion = lowerText.includes('task is complete') ||
1153
- lowerText.includes('task complete') ||
1154
- lowerText.includes('goal completed') ||
1155
- lowerText.includes('goal is completed') ||
1156
- lowerText.includes('all tasks completed') ||
1157
- lowerText.includes('i have completed') ||
1158
- lowerText.includes('no further changes needed') ||
1159
- lowerText.includes('the fix is complete') ||
1160
- lowerText.includes('has been created') ||
1161
- lowerText.includes('successfully created') ||
1162
- lowerText.includes('created the file') ||
1163
- lowerText.includes('file created') ||
1164
- lowerText.includes('implementation complete') ||
1165
- lowerText.includes('setup is complete') ||
1166
- lowerText.includes('setup complete') ||
1167
- lowerText.includes('instructions have been executed') ||
1168
- lowerText.includes('work is complete');
1169
- const isIntermediateThought = /^(?:the\s+user\s+wants|i\s+will|i'll|let\s+me|i\s+need\s+to|i\s+am\s+going\s+to|first|starting|next|looking\s+at|checking|we\s+need\s+to|we\s+will)\b/i.test(lowerText);
1170
- const hasActionDirective = /\b(execute|run|setup|set\s+up|install|configure|create|make|write|edit|modify|fix|update|refactor|build|delete|remove|patch|implement|apply|download|save|deploy)\b/i.test(userGoal);
1171
- const isInformationalGoal = !hasActionDirective && (/^(?:lookup|look\s*up|check|find|who|what|why|where|how|tell|show|explain|display|list|search|query|status|info|describe)\b/i.test(userGoal.trim()) ||
1172
- !/\b(create|make|write|edit|modify|fix|update|refactor|build|delete|remove|patch|implement|execute|run|setup|set\s+up|install)\b/i.test(userGoal.trim()));
1173
- const isAnsweringInformational = !isIntermediateThought && isInformationalGoal && textContent.trim().length > 20 && !lowerText.includes('error occurred') && !lowerText.includes('cannot complete');
1174
- const isSummaryAfterModifications = !isIntermediateThought && this.modifiedFiles.size > 0 && !lowerText.includes('?') && textContent.trim().length > 30;
1175
- if (isExplicitCompletion || isAnsweringInformational || isSummaryAfterModifications) {
1176
- saveAgentSession({
1177
- goal: userGoal,
1178
- summary: textContent,
1179
- modifiedFiles: Array.from(this.modifiedFiles),
1180
- });
1181
- return { success: true, summary: textContent };
1266
+ catch (err) {
1267
+ stepDurations.push(Date.now() - stepStartTime);
1268
+ if (isQuotaExceededError(err)) {
1269
+ stepSpinner.stop(chalk.red(`Oops! it\'s not you, it\'s us`));
1270
+ safeNote(`${chalk.bold.red(`Something went wrong in (Step ${step}), please try again in a moment`)}\n\n` +
1271
+ `${chalk.yellow('The configured AI provider has reached its API usage limit or rate cap.')}\n` +
1272
+ `${chalk.dim('This is separate from your Scout credit balance shown by `scout quota`.')}\n\n` +
1273
+ `${chalk.bold.cyan(' Please come back and try again in a few hours (or check back later today).')}\n\n` +
1274
+ `${chalk.dim('Scout Agent session has ended gracefully to protect remaining workflow.')}`, '️ API Quota Limit Reached');
1275
+ return {
1276
+ success: false,
1277
+ summary: 'Something went wrong, please try again in a moment.',
1278
+ };
1182
1279
  }
1280
+ stepSpinner.stop(chalk.red(`Step ${step} execution error: ${err?.message || String(err)}`));
1281
+ this.historyMessages.push({
1282
+ role: 'user',
1283
+ content: `Error in previous turn: ${err?.message || String(err)}. Please try alternative steps or call tools.`,
1284
+ });
1183
1285
  }
1184
- // If assistant responded with text without calling tools, prompt it to execute tools to complete the goal
1185
- this.historyMessages.push({
1186
- role: 'user',
1187
- content: 'You provided a text response but have not called any tools (write_file, edit_file, run_command, task_completed). Please execute necessary tool calls to complete the user goal, or invoke task_completed if finished.',
1188
- });
1189
- stepDurations.push(Date.now() - stepStartTime);
1190
- }
1191
- catch (err) {
1192
- stepDurations.push(Date.now() - stepStartTime);
1193
- if (isQuotaExceededError(err)) {
1194
- stepSpinner.stop(chalk.red(`Oops! it\'s not you, it\'s us`));
1195
- safeNote(`${chalk.bold.red(`Something went wrong in (Step ${step}), please try again in a moment`)}\n\n` +
1196
- `${chalk.yellow('The configured AI provider has reached its API usage limit or rate cap.')}\n` +
1197
- `${chalk.dim('This is separate from your Scout credit balance shown by `scout quota`.')}\n\n` +
1198
- `${chalk.bold.cyan(' Please come back and try again in a few hours (or check back later today).')}\n\n` +
1199
- `${chalk.dim('Scout Agent session has ended gracefully to protect remaining workflow.')}`, '️ API Quota Limit Reached');
1200
- return {
1201
- success: false,
1202
- summary: 'Something went wrong, please try again in a moment.',
1203
- };
1286
+ // Step limit check: Only triggered if user explicitly supplied a finite maxSteps
1287
+ if (Number.isFinite(this.maxSteps) && step >= this.maxSteps) {
1288
+ safeNote(chalk.bold.yellow(`⚡ Iteration limit reached (${this.maxSteps} steps). Task completed or paused.`), ' Step Limit Reached');
1289
+ break;
1204
1290
  }
1205
- stepSpinner.stop(chalk.red(`Step ${step} execution error: ${err?.message || String(err)}`));
1206
- this.historyMessages.push({
1207
- role: 'user',
1208
- content: `Error in previous turn: ${err?.message || String(err)}. Please try alternative steps or call tools.`,
1209
- });
1210
- }
1211
- // Step limit check: Free tier only. Pro and Enterprise have unlimited steps.
1212
- if (!isPaid && step >= this.maxSteps) {
1213
- safeNote(chalk.bold.yellow(`⚡ Free Tier limit reached (${this.maxSteps} steps).\nFree developers can perform basic code editing, creating files/folders, and running commands.\nTo unlock unlimited autonomous multi-step loops and scratchpad reasoning, upgrade to Pro at https://scout.frontterrain.com/plans or run 'scout dashboard'.`), ' Free Tier Step Limit');
1214
- break;
1215
1291
  }
1292
+ return {
1293
+ success: false,
1294
+ summary: Number.isFinite(this.maxSteps)
1295
+ ? `Reached max iteration steps limit (${this.maxSteps}). Modified files: ${Array.from(this.modifiedFiles).join(', ')}`
1296
+ : `Task ended after ${step} iteration steps. Modified files: ${Array.from(this.modifiedFiles).join(', ')}`,
1297
+ };
1298
+ }
1299
+ finally {
1300
+ interruptManager.detach();
1216
1301
  }
1217
- return {
1218
- success: false,
1219
- summary: isPaid
1220
- ? `Task ended after ${step} iteration steps. Modified files: ${Array.from(this.modifiedFiles).join(', ')}`
1221
- : `Reached max iteration steps limit (${this.maxSteps}). Modified files: ${Array.from(this.modifiedFiles).join(', ')}`,
1222
- };
1223
1302
  }
1224
1303
  extractJsonToolCall(content) {
1225
1304
  if (!content)
@@ -1348,10 +1427,8 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1348
1427
  actionDesc = `Scratchpad (${args.action || 'read'})`;
1349
1428
  else if (name === 'task_completed')
1350
1429
  actionDesc = `Task finished`;
1351
- const badge = chalk.bgCyan.black.bold(` 🛠️ TOOL: ${name} `);
1352
- const descText = actionDesc ? chalk.yellow.bold(` → ${actionDesc}`) : '';
1353
- console.log(`\n${badge}${descText} ${chalk.dim(JSON.stringify(args))}`);
1354
- const isPaid = this.mockMode || this.userTier === 'pro' || this.userTier === 'enterprise';
1430
+ renderToolCall({ name, args, step: this.currentStep });
1431
+ const isPaid = this.mockMode || isProOrHigher(this.userTier);
1355
1432
  // 1. Scratchpad Feature Gating (Pro & Enterprise only)
1356
1433
  if (name === 'scratchpad') {
1357
1434
  if (!isPaid) {
@@ -1362,41 +1439,25 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1362
1439
  }
1363
1440
  const action = String(args.action || 'read').toLowerCase().trim();
1364
1441
  const content = String(args.content || '');
1365
- const ftDir = path.join(this.cwd, '.ft');
1366
- const scratchPath = path.join(ftDir, 'scratchpad.md');
1367
- fs.mkdirSync(ftDir, { recursive: true });
1368
- let currentScratch = '';
1369
- if (fs.existsSync(scratchPath)) {
1370
- try {
1371
- currentScratch = fs.readFileSync(scratchPath, 'utf-8');
1372
- }
1373
- catch { }
1374
- }
1375
1442
  if (action === 'write') {
1376
- fs.writeFileSync(scratchPath, content, 'utf-8');
1377
- try {
1378
- fs.writeFileSync(path.join(ftDir, 'scratchpad.cdp'), compress(Buffer.from(content, 'utf-8'), LEVEL_FAST));
1379
- }
1380
- catch { }
1443
+ this.agentWorkspace.setScratchpad(content);
1381
1444
  this.taskStateManager.addObservation(name, `Scratchpad updated (${content.length} chars, Codrop .cdp archived)`, true);
1382
1445
  return { result: `Scratchpad updated successfully:\n${content}` };
1383
1446
  }
1384
1447
  else if (action === 'append') {
1448
+ const currentScratch = this.agentWorkspace.getScratchpad();
1385
1449
  const updated = currentScratch ? `${currentScratch}\n\n---\n<!-- ${new Date().toISOString()} -->\n${content}` : content;
1386
- fs.writeFileSync(scratchPath, updated, 'utf-8');
1387
- try {
1388
- fs.writeFileSync(path.join(ftDir, 'scratchpad.cdp'), compress(Buffer.from(updated, 'utf-8'), LEVEL_FAST));
1389
- }
1390
- catch { }
1450
+ this.agentWorkspace.setScratchpad(updated);
1391
1451
  this.taskStateManager.addObservation(name, `Appended to scratchpad (${content.length} chars, Codrop .cdp archived)`, true);
1392
1452
  return { result: `Appended to scratchpad. Current contents:\n${updated}` };
1393
1453
  }
1394
1454
  else if (action === 'clear') {
1395
- fs.writeFileSync(scratchPath, '', 'utf-8');
1455
+ this.agentWorkspace.clearScratchpad();
1396
1456
  this.taskStateManager.addObservation(name, `Cleared scratchpad`, true);
1397
1457
  return { result: `Scratchpad cleared.` };
1398
1458
  }
1399
1459
  else {
1460
+ const currentScratch = this.agentWorkspace.getScratchpad();
1400
1461
  this.taskStateManager.addObservation(name, `Read scratchpad (${currentScratch.length} chars)`, true);
1401
1462
  return { result: currentScratch ? `Scratchpad Contents:\n${currentScratch}` : `Scratchpad is currently empty.` };
1402
1463
  }
@@ -1522,6 +1583,9 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1522
1583
  else if (action === 'diagnostic') {
1523
1584
  name = 'computer_diagnostic';
1524
1585
  }
1586
+ else if (action === 'wait') {
1587
+ name = 'computer_wait';
1588
+ }
1525
1589
  }
1526
1590
  // Tier Gating Enforcement
1527
1591
  if (!isPaid) {
@@ -1926,11 +1990,7 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1926
1990
  }
1927
1991
  case 'speak_text': {
1928
1992
  const phrase = String(args.text || args.phrase || '').trim();
1929
- if (phrase) {
1930
- await speakText(phrase, { async: true });
1931
- return { result: `Spoke text out loud: "${phrase}"` };
1932
- }
1933
- return { result: 'No text provided to speak.' };
1993
+ return { result: `[TTS DISABLED]: Text-to-speech audio synthesis has been disabled. Text displayed: "${phrase}"` };
1934
1994
  }
1935
1995
  case 'browser_navigate': {
1936
1996
  const targetUrl = String(args.url || '').trim();
@@ -2002,35 +2062,6 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2002
2062
  this.taskStateManager.addObservation('browser_scroll', res.output, res.success);
2003
2063
  return { result: res.output };
2004
2064
  }
2005
- case 'scratchpad': {
2006
- const action = String(args.action || 'read').toLowerCase().trim();
2007
- const scratchpadPath = path.resolve(this.cwd, '.ft', 'scratchpad.md');
2008
- fs.mkdirSync(path.dirname(scratchpadPath), { recursive: true });
2009
- if (action === 'read') {
2010
- const content = fs.existsSync(scratchpadPath) ? fs.readFileSync(scratchpadPath, 'utf-8') : '(Scratchpad is empty)';
2011
- this.taskStateManager.addObservation('scratchpad', 'Read scratchpad content', true);
2012
- return { result: `Scratchpad Content:\n${content || '(empty)'}` };
2013
- }
2014
- else if (action === 'write') {
2015
- const newContent = String(args.content || '');
2016
- fs.writeFileSync(scratchpadPath, newContent, 'utf-8');
2017
- this.taskStateManager.addObservation('scratchpad', `Wrote scratchpad (${newContent.length} chars)`, true);
2018
- return { result: `Scratchpad updated (${newContent.length} chars).` };
2019
- }
2020
- else if (action === 'append') {
2021
- const appendContent = String(args.content || '');
2022
- fs.appendFileSync(scratchpadPath, `\n${appendContent}`, 'utf-8');
2023
- this.taskStateManager.addObservation('scratchpad', `Appended to scratchpad (${appendContent.length} chars)`, true);
2024
- return { result: `Appended to scratchpad (${appendContent.length} chars).` };
2025
- }
2026
- else if (action === 'clear') {
2027
- if (fs.existsSync(scratchpadPath))
2028
- fs.unlinkSync(scratchpadPath);
2029
- this.taskStateManager.addObservation('scratchpad', 'Cleared scratchpad', true);
2030
- return { result: 'Scratchpad cleared.' };
2031
- }
2032
- return { result: `Unknown scratchpad action: "${action}". Supported: read, write, append, clear.` };
2033
- }
2034
2065
  case 'computer_screenshot': {
2035
2066
  const res = await this.computerController.screenshot();
2036
2067
  if (res.path) {
@@ -2293,6 +2324,15 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2293
2324
  };
2294
2325
  return { result: JSON.stringify(structuredRes, null, 2) };
2295
2326
  }
2327
+ case 'computer': {
2328
+ return {
2329
+ result: JSON.stringify({
2330
+ success: false,
2331
+ error: 'InvalidComputerAction',
2332
+ 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.`
2333
+ }, null, 2)
2334
+ };
2335
+ }
2296
2336
  case 'delegate_subtask': {
2297
2337
  const role = (args.role || 'general');
2298
2338
  const task = String(args.task || '').trim();
@@ -2344,13 +2384,18 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
2344
2384
  if (mcpTarget) {
2345
2385
  const mcpRes = await mcpManager.executeTool(name, args);
2346
2386
  const isSuccess = mcpRes.status === 'success';
2387
+ const resObj = (typeof mcpRes.result === 'object' && mcpRes.result !== null)
2388
+ ? mcpRes.result
2389
+ : null;
2347
2390
  const outputStr = typeof mcpRes.result === 'string'
2348
2391
  ? mcpRes.result
2349
- : (mcpRes.result?.text ? String(mcpRes.result.text) : JSON.stringify(mcpRes.result ?? { status: mcpRes.status, error: mcpRes.error }));
2392
+ : (resObj && 'text' in resObj && typeof resObj.text === 'string'
2393
+ ? resObj.text
2394
+ : JSON.stringify(mcpRes.result ?? { status: mcpRes.status, error: mcpRes.error }));
2350
2395
  this.taskStateManager.addObservation(name, mcpRes.outputSummary || outputStr, isSuccess);
2351
2396
  // Check if MCP result generated or referenced local files/artifacts
2352
- if (isSuccess && typeof mcpRes.result === 'object' && mcpRes.result !== null) {
2353
- const possiblePath = mcpRes.result.path || mcpRes.result.filePath || mcpRes.result.file || args.destPath || args.path || args.outputPath;
2397
+ if (isSuccess && resObj) {
2398
+ const possiblePath = resObj.path || resObj.filePath || resObj.file || args.destPath || args.path || args.outputPath;
2354
2399
  if (typeof possiblePath === 'string' && fs.existsSync(path.resolve(this.cwd, possiblePath))) {
2355
2400
  this.modifiedFiles.add(path.relative(this.cwd, path.resolve(this.cwd, possiblePath)).replace(/\\/g, '/'));
2356
2401
  }