@hasna/terminal 4.3.0 → 4.3.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.
Files changed (75) hide show
  1. package/package.json +4 -3
  2. package/src/ai.ts +4 -4
  3. package/src/mcp/server.ts +26 -1704
  4. package/src/mcp/tools/batch.ts +106 -0
  5. package/src/mcp/tools/execute.ts +248 -0
  6. package/src/mcp/tools/files.ts +369 -0
  7. package/src/mcp/tools/git.ts +306 -0
  8. package/src/mcp/tools/helpers.ts +92 -0
  9. package/src/mcp/tools/memory.ts +170 -0
  10. package/src/mcp/tools/meta.ts +202 -0
  11. package/src/mcp/tools/process.ts +94 -0
  12. package/src/mcp/tools/project.ts +297 -0
  13. package/src/mcp/tools/search.ts +118 -0
  14. package/src/snapshots.ts +2 -2
  15. package/dist/App.js +0 -404
  16. package/dist/Browse.js +0 -79
  17. package/dist/FuzzyPicker.js +0 -47
  18. package/dist/Onboarding.js +0 -51
  19. package/dist/Spinner.js +0 -12
  20. package/dist/StatusBar.js +0 -49
  21. package/dist/ai.js +0 -315
  22. package/dist/cache.js +0 -42
  23. package/dist/cli.js +0 -778
  24. package/dist/command-rewriter.js +0 -64
  25. package/dist/command-validator.js +0 -86
  26. package/dist/compression.js +0 -91
  27. package/dist/context-hints.js +0 -285
  28. package/dist/diff-cache.js +0 -107
  29. package/dist/discover.js +0 -212
  30. package/dist/economy.js +0 -155
  31. package/dist/expand-store.js +0 -44
  32. package/dist/file-cache.js +0 -72
  33. package/dist/file-index.js +0 -62
  34. package/dist/history.js +0 -62
  35. package/dist/lazy-executor.js +0 -54
  36. package/dist/line-dedup.js +0 -59
  37. package/dist/loop-detector.js +0 -75
  38. package/dist/mcp/install.js +0 -189
  39. package/dist/mcp/server.js +0 -1375
  40. package/dist/noise-filter.js +0 -94
  41. package/dist/output-processor.js +0 -233
  42. package/dist/output-router.js +0 -41
  43. package/dist/output-store.js +0 -111
  44. package/dist/parsers/base.js +0 -2
  45. package/dist/parsers/build.js +0 -64
  46. package/dist/parsers/errors.js +0 -101
  47. package/dist/parsers/files.js +0 -78
  48. package/dist/parsers/git.js +0 -99
  49. package/dist/parsers/index.js +0 -48
  50. package/dist/parsers/tests.js +0 -89
  51. package/dist/providers/anthropic.js +0 -43
  52. package/dist/providers/base.js +0 -4
  53. package/dist/providers/cerebras.js +0 -8
  54. package/dist/providers/groq.js +0 -8
  55. package/dist/providers/index.js +0 -142
  56. package/dist/providers/openai-compat.js +0 -93
  57. package/dist/providers/xai.js +0 -8
  58. package/dist/recipes/model.js +0 -20
  59. package/dist/recipes/storage.js +0 -153
  60. package/dist/search/content-search.js +0 -70
  61. package/dist/search/file-search.js +0 -61
  62. package/dist/search/filters.js +0 -34
  63. package/dist/search/index.js +0 -5
  64. package/dist/search/semantic.js +0 -346
  65. package/dist/session-boot.js +0 -59
  66. package/dist/session-context.js +0 -55
  67. package/dist/sessions-db.js +0 -231
  68. package/dist/smart-display.js +0 -286
  69. package/dist/snapshots.js +0 -51
  70. package/dist/supervisor.js +0 -112
  71. package/dist/test-watchlist.js +0 -131
  72. package/dist/tokens.js +0 -17
  73. package/dist/tool-profiles.js +0 -129
  74. package/dist/tree.js +0 -94
  75. package/dist/usage-cache.js +0 -65
package/dist/ai.js DELETED
@@ -1,315 +0,0 @@
1
- import { cacheGet, cacheSet } from "./cache.js";
2
- import { getProvider } from "./providers/index.js";
3
- import { existsSync, readFileSync } from "fs";
4
- import { join } from "path";
5
- import { discoverProjectHints, discoverSafetyHints, formatHints } from "./context-hints.js";
6
- // ── model routing ─────────────────────────────────────────────────────────────
7
- // Config-driven model selection. Defaults per provider, user can override in ~/.terminal/config.json
8
- const COMPLEX_SIGNALS = [
9
- /\b(undo|revert|rollback|previous|last)\b/i,
10
- /\b(all files?|recursively|bulk|batch)\b/i,
11
- /\b(pipeline|chain|then|and then|after)\b/i,
12
- /\b(if|when|unless|only if)\b/i,
13
- /\b(go into|go to|navigate|cd into|enter)\b.*\b(and|then)\b/i,
14
- /\b(inside|within|under)\b/i,
15
- /[|&;]{2}/,
16
- ];
17
- /** Default models per provider — user can override in ~/.terminal/config.json under "models" */
18
- const MODEL_DEFAULTS = {
19
- cerebras: { fast: "qwen-3-235b-a22b-instruct-2507", smart: "qwen-3-235b-a22b-instruct-2507" },
20
- groq: { fast: "openai/gpt-oss-120b", smart: "moonshotai/kimi-k2-instruct" },
21
- xai: { fast: "grok-code-fast-1", smart: "grok-4-fast-non-reasoning" },
22
- anthropic: { fast: "claude-haiku-4-5-20251001", smart: "claude-sonnet-4-6" },
23
- };
24
- /** Load user model overrides from ~/.terminal/config.json (cached 30s) */
25
- let _modelOverrides = null;
26
- let _modelOverridesAt = 0;
27
- function loadModelOverrides() {
28
- const now = Date.now();
29
- if (_modelOverrides && now - _modelOverridesAt < 30_000)
30
- return _modelOverrides;
31
- try {
32
- const configPath = join(process.env.HOME ?? "~", ".terminal", "config.json");
33
- if (existsSync(configPath)) {
34
- const config = JSON.parse(readFileSync(configPath, "utf8"));
35
- _modelOverrides = config.models ?? {};
36
- _modelOverridesAt = now;
37
- return _modelOverrides;
38
- }
39
- }
40
- catch { }
41
- _modelOverrides = {};
42
- _modelOverridesAt = now;
43
- return _modelOverrides;
44
- }
45
- /** Model routing per provider — config-driven with defaults */
46
- function pickModel(nl) {
47
- const isComplex = COMPLEX_SIGNALS.some((r) => r.test(nl)) || nl.split(" ").length > 10;
48
- const provider = getProvider();
49
- const defaults = MODEL_DEFAULTS[provider.name] ?? MODEL_DEFAULTS.cerebras;
50
- const overrides = loadModelOverrides()[provider.name] ?? {};
51
- return {
52
- fast: overrides.fast ?? defaults.fast,
53
- smart: overrides.smart ?? defaults.smart,
54
- pick: isComplex ? "smart" : "fast",
55
- };
56
- }
57
- // ── irreversibility ───────────────────────────────────────────────────────────
58
- const IRREVERSIBLE_PATTERNS = [
59
- /\brm\s/, /\brmdir\b/, /\btruncate\b/, /\bdrop\s+table\b/i,
60
- /\bdelete\s+from\b/i, /\bmv\b.*\/dev\/null/, /\becho\b.*>\s*[^>]/, /\bcat\b.*>\s*[^>]/,
61
- /\bdd\b/, /\bmkfs\b/, /\bformat\b/, /\bshred\b/,
62
- // Process/service killing
63
- /\bkill\b/, /\bkillall\b/, /\bpkill\b/,
64
- // Git push/force operations
65
- /\bgit\s+push\b/, /\bgit\s+reset\s+--hard\b/, /\bgit\s+force\b/,
66
- // Code modification / package installation (security risk)
67
- /\bnpx\s+\S+/, /\bnpm\s+install\b/, /\bbun\s+add\b/, /\bpip\s+install\b/,
68
- /\bcodemod\b/, /\bsed\s+-i\b/, /\bawk\s.*>\s*\S+\.\w+/, /\bperl\s+-[pi]\b/,
69
- // File creation/modification (READ-ONLY terminal)
70
- /\btouch\b/, /\bmkdir\b/, /\becho\s.*>/, /\btee\b/, /\bcp\b/, /\bmv\b/,
71
- // Starting servers/processes (dangerous from NL)
72
- /\b(bun|npm|pnpm|yarn)\s+run\s+dev\b/, /\b(bun|npm)\s+start\b/,
73
- ];
74
- // Commands that are ALWAYS safe (read-only git, etc.)
75
- const SAFE_OVERRIDES = [
76
- /^\s*git\s+(log|show|diff|branch|status|blame|tag|remote|stash\s+list)\b/,
77
- /^\s*git\s+log\b/,
78
- // find -exec with read-only tools is safe
79
- /\bfind\b.*-exec\s+(wc|cat|head|tail|grep|stat|file|du|ls)\b/,
80
- // find without -exec is always safe
81
- /^\s*find\b(?!.*-exec\s+(rm|mv|chmod|chown|sed))/,
82
- // xargs with read-only tools is safe
83
- /\bxargs\s+(wc|cat|head|tail|grep|stat|file|du|ls|git\s+log|git\s+show|git\s+blame)\b/,
84
- /\bxargs\s+-I\s*\S+\s+(wc|cat|head|tail|grep|stat|git)\b/,
85
- ];
86
- export function isIrreversible(command) {
87
- // Safe overrides take priority
88
- if (SAFE_OVERRIDES.some((r) => r.test(command)))
89
- return false;
90
- return IRREVERSIBLE_PATTERNS.some((r) => r.test(command));
91
- }
92
- // ── permissions ───────────────────────────────────────────────────────────────
93
- const DESTRUCTIVE_PATTERNS = [/\brm\b/, /\brmdir\b/, /\btruncate\b/, /\bdrop\s+table\b/i, /\bdelete\s+from\b/i];
94
- const NETWORK_PATTERNS = [/\bcurl\b/, /\bwget\b/, /\bssh\b/, /\bscp\b/, /\bping\b/, /\bnc\b/, /\bnetcat\b/];
95
- const SUDO_PATTERNS = [/\bsudo\b/];
96
- const INSTALL_PATTERNS = [/\bbrew\s+install\b/, /\bnpm\s+install\s+-g\b/, /\bpip\s+install\b/, /\bapt\s+install\b/, /\byum\s+install\b/];
97
- const WRITE_OUTSIDE_PATTERNS = [/\s(\/etc|\/usr|\/var|\/opt|\/root|~\/[^.])/, />\s*\//];
98
- export function checkPermissions(command, perms) {
99
- if (!perms.destructive && DESTRUCTIVE_PATTERNS.some((r) => r.test(command)))
100
- return "destructive commands are disabled";
101
- if (!perms.network && NETWORK_PATTERNS.some((r) => r.test(command)))
102
- return "network commands are disabled";
103
- if (!perms.sudo && SUDO_PATTERNS.some((r) => r.test(command)))
104
- return "sudo is disabled";
105
- if (!perms.install && INSTALL_PATTERNS.some((r) => r.test(command)))
106
- return "package installation is disabled";
107
- if (!perms.write_outside_cwd && WRITE_OUTSIDE_PATTERNS.some((r) => r.test(command)))
108
- return "writing outside cwd is disabled";
109
- return null;
110
- }
111
- // ── correction memory ───────────────────────────────────────────────────────
112
- /** Load past corrections relevant to a prompt — injected as negative examples */
113
- function loadCorrectionHints(prompt) {
114
- try {
115
- // Dynamic import to avoid circular deps
116
- const { findSimilarCorrections } = require("./sessions-db.js");
117
- const corrections = findSimilarCorrections(prompt, 3);
118
- if (corrections.length === 0)
119
- return "";
120
- const lines = corrections.map((c) => `AVOID: "${c.failed_command}" (failed: ${c.error_type}). USE: "${c.corrected_command}" instead.`);
121
- return `\n\nLEARNED CORRECTIONS (from past failures):\n${lines.join("\n")}`;
122
- }
123
- catch {
124
- return "";
125
- }
126
- }
127
- // ── project context (powered by context-hints) ──────────────────────────────
128
- function detectProjectContext() {
129
- const hints = discoverProjectHints(process.cwd());
130
- return hints.length > 0 ? `\n\n${formatHints(hints)}` : "";
131
- }
132
- // ── system prompt ─────────────────────────────────────────────────────────────
133
- function buildSystemPrompt(perms, sessionEntries, currentPrompt) {
134
- const nl = currentPrompt?.toLowerCase() ?? "";
135
- const restrictions = [];
136
- if (!perms.destructive)
137
- restrictions.push("- NEVER generate commands that delete, remove, or overwrite files/data");
138
- if (!perms.network)
139
- restrictions.push("- NEVER generate commands that make network requests (curl, wget, ssh, etc.)");
140
- if (!perms.sudo)
141
- restrictions.push("- NEVER generate commands requiring sudo");
142
- if (!perms.write_outside_cwd)
143
- restrictions.push("- NEVER write to paths outside the current working directory");
144
- if (!perms.install)
145
- restrictions.push("- NEVER install packages (brew, npm -g, pip, apt, etc.)");
146
- const restrictionBlock = restrictions.length > 0
147
- ? `\n\nRESTRICTIONS:\n${restrictions.join("\n")}\nIf restricted, output: BLOCKED: <reason>`
148
- : "";
149
- let contextBlock = "";
150
- if (sessionEntries.length > 0) {
151
- const lines = [];
152
- for (const e of sessionEntries.slice(-5)) {
153
- lines.push(`> ${e.nl}`);
154
- lines.push(`$ ${e.cmd}`);
155
- if (e.output)
156
- lines.push(e.output);
157
- if (e.error)
158
- lines.push("(command failed)");
159
- }
160
- contextBlock = `\n\nSESSION HISTORY (user intent > command $ output):\n${lines.join("\n")}`;
161
- }
162
- const projectContext = detectProjectContext();
163
- const safetyBlock = sessionEntries.length > 0
164
- ? (() => {
165
- const lastCmd = sessionEntries[sessionEntries.length - 1]?.cmd;
166
- if (lastCmd) {
167
- const safetyHints = discoverSafetyHints(lastCmd);
168
- return safetyHints.length > 0 ? `\n\nLAST COMMAND SAFETY:\n${safetyHints.join("\n")}` : "";
169
- }
170
- return "";
171
- })()
172
- : "";
173
- // ── Conditional sections (only included when relevant) ──
174
- const wantsStructure = /\b(function|class|interface|export|symbol|structure|hierarchy|outline)\b/i.test(nl);
175
- const astBlock = wantsStructure ? `\nAST-POWERED QUERIES: For code STRUCTURE questions, use "terminal symbols" instead of grep. It uses AST parsing for TypeScript, Python, Go, Rust.` : "";
176
- const wantsMultiple = /\b(and|both|also|plus|as well)\b/i.test(nl);
177
- const compoundBlock = wantsMultiple ? `\nCOMPOUND QUESTIONS: Prefer ONE command that captures all info. NEVER split into separate expensive commands.` : "";
178
- const wantsAnalysis = /\b(quality|lint|coverage|complexity|unused|dead code|security|audit|scan|dependency)\b/i.test(nl);
179
- const blockedAltBlock = wantsAnalysis ? `\nBLOCKED ALTERNATIVES: If your preferred command needs installing packages, try READ-ONLY alternatives (grep, cat, wc, awk). NEVER give up on analysis questions.` : "";
180
- return `Translate to bash. One command. Simplest form. No explanation.
181
-
182
- list files in current directory → ls
183
- list all files including hidden → ls -a
184
- show open files → lsof
185
- create copy of a.txt as b.txt → cp a.txt b.txt
186
- create file test.txt → touch test.txt
187
- make directory testdir → mkdir testdir
188
- display routing table → route
189
- show last logged in users → last
190
- show file stats → stat file
191
- print directory tree 2 levels → tree -L 2
192
- count word occurrences in file → grep -c "word" file
193
- print number of files in dir → ls -1 | wc -l
194
- print first line of file → head -1 file
195
- print last line of file → tail -1 file
196
- print lines 3 to 5 of file → sed -n '3,5p' file
197
- print every other line → awk 'NR%2==1' file
198
- count words in file → wc -w file
199
- find empty files not in subdirs → find . -maxdepth 1 -type f -empty
200
- show system load → w
201
- system utilization stats → vmstat
202
- DNS servers → cat /etc/resolv.conf | grep nameserver
203
- long integer size → getconf LONG_BIT
204
- base64 decode string → echo 'str' | base64 -d
205
- change owner to nobody → chown nobody file
206
- unique lines in file → uniq file
207
- max cpu time → ulimit -t
208
- memory info → lsmem
209
- process priority → nice
210
- bash profile → cat ~/.bashrc
211
- search recursively → grep -rn "pattern" src/
212
- ${astBlock}${compoundBlock}${blockedAltBlock}
213
- cwd: ${process.cwd()}
214
- shell: zsh / macOS${projectContext}${safetyBlock}${restrictionBlock}${contextBlock}${currentPrompt ? loadCorrectionHints(currentPrompt) : ""}
215
-
216
- Q:`;
217
- }
218
- // ── streaming translate ───────────────────────────────────────────────────────
219
- export async function translateToCommand(nl, perms, sessionEntries, onToken) {
220
- // Only use cache when there's no session context (context makes same NL produce different commands)
221
- if (sessionEntries.length === 0) {
222
- const cached = cacheGet(nl);
223
- if (cached) {
224
- onToken?.(cached);
225
- return cached;
226
- }
227
- }
228
- const provider = getProvider();
229
- const routing = pickModel(nl);
230
- const model = routing.pick === "smart" ? routing.smart : routing.fast;
231
- const system = buildSystemPrompt(perms, sessionEntries, nl);
232
- let text;
233
- if (onToken) {
234
- text = await provider.stream(nl, { model, maxTokens: 256, temperature: 0, stop: ["\n"], system }, {
235
- onToken: (partial) => onToken(partial),
236
- });
237
- }
238
- else {
239
- text = await provider.complete(nl, { model, maxTokens: 256, temperature: 0, stop: ["\n"], system });
240
- }
241
- if (text.startsWith("BLOCKED:"))
242
- throw new Error(text);
243
- // Strip AI reasoning — extract ONLY the shell command (first line)
244
- let cleaned = text.trim();
245
- // Remove ALL markdown code blocks and their content markers
246
- cleaned = cleaned.replace(/```(?:bash|sh|shell)?\n?/g, "").replace(/```/g, "");
247
- // Split into lines and find the FIRST one that looks like a SHELL COMMAND
248
- const lines = cleaned.split("\n");
249
- let command = "";
250
- for (const line of lines) {
251
- const t = line.trim();
252
- if (!t)
253
- continue;
254
- // Skip lines that are clearly English prose, not commands
255
- if (/^(Based on|I |This |The |Let me|Here|Note:|Since|Looking|To |However|BLOCKED:|If |You |We |For |It |A |An |That )/.test(t))
256
- continue;
257
- if (/^[A-Z][a-z].*[.;:!?,]/.test(t))
258
- continue; // English sentence with punctuation anywhere
259
- if (t.split(" ").length > 15 && !/[|&;><$]/.test(t))
260
- continue; // Long line without shell operators = prose
261
- // Must start with a plausible command character (lowercase, /, ., $, or common tool)
262
- if (/^[a-z./$~(]/.test(t) || /^[A-Z]+[_=]/.test(t)) {
263
- command = t;
264
- break;
265
- }
266
- }
267
- cleaned = command || lines[0]?.trim() || cleaned;
268
- cacheSet(nl, cleaned);
269
- return cleaned;
270
- }
271
- // ── prefetch ──────────────────────────────────────────────────────────────────
272
- export function prefetchNext(lastNl, perms, sessionEntries) {
273
- if (sessionEntries.length === 0 && cacheGet(lastNl))
274
- return;
275
- translateToCommand(lastNl, perms, sessionEntries).catch(() => { });
276
- }
277
- // ── explain ───────────────────────────────────────────────────────────────────
278
- export async function explainCommand(command) {
279
- const provider = getProvider();
280
- const routing = pickModel("explain"); // simple = fast model
281
- return provider.complete(command, {
282
- model: routing.fast,
283
- maxTokens: 128,
284
- temperature: 0,
285
- system: "Explain what this shell command does in one plain English sentence. No markdown, no code blocks.",
286
- });
287
- }
288
- // ── auto-fix ──────────────────────────────────────────────────────────────────
289
- export async function fixCommand(originalNl, failedCommand, errorOutput, perms, _sessionEntries) {
290
- const provider = getProvider();
291
- const routing = pickModel(originalNl);
292
- // Lightweight fix prompt — no full project context, just rules + restrictions
293
- const restrictions = [];
294
- if (!perms.destructive)
295
- restrictions.push("- NEVER delete/remove/overwrite files");
296
- if (!perms.network)
297
- restrictions.push("- NEVER make network requests");
298
- if (!perms.install)
299
- restrictions.push("- NEVER install packages");
300
- const fixSystem = `You are a terminal assistant. Output ONLY the corrected shell command — no explanation.
301
- macOS/BSD tools. NEVER use grep -P. Use grep -E for extended regex.
302
- NEVER install packages. READ-ONLY terminal.
303
- cwd: ${process.cwd()}${restrictions.length > 0 ? `\nRESTRICTIONS:\n${restrictions.join("\n")}` : ""}`;
304
- const text = await provider.complete(`I wanted to: ${originalNl}\nI ran: ${failedCommand}\nError:\n${errorOutput.slice(0, 2000)}\n\nGive me the corrected command only.`, {
305
- model: routing.smart,
306
- maxTokens: 256,
307
- temperature: 0,
308
- stop: ["\n"],
309
- system: fixSystem,
310
- });
311
- if (text.startsWith("BLOCKED:"))
312
- throw new Error(text);
313
- return text.trim();
314
- }
315
- // summarizeOutput() removed — all output processing goes through processOutput() in output-processor.ts
package/dist/cache.js DELETED
@@ -1,42 +0,0 @@
1
- // In-memory LRU cache + disk persistence for command translations
2
- import { existsSync, readFileSync, writeFileSync } from "fs";
3
- import { homedir } from "os";
4
- import { join } from "path";
5
- const CACHE_FILE = join(homedir(), ".terminal", "cache.json");
6
- const MAX_ENTRIES = 500;
7
- let mem = {};
8
- export function loadCache() {
9
- if (!existsSync(CACHE_FILE))
10
- return;
11
- try {
12
- mem = JSON.parse(readFileSync(CACHE_FILE, "utf8"));
13
- }
14
- catch { }
15
- }
16
- function persistCache() {
17
- try {
18
- writeFileSync(CACHE_FILE, JSON.stringify(mem));
19
- }
20
- catch { }
21
- }
22
- /** Normalize a natural language query for cache lookup.
23
- * Keeps . / - _ which are meaningful in file paths and shell context. */
24
- export function normalizeNl(nl) {
25
- return nl
26
- .toLowerCase()
27
- .trim()
28
- .replace(/[^a-z0-9\s.\/_-]/g, "") // keep meaningful shell chars
29
- .replace(/\s+/g, " ");
30
- }
31
- export function cacheGet(nl) {
32
- return mem[normalizeNl(nl)] ?? null;
33
- }
34
- export function cacheSet(nl, command) {
35
- const key = normalizeNl(nl);
36
- // evict oldest if full
37
- const keys = Object.keys(mem);
38
- if (keys.length >= MAX_ENTRIES)
39
- delete mem[keys[0]];
40
- mem[key] = command;
41
- persistCache();
42
- }