@hasna/terminal 0.1.5 → 0.2.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 (74) hide show
  1. package/.claude/scheduled_tasks.lock +1 -1
  2. package/README.md +186 -0
  3. package/dist/ai.js +45 -50
  4. package/dist/cli.js +138 -6
  5. package/dist/compression.js +107 -0
  6. package/dist/compression.test.js +42 -0
  7. package/dist/diff-cache.js +87 -0
  8. package/dist/diff-cache.test.js +27 -0
  9. package/dist/economy.js +79 -0
  10. package/dist/economy.test.js +13 -0
  11. package/dist/mcp/install.js +98 -0
  12. package/dist/mcp/server.js +333 -0
  13. package/dist/output-router.js +41 -0
  14. package/dist/parsers/base.js +2 -0
  15. package/dist/parsers/build.js +64 -0
  16. package/dist/parsers/errors.js +101 -0
  17. package/dist/parsers/files.js +78 -0
  18. package/dist/parsers/git.js +86 -0
  19. package/dist/parsers/index.js +48 -0
  20. package/dist/parsers/parsers.test.js +136 -0
  21. package/dist/parsers/tests.js +89 -0
  22. package/dist/providers/anthropic.js +39 -0
  23. package/dist/providers/base.js +4 -0
  24. package/dist/providers/cerebras.js +95 -0
  25. package/dist/providers/index.js +49 -0
  26. package/dist/providers/providers.test.js +14 -0
  27. package/dist/recipes/model.js +20 -0
  28. package/dist/recipes/recipes.test.js +36 -0
  29. package/dist/recipes/storage.js +118 -0
  30. package/dist/search/content-search.js +61 -0
  31. package/dist/search/file-search.js +61 -0
  32. package/dist/search/filters.js +34 -0
  33. package/dist/search/index.js +4 -0
  34. package/dist/search/search.test.js +22 -0
  35. package/dist/snapshots.js +51 -0
  36. package/dist/supervisor.js +112 -0
  37. package/dist/tree.js +94 -0
  38. package/package.json +7 -4
  39. package/src/ai.ts +63 -51
  40. package/src/cli.tsx +132 -6
  41. package/src/compression.test.ts +50 -0
  42. package/src/compression.ts +140 -0
  43. package/src/diff-cache.test.ts +30 -0
  44. package/src/diff-cache.ts +125 -0
  45. package/src/economy.test.ts +16 -0
  46. package/src/economy.ts +99 -0
  47. package/src/mcp/install.ts +94 -0
  48. package/src/mcp/server.ts +476 -0
  49. package/src/output-router.ts +56 -0
  50. package/src/parsers/base.ts +72 -0
  51. package/src/parsers/build.ts +73 -0
  52. package/src/parsers/errors.ts +107 -0
  53. package/src/parsers/files.ts +91 -0
  54. package/src/parsers/git.ts +86 -0
  55. package/src/parsers/index.ts +66 -0
  56. package/src/parsers/parsers.test.ts +153 -0
  57. package/src/parsers/tests.ts +98 -0
  58. package/src/providers/anthropic.ts +44 -0
  59. package/src/providers/base.ts +34 -0
  60. package/src/providers/cerebras.ts +108 -0
  61. package/src/providers/index.ts +60 -0
  62. package/src/providers/providers.test.ts +16 -0
  63. package/src/recipes/model.ts +55 -0
  64. package/src/recipes/recipes.test.ts +44 -0
  65. package/src/recipes/storage.ts +142 -0
  66. package/src/search/content-search.ts +97 -0
  67. package/src/search/file-search.ts +86 -0
  68. package/src/search/filters.ts +36 -0
  69. package/src/search/index.ts +7 -0
  70. package/src/search/search.test.ts +25 -0
  71. package/src/snapshots.ts +67 -0
  72. package/src/supervisor.ts +129 -0
  73. package/src/tree.ts +101 -0
  74. package/tsconfig.json +2 -1
@@ -0,0 +1,39 @@
1
+ import Anthropic from "@anthropic-ai/sdk";
2
+ export class AnthropicProvider {
3
+ name = "anthropic";
4
+ client;
5
+ constructor() {
6
+ this.client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
7
+ }
8
+ isAvailable() {
9
+ return !!process.env.ANTHROPIC_API_KEY;
10
+ }
11
+ async complete(prompt, options) {
12
+ const message = await this.client.messages.create({
13
+ model: options.model ?? "claude-haiku-4-5-20251001",
14
+ max_tokens: options.maxTokens ?? 256,
15
+ system: options.system,
16
+ messages: [{ role: "user", content: prompt }],
17
+ });
18
+ const block = message.content[0];
19
+ if (block.type !== "text")
20
+ throw new Error("Unexpected response type");
21
+ return block.text.trim();
22
+ }
23
+ async stream(prompt, options, callbacks) {
24
+ let result = "";
25
+ const stream = await this.client.messages.stream({
26
+ model: options.model ?? "claude-haiku-4-5-20251001",
27
+ max_tokens: options.maxTokens ?? 256,
28
+ system: options.system,
29
+ messages: [{ role: "user", content: prompt }],
30
+ });
31
+ for await (const chunk of stream) {
32
+ if (chunk.type === "content_block_delta" && chunk.delta.type === "text_delta") {
33
+ result += chunk.delta.text;
34
+ callbacks.onToken(result.trim());
35
+ }
36
+ }
37
+ return result.trim();
38
+ }
39
+ }
@@ -0,0 +1,4 @@
1
+ // Provider interface for LLM backends (Anthropic, Cerebras, etc.)
2
+ export const DEFAULT_PROVIDER_CONFIG = {
3
+ provider: "auto",
4
+ };
@@ -0,0 +1,95 @@
1
+ // Cerebras provider — uses OpenAI-compatible API
2
+ // Default for open-source users. Fast inference on Llama models.
3
+ const CEREBRAS_BASE_URL = "https://api.cerebras.ai/v1";
4
+ const DEFAULT_MODEL = "llama3.1-8b";
5
+ export class CerebrasProvider {
6
+ name = "cerebras";
7
+ apiKey;
8
+ constructor() {
9
+ this.apiKey = process.env.CEREBRAS_API_KEY ?? "";
10
+ }
11
+ isAvailable() {
12
+ return !!process.env.CEREBRAS_API_KEY;
13
+ }
14
+ async complete(prompt, options) {
15
+ const model = options.model ?? DEFAULT_MODEL;
16
+ const res = await fetch(`${CEREBRAS_BASE_URL}/chat/completions`, {
17
+ method: "POST",
18
+ headers: {
19
+ "Content-Type": "application/json",
20
+ Authorization: `Bearer ${this.apiKey}`,
21
+ },
22
+ body: JSON.stringify({
23
+ model,
24
+ max_tokens: options.maxTokens ?? 256,
25
+ messages: [
26
+ { role: "system", content: options.system },
27
+ { role: "user", content: prompt },
28
+ ],
29
+ }),
30
+ });
31
+ if (!res.ok) {
32
+ const text = await res.text();
33
+ throw new Error(`Cerebras API error ${res.status}: ${text}`);
34
+ }
35
+ const json = (await res.json());
36
+ return (json.choices?.[0]?.message?.content ?? "").trim();
37
+ }
38
+ async stream(prompt, options, callbacks) {
39
+ const model = options.model ?? DEFAULT_MODEL;
40
+ const res = await fetch(`${CEREBRAS_BASE_URL}/chat/completions`, {
41
+ method: "POST",
42
+ headers: {
43
+ "Content-Type": "application/json",
44
+ Authorization: `Bearer ${this.apiKey}`,
45
+ },
46
+ body: JSON.stringify({
47
+ model,
48
+ max_tokens: options.maxTokens ?? 256,
49
+ stream: true,
50
+ messages: [
51
+ { role: "system", content: options.system },
52
+ { role: "user", content: prompt },
53
+ ],
54
+ }),
55
+ });
56
+ if (!res.ok) {
57
+ const text = await res.text();
58
+ throw new Error(`Cerebras API error ${res.status}: ${text}`);
59
+ }
60
+ let result = "";
61
+ const reader = res.body?.getReader();
62
+ if (!reader)
63
+ throw new Error("No response body");
64
+ const decoder = new TextDecoder();
65
+ let buffer = "";
66
+ while (true) {
67
+ const { done, value } = await reader.read();
68
+ if (done)
69
+ break;
70
+ buffer += decoder.decode(value, { stream: true });
71
+ const lines = buffer.split("\n");
72
+ buffer = lines.pop() ?? "";
73
+ for (const line of lines) {
74
+ const trimmed = line.trim();
75
+ if (!trimmed.startsWith("data: "))
76
+ continue;
77
+ const data = trimmed.slice(6);
78
+ if (data === "[DONE]")
79
+ break;
80
+ try {
81
+ const parsed = JSON.parse(data);
82
+ const delta = parsed.choices?.[0]?.delta?.content;
83
+ if (delta) {
84
+ result += delta;
85
+ callbacks.onToken(result.trim());
86
+ }
87
+ }
88
+ catch {
89
+ // skip malformed chunks
90
+ }
91
+ }
92
+ }
93
+ return result.trim();
94
+ }
95
+ }
@@ -0,0 +1,49 @@
1
+ // Provider auto-detection and management
2
+ import { DEFAULT_PROVIDER_CONFIG } from "./base.js";
3
+ import { AnthropicProvider } from "./anthropic.js";
4
+ import { CerebrasProvider } from "./cerebras.js";
5
+ export { DEFAULT_PROVIDER_CONFIG } from "./base.js";
6
+ let _provider = null;
7
+ /** Get the active LLM provider. Auto-detects based on available API keys. */
8
+ export function getProvider(config) {
9
+ if (_provider)
10
+ return _provider;
11
+ const cfg = config ?? DEFAULT_PROVIDER_CONFIG;
12
+ _provider = resolveProvider(cfg);
13
+ return _provider;
14
+ }
15
+ /** Reset the cached provider (useful when config changes). */
16
+ export function resetProvider() {
17
+ _provider = null;
18
+ }
19
+ function resolveProvider(config) {
20
+ if (config.provider === "cerebras") {
21
+ const p = new CerebrasProvider();
22
+ if (!p.isAvailable())
23
+ throw new Error("CEREBRAS_API_KEY not set. Run: export CEREBRAS_API_KEY=your-key");
24
+ return p;
25
+ }
26
+ if (config.provider === "anthropic") {
27
+ const p = new AnthropicProvider();
28
+ if (!p.isAvailable())
29
+ throw new Error("ANTHROPIC_API_KEY not set. Run: export ANTHROPIC_API_KEY=your-key");
30
+ return p;
31
+ }
32
+ // auto: prefer Cerebras (open-source friendly), fall back to Anthropic
33
+ const cerebras = new CerebrasProvider();
34
+ if (cerebras.isAvailable())
35
+ return cerebras;
36
+ const anthropic = new AnthropicProvider();
37
+ if (anthropic.isAvailable())
38
+ return anthropic;
39
+ throw new Error("No API key found. Set one of:\n" +
40
+ " export CEREBRAS_API_KEY=your-key (free, open-source)\n" +
41
+ " export ANTHROPIC_API_KEY=your-key (Claude)");
42
+ }
43
+ /** List available providers (for onboarding UI). */
44
+ export function availableProviders() {
45
+ return [
46
+ { name: "cerebras", available: new CerebrasProvider().isAvailable() },
47
+ { name: "anthropic", available: new AnthropicProvider().isAvailable() },
48
+ ];
49
+ }
@@ -0,0 +1,14 @@
1
+ import { describe, it, expect } from "bun:test";
2
+ import { availableProviders, resetProvider } from "./index.js";
3
+ describe("providers", () => {
4
+ it("lists available providers", () => {
5
+ const providers = availableProviders();
6
+ expect(providers.length).toBe(2);
7
+ expect(providers[0].name).toBe("cerebras");
8
+ expect(providers[1].name).toBe("anthropic");
9
+ });
10
+ it("resetProvider clears cache", () => {
11
+ // Should not throw
12
+ resetProvider();
13
+ });
14
+ });
@@ -0,0 +1,20 @@
1
+ // Recipes data model — reusable command templates with collections and projects
2
+ /** Generate a short random ID */
3
+ export function genId() {
4
+ return Math.random().toString(36).slice(2, 10);
5
+ }
6
+ /** Substitute variables in a command template */
7
+ export function substituteVariables(command, vars) {
8
+ let result = command;
9
+ for (const [name, value] of Object.entries(vars)) {
10
+ result = result.replace(new RegExp(`\\{${name}\\}`, "g"), value);
11
+ }
12
+ return result;
13
+ }
14
+ /** Extract variable placeholders from a command */
15
+ export function extractVariables(command) {
16
+ const matches = command.match(/\{(\w+)\}/g);
17
+ if (!matches)
18
+ return [];
19
+ return [...new Set(matches.map(m => m.slice(1, -1)))];
20
+ }
@@ -0,0 +1,36 @@
1
+ import { describe, it, expect } from "bun:test";
2
+ import { genId, substituteVariables, extractVariables } from "./model.js";
3
+ describe("genId", () => {
4
+ it("generates unique ids", () => {
5
+ const a = genId();
6
+ const b = genId();
7
+ expect(a).not.toBe(b);
8
+ expect(a.length).toBe(8);
9
+ });
10
+ });
11
+ describe("substituteVariables", () => {
12
+ it("replaces {var} placeholders", () => {
13
+ expect(substituteVariables("kill -9 {pid}", { pid: "1234" })).toBe("kill -9 1234");
14
+ });
15
+ it("replaces multiple variables", () => {
16
+ expect(substituteVariables("curl {host}:{port}", { host: "localhost", port: "3000" }))
17
+ .toBe("curl localhost:3000");
18
+ });
19
+ it("replaces all occurrences of same variable", () => {
20
+ expect(substituteVariables("{x} and {x}", { x: "y" })).toBe("y and y");
21
+ });
22
+ it("leaves unmatched vars alone", () => {
23
+ expect(substituteVariables("{a} {b}", { a: "1" })).toBe("1 {b}");
24
+ });
25
+ });
26
+ describe("extractVariables", () => {
27
+ it("extracts variable names from command", () => {
28
+ expect(extractVariables("lsof -i :{port} -t | xargs kill")).toEqual(["port"]);
29
+ });
30
+ it("deduplicates", () => {
31
+ expect(extractVariables("{x} {x} {y}")).toEqual(["x", "y"]);
32
+ });
33
+ it("returns empty for no variables", () => {
34
+ expect(extractVariables("ls -la")).toEqual([]);
35
+ });
36
+ });
@@ -0,0 +1,118 @@
1
+ // Recipes storage — global (~/.terminal/recipes.json) + per-project (.terminal/recipes.json)
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
3
+ import { homedir } from "os";
4
+ import { join } from "path";
5
+ import { genId, extractVariables } from "./model.js";
6
+ const GLOBAL_DIR = join(homedir(), ".terminal");
7
+ const GLOBAL_FILE = join(GLOBAL_DIR, "recipes.json");
8
+ function projectFile(projectPath) {
9
+ return join(projectPath, ".terminal", "recipes.json");
10
+ }
11
+ function loadStore(filePath) {
12
+ if (!existsSync(filePath))
13
+ return { recipes: [], collections: [] };
14
+ try {
15
+ return JSON.parse(readFileSync(filePath, "utf8"));
16
+ }
17
+ catch {
18
+ return { recipes: [], collections: [] };
19
+ }
20
+ }
21
+ function saveStore(filePath, store) {
22
+ const dir = filePath.replace(/\/[^/]+$/, "");
23
+ if (!existsSync(dir))
24
+ mkdirSync(dir, { recursive: true });
25
+ writeFileSync(filePath, JSON.stringify(store, null, 2));
26
+ }
27
+ // ── CRUD operations ──────────────────────────────────────────────────────────
28
+ /** Get all recipes (merged: global + project-scoped) */
29
+ export function listRecipes(projectPath) {
30
+ const global = loadStore(GLOBAL_FILE).recipes;
31
+ if (!projectPath)
32
+ return global;
33
+ const project = loadStore(projectFile(projectPath)).recipes;
34
+ return [...project, ...global]; // project recipes first (higher priority)
35
+ }
36
+ /** Get recipes filtered by collection */
37
+ export function listByCollection(collection, projectPath) {
38
+ return listRecipes(projectPath).filter(r => r.collection === collection);
39
+ }
40
+ /** Get a recipe by name */
41
+ export function getRecipe(name, projectPath) {
42
+ return listRecipes(projectPath).find(r => r.name === name) ?? null;
43
+ }
44
+ /** Create a recipe */
45
+ export function createRecipe(opts) {
46
+ const filePath = opts.project ? projectFile(opts.project) : GLOBAL_FILE;
47
+ const store = loadStore(filePath);
48
+ // Auto-detect variables from command if not explicitly provided
49
+ const detectedVars = extractVariables(opts.command);
50
+ const variables = opts.variables ?? detectedVars.map(name => ({ name, required: true }));
51
+ const recipe = {
52
+ id: genId(),
53
+ name: opts.name,
54
+ description: opts.description,
55
+ command: opts.command,
56
+ tags: opts.tags ?? [],
57
+ collection: opts.collection,
58
+ project: opts.project,
59
+ variables,
60
+ createdAt: Date.now(),
61
+ updatedAt: Date.now(),
62
+ };
63
+ store.recipes.push(recipe);
64
+ saveStore(filePath, store);
65
+ return recipe;
66
+ }
67
+ /** Delete a recipe by name — tries project first, then global */
68
+ export function deleteRecipe(name, projectPath) {
69
+ // Try project-scoped first
70
+ if (projectPath) {
71
+ const pFile = projectFile(projectPath);
72
+ const pStore = loadStore(pFile);
73
+ const before = pStore.recipes.length;
74
+ pStore.recipes = pStore.recipes.filter(r => r.name !== name);
75
+ if (pStore.recipes.length < before) {
76
+ saveStore(pFile, pStore);
77
+ return true;
78
+ }
79
+ }
80
+ // Fall back to global
81
+ const store = loadStore(GLOBAL_FILE);
82
+ const before = store.recipes.length;
83
+ store.recipes = store.recipes.filter(r => r.name !== name);
84
+ if (store.recipes.length < before) {
85
+ saveStore(GLOBAL_FILE, store);
86
+ return true;
87
+ }
88
+ return false;
89
+ }
90
+ // ── Collections ──────────────────────────────────────────────────────────────
91
+ export function listCollections(projectPath) {
92
+ const global = loadStore(GLOBAL_FILE).collections;
93
+ if (!projectPath)
94
+ return global;
95
+ const project = loadStore(projectFile(projectPath)).collections;
96
+ return [...project, ...global];
97
+ }
98
+ export function createCollection(opts) {
99
+ const filePath = opts.project ? projectFile(opts.project) : GLOBAL_FILE;
100
+ const store = loadStore(filePath);
101
+ const collection = {
102
+ id: genId(),
103
+ name: opts.name,
104
+ description: opts.description,
105
+ project: opts.project,
106
+ createdAt: Date.now(),
107
+ };
108
+ store.collections.push(collection);
109
+ saveStore(filePath, store);
110
+ return collection;
111
+ }
112
+ /** Initialize project-scoped recipes file */
113
+ export function initProject(projectPath) {
114
+ const file = projectFile(projectPath);
115
+ if (!existsSync(file)) {
116
+ saveStore(file, { recipes: [], collections: [] });
117
+ }
118
+ }
@@ -0,0 +1,61 @@
1
+ // Smart content search — structured grep/ripgrep with grouping and dedup
2
+ import { spawn } from "child_process";
3
+ import { DEFAULT_EXCLUDE_DIRS, relevanceScore } from "./filters.js";
4
+ function exec(command, cwd) {
5
+ return new Promise((resolve) => {
6
+ const proc = spawn("/bin/zsh", ["-c", command], { cwd, stdio: ["ignore", "pipe", "pipe"] });
7
+ let out = "";
8
+ proc.stdout?.on("data", (d) => { out += d.toString(); });
9
+ proc.on("close", () => resolve(out));
10
+ });
11
+ }
12
+ export async function searchContent(pattern, cwd, options = {}) {
13
+ const { fileType, maxResults = 30, contextLines = 0 } = options;
14
+ // Prefer ripgrep, fall back to grep
15
+ const excludeArgs = DEFAULT_EXCLUDE_DIRS.map(d => `--glob '!${d}'`).join(" ");
16
+ const typeArg = fileType ? `--type ${fileType}` : "";
17
+ const contextArg = contextLines > 0 ? `-C ${contextLines}` : "";
18
+ // Try rg first, fall back to grep
19
+ const rgCmd = `rg --line-number --no-heading ${contextArg} ${typeArg} ${excludeArgs} '${pattern.replace(/'/g, "'\\''")}' 2>/dev/null | head -500`;
20
+ const grepCmd = `grep -rn ${contextArg} '${pattern.replace(/'/g, "'\\''")}' . --include='*.ts' --include='*.js' --include='*.py' --include='*.go' --include='*.rs' --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist 2>/dev/null | head -500`;
21
+ let raw = await exec(rgCmd, cwd);
22
+ if (!raw.trim()) {
23
+ raw = await exec(grepCmd, cwd);
24
+ }
25
+ const lines = raw.split("\n").filter(l => l.trim());
26
+ const fileMap = new Map();
27
+ let filteredCount = 0;
28
+ for (const line of lines) {
29
+ // Format: path:line:content
30
+ const match = line.match(/^([^:]+):(\d+):(.*)$/);
31
+ if (!match)
32
+ continue;
33
+ const [, path, lineNum, content] = match;
34
+ if (DEFAULT_EXCLUDE_DIRS.some(d => path.includes(`/${d}/`))) {
35
+ filteredCount++;
36
+ continue;
37
+ }
38
+ if (!fileMap.has(path))
39
+ fileMap.set(path, []);
40
+ fileMap.get(path).push({
41
+ line: parseInt(lineNum),
42
+ content: content.trim(),
43
+ });
44
+ }
45
+ // Sort files by relevance
46
+ const files = [...fileMap.entries()]
47
+ .map(([path, matches]) => ({
48
+ path,
49
+ matches: matches.slice(0, 5), // max 5 matches per file
50
+ relevance: relevanceScore(path),
51
+ }))
52
+ .sort((a, b) => b.relevance - a.relevance)
53
+ .slice(0, maxResults);
54
+ const totalMatches = [...fileMap.values()].reduce((sum, m) => sum + m.length, 0);
55
+ const filtered = filteredCount > 0 ? [{ count: filteredCount, reason: "excluded directories" }] : [];
56
+ const rawTokens = Math.ceil(raw.length / 4);
57
+ const result = { query: pattern, totalMatches, files, filtered };
58
+ const resultTokens = Math.ceil(JSON.stringify(result).length / 4);
59
+ result.tokensSaved = Math.max(0, rawTokens - resultTokens);
60
+ return result;
61
+ }
@@ -0,0 +1,61 @@
1
+ // Smart file search — structured, filtered, token-efficient results
2
+ import { spawn } from "child_process";
3
+ import { DEFAULT_EXCLUDE_DIRS, isSourceFile, isExcludedDir, relevanceScore } from "./filters.js";
4
+ function exec(command, cwd) {
5
+ return new Promise((resolve) => {
6
+ const proc = spawn("/bin/zsh", ["-c", command], { cwd, stdio: ["ignore", "pipe", "pipe"] });
7
+ let out = "";
8
+ proc.stdout?.on("data", (d) => { out += d.toString(); });
9
+ proc.stderr?.on("data", (d) => { out += d.toString(); });
10
+ proc.on("close", () => resolve(out));
11
+ });
12
+ }
13
+ export async function searchFiles(pattern, cwd, options = {}) {
14
+ const { includeNodeModules = false, maxResults = 50 } = options;
15
+ // Build find command
16
+ const excludes = includeNodeModules
17
+ ? DEFAULT_EXCLUDE_DIRS.filter(d => d !== "node_modules")
18
+ : DEFAULT_EXCLUDE_DIRS;
19
+ const excludeArgs = excludes.map(d => `-not -path '*/${d}/*'`).join(" ");
20
+ const command = `find . -name '${pattern}' -type f ${excludeArgs} 2>/dev/null | head -${maxResults * 3}`;
21
+ const raw = await exec(command, cwd);
22
+ const allPaths = raw.split("\n").filter(l => l.trim());
23
+ // Categorize
24
+ const source = [];
25
+ const config = [];
26
+ const other = [];
27
+ const filteredCounts = {};
28
+ for (const path of allPaths) {
29
+ if (isExcludedDir(path)) {
30
+ const dir = DEFAULT_EXCLUDE_DIRS.find(d => path.includes(`/${d}/`)) ?? "other";
31
+ filteredCounts[dir] = (filteredCounts[dir] ?? 0) + 1;
32
+ continue;
33
+ }
34
+ if (isSourceFile(path)) {
35
+ source.push(path);
36
+ }
37
+ else if (path.match(/\.(json|yaml|yml|toml|ini|env)/)) {
38
+ config.push(path);
39
+ }
40
+ else {
41
+ other.push(path);
42
+ }
43
+ }
44
+ // Sort by relevance
45
+ source.sort((a, b) => relevanceScore(b) - relevanceScore(a));
46
+ // Limit results
47
+ const filtered = Object.entries(filteredCounts).map(([reason, count]) => ({ reason, count }));
48
+ // Estimate token savings
49
+ const rawTokens = Math.ceil(raw.length / 4);
50
+ const result = {
51
+ query: pattern,
52
+ total: allPaths.length,
53
+ source: source.slice(0, maxResults),
54
+ config: config.slice(0, 10),
55
+ other: other.slice(0, 10),
56
+ filtered,
57
+ };
58
+ const resultTokens = Math.ceil(JSON.stringify(result).length / 4);
59
+ result.tokensSaved = Math.max(0, rawTokens - resultTokens);
60
+ return result;
61
+ }
@@ -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,4 @@
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";
@@ -0,0 +1,22 @@
1
+ import { describe, it, expect } from "bun:test";
2
+ import { isSourceFile, isExcludedDir, relevanceScore } from "./filters.js";
3
+ describe("filters", () => {
4
+ it("identifies source files", () => {
5
+ expect(isSourceFile("src/app.ts")).toBe(true);
6
+ expect(isSourceFile("index.tsx")).toBe(true);
7
+ expect(isSourceFile("main.py")).toBe(true);
8
+ expect(isSourceFile("image.png")).toBe(false);
9
+ expect(isSourceFile("binary")).toBe(false);
10
+ });
11
+ it("identifies excluded directories", () => {
12
+ expect(isExcludedDir("./node_modules/foo/bar.js")).toBe(true);
13
+ expect(isExcludedDir("./dist/index.js")).toBe(true);
14
+ expect(isExcludedDir("./.git/config")).toBe(true);
15
+ expect(isExcludedDir("./src/lib/utils.ts")).toBe(false);
16
+ });
17
+ it("scores source files highest", () => {
18
+ expect(relevanceScore("src/app.ts")).toBe(10);
19
+ expect(relevanceScore("./node_modules/foo.js")).toBe(0);
20
+ expect(relevanceScore("binary")).toBe(3);
21
+ });
22
+ });
@@ -0,0 +1,51 @@
1
+ // Session snapshots — capture terminal state for agent context handoff
2
+ import { loadHistory } from "./history.js";
3
+ import { bgStatus } from "./supervisor.js";
4
+ import { getEconomyStats, formatTokens } from "./economy.js";
5
+ import { listRecipes } from "./recipes/storage.js";
6
+ /** Capture a compact snapshot of the current terminal state */
7
+ export function captureSnapshot() {
8
+ // Filtered env — only relevant vars, no secrets
9
+ const safeEnvKeys = [
10
+ "PATH", "HOME", "USER", "SHELL", "NODE_ENV", "PWD", "LANG",
11
+ "TERM", "EDITOR", "VISUAL",
12
+ ];
13
+ const env = {};
14
+ for (const key of safeEnvKeys) {
15
+ if (process.env[key])
16
+ env[key] = process.env[key];
17
+ }
18
+ // Running processes
19
+ const processes = bgStatus().map(p => ({
20
+ pid: p.pid,
21
+ command: p.command,
22
+ port: p.port,
23
+ uptime: Date.now() - p.startedAt,
24
+ }));
25
+ // Recent commands (last 10, compressed)
26
+ const history = loadHistory().slice(-10);
27
+ const recentCommands = history.map(h => ({
28
+ cmd: h.cmd,
29
+ exitCode: h.error,
30
+ summary: h.nl !== h.cmd ? h.nl : undefined,
31
+ }));
32
+ // Project recipes
33
+ const recipes = listRecipes(process.cwd()).slice(0, 10).map(r => ({
34
+ name: r.name,
35
+ command: r.command,
36
+ }));
37
+ // Economy
38
+ const econ = getEconomyStats();
39
+ return {
40
+ cwd: process.cwd(),
41
+ env,
42
+ runningProcesses: processes,
43
+ recentCommands,
44
+ recipes,
45
+ economy: {
46
+ tokensSaved: formatTokens(econ.totalTokensSaved),
47
+ tokensUsed: formatTokens(econ.totalTokensUsed),
48
+ },
49
+ timestamp: Date.now(),
50
+ };
51
+ }