@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
@@ -1,346 +0,0 @@
1
- // Semantic code search — AST-powered search that understands code structure
2
- // Instead of raw grep, searches by meaning: "find auth functions" → login(), verifyToken()
3
- import { spawn } from "child_process";
4
- import { readFileSync, existsSync } from "fs";
5
- import { join } from "path";
6
- function exec(command, cwd) {
7
- return new Promise((resolve) => {
8
- const proc = spawn("/bin/zsh", ["-c", command], { cwd, stdio: ["ignore", "pipe", "pipe"] });
9
- let out = "";
10
- proc.stdout?.on("data", (d) => { out += d.toString(); });
11
- proc.stderr?.on("data", (d) => { });
12
- proc.on("close", () => resolve(out));
13
- });
14
- }
15
- /** Extract code symbols from a TypeScript/JavaScript file using regex-based parsing */
16
- export function extractSymbolsFromFile(filePath) {
17
- return extractSymbols(filePath);
18
- }
19
- /** Extract the complete code block for a symbol by name */
20
- export function extractBlock(filePath, symbolName) {
21
- if (!existsSync(filePath))
22
- return null;
23
- const content = readFileSync(filePath, "utf8");
24
- const lines = content.split("\n");
25
- const symbols = extractSymbols(filePath);
26
- const symbol = symbols.find(s => s.name === symbolName && s.kind !== "import");
27
- if (!symbol)
28
- return null;
29
- const startLine = symbol.line - 1; // 0-indexed
30
- let braceDepth = 0;
31
- let foundOpen = false;
32
- let endLine = startLine;
33
- for (let i = startLine; i < lines.length; i++) {
34
- const line = lines[i];
35
- for (const ch of line) {
36
- if (ch === "{") {
37
- braceDepth++;
38
- foundOpen = true;
39
- }
40
- if (ch === "}") {
41
- braceDepth--;
42
- }
43
- }
44
- endLine = i;
45
- if (foundOpen && braceDepth <= 0)
46
- break;
47
- // For single-line arrow functions without braces
48
- if (i === startLine && !line.includes("{") && line.includes("=>"))
49
- break;
50
- }
51
- return {
52
- code: lines.slice(startLine, endLine + 1).join("\n"),
53
- startLine: startLine + 1, // 1-indexed
54
- endLine: endLine + 1,
55
- };
56
- }
57
- function extractSymbols(filePath) {
58
- if (!existsSync(filePath))
59
- return [];
60
- const content = readFileSync(filePath, "utf8");
61
- const lines = content.split("\n");
62
- const symbols = [];
63
- const file = filePath;
64
- const ext = filePath.match(/\.(\w+)$/)?.[1] ?? "";
65
- // Python support
66
- if (ext === "py") {
67
- for (let i = 0; i < lines.length; i++) {
68
- const line = lines[i];
69
- const defMatch = line.match(/^(\s*)(?:async\s+)?def\s+(\w+)\s*\(/);
70
- if (defMatch) {
71
- symbols.push({ name: defMatch[2], kind: "function", file, line: i + 1, signature: line.trim(), exported: !defMatch[2].startsWith("_") });
72
- }
73
- const classMatch = line.match(/^class\s+(\w+)/);
74
- if (classMatch) {
75
- symbols.push({ name: classMatch[1], kind: "class", file, line: i + 1, signature: line.trim(), exported: true });
76
- }
77
- }
78
- return symbols;
79
- }
80
- // Go support
81
- if (ext === "go") {
82
- for (let i = 0; i < lines.length; i++) {
83
- const line = lines[i];
84
- const funcMatch = line.match(/^func\s+(?:\(\w+\s+\*?\w+\)\s+)?(\w+)\s*\(/);
85
- if (funcMatch) {
86
- symbols.push({ name: funcMatch[1], kind: "function", file, line: i + 1, signature: line.trim(), exported: /^[A-Z]/.test(funcMatch[1]) });
87
- }
88
- const typeMatch = line.match(/^type\s+(\w+)\s+(struct|interface)/);
89
- if (typeMatch) {
90
- symbols.push({ name: typeMatch[1], kind: typeMatch[2] === "interface" ? "interface" : "class", file, line: i + 1, signature: line.trim(), exported: /^[A-Z]/.test(typeMatch[1]) });
91
- }
92
- }
93
- return symbols;
94
- }
95
- // Rust support
96
- if (ext === "rs") {
97
- for (let i = 0; i < lines.length; i++) {
98
- const line = lines[i];
99
- const fnMatch = line.match(/^\s*(?:pub\s+)?(?:async\s+)?fn\s+(\w+)/);
100
- if (fnMatch) {
101
- symbols.push({ name: fnMatch[1], kind: "function", file, line: i + 1, signature: line.trim(), exported: line.includes("pub") });
102
- }
103
- const structMatch = line.match(/^\s*(?:pub\s+)?struct\s+(\w+)/);
104
- if (structMatch) {
105
- symbols.push({ name: structMatch[1], kind: "class", file, line: i + 1, signature: line.trim(), exported: line.includes("pub") });
106
- }
107
- const enumMatch = line.match(/^\s*(?:pub\s+)?enum\s+(\w+)/);
108
- if (enumMatch) {
109
- symbols.push({ name: enumMatch[1], kind: "type", file, line: i + 1, signature: line.trim(), exported: line.includes("pub") });
110
- }
111
- const traitMatch = line.match(/^\s*(?:pub\s+)?trait\s+(\w+)/);
112
- if (traitMatch) {
113
- symbols.push({ name: traitMatch[1], kind: "interface", file, line: i + 1, signature: line.trim(), exported: line.includes("pub") });
114
- }
115
- }
116
- return symbols;
117
- }
118
- // TypeScript/JavaScript (default)
119
- for (let i = 0; i < lines.length; i++) {
120
- const line = lines[i];
121
- const lineNum = i + 1;
122
- const isExported = line.trimStart().startsWith("export");
123
- // Functions: export function X(...) or export const X = (...) =>
124
- const funcMatch = line.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)\s*\(/);
125
- if (funcMatch) {
126
- const prevLine = i > 0 ? lines[i - 1] : "";
127
- const doc = prevLine.trim().startsWith("/**") || prevLine.trim().startsWith("//")
128
- ? prevLine.trim().replace(/^\/\*\*\s*|\s*\*\/$/g, "").replace(/^\/\/\s*/, "")
129
- : undefined;
130
- symbols.push({
131
- name: funcMatch[1], kind: "function", file, line: lineNum,
132
- signature: line.trim().replace(/\{.*$/, "").trim(),
133
- exported: isExported, doc,
134
- });
135
- continue;
136
- }
137
- // Arrow functions: export const X = (...) =>
138
- const arrowMatch = line.match(/(?:export\s+)?(?:const|let)\s+(\w+)\s*=\s*(?:async\s+)?\(([^)]*)\)\s*(?::\s*\w[^=]*)?\s*=>/);
139
- if (arrowMatch) {
140
- // Detect React hooks
141
- const isHook = arrowMatch[1].startsWith("use");
142
- const isComponent = /^[A-Z]/.test(arrowMatch[1]);
143
- symbols.push({
144
- name: arrowMatch[1],
145
- kind: isHook ? "hook" : isComponent ? "component" : "function",
146
- file, line: lineNum,
147
- signature: line.trim().replace(/\{.*$/, "").replace(/=>.*$/, "=>").trim(),
148
- exported: isExported,
149
- });
150
- continue;
151
- }
152
- // Classes — also extract methods inside the class body
153
- const classMatch = line.match(/(?:export\s+)?class\s+(\w+)(?:\s+extends\s+(\w+))?/);
154
- if (classMatch) {
155
- const className = classMatch[1];
156
- symbols.push({
157
- name: className, kind: "class", file, line: lineNum,
158
- signature: line.trim().replace(/\{.*$/, "").trim(),
159
- exported: isExported,
160
- });
161
- // Walk class body to find methods
162
- let braceDepth = 0;
163
- for (let j = i; j < lines.length; j++) {
164
- for (const ch of lines[j]) {
165
- if (ch === "{")
166
- braceDepth++;
167
- if (ch === "}")
168
- braceDepth--;
169
- }
170
- if (j > i) {
171
- const memberLine = lines[j];
172
- // Class methods: async methodName(...), methodName(...), get/set name(...)
173
- const methodMatch = memberLine.match(/^\s+(?:async\s+)?(?:(?:public|private|protected|static|readonly|override|abstract)\s+)*(?:get\s+|set\s+)?(\w+)\s*[\(<]/);
174
- const RESERVED = new Set(["if", "for", "while", "switch", "catch", "return", "throw", "new", "delete", "typeof", "void", "yield", "await", "try", "else"]);
175
- if (methodMatch && !RESERVED.has(methodMatch[1])) {
176
- symbols.push({
177
- name: `${className}.${methodMatch[1]}`, kind: "function", file, line: j + 1,
178
- signature: memberLine.trim().replace(/\{.*$/, "").trim(),
179
- exported: isExported,
180
- });
181
- }
182
- }
183
- if (braceDepth === 0 && j > i)
184
- break; // end of class
185
- }
186
- continue;
187
- }
188
- // Interfaces
189
- const ifaceMatch = line.match(/(?:export\s+)?interface\s+(\w+)/);
190
- if (ifaceMatch) {
191
- symbols.push({
192
- name: ifaceMatch[1], kind: "interface", file, line: lineNum,
193
- signature: line.trim().replace(/\{.*$/, "").trim(),
194
- exported: isExported,
195
- });
196
- continue;
197
- }
198
- // Type aliases
199
- const typeMatch = line.match(/(?:export\s+)?type\s+(\w+)\s*=/);
200
- if (typeMatch) {
201
- symbols.push({
202
- name: typeMatch[1], kind: "type", file, line: lineNum,
203
- signature: line.trim(),
204
- exported: isExported,
205
- });
206
- continue;
207
- }
208
- // Imports (for dependency tracking)
209
- const importMatch = line.match(/import\s+(?:\{([^}]+)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/);
210
- if (importMatch) {
211
- const names = importMatch[1]
212
- ? importMatch[1].split(",").map(s => s.trim().split(" as ")[0].trim())
213
- : [importMatch[2]];
214
- for (const name of names) {
215
- if (name) {
216
- symbols.push({
217
- name, kind: "import", file, line: lineNum,
218
- signature: `from '${importMatch[3]}'`,
219
- exported: false,
220
- });
221
- }
222
- }
223
- continue;
224
- }
225
- // Exported constants/variables
226
- const constMatch = line.match(/export\s+const\s+(\w+)\s*[=:]/);
227
- if (constMatch && !arrowMatch) {
228
- symbols.push({
229
- name: constMatch[1], kind: "variable", file, line: lineNum,
230
- signature: line.trim().slice(0, 80),
231
- exported: true,
232
- });
233
- }
234
- }
235
- return symbols;
236
- }
237
- /** Find all source files in a directory */
238
- async function findSourceFiles(cwd, maxFiles = 200) {
239
- const excludes = ["node_modules", ".git", "dist", "build", ".next", "coverage", "__pycache__"];
240
- const excludeArgs = excludes.map(d => `-not -path '*/${d}/*'`).join(" ");
241
- const extensions = "\\( -name '*.ts' -o -name '*.tsx' -o -name '*.js' -o -name '*.jsx' \\)";
242
- const cmd = `find . ${extensions} ${excludeArgs} -type f 2>/dev/null | head -${maxFiles}`;
243
- const output = await exec(cmd, cwd);
244
- return output.split("\n").filter(l => l.trim()).map(l => join(cwd, l.trim()));
245
- }
246
- /** Semantic search: find symbols matching a natural language query */
247
- export async function semanticSearch(query, cwd, options = {}) {
248
- const { kinds, exportedOnly = false, maxResults = 30 } = options;
249
- // Find all source files
250
- const files = await findSourceFiles(cwd);
251
- // Extract symbols from all files
252
- let allSymbols = [];
253
- for (const file of files) {
254
- try {
255
- allSymbols.push(...extractSymbols(file));
256
- }
257
- catch { /* skip unreadable files */ }
258
- }
259
- // Filter by kind
260
- if (kinds) {
261
- allSymbols = allSymbols.filter(s => kinds.includes(s.kind));
262
- }
263
- // Filter by exported
264
- if (exportedOnly) {
265
- allSymbols = allSymbols.filter(s => s.exported);
266
- }
267
- // Score each symbol against the query
268
- const queryLower = query.toLowerCase();
269
- const queryWords = queryLower.split(/\s+/).filter(w => w.length > 2);
270
- const scored = allSymbols.map(symbol => {
271
- let score = 0;
272
- const nameLower = symbol.name.toLowerCase();
273
- const sigLower = (symbol.signature ?? "").toLowerCase();
274
- const fileLower = symbol.file.toLowerCase();
275
- // Exact name match
276
- if (queryWords.some(w => nameLower === w))
277
- score += 10;
278
- // Name contains query word
279
- if (queryWords.some(w => nameLower.includes(w)))
280
- score += 5;
281
- // Signature contains query word
282
- if (queryWords.some(w => sigLower.includes(w)))
283
- score += 3;
284
- // File path contains query word
285
- if (queryWords.some(w => fileLower.includes(w)))
286
- score += 2;
287
- // Doc contains query word
288
- if (symbol.doc && queryWords.some(w => symbol.doc.toLowerCase().includes(w)))
289
- score += 4;
290
- // Boost exported symbols
291
- if (symbol.exported)
292
- score += 1;
293
- // Boost functions/classes over imports
294
- if (symbol.kind === "function" || symbol.kind === "class")
295
- score += 1;
296
- // Semantic matching for common patterns
297
- if (queryLower.includes("component") && symbol.kind === "component")
298
- score += 5;
299
- if (queryLower.includes("hook") && symbol.kind === "hook")
300
- score += 5;
301
- if (queryLower.includes("type") && (symbol.kind === "type" || symbol.kind === "interface"))
302
- score += 5;
303
- if (queryLower.includes("import") && symbol.kind === "import")
304
- score += 5;
305
- if (queryLower.includes("class") && symbol.kind === "class")
306
- score += 5;
307
- return { symbol, score };
308
- });
309
- // Sort by score, filter zero scores
310
- const results = scored
311
- .filter(s => s.score > 0)
312
- .sort((a, b) => b.score - a.score)
313
- .slice(0, maxResults)
314
- .map(s => s.symbol);
315
- // Make file paths relative
316
- for (const r of results) {
317
- if (r.file.startsWith(cwd)) {
318
- r.file = "." + r.file.slice(cwd.length);
319
- }
320
- }
321
- // Estimate token savings
322
- const rawGrep = await exec(`grep -rn '${queryWords[0] ?? query}' . --include='*.ts' --include='*.tsx' 2>/dev/null | head -100`, cwd);
323
- const rawTokens = Math.ceil(rawGrep.length / 4);
324
- const resultTokens = Math.ceil(JSON.stringify(results).length / 4);
325
- return {
326
- query,
327
- symbols: results,
328
- totalFiles: files.length,
329
- tokensSaved: Math.max(0, rawTokens - resultTokens),
330
- };
331
- }
332
- /** Quick helper: find all exported functions */
333
- export async function findExports(cwd) {
334
- const result = await semanticSearch("export", cwd, { exportedOnly: true, maxResults: 100 });
335
- return result.symbols;
336
- }
337
- /** Quick helper: find all React components */
338
- export async function findComponents(cwd) {
339
- const result = await semanticSearch("component", cwd, { kinds: ["component"], maxResults: 50 });
340
- return result.symbols;
341
- }
342
- /** Quick helper: find all hooks */
343
- export async function findHooks(cwd) {
344
- const result = await semanticSearch("hook", cwd, { kinds: ["hook"], maxResults: 50 });
345
- return result.symbols;
346
- }
@@ -1,59 +0,0 @@
1
- // Session boot cache — precompute common data on first MCP call
2
- // Agents always start with git status + file tree + package.json — do it once
3
- import { spawn } from "child_process";
4
- import { existsSync, readFileSync } from "fs";
5
- import { join } from "path";
6
- let bootCache = null;
7
- let bootCwd = "";
8
- function exec(command, cwd) {
9
- return new Promise((resolve) => {
10
- const proc = spawn("/bin/zsh", ["-c", command], { cwd, stdio: ["ignore", "pipe", "pipe"] });
11
- let out = "";
12
- proc.stdout?.on("data", (d) => { out += d.toString(); });
13
- proc.on("close", () => resolve(out.trim()));
14
- });
15
- }
16
- /** Get or build session boot context */
17
- export async function getBootContext(cwd) {
18
- if (bootCache && bootCwd === cwd)
19
- return bootCache;
20
- const [branch, status, log, srcLs] = await Promise.all([
21
- exec("git branch --show-current 2>/dev/null", cwd),
22
- exec("git status --porcelain 2>/dev/null", cwd),
23
- exec("git log --oneline -8 2>/dev/null", cwd),
24
- exec("ls -1 src/ 2>/dev/null || ls -1 lib/ 2>/dev/null || echo ''", cwd),
25
- ]);
26
- let pkg = null;
27
- const pkgPath = join(cwd, "package.json");
28
- if (existsSync(pkgPath)) {
29
- try {
30
- pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
31
- }
32
- catch { }
33
- }
34
- bootCache = {
35
- cwd,
36
- git: {
37
- branch: branch || null,
38
- dirty: status.length > 0,
39
- changedFiles: status.split("\n").filter(l => l.trim()).length,
40
- recentCommits: log.split("\n").filter(l => l.trim()).slice(0, 5).map(l => {
41
- const m = l.match(/^([a-f0-9]+)\s+(.+)$/);
42
- return m ? { hash: m[1], message: m[2] } : null;
43
- }).filter(Boolean),
44
- },
45
- project: pkg ? {
46
- name: pkg.name,
47
- version: pkg.version,
48
- scripts: pkg.scripts ? Object.keys(pkg.scripts) : [],
49
- deps: pkg.dependencies ? Object.keys(pkg.dependencies).length : 0,
50
- } : null,
51
- sourceFiles: srcLs.split("\n").filter(l => l.trim()),
52
- };
53
- bootCwd = cwd;
54
- return bootCache;
55
- }
56
- /** Invalidate boot cache (call after git operations or file changes) */
57
- export function invalidateBootCache() {
58
- bootCache = null;
59
- }
@@ -1,55 +0,0 @@
1
- // Session context — stores last N command+output pairs for follow-up queries
2
- // Enables: terminal "show auth code" → terminal "explain that function"
3
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
4
- import { homedir } from "os";
5
- import { join } from "path";
6
- const DIR = join(homedir(), ".terminal");
7
- const CTX_FILE = join(DIR, "session-context.json");
8
- const MAX_ENTRIES = 5;
9
- function ensureDir() {
10
- if (!existsSync(DIR))
11
- mkdirSync(DIR, { recursive: true });
12
- }
13
- /** Load session context */
14
- export function loadContext() {
15
- ensureDir();
16
- if (!existsSync(CTX_FILE))
17
- return [];
18
- try {
19
- const entries = JSON.parse(readFileSync(CTX_FILE, "utf8"));
20
- // Only return entries from last 30 minutes (session freshness)
21
- const cutoff = Date.now() - 30 * 60 * 1000;
22
- return entries.filter(e => e.timestamp > cutoff).slice(-MAX_ENTRIES);
23
- }
24
- catch {
25
- return [];
26
- }
27
- }
28
- /** Save a command to session context */
29
- export function saveContext(prompt, command, output) {
30
- ensureDir();
31
- const entries = loadContext();
32
- entries.push({
33
- prompt,
34
- command,
35
- output: output.slice(0, 500),
36
- timestamp: Date.now(),
37
- });
38
- // Keep only last N
39
- const trimmed = entries.slice(-MAX_ENTRIES);
40
- writeFileSync(CTX_FILE, JSON.stringify(trimmed, null, 2));
41
- }
42
- /** Format context for AI prompt injection */
43
- export function formatContext() {
44
- const entries = loadContext();
45
- if (entries.length === 0)
46
- return "";
47
- const lines = ["\nRECENT SESSION CONTEXT (for follow-up references like 'that', 'it', 'the same'):"];
48
- for (const e of entries.slice(-3)) {
49
- lines.push(`> ${e.prompt}`);
50
- lines.push(`$ ${e.command}`);
51
- if (e.output)
52
- lines.push(e.output.slice(0, 200));
53
- }
54
- return lines.join("\n");
55
- }