@hasna/terminal 1.5.0 → 1.6.0

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.
package/dist/cli.js CHANGED
@@ -467,9 +467,27 @@ else if (args.length > 0) {
467
467
  process.exit(1);
468
468
  }
469
469
  }
470
+ // Step 2: Validate command before executing
471
+ const { validateCommand } = await import("./command-validator.js");
472
+ const validation = validateCommand(command, process.cwd());
473
+ if (!validation.valid) {
474
+ // Auto-retry: re-translate with simpler constraints
475
+ console.error(`[open-terminal] invalid command detected: ${validation.issues.join(", ")}`);
476
+ try {
477
+ const retryCommand = await translateToCommand(`${prompt} (IMPORTANT: keep it simple. Use basic grep/find/cat/ls/wc commands. No complex awk/sed pipelines. No GNU flags. Verify file paths from the project context.)`, perms, []);
478
+ if (retryCommand && retryCommand !== command) {
479
+ const retryValidation = validateCommand(retryCommand, process.cwd());
480
+ if (retryValidation.valid || retryValidation.issues.length < validation.issues.length) {
481
+ command = retryCommand;
482
+ console.error(`[open-terminal] retried: $ ${command}`);
483
+ }
484
+ }
485
+ }
486
+ catch { }
487
+ }
470
488
  // Show what we're running
471
489
  console.error(`$ ${command}`);
472
- // Step 2: Rewrite for optimization
490
+ // Step 3: Rewrite for optimization
473
491
  const rw = rewriteCommand(command);
474
492
  const actualCmd = rw.changed ? rw.rewritten : command;
475
493
  if (rw.changed)
@@ -529,6 +547,23 @@ else if (args.length > 0) {
529
547
  console.log(`No results found for: ${prompt}`);
530
548
  process.exit(0);
531
549
  }
550
+ // Auto-retry: if command failed (exit 2+), ask AI for a simpler alternative
551
+ if (e.status >= 2 && !actualCmd.includes("(retry)")) {
552
+ try {
553
+ const retryCmd = await translateToCommand(`${prompt} (The previous command failed with: ${errStderr.slice(0, 200)}. Try a SIMPLER approach. Use basic commands only.)`, perms, []);
554
+ if (retryCmd && !isIrreversible(retryCmd) && !checkPermissions(retryCmd, perms)) {
555
+ console.error(`[open-terminal] retrying: $ ${retryCmd}`);
556
+ const retryResult = execSync(retryCmd + " #(retry)", { encoding: "utf8", maxBuffer: 10 * 1024 * 1024, cwd: process.cwd() });
557
+ const retryClean = stripNoise(stripAnsi(retryResult)).cleaned;
558
+ if (retryClean.length > 5) {
559
+ const processed = await processOutput(retryCmd, retryClean, prompt);
560
+ console.log(processed.aiProcessed ? processed.summary : retryClean);
561
+ process.exit(0);
562
+ }
563
+ }
564
+ }
565
+ catch { /* retry also failed, fall through */ }
566
+ }
532
567
  // Combine stdout+stderr and try AI answer framing (for audit/lint/test commands)
533
568
  const combined = errStderr && errStdout.includes(errStderr.trim()) ? errStdout : errStdout + errStderr;
534
569
  const errorClean = stripNoise(stripAnsi(combined)).cleaned;
@@ -0,0 +1,77 @@
1
+ // Command validator — catch invalid commands BEFORE executing
2
+ // Prevents shell errors from hallucinated flags, wrong paths, bad syntax
3
+ import { existsSync } from "fs";
4
+ import { join } from "path";
5
+ /** Extract file paths referenced in a command */
6
+ function extractPaths(command) {
7
+ const paths = [];
8
+ // Match quoted paths
9
+ const quoted = command.match(/["']([^"']+\.\w+)["']/g);
10
+ if (quoted)
11
+ paths.push(...quoted.map(q => q.replace(/["']/g, "")));
12
+ // Match unquoted paths with extensions or directory separators
13
+ const tokens = command.split(/\s+/);
14
+ for (const t of tokens) {
15
+ if (t.includes("/") && !t.startsWith("-") && !t.startsWith("|") && !t.startsWith("&")) {
16
+ // Clean shell operators from end
17
+ const clean = t.replace(/[;|&>]+$/, "");
18
+ if (clean && !clean.startsWith("-"))
19
+ paths.push(clean);
20
+ }
21
+ }
22
+ return [...new Set(paths)];
23
+ }
24
+ /** Check for obviously broken shell syntax */
25
+ function checkSyntax(command) {
26
+ const issues = [];
27
+ // Unmatched quotes
28
+ const singleQuotes = (command.match(/'/g) || []).length;
29
+ const doubleQuotes = (command.match(/"/g) || []).length;
30
+ if (singleQuotes % 2 !== 0)
31
+ issues.push("unmatched single quote");
32
+ if (doubleQuotes % 2 !== 0)
33
+ issues.push("unmatched double quote");
34
+ // Unmatched parentheses
35
+ const openParens = (command.match(/\(/g) || []).length;
36
+ const closeParens = (command.match(/\)/g) || []).length;
37
+ if (openParens !== closeParens)
38
+ issues.push("unmatched parentheses");
39
+ // Empty pipe targets
40
+ if (/\|\s*$/.test(command))
41
+ issues.push("pipe with no target");
42
+ if (/^\s*\|/.test(command))
43
+ issues.push("pipe with no source");
44
+ return issues;
45
+ }
46
+ /** Validate a command before execution */
47
+ export function validateCommand(command, cwd) {
48
+ const issues = [];
49
+ // Check syntax
50
+ issues.push(...checkSyntax(command));
51
+ // Check file paths exist
52
+ const paths = extractPaths(command);
53
+ for (const p of paths) {
54
+ const fullPath = p.startsWith("/") ? p : join(cwd, p);
55
+ if (p.includes("*") || p.includes("?"))
56
+ continue; // skip globs
57
+ if (p.startsWith("-"))
58
+ continue; // skip flags
59
+ if ([".", "..", "/", "~"].includes(p))
60
+ continue; // skip special
61
+ if (!existsSync(fullPath) && !existsSync(p)) {
62
+ // Only flag source file paths, not output paths
63
+ if (/\.(ts|tsx|js|jsx|json|md|yaml|yml|py|go|rs)$/.test(p)) {
64
+ issues.push(`file not found: ${p}`);
65
+ }
66
+ }
67
+ }
68
+ // Check for common GNU flags on macOS
69
+ const gnuFlags = command.match(/--max-depth|--color=|--sort=|--field-type|--no-deps/g);
70
+ if (gnuFlags) {
71
+ issues.push(`GNU flag on macOS: ${gnuFlags.join(", ")}`);
72
+ }
73
+ return {
74
+ valid: issues.length === 0,
75
+ issues,
76
+ };
77
+ }
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hasna/terminal",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Smart terminal wrapper for AI agents and humans — structured output, token compression, MCP server, natural language",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.tsx CHANGED
@@ -448,10 +448,31 @@ else if (args.length > 0) {
448
448
  }
449
449
  }
450
450
 
451
+ // Step 2: Validate command before executing
452
+ const { validateCommand } = await import("./command-validator.js");
453
+ const validation = validateCommand(command, process.cwd());
454
+ if (!validation.valid) {
455
+ // Auto-retry: re-translate with simpler constraints
456
+ console.error(`[open-terminal] invalid command detected: ${validation.issues.join(", ")}`);
457
+ try {
458
+ const retryCommand = await translateToCommand(
459
+ `${prompt} (IMPORTANT: keep it simple. Use basic grep/find/cat/ls/wc commands. No complex awk/sed pipelines. No GNU flags. Verify file paths from the project context.)`,
460
+ perms, []
461
+ );
462
+ if (retryCommand && retryCommand !== command) {
463
+ const retryValidation = validateCommand(retryCommand, process.cwd());
464
+ if (retryValidation.valid || retryValidation.issues.length < validation.issues.length) {
465
+ command = retryCommand;
466
+ console.error(`[open-terminal] retried: $ ${command}`);
467
+ }
468
+ }
469
+ } catch {}
470
+ }
471
+
451
472
  // Show what we're running
452
473
  console.error(`$ ${command}`);
453
474
 
454
- // Step 2: Rewrite for optimization
475
+ // Step 3: Rewrite for optimization
455
476
  const rw = rewriteCommand(command);
456
477
  const actualCmd = rw.changed ? rw.rewritten : command;
457
478
  if (rw.changed) console.error(`[open-terminal] optimized: ${actualCmd}`);
@@ -509,6 +530,27 @@ else if (args.length > 0) {
509
530
  console.log(`No results found for: ${prompt}`);
510
531
  process.exit(0);
511
532
  }
533
+
534
+ // Auto-retry: if command failed (exit 2+), ask AI for a simpler alternative
535
+ if (e.status >= 2 && !actualCmd.includes("(retry)")) {
536
+ try {
537
+ const retryCmd = await translateToCommand(
538
+ `${prompt} (The previous command failed with: ${errStderr.slice(0, 200)}. Try a SIMPLER approach. Use basic commands only.)`,
539
+ perms, []
540
+ );
541
+ if (retryCmd && !isIrreversible(retryCmd) && !checkPermissions(retryCmd, perms)) {
542
+ console.error(`[open-terminal] retrying: $ ${retryCmd}`);
543
+ const retryResult = execSync(retryCmd + " #(retry)", { encoding: "utf8", maxBuffer: 10 * 1024 * 1024, cwd: process.cwd() });
544
+ const retryClean = stripNoise(stripAnsi(retryResult)).cleaned;
545
+ if (retryClean.length > 5) {
546
+ const processed = await processOutput(retryCmd, retryClean, prompt);
547
+ console.log(processed.aiProcessed ? processed.summary : retryClean);
548
+ process.exit(0);
549
+ }
550
+ }
551
+ } catch { /* retry also failed, fall through */ }
552
+ }
553
+
512
554
  // Combine stdout+stderr and try AI answer framing (for audit/lint/test commands)
513
555
  const combined = errStderr && errStdout.includes(errStderr.trim()) ? errStdout : errStdout + errStderr;
514
556
  const errorClean = stripNoise(stripAnsi(combined)).cleaned;
@@ -0,0 +1,85 @@
1
+ // Command validator — catch invalid commands BEFORE executing
2
+ // Prevents shell errors from hallucinated flags, wrong paths, bad syntax
3
+
4
+ import { existsSync } from "fs";
5
+ import { join } from "path";
6
+
7
+ export interface ValidationResult {
8
+ valid: boolean;
9
+ issues: string[];
10
+ fixedCommand?: string;
11
+ }
12
+
13
+ /** Extract file paths referenced in a command */
14
+ function extractPaths(command: string): string[] {
15
+ const paths: string[] = [];
16
+ // Match quoted paths
17
+ const quoted = command.match(/["']([^"']+\.\w+)["']/g);
18
+ if (quoted) paths.push(...quoted.map(q => q.replace(/["']/g, "")));
19
+ // Match unquoted paths with extensions or directory separators
20
+ const tokens = command.split(/\s+/);
21
+ for (const t of tokens) {
22
+ if (t.includes("/") && !t.startsWith("-") && !t.startsWith("|") && !t.startsWith("&")) {
23
+ // Clean shell operators from end
24
+ const clean = t.replace(/[;|&>]+$/, "");
25
+ if (clean && !clean.startsWith("-")) paths.push(clean);
26
+ }
27
+ }
28
+ return [...new Set(paths)];
29
+ }
30
+
31
+ /** Check for obviously broken shell syntax */
32
+ function checkSyntax(command: string): string[] {
33
+ const issues: string[] = [];
34
+
35
+ // Unmatched quotes
36
+ const singleQuotes = (command.match(/'/g) || []).length;
37
+ const doubleQuotes = (command.match(/"/g) || []).length;
38
+ if (singleQuotes % 2 !== 0) issues.push("unmatched single quote");
39
+ if (doubleQuotes % 2 !== 0) issues.push("unmatched double quote");
40
+
41
+ // Unmatched parentheses
42
+ const openParens = (command.match(/\(/g) || []).length;
43
+ const closeParens = (command.match(/\)/g) || []).length;
44
+ if (openParens !== closeParens) issues.push("unmatched parentheses");
45
+
46
+ // Empty pipe targets
47
+ if (/\|\s*$/.test(command)) issues.push("pipe with no target");
48
+ if (/^\s*\|/.test(command)) issues.push("pipe with no source");
49
+
50
+ return issues;
51
+ }
52
+
53
+ /** Validate a command before execution */
54
+ export function validateCommand(command: string, cwd: string): ValidationResult {
55
+ const issues: string[] = [];
56
+
57
+ // Check syntax
58
+ issues.push(...checkSyntax(command));
59
+
60
+ // Check file paths exist
61
+ const paths = extractPaths(command);
62
+ for (const p of paths) {
63
+ const fullPath = p.startsWith("/") ? p : join(cwd, p);
64
+ if (p.includes("*") || p.includes("?")) continue; // skip globs
65
+ if (p.startsWith("-")) continue; // skip flags
66
+ if ([".", "..", "/", "~"].includes(p)) continue; // skip special
67
+ if (!existsSync(fullPath) && !existsSync(p)) {
68
+ // Only flag source file paths, not output paths
69
+ if (/\.(ts|tsx|js|jsx|json|md|yaml|yml|py|go|rs)$/.test(p)) {
70
+ issues.push(`file not found: ${p}`);
71
+ }
72
+ }
73
+ }
74
+
75
+ // Check for common GNU flags on macOS
76
+ const gnuFlags = command.match(/--max-depth|--color=|--sort=|--field-type|--no-deps/g);
77
+ if (gnuFlags) {
78
+ issues.push(`GNU flag on macOS: ${gnuFlags.join(", ")}`);
79
+ }
80
+
81
+ return {
82
+ valid: issues.length === 0,
83
+ issues,
84
+ };
85
+ }