@hasna/terminal 2.3.1 → 3.0.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 (99) hide show
  1. package/dist/App.js +404 -0
  2. package/dist/Browse.js +79 -0
  3. package/dist/FuzzyPicker.js +47 -0
  4. package/dist/Onboarding.js +51 -0
  5. package/dist/Spinner.js +12 -0
  6. package/dist/StatusBar.js +49 -0
  7. package/dist/ai.js +296 -0
  8. package/dist/cache.js +42 -0
  9. package/dist/cli.js +1 -1
  10. package/dist/command-rewriter.js +64 -0
  11. package/dist/command-validator.js +86 -0
  12. package/dist/compression.js +85 -0
  13. package/dist/context-hints.js +285 -0
  14. package/dist/diff-cache.js +107 -0
  15. package/dist/discover.js +212 -0
  16. package/dist/economy.js +155 -0
  17. package/dist/expand-store.js +44 -0
  18. package/dist/file-cache.js +72 -0
  19. package/dist/file-index.js +62 -0
  20. package/dist/history.js +62 -0
  21. package/dist/lazy-executor.js +54 -0
  22. package/dist/line-dedup.js +59 -0
  23. package/dist/loop-detector.js +75 -0
  24. package/dist/mcp/install.js +98 -0
  25. package/dist/mcp/server.js +545 -0
  26. package/dist/noise-filter.js +86 -0
  27. package/dist/output-processor.js +132 -0
  28. package/dist/output-router.js +41 -0
  29. package/dist/output-store.js +111 -0
  30. package/dist/parsers/base.js +2 -0
  31. package/dist/parsers/build.js +64 -0
  32. package/dist/parsers/errors.js +101 -0
  33. package/dist/parsers/files.js +78 -0
  34. package/dist/parsers/git.js +99 -0
  35. package/dist/parsers/index.js +48 -0
  36. package/dist/parsers/tests.js +89 -0
  37. package/dist/providers/anthropic.js +43 -0
  38. package/dist/providers/base.js +4 -0
  39. package/dist/providers/cerebras.js +8 -0
  40. package/dist/providers/groq.js +8 -0
  41. package/dist/providers/index.js +122 -0
  42. package/dist/providers/openai-compat.js +93 -0
  43. package/dist/providers/xai.js +8 -0
  44. package/dist/recipes/model.js +20 -0
  45. package/dist/recipes/storage.js +136 -0
  46. package/dist/search/content-search.js +68 -0
  47. package/dist/search/file-search.js +61 -0
  48. package/dist/search/filters.js +34 -0
  49. package/dist/search/index.js +5 -0
  50. package/dist/search/semantic.js +320 -0
  51. package/dist/session-boot.js +59 -0
  52. package/dist/session-context.js +55 -0
  53. package/dist/sessions-db.js +173 -0
  54. package/dist/smart-display.js +286 -0
  55. package/dist/snapshots.js +51 -0
  56. package/dist/supervisor.js +112 -0
  57. package/dist/test-watchlist.js +131 -0
  58. package/dist/tokens.js +17 -0
  59. package/dist/tool-profiles.js +129 -0
  60. package/dist/tree.js +94 -0
  61. package/dist/usage-cache.js +65 -0
  62. package/package.json +8 -1
  63. package/src/ai.ts +60 -90
  64. package/src/cache.ts +3 -2
  65. package/src/cli.tsx +1 -1
  66. package/src/compression.ts +8 -35
  67. package/src/context-hints.ts +20 -10
  68. package/src/diff-cache.ts +1 -1
  69. package/src/discover.ts +1 -1
  70. package/src/economy.ts +37 -5
  71. package/src/expand-store.ts +8 -1
  72. package/src/mcp/server.ts +45 -73
  73. package/src/output-processor.ts +11 -8
  74. package/src/providers/anthropic.ts +6 -2
  75. package/src/providers/base.ts +2 -0
  76. package/src/providers/cerebras.ts +6 -105
  77. package/src/providers/groq.ts +6 -105
  78. package/src/providers/index.ts +84 -33
  79. package/src/providers/openai-compat.ts +109 -0
  80. package/src/providers/xai.ts +6 -105
  81. package/src/tokens.ts +18 -0
  82. package/src/tool-profiles.ts +9 -2
  83. package/.claude/scheduled_tasks.lock +0 -1
  84. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -20
  85. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -14
  86. package/CONTRIBUTING.md +0 -80
  87. package/benchmarks/benchmark.mjs +0 -115
  88. package/imported_modules.txt +0 -0
  89. package/src/compression.test.ts +0 -49
  90. package/src/output-router.ts +0 -56
  91. package/src/parsers/base.ts +0 -72
  92. package/src/parsers/build.ts +0 -73
  93. package/src/parsers/errors.ts +0 -107
  94. package/src/parsers/files.ts +0 -91
  95. package/src/parsers/git.ts +0 -101
  96. package/src/parsers/index.ts +0 -66
  97. package/src/parsers/parsers.test.ts +0 -153
  98. package/src/parsers/tests.ts +0 -98
  99. package/tsconfig.json +0 -15
@@ -0,0 +1,34 @@
1
+ // Smart filters for search results — auto-hide noise, prioritize source files
2
+ export const DEFAULT_EXCLUDE_DIRS = [
3
+ "node_modules", ".git", "dist", "build", ".next", "__pycache__",
4
+ "coverage", ".turbo", ".cache", ".output", "vendor", "target",
5
+ ];
6
+ export const SOURCE_EXTENSIONS = new Set([
7
+ ".ts", ".tsx", ".js", ".jsx", ".py", ".go", ".rs", ".java", ".rb",
8
+ ".sh", ".c", ".cpp", ".h", ".css", ".scss", ".html", ".vue", ".svelte",
9
+ ".md", ".json", ".yaml", ".yml", ".toml", ".sql", ".graphql",
10
+ ]);
11
+ export const CONFIG_EXTENSIONS = new Set([
12
+ ".json", ".yaml", ".yml", ".toml", ".ini", ".env", ".config.js",
13
+ ".config.ts", ".config.mjs",
14
+ ]);
15
+ export function isSourceFile(path) {
16
+ const ext = path.match(/\.\w+$/)?.[0] ?? "";
17
+ return SOURCE_EXTENSIONS.has(ext);
18
+ }
19
+ export function isExcludedDir(path) {
20
+ return DEFAULT_EXCLUDE_DIRS.some(d => path.includes(`/${d}/`) || path.includes(`/${d}`));
21
+ }
22
+ /** Relevance score: higher = more relevant */
23
+ export function relevanceScore(path) {
24
+ if (isExcludedDir(path))
25
+ return 0;
26
+ const ext = path.match(/\.\w+$/)?.[0] ?? "";
27
+ if (SOURCE_EXTENSIONS.has(ext))
28
+ return 10;
29
+ if (CONFIG_EXTENSIONS.has(ext))
30
+ return 5;
31
+ if (path.includes("/test") || path.includes(".test.") || path.includes(".spec."))
32
+ return 7;
33
+ return 3;
34
+ }
@@ -0,0 +1,5 @@
1
+ // Smart search — unified entry point for file + content search
2
+ export { searchFiles } from "./file-search.js";
3
+ export { searchContent } from "./content-search.js";
4
+ export { DEFAULT_EXCLUDE_DIRS, SOURCE_EXTENSIONS, isSourceFile, isExcludedDir, relevanceScore } from "./filters.js";
5
+ export { semanticSearch, findExports, findComponents, findHooks } from "./semantic.js";
@@ -0,0 +1,320 @@
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
153
+ const classMatch = line.match(/(?:export\s+)?class\s+(\w+)(?:\s+extends\s+(\w+))?/);
154
+ if (classMatch) {
155
+ symbols.push({
156
+ name: classMatch[1], kind: "class", file, line: lineNum,
157
+ signature: line.trim().replace(/\{.*$/, "").trim(),
158
+ exported: isExported,
159
+ });
160
+ continue;
161
+ }
162
+ // Interfaces
163
+ const ifaceMatch = line.match(/(?:export\s+)?interface\s+(\w+)/);
164
+ if (ifaceMatch) {
165
+ symbols.push({
166
+ name: ifaceMatch[1], kind: "interface", file, line: lineNum,
167
+ signature: line.trim().replace(/\{.*$/, "").trim(),
168
+ exported: isExported,
169
+ });
170
+ continue;
171
+ }
172
+ // Type aliases
173
+ const typeMatch = line.match(/(?:export\s+)?type\s+(\w+)\s*=/);
174
+ if (typeMatch) {
175
+ symbols.push({
176
+ name: typeMatch[1], kind: "type", file, line: lineNum,
177
+ signature: line.trim(),
178
+ exported: isExported,
179
+ });
180
+ continue;
181
+ }
182
+ // Imports (for dependency tracking)
183
+ const importMatch = line.match(/import\s+(?:\{([^}]+)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/);
184
+ if (importMatch) {
185
+ const names = importMatch[1]
186
+ ? importMatch[1].split(",").map(s => s.trim().split(" as ")[0].trim())
187
+ : [importMatch[2]];
188
+ for (const name of names) {
189
+ if (name) {
190
+ symbols.push({
191
+ name, kind: "import", file, line: lineNum,
192
+ signature: `from '${importMatch[3]}'`,
193
+ exported: false,
194
+ });
195
+ }
196
+ }
197
+ continue;
198
+ }
199
+ // Exported constants/variables
200
+ const constMatch = line.match(/export\s+const\s+(\w+)\s*[=:]/);
201
+ if (constMatch && !arrowMatch) {
202
+ symbols.push({
203
+ name: constMatch[1], kind: "variable", file, line: lineNum,
204
+ signature: line.trim().slice(0, 80),
205
+ exported: true,
206
+ });
207
+ }
208
+ }
209
+ return symbols;
210
+ }
211
+ /** Find all source files in a directory */
212
+ async function findSourceFiles(cwd, maxFiles = 200) {
213
+ const excludes = ["node_modules", ".git", "dist", "build", ".next", "coverage", "__pycache__"];
214
+ const excludeArgs = excludes.map(d => `-not -path '*/${d}/*'`).join(" ");
215
+ const extensions = "\\( -name '*.ts' -o -name '*.tsx' -o -name '*.js' -o -name '*.jsx' \\)";
216
+ const cmd = `find . ${extensions} ${excludeArgs} -type f 2>/dev/null | head -${maxFiles}`;
217
+ const output = await exec(cmd, cwd);
218
+ return output.split("\n").filter(l => l.trim()).map(l => join(cwd, l.trim()));
219
+ }
220
+ /** Semantic search: find symbols matching a natural language query */
221
+ export async function semanticSearch(query, cwd, options = {}) {
222
+ const { kinds, exportedOnly = false, maxResults = 30 } = options;
223
+ // Find all source files
224
+ const files = await findSourceFiles(cwd);
225
+ // Extract symbols from all files
226
+ let allSymbols = [];
227
+ for (const file of files) {
228
+ try {
229
+ allSymbols.push(...extractSymbols(file));
230
+ }
231
+ catch { /* skip unreadable files */ }
232
+ }
233
+ // Filter by kind
234
+ if (kinds) {
235
+ allSymbols = allSymbols.filter(s => kinds.includes(s.kind));
236
+ }
237
+ // Filter by exported
238
+ if (exportedOnly) {
239
+ allSymbols = allSymbols.filter(s => s.exported);
240
+ }
241
+ // Score each symbol against the query
242
+ const queryLower = query.toLowerCase();
243
+ const queryWords = queryLower.split(/\s+/).filter(w => w.length > 2);
244
+ const scored = allSymbols.map(symbol => {
245
+ let score = 0;
246
+ const nameLower = symbol.name.toLowerCase();
247
+ const sigLower = (symbol.signature ?? "").toLowerCase();
248
+ const fileLower = symbol.file.toLowerCase();
249
+ // Exact name match
250
+ if (queryWords.some(w => nameLower === w))
251
+ score += 10;
252
+ // Name contains query word
253
+ if (queryWords.some(w => nameLower.includes(w)))
254
+ score += 5;
255
+ // Signature contains query word
256
+ if (queryWords.some(w => sigLower.includes(w)))
257
+ score += 3;
258
+ // File path contains query word
259
+ if (queryWords.some(w => fileLower.includes(w)))
260
+ score += 2;
261
+ // Doc contains query word
262
+ if (symbol.doc && queryWords.some(w => symbol.doc.toLowerCase().includes(w)))
263
+ score += 4;
264
+ // Boost exported symbols
265
+ if (symbol.exported)
266
+ score += 1;
267
+ // Boost functions/classes over imports
268
+ if (symbol.kind === "function" || symbol.kind === "class")
269
+ score += 1;
270
+ // Semantic matching for common patterns
271
+ if (queryLower.includes("component") && symbol.kind === "component")
272
+ score += 5;
273
+ if (queryLower.includes("hook") && symbol.kind === "hook")
274
+ score += 5;
275
+ if (queryLower.includes("type") && (symbol.kind === "type" || symbol.kind === "interface"))
276
+ score += 5;
277
+ if (queryLower.includes("import") && symbol.kind === "import")
278
+ score += 5;
279
+ if (queryLower.includes("class") && symbol.kind === "class")
280
+ score += 5;
281
+ return { symbol, score };
282
+ });
283
+ // Sort by score, filter zero scores
284
+ const results = scored
285
+ .filter(s => s.score > 0)
286
+ .sort((a, b) => b.score - a.score)
287
+ .slice(0, maxResults)
288
+ .map(s => s.symbol);
289
+ // Make file paths relative
290
+ for (const r of results) {
291
+ if (r.file.startsWith(cwd)) {
292
+ r.file = "." + r.file.slice(cwd.length);
293
+ }
294
+ }
295
+ // Estimate token savings
296
+ const rawGrep = await exec(`grep -rn '${queryWords[0] ?? query}' . --include='*.ts' --include='*.tsx' 2>/dev/null | head -100`, cwd);
297
+ const rawTokens = Math.ceil(rawGrep.length / 4);
298
+ const resultTokens = Math.ceil(JSON.stringify(results).length / 4);
299
+ return {
300
+ query,
301
+ symbols: results,
302
+ totalFiles: files.length,
303
+ tokensSaved: Math.max(0, rawTokens - resultTokens),
304
+ };
305
+ }
306
+ /** Quick helper: find all exported functions */
307
+ export async function findExports(cwd) {
308
+ const result = await semanticSearch("export", cwd, { exportedOnly: true, maxResults: 100 });
309
+ return result.symbols;
310
+ }
311
+ /** Quick helper: find all React components */
312
+ export async function findComponents(cwd) {
313
+ const result = await semanticSearch("component", cwd, { kinds: ["component"], maxResults: 50 });
314
+ return result.symbols;
315
+ }
316
+ /** Quick helper: find all hooks */
317
+ export async function findHooks(cwd) {
318
+ const result = await semanticSearch("hook", cwd, { kinds: ["hook"], maxResults: 50 });
319
+ return result.symbols;
320
+ }
@@ -0,0 +1,59 @@
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
+ }
@@ -0,0 +1,55 @@
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
+ }
@@ -0,0 +1,173 @@
1
+ // SQLite session database — tracks every terminal interaction
2
+ // @ts-ignore — bun:sqlite is a bun built-in
3
+ import { Database } from "bun:sqlite";
4
+ import { existsSync, mkdirSync } from "fs";
5
+ import { homedir } from "os";
6
+ import { join } from "path";
7
+ import { randomUUID } from "crypto";
8
+ const DIR = join(homedir(), ".terminal");
9
+ const DB_PATH = join(DIR, "sessions.db");
10
+ let db = null;
11
+ function getDb() {
12
+ if (db)
13
+ return db;
14
+ if (!existsSync(DIR))
15
+ mkdirSync(DIR, { recursive: true });
16
+ db = new Database(DB_PATH);
17
+ db.exec("PRAGMA journal_mode = WAL");
18
+ db.exec(`
19
+ CREATE TABLE IF NOT EXISTS sessions (
20
+ id TEXT PRIMARY KEY,
21
+ started_at INTEGER NOT NULL,
22
+ ended_at INTEGER,
23
+ cwd TEXT NOT NULL,
24
+ provider TEXT,
25
+ model TEXT
26
+ );
27
+
28
+ CREATE TABLE IF NOT EXISTS interactions (
29
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
30
+ session_id TEXT NOT NULL REFERENCES sessions(id),
31
+ nl TEXT NOT NULL,
32
+ command TEXT,
33
+ output TEXT,
34
+ exit_code INTEGER,
35
+ tokens_used INTEGER DEFAULT 0,
36
+ tokens_saved INTEGER DEFAULT 0,
37
+ duration_ms INTEGER,
38
+ model TEXT,
39
+ cached INTEGER DEFAULT 0,
40
+ created_at INTEGER NOT NULL
41
+ );
42
+
43
+ CREATE INDEX IF NOT EXISTS idx_interactions_session ON interactions(session_id);
44
+ CREATE INDEX IF NOT EXISTS idx_sessions_started ON sessions(started_at);
45
+
46
+ CREATE TABLE IF NOT EXISTS corrections (
47
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
48
+ prompt TEXT NOT NULL,
49
+ failed_command TEXT NOT NULL,
50
+ error_output TEXT,
51
+ corrected_command TEXT NOT NULL,
52
+ worked INTEGER DEFAULT 1,
53
+ error_type TEXT,
54
+ created_at INTEGER NOT NULL
55
+ );
56
+
57
+ CREATE TABLE IF NOT EXISTS outputs (
58
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
59
+ session_id TEXT,
60
+ command TEXT NOT NULL,
61
+ raw_output_path TEXT,
62
+ compressed_summary TEXT,
63
+ tokens_raw INTEGER DEFAULT 0,
64
+ tokens_compressed INTEGER DEFAULT 0,
65
+ provider TEXT,
66
+ model TEXT,
67
+ created_at INTEGER NOT NULL
68
+ );
69
+
70
+ CREATE INDEX IF NOT EXISTS idx_corrections_prompt ON corrections(prompt);
71
+ `);
72
+ return db;
73
+ }
74
+ // ── Sessions ─────────────────────────────────────────────────────────────────
75
+ export function createSession(cwd, provider, model) {
76
+ const id = randomUUID();
77
+ getDb().prepare("INSERT INTO sessions (id, started_at, cwd, provider, model) VALUES (?, ?, ?, ?, ?)").run(id, Date.now(), cwd, provider ?? null, model ?? null);
78
+ return id;
79
+ }
80
+ export function endSession(sessionId) {
81
+ getDb().prepare("UPDATE sessions SET ended_at = ? WHERE id = ?").run(Date.now(), sessionId);
82
+ }
83
+ export function listSessions(limit = 20) {
84
+ return getDb().prepare("SELECT * FROM sessions ORDER BY started_at DESC LIMIT ?").all(limit);
85
+ }
86
+ export function getSession(id) {
87
+ return getDb().prepare("SELECT * FROM sessions WHERE id = ?").get(id);
88
+ }
89
+ export function logInteraction(sessionId, data) {
90
+ const result = getDb().prepare(`INSERT INTO interactions (session_id, nl, command, output, exit_code, tokens_used, tokens_saved, duration_ms, model, cached, created_at)
91
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(sessionId, data.nl, data.command ?? null, data.output ? data.output.slice(0, 500) : null, data.exitCode ?? null, data.tokensUsed ?? 0, data.tokensSaved ?? 0, data.durationMs ?? null, data.model ?? null, data.cached ? 1 : 0, Date.now());
92
+ // bun:sqlite — lastInsertRowid is a property on the statement after run()
93
+ const lastId = getDb().prepare("SELECT last_insert_rowid() as id").get();
94
+ return lastId?.id ?? 0;
95
+ }
96
+ export function updateInteraction(id, data) {
97
+ const sets = [];
98
+ const vals = [];
99
+ if (data.command !== undefined) {
100
+ sets.push("command = ?");
101
+ vals.push(data.command);
102
+ }
103
+ if (data.output !== undefined) {
104
+ sets.push("output = ?");
105
+ vals.push(data.output.slice(0, 500));
106
+ }
107
+ if (data.exitCode !== undefined) {
108
+ sets.push("exit_code = ?");
109
+ vals.push(data.exitCode);
110
+ }
111
+ if (data.tokensSaved !== undefined) {
112
+ sets.push("tokens_saved = ?");
113
+ vals.push(data.tokensSaved);
114
+ }
115
+ if (sets.length === 0)
116
+ return;
117
+ vals.push(id);
118
+ getDb().prepare(`UPDATE interactions SET ${sets.join(", ")} WHERE id = ?`).run(...vals);
119
+ }
120
+ export function getSessionInteractions(sessionId) {
121
+ return getDb().prepare("SELECT * FROM interactions WHERE session_id = ? ORDER BY created_at ASC").all(sessionId);
122
+ }
123
+ export function getSessionStats() {
124
+ const d = getDb();
125
+ const sessions = d.prepare("SELECT COUNT(*) as c FROM sessions").get();
126
+ const interactions = d.prepare("SELECT COUNT(*) as c, SUM(tokens_saved) as saved, SUM(tokens_used) as used FROM interactions").get();
127
+ const cached = d.prepare("SELECT COUNT(*) as c FROM interactions WHERE cached = 1").get();
128
+ const errors = d.prepare("SELECT COUNT(*) as c FROM interactions WHERE exit_code IS NOT NULL AND exit_code != 0").get();
129
+ const totalInteractions = interactions.c ?? 0;
130
+ return {
131
+ totalSessions: sessions.c ?? 0,
132
+ totalInteractions,
133
+ totalTokensSaved: interactions.saved ?? 0,
134
+ totalTokensUsed: interactions.used ?? 0,
135
+ cacheHitRate: totalInteractions > 0 ? (cached.c ?? 0) / totalInteractions : 0,
136
+ avgInteractionsPerSession: sessions.c > 0 ? totalInteractions / sessions.c : 0,
137
+ errorRate: totalInteractions > 0 ? (errors.c ?? 0) / totalInteractions : 0,
138
+ };
139
+ }
140
+ // ── Corrections ─────────────────────────────────────────────────────────────
141
+ /** Record a correction: command failed, then AI retried with a better one */
142
+ export function recordCorrection(prompt, failedCommand, errorOutput, correctedCommand, worked, errorType) {
143
+ getDb().prepare("INSERT INTO corrections (prompt, failed_command, error_output, corrected_command, worked, error_type, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)").run(prompt, failedCommand, errorOutput?.slice(0, 2000) ?? "", correctedCommand, worked ? 1 : 0, errorType ?? null, Date.now());
144
+ }
145
+ /** Find similar corrections for a prompt — used to inject as negative examples */
146
+ export function findSimilarCorrections(prompt, limit = 5) {
147
+ // Simple keyword matching — extract significant words from prompt
148
+ const words = prompt.toLowerCase().split(/\s+/).filter(w => w.length > 3);
149
+ if (words.length === 0)
150
+ return [];
151
+ // Search corrections where the prompt shares keywords
152
+ const all = getDb().prepare("SELECT prompt, failed_command, corrected_command, error_type FROM corrections WHERE worked = 1 ORDER BY created_at DESC LIMIT 100").all();
153
+ return all
154
+ .filter(c => {
155
+ const cWords = c.prompt.toLowerCase().split(/\s+/);
156
+ const overlap = words.filter((w) => cWords.some((cw) => cw.includes(w) || w.includes(cw)));
157
+ return overlap.length >= Math.min(2, words.length);
158
+ })
159
+ .slice(0, limit)
160
+ .map(c => ({ failed_command: c.failed_command, corrected_command: c.corrected_command, error_type: c.error_type ?? "unknown" }));
161
+ }
162
+ // ── Output tracking ─────────────────────────────────────────────────────────
163
+ /** Record a compressed output for audit trail */
164
+ export function recordOutput(command, rawOutputPath, compressedSummary, tokensRaw, tokensCompressed, provider, model, sessionId) {
165
+ getDb().prepare("INSERT INTO outputs (session_id, command, raw_output_path, compressed_summary, tokens_raw, tokens_compressed, provider, model, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(sessionId ?? null, command, rawOutputPath ?? null, compressedSummary?.slice(0, 5000) ?? "", tokensRaw, tokensCompressed, provider ?? null, model ?? null, Date.now());
166
+ }
167
+ /** Close the database connection */
168
+ export function closeDb() {
169
+ if (db) {
170
+ db.close();
171
+ db = null;
172
+ }
173
+ }