ft-scout 9.5.6 → 9.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,12 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+ import dotenv from 'dotenv';
1
5
  import {} from './types.js';
6
+ const __filename = fileURLToPath(import.meta.url);
7
+ const __dirname = path.dirname(__filename);
8
+ dotenv.config({ path: path.resolve(__dirname, '../../../../.env'), quiet: true });
9
+ dotenv.config({ quiet: true });
2
10
  export class HarpReasoningProvider {
3
11
  providerName = 'harp';
4
12
  defaultModel = 'harp-1b-instruct';
@@ -27,6 +35,46 @@ export class HarpReasoningProvider {
27
35
  finishReason: (rawRes.toolCalls && rawRes.toolCalls.length > 0) ? 'tool_calls' : 'stop',
28
36
  };
29
37
  }
38
+ // Live FrontTerrain HARP Neural Inference API (when available and not in synthetic tool-matching mode)
39
+ const endpointUrl = process.env.HARP_API_URL;
40
+ if (endpointUrl && (!request.tools || request.tools.length === 0)) {
41
+ try {
42
+ const response = await fetch(endpointUrl, {
43
+ method: 'POST',
44
+ headers: { 'Content-Type': 'application/json' },
45
+ body: JSON.stringify({
46
+ model: activeModel,
47
+ messages: request.messages,
48
+ max_tokens: 1024,
49
+ }),
50
+ });
51
+ if (response.ok) {
52
+ const data = await response.json();
53
+ const choice = data.choices?.[0]?.message;
54
+ if (choice) {
55
+ const content = choice.content || '';
56
+ const latencyMs = Date.now() - startTime;
57
+ return {
58
+ thought: `HARP-1B analyzed task objective and completed live neural inference.`,
59
+ content,
60
+ toolCalls: [],
61
+ model: activeModel,
62
+ provider: this.providerName,
63
+ usage: data.usage || {
64
+ promptTokens: this.estimateTokens(request.messages),
65
+ completionTokens: this.estimateTokens([{ role: 'assistant', content }]),
66
+ totalTokens: this.estimateTokens(request.messages) + this.estimateTokens([{ role: 'assistant', content }]),
67
+ },
68
+ latencyMs,
69
+ finishReason: 'stop',
70
+ };
71
+ }
72
+ }
73
+ }
74
+ catch {
75
+ // Fall back gracefully to structured generator
76
+ }
77
+ }
30
78
  // Native HARP inference engine simulation / structured generator
31
79
  const latencyMs = Date.now() - startTime;
32
80
  const lastMsg = request.messages[request.messages.length - 1]?.content || '';
@@ -20,7 +20,7 @@ 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';
23
+ import { renderStepHeader, renderThoughtBox, renderToolCall, renderToolResult, renderTaskCompletedCard, getActionFriendlyDescription, } from '../../utils/claudeUI.js';
24
24
  import { loadWorkspaceRules } from '../../utils/rules.js';
25
25
  import { InterruptManager } from '../../utils/interruptHandler.js';
26
26
  export class AgentRuntime {
@@ -492,9 +492,21 @@ Action Rules:
492
492
  }
493
493
  const msg = sanitizeMessage(choice.message);
494
494
  this.historyMessages.push(msg);
495
- if (msg.content && msg.content.trim()) {
496
- renderThoughtBox(msg.content, step);
495
+ let fallbackDesc;
496
+ if (msg.tool_calls && msg.tool_calls.length > 0) {
497
+ const firstTc = msg.tool_calls[0];
498
+ if (firstTc?.function?.name) {
499
+ let callArgs = {};
500
+ try {
501
+ callArgs = JSON.parse(firstTc.function.arguments || '{}');
502
+ }
503
+ catch { }
504
+ fallbackDesc = getActionFriendlyDescription(firstTc.function.name, callArgs);
505
+ }
497
506
  }
507
+ const rawReasoning = choice.message?.reasoning_content || choice.message?.thinking || choice.message?.thought || '';
508
+ const combinedReasoning = rawReasoning ? `${rawReasoning}\n${msg.content || ''}` : (msg.content || '');
509
+ renderThoughtBox(combinedReasoning, step, fallbackDesc);
498
510
  let toolCallsToExecute = [];
499
511
  if (msg.tool_calls && msg.tool_calls.length > 0) {
500
512
  for (const tc of msg.tool_calls) {
@@ -1331,12 +1343,20 @@ Action Rules:
1331
1343
  return { result: `Successfully wrote file "${targetPath}".` };
1332
1344
  }
1333
1345
  case 'edit_file': {
1334
- const targetPath = String(args.path || '').trim();
1346
+ const targetPath = String(args.path || args.filePath || args.file || '').trim();
1347
+ let target = String(args.target ?? args.old_string ?? args.old_str ?? args.oldText ?? args.find ?? args.search ?? '');
1348
+ let replacement = String(args.replacement ?? args.new_string ?? args.new_str ?? args.newText ?? args.replace ?? '');
1349
+ if (replacement.includes('\\n') && !replacement.includes('\n')) {
1350
+ replacement = replacement.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
1351
+ }
1352
+ if (target.includes('\\n') && !target.includes('\n')) {
1353
+ target = target.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
1354
+ }
1335
1355
  const fullPath = path.isAbsolute(targetPath) ? targetPath : path.resolve(this.cwd, targetPath);
1336
1356
  if (!fs.existsSync(fullPath))
1337
1357
  return { result: `Error: File "${targetPath}" does not exist.` };
1338
1358
  const currentContent = fs.readFileSync(fullPath, 'utf-8');
1339
- const replaceRes = robustSnippetReplace(currentContent, args.target, args.replacement);
1359
+ const replaceRes = robustSnippetReplace(currentContent, target, replacement);
1340
1360
  if (!replaceRes.success) {
1341
1361
  return { result: `Error: ${replaceRes.error}` };
1342
1362
  }
@@ -1405,7 +1425,7 @@ Action Rules:
1405
1425
  };
1406
1426
  }
1407
1427
  case 'multi_edit_file': {
1408
- const targetPath = String(args.path || '').trim();
1428
+ const targetPath = String(args.path || args.filePath || args.file || '').trim();
1409
1429
  const edits = Array.isArray(args.edits) ? args.edits : [];
1410
1430
  const fullPath = path.isAbsolute(targetPath) ? targetPath : path.resolve(this.cwd, targetPath);
1411
1431
  if (!fs.existsSync(fullPath))
@@ -1413,7 +1433,13 @@ Action Rules:
1413
1433
  let content = fs.readFileSync(fullPath, 'utf-8');
1414
1434
  let count = 0;
1415
1435
  for (const ed of edits) {
1416
- const res = robustSnippetReplace(content, ed.target, ed.replacement);
1436
+ let target = String(ed.target ?? ed.old_string ?? ed.old_str ?? ed.oldText ?? ed.find ?? ed.search ?? '');
1437
+ let replacement = String(ed.replacement ?? ed.new_string ?? ed.new_str ?? ed.newText ?? ed.replace ?? '');
1438
+ if (target.includes('\\n') && !target.includes('\n'))
1439
+ target = target.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
1440
+ if (replacement.includes('\\n') && !replacement.includes('\n'))
1441
+ replacement = replacement.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
1442
+ const res = robustSnippetReplace(content, target, replacement);
1417
1443
  if (res.success) {
1418
1444
  content = res.updatedContent;
1419
1445
  count++;
@@ -6,6 +6,7 @@ import {} from './types.js';
6
6
  import {} from '../browser/actions/types.js';
7
7
  import {} from '../browser/observer/browserObserver.js';
8
8
  import {} from '../computer/computerController.js';
9
+ import { robustSnippetReplace } from '../agentEngine.js';
9
10
  const execAsync = promisify(exec);
10
11
  // ============================================================================
11
12
  // 1. Browser Domain Handler
@@ -308,16 +309,52 @@ export class FilesystemHandler {
308
309
  throw new Error(`File not found for editing: ${resolvedPath}`);
309
310
  }
310
311
  let content = await fs.promises.readFile(resolvedPath, 'utf-8');
311
- const target = args.target;
312
- const replacement = args.replacement ?? '';
313
- if (typeof target === 'string') {
314
- if (!content.includes(target)) {
315
- throw new Error(`Target text to replace not found in ${resolvedPath}`);
312
+ let target = String(args.target ?? args.old_string ?? args.old_str ?? args.oldText ?? args.find ?? args.search ?? '');
313
+ let replacement = String(args.replacement ?? args.new_string ?? args.new_str ?? args.newText ?? args.replace ?? '');
314
+ if (target.includes('\\n') && !target.includes('\n'))
315
+ target = target.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
316
+ if (replacement.includes('\\n') && !replacement.includes('\n'))
317
+ replacement = replacement.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
318
+ const replaceRes = robustSnippetReplace(content, target, replacement);
319
+ if (!replaceRes.success) {
320
+ throw new Error(replaceRes.error || `Target text to replace not found in ${resolvedPath}`);
321
+ }
322
+ await fs.promises.writeFile(resolvedPath, replaceRes.updatedContent, 'utf-8');
323
+ return { success: true, path: resolvedPath };
324
+ }
325
+ case 'multi_edit_file': {
326
+ if (!fs.existsSync(resolvedPath)) {
327
+ throw new Error(`File not found for multi-editing: ${resolvedPath}`);
328
+ }
329
+ const edits = Array.isArray(args.edits) ? args.edits : [];
330
+ if (edits.length === 0) {
331
+ throw new Error(`No edits provided for multi_edit_file on ${resolvedPath}`);
332
+ }
333
+ let content = await fs.promises.readFile(resolvedPath, 'utf-8');
334
+ let count = 0;
335
+ const errors = [];
336
+ for (let i = 0; i < edits.length; i++) {
337
+ const ed = edits[i];
338
+ let target = String(ed.target ?? ed.old_string ?? ed.old_str ?? ed.oldText ?? ed.find ?? ed.search ?? '');
339
+ let replacement = String(ed.replacement ?? ed.new_string ?? ed.new_str ?? ed.newText ?? ed.replace ?? '');
340
+ if (target.includes('\\n') && !target.includes('\n'))
341
+ target = target.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
342
+ if (replacement.includes('\\n') && !replacement.includes('\n'))
343
+ replacement = replacement.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
344
+ const res = robustSnippetReplace(content, target, replacement);
345
+ if (res.success) {
346
+ content = res.updatedContent;
347
+ count++;
348
+ }
349
+ else {
350
+ errors.push(`Edit #${i + 1}: ${res.error}`);
316
351
  }
317
- content = content.replaceAll(target, replacement);
352
+ }
353
+ if (count === 0) {
354
+ throw new Error(`All ${edits.length} edits failed on ${resolvedPath}:\n${errors.join('\n')}`);
318
355
  }
319
356
  await fs.promises.writeFile(resolvedPath, content, 'utf-8');
320
- return { success: true, path: resolvedPath };
357
+ return { success: true, path: resolvedPath, appliedCount: count, totalEdits: edits.length, errors };
321
358
  }
322
359
  case 'list_dir': {
323
360
  const dirPath = fs.existsSync(resolvedPath) ? resolvedPath : (context?.cwd || process.cwd());
@@ -69,9 +69,11 @@ export function inferExecutionIntent(goal) {
69
69
  }
70
70
  const hasBrowserApp = requiredApplications.some(a => ['Google Chrome', 'Mozilla Firefox', 'Microsoft Edge', 'Web Browser'].includes(a));
71
71
  const isExplicitBrowserAction = /\b(?:browse\s+(?:to\s+)?https?:\/\/|navigate\s+to\s+https?:\/\/|open\s+(?:the\s+)?(?:webpage|website|url\s+in\s+browser)|in\s+(?:the\s+)?browser)\b/i.test(lower);
72
- const isBrowserGoal = hasBrowserApp || isExplicitBrowserAction;
72
+ const isAppLaunchCommand = /\b(?:open|launch|start|run|switch\s+to|focus|bring\s+up|close|kill|exit|khol|kholo|chala|chalao|band)\b/i.test(lower);
73
73
  const isDesktopAppGoal = requiredApplications.some(a => !['Google Chrome', 'Mozilla Firefox', 'Microsoft Edge', 'Web Browser'].includes(a)) ||
74
- /\b(?:open|launch|switch to|in)\s+(?:the\s+)?(?:notepad|excel|word|calculator|paint|terminal|powershell|cmd|app|window)\b/i.test(lower);
74
+ (hasBrowserApp && isAppLaunchCommand) ||
75
+ /\b(?:open|launch|switch to|in)\s+(?:the\s+)?(?:notepad|excel|word|calculator|paint|terminal|powershell|cmd|app|window|browser|chrome|edge)\b/i.test(lower);
76
+ const isBrowserGoal = isExplicitBrowserAction || (hasBrowserApp && !isAppLaunchCommand);
75
77
  if (isDesktopAppGoal && isBrowserGoal) {
76
78
  return {
77
79
  requiredApplications,
package/bin/src/index.js CHANGED
@@ -39,13 +39,13 @@ program
39
39
  .name('scout')
40
40
  .alias('ft')
41
41
  .description('FrontTerrain The Onboarding Co-Pilot for New Codebases')
42
- .version('9.5.6');
42
+ .version('9.5.7');
43
43
  // Header UI on execution with FrontTerrain proprietary logo & version auto-checker
44
44
  program.hook('preAction', async (_thisCommand, actionCommand) => {
45
- intro(renderBranding('9.5.6'));
45
+ intro(renderBranding('9.5.7'));
46
46
  const cmdName = actionCommand ? actionCommand.name() : '';
47
47
  if (cmdName !== 'upgrade') {
48
- await checkForUpdates('9.5.6');
48
+ await checkForUpdates('9.5.7');
49
49
  }
50
50
  // Auth Guard: enforce authentication for all commands except login, signup, upgrade, help, dashboard, auth, status, plan, mcp, switch, accounts, support
51
51
  const EXEMPT_COMMANDS = ['login', 'signin', 'signup', 'register', 'upgrade', 'help', 'dashboard', 'web-ui', 'gui', 'auth', 'status', 'quota', 'usage', 'credits', 'plan', 'pricing', 'subscribe', 'mcp', 'switch', 'accounts', 'account', 'support', 'ticket', 'helpdesk'];
@@ -266,7 +266,7 @@ program
266
266
  .command('upgrade')
267
267
  .description('Check for updates and auto-upgrade Scout to the latest version')
268
268
  .action(async () => {
269
- await checkForUpdates('9.5.6', true);
269
+ await checkForUpdates('9.5.7', true);
270
270
  outro(chalk.cyan('Upgrade check complete.'));
271
271
  });
272
272
  program
@@ -37,7 +37,7 @@ export class MCPClient {
37
37
  },
38
38
  clientInfo: {
39
39
  name: 'scout',
40
- version: '9.5.6',
40
+ version: '9.5.7',
41
41
  },
42
42
  };
43
43
  const result = await this.transport.sendRequest('initialize', initParams, timeoutMs);
@@ -1,7 +1,7 @@
1
1
  import http from 'http';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
- import { exec } from 'child_process';
4
+ import { exec, execFile } from 'child_process';
5
5
  import { fileURLToPath } from 'url';
6
6
  import { loadAuthConfig, saveAuthConfig, clearAuthConfig, clearAllSessions, isLoggedIn, getTierSessionLimit, canStartNewSession, listAccountSessions, switchActiveAccount, removeAccountSession, } from '../utils/auth.js';
7
7
  import { getPublicPaymentConfig, createCheckoutSession, verifyAndApplyUpgrade } from '../utils/payment.js';
@@ -68,8 +68,17 @@ export function startDashboardServer(port = DEFAULT_PORT) {
68
68
  return new Promise((resolve, reject) => {
69
69
  const webDir = getWebDir();
70
70
  const server = http.createServer(async (req, res) => {
71
- // Enable CORS for cross-origin local dashboard sync (including scout.frontterrain.com)
72
- res.setHeader('Access-Control-Allow-Origin', '*');
71
+ // Secure CORS: restrict cross-origin requests to local loopback and official frontterrain domain
72
+ const origin = req.headers.origin;
73
+ const isAllowedOrigin = origin && (/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i.test(origin) ||
74
+ origin === 'https://scout.frontterrain.com' ||
75
+ origin === 'https://frontterrain.com');
76
+ if (isAllowedOrigin) {
77
+ res.setHeader('Access-Control-Allow-Origin', origin);
78
+ }
79
+ else if (!origin) {
80
+ res.setHeader('Access-Control-Allow-Origin', '*');
81
+ }
73
82
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
74
83
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
75
84
  res.setHeader('Access-Control-Allow-Private-Network', 'true');
@@ -376,39 +385,69 @@ export function startDashboardServer(port = DEFAULT_PORT) {
376
385
  });
377
386
  return;
378
387
  }
379
- // POST /api/cli/exec - Execute real CLI command locally
388
+ // POST /api/cli/exec - Execute real CLI command locally (Protected & Sanitized)
380
389
  if (pathname === '/api/cli/exec' && req.method === 'POST') {
390
+ // Block cross-origin requests from arbitrary external websites
391
+ const reqOrigin = req.headers.origin || '';
392
+ if (reqOrigin && !/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i.test(reqOrigin)) {
393
+ res.writeHead(403);
394
+ res.end(JSON.stringify({ error: 'Forbidden: Cross-origin CLI execution is blocked.' }));
395
+ return;
396
+ }
381
397
  let body = '';
382
398
  req.on('data', chunk => body += chunk);
383
399
  req.on('end', () => {
384
400
  try {
385
401
  const data = JSON.parse(body);
386
- let command = data.command || '';
387
- command = command.trim().replace(/^(scout|ft)\s*/i, '');
402
+ let command = String(data.command || '').trim();
403
+ command = command.replace(/^(scout|ft)\s*/i, '').trim();
388
404
  if (!command) {
389
405
  res.writeHead(400);
390
406
  res.end(JSON.stringify({ error: 'Command string required' }));
391
407
  return;
392
408
  }
409
+ // Block shell chaining, redirection and metacharacters
410
+ if (/[;&|`$><]/.test(command)) {
411
+ res.writeHead(400);
412
+ res.end(JSON.stringify({ error: 'Command chaining, redirection, or shell metacharacters are forbidden.' }));
413
+ return;
414
+ }
415
+ // Whitelist recognized safe read/diagnostic scout subcommands
416
+ const allowedSubcommands = new Set([
417
+ 'status', 'brief', 'owners', 'setup', 'risky', 'benchmark',
418
+ 'history', 'checkpoints', 'quota', 'plan', 'mcp', 'accounts',
419
+ 'support', 'help', '--help', '-h', 'version', '--version', '-v'
420
+ ]);
421
+ const rawArgs = command.split(/\s+/).filter(Boolean);
422
+ const firstSubcmd = (rawArgs[0] || '').toLowerCase();
423
+ if (!allowedSubcommands.has(firstSubcmd)) {
424
+ res.writeHead(400);
425
+ res.end(JSON.stringify({ error: `Command "${firstSubcmd}" is not permitted via web dashboard. Permitted commands: ${Array.from(allowedSubcommands).slice(0, 10).join(', ')}...` }));
426
+ return;
427
+ }
393
428
  const pkgRoot = getPackageRoot();
394
429
  const binScript = path.join(pkgRoot, 'bin', 'ft.js');
395
430
  const indexScript = path.join(pkgRoot, 'bin', 'src', 'index.ts');
396
- let execCmd;
397
431
  if (fs.existsSync(binScript)) {
398
- execCmd = `node "${binScript}" ${command}`;
432
+ execFile(process.execPath, [binScript, ...rawArgs], { cwd: process.cwd(), timeout: 30000 }, (err, stdout, stderr) => {
433
+ const output = (stdout || '') + (stderr || '');
434
+ logAuditEvent('cli_exec', { command, success: !err });
435
+ res.writeHead(200);
436
+ res.end(JSON.stringify({ success: !err, output: output || 'Command executed successfully.' }));
437
+ });
399
438
  }
400
439
  else if (fs.existsSync(indexScript)) {
401
- execCmd = `npx tsx "${indexScript}" ${command}`;
440
+ execFile('npx', ['tsx', indexScript, ...rawArgs], { cwd: process.cwd(), timeout: 30000 }, (err, stdout, stderr) => {
441
+ const output = (stdout || '') + (stderr || '');
442
+ logAuditEvent('cli_exec', { command, success: !err });
443
+ res.writeHead(200);
444
+ res.end(JSON.stringify({ success: !err, output: output || 'Command executed successfully.' }));
445
+ });
402
446
  }
403
447
  else {
404
- execCmd = `ft ${command}`;
448
+ res.writeHead(500);
449
+ res.end(JSON.stringify({ error: 'Scout executable entrypoint not found on disk.' }));
405
450
  }
406
- exec(execCmd, { cwd: process.cwd() }, (err, stdout, stderr) => {
407
- const output = (stdout || '') + (stderr || '');
408
- logAuditEvent('cli_exec', { command, success: !err });
409
- res.writeHead(200);
410
- res.end(JSON.stringify({ success: !err, output: output || 'Command executed successfully.' }));
411
- });
412
451
  }
413
452
  catch (err) {
414
453
  res.writeHead(400);
@@ -1233,8 +1272,8 @@ export function startDashboardServer(port = DEFAULT_PORT) {
1233
1272
  reject(err);
1234
1273
  }
1235
1274
  });
1236
- server.listen(port, () => {
1237
- const url = `http://localhost:${port}`;
1275
+ server.listen(port, '127.0.0.1', () => {
1276
+ const url = `http://127.0.0.1:${port}`;
1238
1277
  resolve({ server, url });
1239
1278
  });
1240
1279
  });
@@ -1,5 +1,5 @@
1
1
  import chalk from 'chalk';
2
- export function renderBranding(version = '9.5.6') {
2
+ export function renderBranding(version = '9.5.7') {
3
3
  const logo = chalk.cyan.bold(' ███████╗████████╗') + ' ' + chalk.cyan.bold('███████╗ ██████╗ ██████╗ ██╗ ██╗████████╗') + '\n' +
4
4
  chalk.cyan.bold(' ██╔════╝╚══██╔══╝') + ' ' + chalk.cyan.bold('██╔════╝ ██╔════╝██╔═══██╗ ██║ ██║╚══██╔══╝') + '\n' +
5
5
  chalk.cyan.bold(' █████╗ ██║ ') + ' ' + chalk.cyan.bold(' ███████╗ ██║ ██║ ██║ ██║ ██║ ██║ ') + '\n' +
@@ -61,13 +61,22 @@ export interface TaskCompletedUIParams {
61
61
  * ╭── ● Step 2 ── Scout Operating ──────────── ⏱ 1.2s • 3,250 tok • PRO ─╮
62
62
  */
63
63
  export declare function renderStepHeader(telemetry: StepTelemetry): void;
64
+ /**
65
+ * Human-friendly action descriptions for synthesized reasoning and fallback thought completion.
66
+ */
67
+ export declare function getActionFriendlyDescription(fnName: string, args?: any): string;
68
+ /**
69
+ * Validates and completes fragmented or truncated reasoning sentences
70
+ * so Scout always outputs complete, grammatically sound thoughts in the terminal.
71
+ */
72
+ export declare function ensureCompleteSentence(text: string, fallbackDesc?: string): string;
64
73
  /**
65
74
  * Renders Claude Code-style Collapsible / Styled Thought Reasoning Box:
66
75
  * ╭── 💭 Scout Reasoning ──────────────────────────────────────────────────
67
76
  * │ Analyzing workspace files to identify the missing dependency...
68
77
  * ╰────────────────────────────────────────────────────────────────────────
69
78
  */
70
- export declare function renderThoughtBox(thought: string, step?: number): void;
79
+ export declare function renderThoughtBox(thought: string, step?: number, fallbackDesc?: string): void;
71
80
  /**
72
81
  * Renders Claude Code-style Rich Tool Call Invocation Block:
73
82
  * ╭── 📖 Read File ── src/engine/agentEngine.ts ───────────────────────────
@@ -31,24 +31,154 @@ export function renderStepHeader(telemetry) {
31
31
  console.log();
32
32
  console.log(chalk.cyan(leftPart) + chalk.cyan('─'.repeat(fillLen)) + chalk.cyan(rightPart));
33
33
  }
34
+ /**
35
+ * Human-friendly action descriptions for synthesized reasoning and fallback thought completion.
36
+ */
37
+ export function getActionFriendlyDescription(fnName, args = {}) {
38
+ switch (fnName) {
39
+ case 'computer_open_app':
40
+ return `Opening ${args?.appName || args?.app || 'the application'} to prepare for the requested actions.`;
41
+ case 'computer_type':
42
+ return `Typing the requested text into ${args?.targetApp || args?.app || 'the active window'}.`;
43
+ case 'computer_close_app':
44
+ return `Closing ${args?.appName || args?.app || 'the application'} as requested.`;
45
+ case 'computer_switch_window':
46
+ return `Switching focus to ${args?.windowTitleOrApp || args?.appName || 'the target window'}.`;
47
+ case 'computer_click':
48
+ return `Clicking screen coordinates (${args?.x ?? 0}, ${args?.y ?? 0}) to interact with the target element.`;
49
+ case 'computer_double_click':
50
+ return `Double clicking at (${args?.x ?? 0}, ${args?.y ?? 0}) to activate the target element.`;
51
+ case 'computer_right_click':
52
+ return `Right clicking at (${args?.x ?? 0}, ${args?.y ?? 0}) to open the context menu.`;
53
+ case 'computer_screenshot':
54
+ return `Observing the computer screen to inspect the current visual state.`;
55
+ case 'computer_inspect_ui':
56
+ return `Inspecting active desktop windows and interactive UI elements.`;
57
+ case 'browser_navigate':
58
+ return `Navigating to ${args?.url || 'the requested web page'}.`;
59
+ case 'browser_click':
60
+ return `Clicking element "${args?.selectorOrText || 'target'}" in the browser.`;
61
+ case 'browser_type':
62
+ return `Entering text into "${args?.selectorOrText || 'input field'}" in the browser.`;
63
+ case 'browser_content':
64
+ return `Extracting structured text and content from the current web page.`;
65
+ case 'browser_screenshot':
66
+ return `Capturing a visual screenshot of the current browser page.`;
67
+ case 'read_file':
68
+ return `Reading ${args?.path || 'the file'} to inspect its contents.`;
69
+ case 'write_file':
70
+ return `Writing contents to ${args?.path || 'the target file'}.`;
71
+ case 'edit_file':
72
+ return `Applying modifications to ${args?.path || 'the target file'}.`;
73
+ case 'run_command':
74
+ return `Running command: "${args?.command || args?.cmd || ''}".`;
75
+ case 'list_dir':
76
+ return `Listing files in ${args?.path || '.'} to understand workspace structure.`;
77
+ case 'grep_search':
78
+ return `Searching for "${args?.query || args?.pattern || ''}" across workspace files.`;
79
+ case 'task_completed':
80
+ return `Finalizing the task and preparing the completion summary.`;
81
+ default:
82
+ return `Executing ${fnName.replace(/_/g, ' ')} to proceed with the objective.`;
83
+ }
84
+ }
85
+ /**
86
+ * Validates and completes fragmented or truncated reasoning sentences
87
+ * so Scout always outputs complete, grammatically sound thoughts in the terminal.
88
+ */
89
+ export function ensureCompleteSentence(text, fallbackDesc) {
90
+ if (!text || !text.trim())
91
+ return fallbackDesc || '';
92
+ let cleaned = text.trim();
93
+ // Strip unclosed <think> or <think>...</think>
94
+ cleaned = cleaned.replace(/<think>[\s\S]*?<\/think>/gi, '');
95
+ cleaned = cleaned.replace(/<think>[\s\S]*$/gi, '');
96
+ cleaned = cleaned.replace(/<\/think>/gi, '');
97
+ cleaned = cleaned.replace(/```json[\s\S]*?```/gi, '');
98
+ cleaned = cleaned.replace(/```[\s\S]*?```/gi, '');
99
+ cleaned = cleaned.replace(/<function=[^>]+>[\s\S]*?<\/function>/gi, '');
100
+ cleaned = cleaned.replace(/<[a-zA-Z0-9_]+>[\s\S]*?<\/[a-zA-Z0-9_]+>/gi, '');
101
+ cleaned = cleaned.replace(/\{[\s\S]*"tool"\s*:[\s\S]*\}/gi, '');
102
+ cleaned = cleaned.replace(/[\u0600-\u06FF\u0750-\u077F\uAC00-\uD7AF\u3040-\u30FF\u4E00-\u9FFF\u0D80-\u0DFF]+/g, '');
103
+ cleaned = cleaned.trim();
104
+ if (!cleaned)
105
+ return fallbackDesc || '';
106
+ // Indicators of incomplete ending: colons, dashes, prepositions, conjunctions, or action verbs
107
+ const incompleteEndingRegex = /(?:[:;,–—\\]|\.{2,}|\b(?:to|and|by|using|with|for|in|a|the|so\s+that|because|as|into|from|of|that|which|if|or|about|then|while|when|after|before|write|type|open|launch|click|press|close|read|edit|create|run|check|see|view|focus|switch|start|navigate))\s*$/i;
108
+ const isFragment = cleaned.length < 15 ||
109
+ /^(?:i\s+will|i'll|let\s+me|i\s+need\s+to|i\s+am\s+going\s+to|starting\s+by|first\s+step\s+is\s+to|to\s+do\s+this\s+i\s+will|in\s+order\s+to)\s*$/i.test(cleaned) ||
110
+ incompleteEndingRegex.test(cleaned) ||
111
+ (!/[.!?]$/.test(cleaned) && cleaned.split(/\s+/).length <= 4);
112
+ if (isFragment) {
113
+ if (fallbackDesc) {
114
+ const strippedLead = cleaned.replace(/[:;,–—\.]+\s*$/, '').trim();
115
+ if (strippedLead.length >= 15 && !incompleteEndingRegex.test(strippedLead)) {
116
+ cleaned = `${strippedLead}. ${fallbackDesc}`;
117
+ }
118
+ else {
119
+ cleaned = fallbackDesc;
120
+ }
121
+ }
122
+ else {
123
+ cleaned = cleaned.replace(/[:;,–—\.]+\s*$/, '').trim();
124
+ if (!/[.!?]$/.test(cleaned)) {
125
+ cleaned += '.';
126
+ }
127
+ }
128
+ }
129
+ else {
130
+ cleaned = cleaned.replace(/[:;,–—]+\s*$/, '').trim();
131
+ if (!/[.!?]$/.test(cleaned)) {
132
+ cleaned += '.';
133
+ }
134
+ }
135
+ return cleaned;
136
+ }
34
137
  /**
35
138
  * Renders Claude Code-style Collapsible / Styled Thought Reasoning Box:
36
139
  * ╭── 💭 Scout Reasoning ──────────────────────────────────────────────────
37
140
  * │ Analyzing workspace files to identify the missing dependency...
38
141
  * ╰────────────────────────────────────────────────────────────────────────
39
142
  */
40
- export function renderThoughtBox(thought, step) {
41
- if (!thought || !thought.trim())
143
+ export function renderThoughtBox(thought, step, fallbackDesc) {
144
+ const completeThought = ensureCompleteSentence(thought, fallbackDesc);
145
+ if (!completeThought || !completeThought.trim())
42
146
  return;
43
147
  const width = getTerminalWidth();
44
148
  const stepLabel = step ? ` (Step ${step})` : '';
45
149
  const headerTitle = `💭 Scout Reasoning${stepLabel}`;
46
150
  const header = `╭── ${chalk.bold.yellow(headerTitle)} ${'─'.repeat(Math.max(4, width - headerTitle.length - 8))}`;
47
151
  console.log(chalk.yellow(header));
48
- const lines = thought.trim().split('\n');
49
- for (const l of lines) {
50
- // Subtle indent with yellow border
51
- console.log(`${chalk.yellow('│')} ${chalk.dim(l)}`);
152
+ const rawLines = completeThought.trim().split('\n');
153
+ const maxContentWidth = Math.max(20, width - 6);
154
+ for (const line of rawLines) {
155
+ const trimmed = line.trimEnd();
156
+ if (!trimmed) {
157
+ console.log(chalk.yellow('│'));
158
+ continue;
159
+ }
160
+ if (trimmed.length <= maxContentWidth) {
161
+ console.log(`${chalk.yellow('│')} ${chalk.dim(trimmed)}`);
162
+ }
163
+ else {
164
+ // Word wrap long sentences cleanly inside the thought box border
165
+ const words = trimmed.split(/\s+/);
166
+ let currentLine = '';
167
+ for (const word of words) {
168
+ if ((currentLine + ' ' + word).trim().length > maxContentWidth) {
169
+ if (currentLine) {
170
+ console.log(`${chalk.yellow('│')} ${chalk.dim(currentLine.trim())}`);
171
+ }
172
+ currentLine = word;
173
+ }
174
+ else {
175
+ currentLine = currentLine ? `${currentLine} ${word}` : word;
176
+ }
177
+ }
178
+ if (currentLine) {
179
+ console.log(`${chalk.yellow('│')} ${chalk.dim(currentLine.trim())}`);
180
+ }
181
+ }
52
182
  }
53
183
  console.log(chalk.yellow(`╰${'─'.repeat(width)}`));
54
184
  }
@@ -105,7 +105,7 @@ export async function startQrPairingSession() {
105
105
  const pairingCode = `SCT-${rawNum}`;
106
106
  const sessionId = `sct_sess_${Date.now().toString(36)}_${crypto.randomBytes(3).toString('hex')}`;
107
107
  const hostName = os.hostname() || 'workstation.local';
108
- const version = '9.5.6';
108
+ const version = '9.5.7';
109
109
  let localIp = '127.0.0.1';
110
110
  try {
111
111
  const nets = os.networkInterfaces();
@@ -52,7 +52,7 @@ export function collectSanitizedDiagnostics() {
52
52
  catch { }
53
53
  }
54
54
  return {
55
- scoutVersion: '9.5.6',
55
+ scoutVersion: '9.5.7',
56
56
  nodeVersion: process.version,
57
57
  platform: process.platform,
58
58
  osRelease: os.release(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ft-scout",
3
- "version": "9.5.6",
3
+ "version": "9.5.7",
4
4
  "type": "module",
5
5
  "description": "FrontTerrain — The Onboarding Co-Pilot for New Codebases",
6
6
  "main": "bin/src/index.js",