@hasna/terminal 1.5.0 → 1.6.1
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/ai.js +13 -2
- package/dist/cli.js +36 -1
- package/dist/command-validator.js +77 -0
- package/imported_modules.txt +0 -0
- package/package.json +1 -1
- package/src/ai.ts +18 -3
- package/src/cli.tsx +43 -1
- package/src/command-validator.ts +85 -0
package/dist/ai.js
CHANGED
|
@@ -119,10 +119,19 @@ function detectProjectContext() {
|
|
|
119
119
|
// Top-level dirs
|
|
120
120
|
const topLevel = execSync("ls -1", { cwd, encoding: "utf8", timeout: 2000 }).trim();
|
|
121
121
|
parts.push(`Top-level: ${topLevel.split("\n").join(", ")}`);
|
|
122
|
+
// Detect monorepo (packages/ or workspaces in package.json)
|
|
123
|
+
const isMonorepo = existsSync(join(cwd, "packages")) || existsSync(join(cwd, "apps"));
|
|
124
|
+
if (isMonorepo) {
|
|
125
|
+
const pkgDirs = execSync(`ls -d packages/*/src 2>/dev/null || ls -d apps/*/src 2>/dev/null || echo ""`, { cwd, encoding: "utf8", timeout: 2000 }).trim();
|
|
126
|
+
if (pkgDirs) {
|
|
127
|
+
parts.push(`MONOREPO: Source is in packages/*/src/, NOT src/. Search packages/ not src/.`);
|
|
128
|
+
parts.push(`Package sources:\n${pkgDirs}`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
122
131
|
// src/ structure — include FILES so AI knows exact filenames + extensions
|
|
123
|
-
for (const srcDir of ["src", "lib", "app"]) {
|
|
132
|
+
for (const srcDir of isMonorepo ? ["packages"] : ["src", "lib", "app"]) {
|
|
124
133
|
if (existsSync(join(cwd, srcDir))) {
|
|
125
|
-
const tree = execSync(`find ${srcDir} -maxdepth 3 -not -path '*/node_modules/*' -not -path '*/dist/*' -not -name '*.test.*' -not -name '*.spec.*' 2>/dev/null | sort | head -
|
|
134
|
+
const tree = execSync(`find ${srcDir} -maxdepth ${isMonorepo ? 4 : 3} -not -path '*/node_modules/*' -not -path '*/dist/*' -not -name '*.test.*' -not -name '*.spec.*' 2>/dev/null | sort | head -80`, { cwd, encoding: "utf8", timeout: 3000 }).trim();
|
|
126
135
|
if (tree)
|
|
127
136
|
parts.push(`Files in ${srcDir}/:\n${tree}`);
|
|
128
137
|
break;
|
|
@@ -203,6 +212,8 @@ SEMANTIC MAPPING: When the user references a concept, search the file tree for R
|
|
|
203
212
|
- When uncertain: grep -rn "keyword" src/ --include="*.ts" -l (list matching files)
|
|
204
213
|
|
|
205
214
|
ACTION vs CONCEPTUAL: If the prompt starts with "run", "execute", "check", "test", "build", "show output of" — ALWAYS generate an executable command. NEVER read README for action requests. Only read docs for "explain why", "what does X mean", "how was X designed".
|
|
215
|
+
|
|
216
|
+
MONOREPO: If the project context says "MONOREPO", search packages/ or apps/ NOT src/. Use: grep -rn "pattern" packages/ --include="*.ts". For specific packages, use packages/PKGNAME/src/.
|
|
206
217
|
cwd: ${process.cwd()}
|
|
207
218
|
shell: zsh / macOS${projectContext}${restrictionBlock}${contextBlock}`;
|
|
208
219
|
}
|
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
|
|
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
package/src/ai.ts
CHANGED
|
@@ -148,12 +148,25 @@ function detectProjectContext(): string {
|
|
|
148
148
|
const topLevel = execSync("ls -1", { cwd, encoding: "utf8", timeout: 2000 }).trim();
|
|
149
149
|
parts.push(`Top-level: ${topLevel.split("\n").join(", ")}`);
|
|
150
150
|
|
|
151
|
+
// Detect monorepo (packages/ or workspaces in package.json)
|
|
152
|
+
const isMonorepo = existsSync(join(cwd, "packages")) || existsSync(join(cwd, "apps"));
|
|
153
|
+
if (isMonorepo) {
|
|
154
|
+
const pkgDirs = execSync(
|
|
155
|
+
`ls -d packages/*/src 2>/dev/null || ls -d apps/*/src 2>/dev/null || echo ""`,
|
|
156
|
+
{ cwd, encoding: "utf8", timeout: 2000 }
|
|
157
|
+
).trim();
|
|
158
|
+
if (pkgDirs) {
|
|
159
|
+
parts.push(`MONOREPO: Source is in packages/*/src/, NOT src/. Search packages/ not src/.`);
|
|
160
|
+
parts.push(`Package sources:\n${pkgDirs}`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
151
164
|
// src/ structure — include FILES so AI knows exact filenames + extensions
|
|
152
|
-
for (const srcDir of ["src", "lib", "app"]) {
|
|
165
|
+
for (const srcDir of isMonorepo ? ["packages"] : ["src", "lib", "app"]) {
|
|
153
166
|
if (existsSync(join(cwd, srcDir))) {
|
|
154
167
|
const tree = execSync(
|
|
155
|
-
`find ${srcDir} -maxdepth 3 -not -path '*/node_modules/*' -not -path '*/dist/*' -not -name '*.test.*' -not -name '*.spec.*' 2>/dev/null | sort | head -
|
|
156
|
-
{ cwd, encoding: "utf8", timeout:
|
|
168
|
+
`find ${srcDir} -maxdepth ${isMonorepo ? 4 : 3} -not -path '*/node_modules/*' -not -path '*/dist/*' -not -name '*.test.*' -not -name '*.spec.*' 2>/dev/null | sort | head -80`,
|
|
169
|
+
{ cwd, encoding: "utf8", timeout: 3000 }
|
|
157
170
|
).trim();
|
|
158
171
|
if (tree) parts.push(`Files in ${srcDir}/:\n${tree}`);
|
|
159
172
|
break;
|
|
@@ -238,6 +251,8 @@ SEMANTIC MAPPING: When the user references a concept, search the file tree for R
|
|
|
238
251
|
- When uncertain: grep -rn "keyword" src/ --include="*.ts" -l (list matching files)
|
|
239
252
|
|
|
240
253
|
ACTION vs CONCEPTUAL: If the prompt starts with "run", "execute", "check", "test", "build", "show output of" — ALWAYS generate an executable command. NEVER read README for action requests. Only read docs for "explain why", "what does X mean", "how was X designed".
|
|
254
|
+
|
|
255
|
+
MONOREPO: If the project context says "MONOREPO", search packages/ or apps/ NOT src/. Use: grep -rn "pattern" packages/ --include="*.ts". For specific packages, use packages/PKGNAME/src/.
|
|
241
256
|
cwd: ${process.cwd()}
|
|
242
257
|
shell: zsh / macOS${projectContext}${restrictionBlock}${contextBlock}`;
|
|
243
258
|
}
|
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
|
|
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
|
+
}
|