@hasna/terminal 1.4.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/ai.js +21 -1
- 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 +21 -1
- package/src/cli.tsx +43 -1
- package/src/command-validator.ts +85 -0
package/dist/ai.js
CHANGED
|
@@ -177,12 +177,32 @@ RULES:
|
|
|
177
177
|
- NEVER install packages (npx, npm install, pip install, brew install). This is a READ-ONLY terminal.
|
|
178
178
|
- NEVER modify source code (sed -i, codemod, awk with redirect). Only observe, never change.
|
|
179
179
|
- Search src/ directory, NOT dist/ or node_modules/ for code queries.
|
|
180
|
-
- For compound questions ("how many X and are they Y"), prefer ONE command that captures all info. Do NOT chain with &&.
|
|
181
180
|
- Use exact file paths from the project context below. Do NOT guess paths.
|
|
182
181
|
- For "what would break if I deleted X": use grep -rn "from.*X\\|import.*X\\|require.*X" src/ to find all importers.
|
|
183
182
|
- For "find where X is defined": use grep -rn "export.*function X\\|export.*class X\\|export.*const X" src/
|
|
184
183
|
- For "show me the code of function X": use grep -A 20 "function X" src/ to show the function body.
|
|
185
184
|
- For conceptual questions about what code does: use cat on the relevant file, the AI summary will explain it.
|
|
185
|
+
|
|
186
|
+
COMPOUND QUESTIONS: For questions asking multiple things, prefer ONE command that captures all info. Extract multiple answers from a single output.
|
|
187
|
+
- "how many tests and do they pass" → bun test (extract count AND pass/fail from output)
|
|
188
|
+
- "what files changed and how many lines" → git log --stat -3 (shows files AND line counts)
|
|
189
|
+
- "what version of node and bun" → node -v && bun -v (only use && for trivial non-failing commands)
|
|
190
|
+
NEVER split into separate test runs or expensive commands chained with &&.
|
|
191
|
+
|
|
192
|
+
BLOCKED ALTERNATIVES: If your preferred command would require installing packages (npx, npm install), ALWAYS try a READ-ONLY alternative:
|
|
193
|
+
- Code quality analysis → grep -rn "TODO\\|FIXME\\|HACK\\|XXX" src/
|
|
194
|
+
- Linting → check if "lint" or "typecheck" exists in package.json scripts, run that
|
|
195
|
+
- Security scan → grep -rn "eval\\|exec\\|spawn\\|password\\|secret" src/
|
|
196
|
+
- Dependency audit → cat package.json | grep -A 50 dependencies
|
|
197
|
+
- Test coverage → bun test --coverage (or npm run test:coverage if available)
|
|
198
|
+
NEVER give up. Always try a grep/find/cat read-only alternative.
|
|
199
|
+
|
|
200
|
+
SEMANTIC MAPPING: When the user references a concept, search the file tree for RELATED terms:
|
|
201
|
+
- Look at directory names: src/agent/ likely contains "agentic" code
|
|
202
|
+
- Look at file names: lazy-executor.ts likely handles "lazy mode"
|
|
203
|
+
- When uncertain: grep -rn "keyword" src/ --include="*.ts" -l (list matching files)
|
|
204
|
+
|
|
205
|
+
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".
|
|
186
206
|
cwd: ${process.cwd()}
|
|
187
207
|
shell: zsh / macOS${projectContext}${restrictionBlock}${contextBlock}`;
|
|
188
208
|
}
|
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
|
@@ -212,12 +212,32 @@ RULES:
|
|
|
212
212
|
- NEVER install packages (npx, npm install, pip install, brew install). This is a READ-ONLY terminal.
|
|
213
213
|
- NEVER modify source code (sed -i, codemod, awk with redirect). Only observe, never change.
|
|
214
214
|
- Search src/ directory, NOT dist/ or node_modules/ for code queries.
|
|
215
|
-
- For compound questions ("how many X and are they Y"), prefer ONE command that captures all info. Do NOT chain with &&.
|
|
216
215
|
- Use exact file paths from the project context below. Do NOT guess paths.
|
|
217
216
|
- For "what would break if I deleted X": use grep -rn "from.*X\\|import.*X\\|require.*X" src/ to find all importers.
|
|
218
217
|
- For "find where X is defined": use grep -rn "export.*function X\\|export.*class X\\|export.*const X" src/
|
|
219
218
|
- For "show me the code of function X": use grep -A 20 "function X" src/ to show the function body.
|
|
220
219
|
- For conceptual questions about what code does: use cat on the relevant file, the AI summary will explain it.
|
|
220
|
+
|
|
221
|
+
COMPOUND QUESTIONS: For questions asking multiple things, prefer ONE command that captures all info. Extract multiple answers from a single output.
|
|
222
|
+
- "how many tests and do they pass" → bun test (extract count AND pass/fail from output)
|
|
223
|
+
- "what files changed and how many lines" → git log --stat -3 (shows files AND line counts)
|
|
224
|
+
- "what version of node and bun" → node -v && bun -v (only use && for trivial non-failing commands)
|
|
225
|
+
NEVER split into separate test runs or expensive commands chained with &&.
|
|
226
|
+
|
|
227
|
+
BLOCKED ALTERNATIVES: If your preferred command would require installing packages (npx, npm install), ALWAYS try a READ-ONLY alternative:
|
|
228
|
+
- Code quality analysis → grep -rn "TODO\\|FIXME\\|HACK\\|XXX" src/
|
|
229
|
+
- Linting → check if "lint" or "typecheck" exists in package.json scripts, run that
|
|
230
|
+
- Security scan → grep -rn "eval\\|exec\\|spawn\\|password\\|secret" src/
|
|
231
|
+
- Dependency audit → cat package.json | grep -A 50 dependencies
|
|
232
|
+
- Test coverage → bun test --coverage (or npm run test:coverage if available)
|
|
233
|
+
NEVER give up. Always try a grep/find/cat read-only alternative.
|
|
234
|
+
|
|
235
|
+
SEMANTIC MAPPING: When the user references a concept, search the file tree for RELATED terms:
|
|
236
|
+
- Look at directory names: src/agent/ likely contains "agentic" code
|
|
237
|
+
- Look at file names: lazy-executor.ts likely handles "lazy mode"
|
|
238
|
+
- When uncertain: grep -rn "keyword" src/ --include="*.ts" -l (list matching files)
|
|
239
|
+
|
|
240
|
+
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".
|
|
221
241
|
cwd: ${process.cwd()}
|
|
222
242
|
shell: zsh / macOS${projectContext}${restrictionBlock}${contextBlock}`;
|
|
223
243
|
}
|
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
|
+
}
|