@wrongstack/tools 0.273.1 → 0.274.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builtin.js +166 -70
- package/dist/builtin.js.map +1 -1
- package/dist/codebase-index/index.js +24 -16
- package/dist/codebase-index/index.js.map +1 -1
- package/dist/codebase-index/worker.js +24 -16
- package/dist/codebase-index/worker.js.map +1 -1
- package/dist/glob.js +61 -11
- package/dist/glob.js.map +1 -1
- package/dist/grep.js +92 -39
- package/dist/grep.js.map +1 -1
- package/dist/index.js +166 -70
- package/dist/index.js.map +1 -1
- package/dist/pack.js +166 -70
- package/dist/pack.js.map +1 -1
- package/package.json +2 -2
package/dist/glob.js
CHANGED
|
@@ -4,6 +4,23 @@ import * as Core from '@wrongstack/core';
|
|
|
4
4
|
import { compileGlob } from '@wrongstack/core';
|
|
5
5
|
|
|
6
6
|
// src/glob.ts
|
|
7
|
+
|
|
8
|
+
// src/_concurrency.ts
|
|
9
|
+
async function mapWithConcurrency(items, limit, fn) {
|
|
10
|
+
if (items.length === 0) return [];
|
|
11
|
+
const effectiveLimit = Math.max(1, Math.min(limit | 0, items.length));
|
|
12
|
+
const results = new Array(items.length);
|
|
13
|
+
let nextIndex = 0;
|
|
14
|
+
const worker = async () => {
|
|
15
|
+
while (true) {
|
|
16
|
+
const i = nextIndex++;
|
|
17
|
+
if (i >= items.length) return;
|
|
18
|
+
results[i] = await fn(items[i]);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
await Promise.all(Array.from({ length: effectiveLimit }, worker));
|
|
22
|
+
return results;
|
|
23
|
+
}
|
|
7
24
|
function resolvePath(input, ctx) {
|
|
8
25
|
return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);
|
|
9
26
|
}
|
|
@@ -28,6 +45,7 @@ function safeResolve(input, ctx) {
|
|
|
28
45
|
|
|
29
46
|
// src/glob.ts
|
|
30
47
|
var DEFAULT_IGNORE = ["node_modules", ".git", "dist", "build", ".next", "coverage", ".turbo"];
|
|
48
|
+
var WALK_CONCURRENCY = 16;
|
|
31
49
|
var globTool = {
|
|
32
50
|
name: "glob",
|
|
33
51
|
category: "Filesystem",
|
|
@@ -65,6 +83,22 @@ var globTool = {
|
|
|
65
83
|
const re = compileGlob(input.pattern);
|
|
66
84
|
const results = [];
|
|
67
85
|
let truncated = false;
|
|
86
|
+
const pushResult = async (full) => {
|
|
87
|
+
if (truncated || results.length >= limit) {
|
|
88
|
+
truncated = true;
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
const st = await fs.stat(full);
|
|
93
|
+
if (truncated || results.length >= limit) {
|
|
94
|
+
truncated = true;
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
results.push({ rel: full, mtime: st.mtimeMs });
|
|
98
|
+
if (results.length >= limit) truncated = true;
|
|
99
|
+
} catch {
|
|
100
|
+
}
|
|
101
|
+
};
|
|
68
102
|
const walk = async (dir, relPrefix) => {
|
|
69
103
|
if (results.length >= limit) {
|
|
70
104
|
truncated = true;
|
|
@@ -76,6 +110,8 @@ var globTool = {
|
|
|
76
110
|
} catch {
|
|
77
111
|
return;
|
|
78
112
|
}
|
|
113
|
+
const subdirs = [];
|
|
114
|
+
const matchedFiles = [];
|
|
79
115
|
for (const e of entries) {
|
|
80
116
|
const name = e.name;
|
|
81
117
|
if (DEFAULT_IGNORE.includes(name)) continue;
|
|
@@ -83,22 +119,36 @@ var globTool = {
|
|
|
83
119
|
const rel = relPrefix ? `${relPrefix}/${name}` : name;
|
|
84
120
|
const full = path.join(dir, name);
|
|
85
121
|
if (e.isDirectory()) {
|
|
86
|
-
|
|
87
|
-
if (truncated) return;
|
|
122
|
+
subdirs.push({ full, rel });
|
|
88
123
|
} else if (e.isFile()) {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
124
|
+
re.lastIndex = 0;
|
|
125
|
+
const relMatch = re.test(rel);
|
|
126
|
+
re.lastIndex = 0;
|
|
127
|
+
const nameMatch = re.test(name);
|
|
128
|
+
if (relMatch || nameMatch) {
|
|
129
|
+
matchedFiles.push(full);
|
|
130
|
+
}
|
|
131
|
+
} else if (e.isSymbolicLink()) {
|
|
132
|
+
try {
|
|
133
|
+
const st = await fs.stat(full);
|
|
134
|
+
if (st.isDirectory()) {
|
|
135
|
+
subdirs.push({ full, rel });
|
|
136
|
+
} else if (st.isFile()) {
|
|
137
|
+
re.lastIndex = 0;
|
|
138
|
+
const relMatch = re.test(rel);
|
|
139
|
+
re.lastIndex = 0;
|
|
140
|
+
const nameMatch = re.test(name);
|
|
141
|
+
if (relMatch || nameMatch) matchedFiles.push(full);
|
|
98
142
|
}
|
|
143
|
+
} catch {
|
|
99
144
|
}
|
|
100
145
|
}
|
|
146
|
+
if (truncated) return;
|
|
101
147
|
}
|
|
148
|
+
await mapWithConcurrency(matchedFiles, WALK_CONCURRENCY, pushResult);
|
|
149
|
+
if (truncated) return;
|
|
150
|
+
const remainingSubdirs = truncated ? [] : subdirs;
|
|
151
|
+
await mapWithConcurrency(remainingSubdirs, WALK_CONCURRENCY, ({ full, rel }) => walk(full, rel));
|
|
102
152
|
};
|
|
103
153
|
await walk(base, "");
|
|
104
154
|
results.sort((a, b) => b.mtime - a.mtime);
|
package/dist/glob.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/_util.ts","../src/glob.ts"],"names":["path2"],"mappings":";;;;;;AA8BO,SAAS,WAAA,CAAY,OAAe,GAAA,EAAsB;AAC/D,EAAA,OAAY,IAAA,CAAA,UAAA,CAAW,KAAK,CAAA,GAAS,IAAA,CAAA,SAAA,CAAU,KAAK,CAAA,GAAS,IAAA,CAAA,OAAA,CAAQ,GAAA,CAAI,UAAA,IAAc,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AACvG;A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AAAA,cACF;AAAA,YACF,CAAA,CAAA,MAAQ;AAAA,YAER;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAA;AACA,IAAA,MAAM,IAAA,CAAK,MAAM,EAAE,CAAA;AACnB,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA,EAAG,MAAM,CAAA,CAAE,KAAA,GAAQ,EAAE,KAAK,CAAA;AACxC,IAAA,OAAO,EAAE,OAAO,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,GAAG,CAAA,EAAG,SAAA,EAAU;AAAA,EACvD;AACF;AAEA,eAAe,cAAc,GAAA,EAAgC;AAC3D,EAAA,IAAI;AACF,IAAA,MAAM,MAAM,MAAS,EAAA,CAAA,QAAA,CAAcA,UAAK,GAAA,EAAK,YAAY,GAAG,MAAM,CAAA;AAClE,IAAA,OAAO,IACJ,KAAA,CAAM,IAAI,EACV,GAAA,CAAI,CAAC,MAAM,CAAA,CAAE,IAAA,EAAM,CAAA,CACnB,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,IAAK,CAAC,CAAA,CAAE,UAAA,CAAW,GAAG,CAAC,CAAA;AAAA,EAC1C,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF","file":"glob.js","sourcesContent":["import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { compileGlob } from '@wrongstack/core';\nimport type { Tool } from '@wrongstack/core';\nimport { safeResolve } from './_util.js';\n\ninterface GlobInput {\n pattern: string;\n path?: string | undefined;\n limit?: number | undefined;\n}\n\ninterface GlobOutput {\n files: string[];\n truncated: boolean;\n}\n\nconst DEFAULT_IGNORE = ['node_modules', '.git', 'dist', 'build', '.next', 'coverage', '.turbo'];\n\nexport const globTool: Tool<GlobInput, GlobOutput> = {\n name: 'glob',\n category: 'Filesystem',\n description:\n 'Find files matching a glob pattern. Fast way to discover relevant files before reading, grepping, or editing them.',\n usageHint:\n 'RECOMMENDED FOR SCOPING SEARCHES:\\n\\n' +\n '- Use early to get a list of files you actually care about.\\n' +\n '- Combine with `path` and `limit`.\\n' +\n '- Default ignores common build/dependency directories.\\n' +\n 'Much more efficient than shell `find` for most use cases inside the agent.',\n permission: 'auto',\n mutating: false,\n capabilities: ['fs.read'],\n icon: 'folder',\n maxOutputBytes: 65_536,\n timeoutMs: 5_000,\n inputSchema: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Glob pattern to match (e.g. \"**/*.ts\", \"src/**\").',\n },\n path: {\n type: 'string',\n description: 'Base directory to search from (defaults to project root).',\n },\n limit: {\n type: 'integer',\n description: 'Maximum number of results to return (default 1000, max 5000).',\n },\n },\n required: ['pattern'],\n },\n async execute(input, ctx) {\n if (!input?.pattern) throw new Error('glob: pattern is required');\n const base = input.path ? safeResolve(input.path, ctx) : ctx.cwd;\n const limit = Math.max(1, Math.min(input.limit ?? 1000, 5000));\n\n const ignored = await readGitignore(base);\n const re = compileGlob(input.pattern);\n\n const results: { rel: string; mtime: number }[] = [];\n let truncated = false;\n const walk = async (dir: string, relPrefix: string): Promise<void> => {\n /* v8 ignore start -- the inner limit guards (file push + post-recursion return) always stop first; this re-entry guard is defensive. */\n if (results.length >= limit) {\n truncated = true;\n return;\n }\n /* v8 ignore stop */\n let entries: import('node:fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const e of entries) {\n const name = e.name;\n if (DEFAULT_IGNORE.includes(name)) continue;\n if (ignored.includes(name)) continue;\n const rel = relPrefix ? `${relPrefix}/${name}` : name;\n const full = path.join(dir, name);\n if (e.isDirectory()) {\n await walk(full, rel);\n if (truncated) return;\n } else if (e.isFile()) {\n if (re.test(rel) || re.test(name)) {\n try {\n const st = await fs.stat(full);\n results.push({ rel: full, mtime: st.mtimeMs });\n if (results.length >= limit) {\n truncated = true;\n return;\n }\n } catch {\n // skip stat error\n }\n }\n }\n }\n };\n await walk(base, '');\n results.sort((a, b) => b.mtime - a.mtime);\n return { files: results.map((r) => r.rel), truncated };\n },\n};\n\nasync function readGitignore(dir: string): Promise<string[]> {\n try {\n const raw = await fs.readFile(path.join(dir, '.gitignore'), 'utf8');\n return raw\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l && !l.startsWith('#'));\n } catch {\n return [];\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/_concurrency.ts","../src/_util.ts","../src/glob.ts"],"names":["path2"],"mappings":";;;;;;;;AAcA,eAAsB,kBAAA,CACpB,KAAA,EACA,KAAA,EACA,EAAA,EACc;AACd,EAAA,IAAI,KAAA,CAAM,MAAA,KAAW,CAAA,EAAG,OAAO,EAAC;AAChC,EAAA,MAAM,cAAA,GAAiB,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,IAAI,KAAA,GAAQ,CAAA,EAAG,KAAA,CAAM,MAAM,CAAC,CAAA;AACpE,EAAA,MAAM,OAAA,GAAe,IAAI,KAAA,CAAM,KAAA,CAAM,MAAM,CAAA;AAC3C,EAAA,IAAI,SAAA,GAAY,CAAA;AAEhB,EAAA,MAAM,SAAS,YAA2B;AACxC,IAAA,OAAO,IAAA,EAAM;AACX,MAAA,MAAM,CAAA,GAAI,SAAA,EAAA;AACV,MAAA,IAAI,CAAA,IAAK,MAAM,MAAA,EAAQ;AACvB,MAAA,OAAA,CAAQ,CAAC,CAAA,GAAI,MAAM,EAAA,CAAG,KAAA,CAAM,CAAC,CAAM,CAAA;AAAA,IACrC;AAAA,EACF,CAAA;AAEA,EAAA,M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Y,GAAG,MAAM,CAAA;AAClE,IAAA,OAAO,IACJ,KAAA,CAAM,IAAI,EACV,GAAA,CAAI,CAAC,MAAM,CAAA,CAAE,IAAA,EAAM,CAAA,CACnB,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,IAAK,CAAC,CAAA,CAAE,UAAA,CAAW,GAAG,CAAC,CAAA;AAAA,EAC1C,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF","file":"glob.js","sourcesContent":["/**\n * Bounded-concurrency async map.\n *\n * Runs `fn` over `items` with at most `limit` in-flight promises. Order of\n * results matches input order. Errors reject the returned promise on the first\n * failure — the remaining in-flight work is not awaited; this matches\n * `Promise.all` semantics for callers that want fail-fast behavior.\n *\n * Lives here (rather than imported from `@wrongstack/bench`) because:\n * 1. tools sits below bench in the dependency graph — bench is a consumer of\n * tools, never the other way around.\n * 2. The semantics used by grep/glob are deliberately simple (fail-fast,\n * no cancellation, no progress) and don't need bench's richer options.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n if (items.length === 0) return [];\n const effectiveLimit = Math.max(1, Math.min(limit | 0, items.length));\n const results: R[] = new Array(items.length);\n let nextIndex = 0;\n\n const worker = async (): Promise<void> => {\n while (true) {\n const i = nextIndex++;\n if (i >= items.length) return;\n results[i] = await fn(items[i] as T);\n }\n };\n\n await Promise.all(Array.from({ length: effectiveLimit }, worker));\n return results;\n}\n","import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { compileGlob } from '@wrongstack/core';\nimport type { Tool } from '@wrongstack/core';\nimport { mapWithConcurrency } from './_concurrency.js';\nimport { safeResolve } from './_util.js';\n\ninterface GlobInput {\n pattern: string;\n path?: string | undefined;\n limit?: number | undefined;\n}\n\ninterface GlobOutput {\n files: string[];\n truncated: boolean;\n}\n\nconst DEFAULT_IGNORE = ['node_modules', '.git', 'dist', 'build', '.next', 'coverage', '.turbo'];\nconst WALK_CONCURRENCY = 16;\n\nexport const globTool: Tool<GlobInput, GlobOutput> = {\n name: 'glob',\n category: 'Filesystem',\n description:\n 'Find files matching a glob pattern. Fast way to discover relevant files before reading, grepping, or editing them.',\n usageHint:\n 'RECOMMENDED FOR SCOPING SEARCHES:\\n\\n' +\n '- Use early to get a list of files you actually care about.\\n' +\n '- Combine with `path` and `limit`.\\n' +\n '- Default ignores common build/dependency directories.\\n' +\n 'Much more efficient than shell `find` for most use cases inside the agent.',\n permission: 'auto',\n mutating: false,\n capabilities: ['fs.read'],\n icon: 'folder',\n maxOutputBytes: 65_536,\n timeoutMs: 5_000,\n inputSchema: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Glob pattern to match (e.g. \"**/*.ts\", \"src/**\").',\n },\n path: {\n type: 'string',\n description: 'Base directory to search from (defaults to project root).',\n },\n limit: {\n type: 'integer',\n description: 'Maximum number of results to return (default 1000, max 5000).',\n },\n },\n required: ['pattern'],\n },\n async execute(input, ctx) {\n if (!input?.pattern) throw new Error('glob: pattern is required');\n const base = input.path ? safeResolve(input.path, ctx) : ctx.cwd;\n const limit = Math.max(1, Math.min(input.limit ?? 1000, 5000));\n\n const ignored = await readGitignore(base);\n const re = compileGlob(input.pattern);\n\n const results: { rel: string; mtime: number }[] = [];\n let truncated = false;\n const pushResult = async (full: string): Promise<void> => {\n // Bail before stat if a concurrent worker has already filled the budget —\n // the limit is a global cap across all parallel walkers, not per-worker.\n if (truncated || results.length >= limit) {\n truncated = true;\n return;\n }\n try {\n const st = await fs.stat(full);\n // Re-check after the await: another worker may have filled the budget\n // while we were waiting on fs.stat.\n if (truncated || results.length >= limit) {\n truncated = true;\n return;\n }\n results.push({ rel: full, mtime: st.mtimeMs });\n if (results.length >= limit) truncated = true;\n } catch {\n // skip stat error\n }\n };\n const walk = async (dir: string, relPrefix: string): Promise<void> => {\n /* v8 ignore start -- the inner limit guards (file push + post-recursion return) always stop first; this re-entry guard is defensive. */\n if (results.length >= limit) {\n truncated = true;\n return;\n }\n /* v8 ignore stop */\n let entries: import('node:fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n const subdirs: Array<{ full: string; rel: string }> = [];\n const matchedFiles: string[] = [];\n for (const e of entries) {\n const name = e.name;\n if (DEFAULT_IGNORE.includes(name)) continue;\n if (ignored.includes(name)) continue;\n const rel = relPrefix ? `${relPrefix}/${name}` : name;\n const full = path.join(dir, name);\n if (e.isDirectory()) {\n subdirs.push({ full, rel });\n } else if (e.isFile()) {\n re.lastIndex = 0;\n const relMatch = re.test(rel);\n re.lastIndex = 0;\n const nameMatch = re.test(name);\n if (relMatch || nameMatch) {\n matchedFiles.push(full);\n }\n } else if (e.isSymbolicLink()) {\n try {\n const st = await fs.stat(full);\n if (st.isDirectory()) {\n subdirs.push({ full, rel });\n } else if (st.isFile()) {\n re.lastIndex = 0;\n const relMatch = re.test(rel);\n re.lastIndex = 0;\n const nameMatch = re.test(name);\n if (relMatch || nameMatch) matchedFiles.push(full);\n }\n } catch {\n // skip broken symlink/stat error\n }\n }\n if (truncated) return;\n }\n await mapWithConcurrency(matchedFiles, WALK_CONCURRENCY, pushResult);\n if (truncated) return;\n // Subdir walks: each one re-checks the limit at entry (re-entry guard),\n // but we also stop dispatching new walks once truncated, so siblings of\n // a hit-limit subdir don't keep adding results.\n const remainingSubdirs = truncated ? [] : subdirs;\n await mapWithConcurrency(remainingSubdirs, WALK_CONCURRENCY, ({ full, rel }) => walk(full, rel));\n };\n await walk(base, '');\n results.sort((a, b) => b.mtime - a.mtime);\n return { files: results.map((r) => r.rel), truncated };\n },\n};\n\nasync function readGitignore(dir: string): Promise<string[]> {\n try {\n const raw = await fs.readFile(path.join(dir, '.gitignore'), 'utf8');\n return raw\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l && !l.startsWith('#'));\n } catch {\n return [];\n }\n}\n"]}
|
package/dist/grep.js
CHANGED
|
@@ -6,6 +6,23 @@ import * as path from 'node:path';
|
|
|
6
6
|
|
|
7
7
|
// src/grep.ts
|
|
8
8
|
|
|
9
|
+
// src/_concurrency.ts
|
|
10
|
+
async function mapWithConcurrency(items, limit, fn) {
|
|
11
|
+
if (items.length === 0) return [];
|
|
12
|
+
const effectiveLimit = Math.max(1, Math.min(limit | 0, items.length));
|
|
13
|
+
const results = new Array(items.length);
|
|
14
|
+
let nextIndex = 0;
|
|
15
|
+
const worker = async () => {
|
|
16
|
+
while (true) {
|
|
17
|
+
const i = nextIndex++;
|
|
18
|
+
if (i >= items.length) return;
|
|
19
|
+
results[i] = await fn(items[i]);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
await Promise.all(Array.from({ length: effectiveLimit }, worker));
|
|
23
|
+
return results;
|
|
24
|
+
}
|
|
25
|
+
|
|
9
26
|
// src/_regex.ts
|
|
10
27
|
var MAX_PATTERN_LEN = 256;
|
|
11
28
|
var DANGEROUS_PATTERNS = [
|
|
@@ -82,6 +99,8 @@ function isBinaryBuffer(buf) {
|
|
|
82
99
|
// src/grep.ts
|
|
83
100
|
var DEFAULT_IGNORE = ["node_modules", ".git", "dist", "build", ".next", "coverage"];
|
|
84
101
|
var NATIVE_SCAN_CONCURRENCY = 32;
|
|
102
|
+
var NATIVE_READ_CHUNK_BYTES = 64 * 1024;
|
|
103
|
+
var NATIVE_MAX_FILE_BYTES = 1e6;
|
|
85
104
|
var grepTool = {
|
|
86
105
|
name: "grep",
|
|
87
106
|
category: "Search",
|
|
@@ -306,7 +325,8 @@ async function runNative(input, base, mode, limit, signal) {
|
|
|
306
325
|
const re = compiled.regex;
|
|
307
326
|
const globRe = input.glob ? compileGlob(input.glob) : null;
|
|
308
327
|
const matches = [];
|
|
309
|
-
const
|
|
328
|
+
const countOnlyFirstHit = mode === "count" && limit === 1;
|
|
329
|
+
const maxBytes = mode === "content" ? NATIVE_MAX_FILE_BYTES : Math.min(NATIVE_MAX_FILE_BYTES, 256 * 1024);
|
|
310
330
|
let total = 0;
|
|
311
331
|
let stopped = false;
|
|
312
332
|
const scanFile = async (full, name) => {
|
|
@@ -315,34 +335,79 @@ async function runNative(input, base, mode, limit, signal) {
|
|
|
315
335
|
if (globRe) globRe.lastIndex = 0;
|
|
316
336
|
try {
|
|
317
337
|
const stat2 = await fs.stat(full);
|
|
318
|
-
if (stat2.size >
|
|
319
|
-
const
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
const
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
338
|
+
if (!stat2.isFile() || stat2.size > maxBytes || stopped || signal.aborted) return;
|
|
339
|
+
const file = await fs.open(full, "r");
|
|
340
|
+
try {
|
|
341
|
+
let bytesReadTotal = 0;
|
|
342
|
+
let lineNumber = 0;
|
|
343
|
+
let fileHits = 0;
|
|
344
|
+
let leftover = "";
|
|
345
|
+
let binaryChecked = false;
|
|
346
|
+
const buffer = Buffer.allocUnsafe(Math.min(NATIVE_READ_CHUNK_BYTES, maxBytes));
|
|
347
|
+
while (!stopped && !signal.aborted && bytesReadTotal < maxBytes) {
|
|
348
|
+
const remaining = maxBytes - bytesReadTotal;
|
|
349
|
+
const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, remaining), null);
|
|
350
|
+
if (bytesRead === 0) break;
|
|
351
|
+
const chunk = buffer.subarray(0, bytesRead);
|
|
352
|
+
if (!binaryChecked) {
|
|
353
|
+
binaryChecked = true;
|
|
354
|
+
if (isBinaryBuffer(chunk)) return;
|
|
355
|
+
}
|
|
356
|
+
bytesReadTotal += bytesRead;
|
|
357
|
+
const text = leftover + chunk.toString("utf8");
|
|
358
|
+
const lines = text.split(/\r?\n/);
|
|
359
|
+
leftover = lines.pop() ?? "";
|
|
360
|
+
for (const rawLine of lines) {
|
|
361
|
+
if (stopped || signal.aborted) break;
|
|
362
|
+
lineNumber++;
|
|
363
|
+
const ln = capSubject(rawLine);
|
|
364
|
+
re.lastIndex = 0;
|
|
365
|
+
if (!re.test(ln)) continue;
|
|
366
|
+
fileHits++;
|
|
367
|
+
total++;
|
|
368
|
+
if (mode === "content") {
|
|
369
|
+
if (matches.length < limit) matches.push(`${full}:${lineNumber}:${ln}`);
|
|
370
|
+
} else if (mode === "files_with_matches") {
|
|
371
|
+
if (fileHits === 1 && matches.length < limit) matches.push(full);
|
|
372
|
+
break;
|
|
373
|
+
} else if (fileHits === 1 && matches.length < limit) {
|
|
374
|
+
matches.push(`${full}:${countOnlyFirstHit ? 1 : 0}`);
|
|
375
|
+
}
|
|
376
|
+
if (countOnlyFirstHit || mode !== "content" && matches.length >= limit) {
|
|
377
|
+
stopped = true;
|
|
378
|
+
break;
|
|
379
|
+
}
|
|
333
380
|
}
|
|
381
|
+
if (mode === "files_with_matches" && fileHits > 0) break;
|
|
334
382
|
}
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
383
|
+
if (!stopped && !signal.aborted && leftover.length > 0) {
|
|
384
|
+
lineNumber++;
|
|
385
|
+
const ln = capSubject(leftover);
|
|
386
|
+
re.lastIndex = 0;
|
|
387
|
+
if (re.test(ln)) {
|
|
388
|
+
fileHits++;
|
|
389
|
+
total++;
|
|
390
|
+
if (mode === "content") {
|
|
391
|
+
if (matches.length < limit) matches.push(`${full}:${lineNumber}:${ln}`);
|
|
392
|
+
} else if (mode === "files_with_matches") {
|
|
393
|
+
if (matches.length < limit) matches.push(full);
|
|
394
|
+
} else if (matches.length < limit) {
|
|
395
|
+
matches.push(`${full}:${countOnlyFirstHit ? 1 : fileHits}`);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
340
398
|
}
|
|
341
|
-
if (
|
|
342
|
-
|
|
399
|
+
if (fileHits > 0) {
|
|
400
|
+
if (mode === "count") {
|
|
401
|
+
const idx = matches.findIndex((entry) => entry.startsWith(`${full}:`));
|
|
402
|
+
if (idx !== -1) matches[idx] = `${full}:${fileHits}`;
|
|
403
|
+
}
|
|
404
|
+
if (mode === "files_with_matches" && matches.length >= limit) stopped = true;
|
|
343
405
|
}
|
|
406
|
+
if (mode === "content" && matches.length >= limit) stopped = true;
|
|
407
|
+
if (mode === "count" && matches.length >= limit && (countOnlyFirstHit || mode !== "count")) stopped = true;
|
|
408
|
+
} finally {
|
|
409
|
+
await file.close();
|
|
344
410
|
}
|
|
345
|
-
if (matches.length >= limit) stopped = true;
|
|
346
411
|
} catch {
|
|
347
412
|
}
|
|
348
413
|
};
|
|
@@ -355,18 +420,20 @@ async function runNative(input, base, mode, limit, signal) {
|
|
|
355
420
|
return;
|
|
356
421
|
}
|
|
357
422
|
const files = [];
|
|
423
|
+
const subdirs = [];
|
|
358
424
|
for (const e of entries) {
|
|
359
425
|
if (stopped) return;
|
|
360
426
|
if (DEFAULT_IGNORE.includes(e.name)) continue;
|
|
361
427
|
if (e.isSymbolicLink()) continue;
|
|
362
428
|
const full = path.join(dir, e.name);
|
|
363
429
|
if (e.isDirectory()) {
|
|
364
|
-
|
|
430
|
+
subdirs.push(full);
|
|
365
431
|
} else if (e.isFile()) {
|
|
366
432
|
files.push({ full, name: e.name });
|
|
367
433
|
}
|
|
368
434
|
}
|
|
369
435
|
await mapWithConcurrency(files, NATIVE_SCAN_CONCURRENCY, ({ full, name }) => scanFile(full, name));
|
|
436
|
+
await mapWithConcurrency(subdirs, Math.min(16, NATIVE_SCAN_CONCURRENCY), walk);
|
|
370
437
|
};
|
|
371
438
|
await walk(base);
|
|
372
439
|
return {
|
|
@@ -376,20 +443,6 @@ async function runNative(input, base, mode, limit, signal) {
|
|
|
376
443
|
used: "native"
|
|
377
444
|
};
|
|
378
445
|
}
|
|
379
|
-
async function mapWithConcurrency(items, concurrency, fn) {
|
|
380
|
-
if (items.length === 0) return;
|
|
381
|
-
let next = 0;
|
|
382
|
-
const workerCount = Math.min(Math.max(1, concurrency), items.length);
|
|
383
|
-
const workers = Array.from({ length: workerCount }, async () => {
|
|
384
|
-
for (; ; ) {
|
|
385
|
-
const idx = next++;
|
|
386
|
-
if (idx >= items.length) return;
|
|
387
|
-
const item = items[idx];
|
|
388
|
-
if (item !== void 0) await fn(item);
|
|
389
|
-
}
|
|
390
|
-
});
|
|
391
|
-
await Promise.all(workers);
|
|
392
|
-
}
|
|
393
446
|
|
|
394
447
|
export { grepTool };
|
|
395
448
|
//# sourceMappingURL=grep.js.map
|
package/dist/grep.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/_regex.ts","../src/_util.ts","../src/grep.ts"],"names":["resolve","stat","path2"],"mappings":";;;;;;;;;AAuBA,IAAM,eAAA,GAAkB,GAAA;AAIxB,IAAM,kBAAA,GAA4C;AAAA;AAAA,EAEhD,0BAAA;AAAA,EACA,6BAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,2BAAA;AAAA;AAAA,EAEA;AACF,CAAA;AAYO,SAAS,gBAAA,CAAiB,SAAiB,KAAA,EAA4C;AAC5F,EAAA,IAAI,OAAO,YAAY,QAAA,EAAU;AAC/B,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,0BAAA,EAA2B;AAAA,EACzD;AACA,EAAA,IAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AACxB,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,kBAAA,EAAmB;AAAA,EACjD;AACA,EAAA,IAAI,OAAA,CAAQ,SAAS,eAAA,EAAiB;AACpC,IAAA,OAAO,EAAE,E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,IAAA,EAAK,KAAM,QAAA,CAAS,IAAA,EAAM,IAAI,CAAC,CAAA;AAAA,EACnG,CAAA;AACA,EAAA,MAAM,KAAK,IAAI,CAAA;AAEf,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,KAAA,EAAO,KAAA;AAAA,IACP,SAAA,EAAW,OAAA;AAAA,IACX,IAAA,EAAM;AAAA,GACR;AACF;AAEA,eAAe,kBAAA,CACb,KAAA,EACA,WAAA,EACA,EAAA,EACe;AACf,EAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACxB,EAAA,IAAI,IAAA,GAAO,CAAA;AACX,EAAA,MAAM,WAAA,GAAc,KAAK,GAAA,CAAI,IAAA,CAAK,IAAI,CAAA,EAAG,WAAW,CAAA,EAAG,KAAA,CAAM,MAAM,CAAA;AACnE,EAAA,MAAM,UAAU,KAAA,CAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,WAAA,IAAe,YAAY;AAC9D,IAAA,WAAS;AACP,MAAA,MAAM,GAAA,GAAM,IAAA,EAAA;AACZ,MAAA,IAAI,GAAA,IAAO,MAAM,MAAA,EAAQ;AACzB,MAAA,MAAM,IAAA,GAAO,MAAM,GAAG,CAAA;AACtB,MAAA,IAAI,IAAA,KAAS,MAAA,EAAW,MAAM,EAAA,CAAG,IAAI,CAAA;AAAA,IACvC;AAAA,EACF,CAAC,CAAA;AACD,EAAA,MAAM,OAAA,CAAQ,IAAI,OAAO,CAAA;AAC3B","file":"grep.js","sourcesContent":["/**\n * Compile a user-supplied regex with conservative bounds against ReDoS.\n *\n * Node's regex engine (V8) is backtracking-based and cannot interrupt a\n * synchronous match — a pattern like `(a+)+$` against a sufficiently long\n * line will pin a worker for seconds. The executor's outer `timeoutMs` only\n * fires between async boundaries, so a long regex eval inside a sync loop\n * is uninterruptible.\n *\n * We can't fully prevent ReDoS without an alternative engine (re2-wasm), but\n * we can sharply limit the blast radius:\n *\n * 1. Cap pattern length — practically all legitimate user patterns are\n * under 256 characters. A 4 KB pattern is almost certainly malicious\n * or a copy-paste accident.\n * 2. Reject patterns containing the most obvious super-linear structures.\n * This is a coarse filter (false-positives are likely; we accept that\n * for hostile-input contexts).\n *\n * Callers should additionally bound the *subject* length (e.g. by capping\n * line size before matching).\n */\n\nconst MAX_PATTERN_LEN = 256;\n\n// Heuristics for catastrophic-backtracking constructs. Not exhaustive; bias\n// toward false-positives in tools that accept LLM-generated input.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n // (a+)+, (.*)+, etc — nested quantifier on a group with internal quantifier\n /(\\([^)]*[+*][^)]*\\))[+*]/,\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/,\n // Adjacent quantifiers: a++ a*+\n /[+*]{2,}/,\n // Quantifier on alternation with length 2+\n /\\([^|)]+\\|[^)]+\\)[+*][+*]/,\n // Greedy quantifier inside lookahead/lookbehind — (?!.*a+)\n /[([][^)\\]]*[+*][^)\\]]*[)\\]][^)]*\\?\\??/,\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking — rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n\n/**\n * Truncate a subject line to a safe length for synchronous regex eval.\n * The cap is conservative; tools that need exact-line matching against very\n * long lines should use ripgrep externally rather than the native walker.\n */\nexport const MAX_SUBJECT_LEN = 64 * 1024;\n\nexport function capSubject(line: string): string {\n return line.length > MAX_SUBJECT_LEN ? line.slice(0, MAX_SUBJECT_LEN) : line;\n}\n","import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import { expectDefined } from '@wrongstack/core';\nimport { spawn } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { Tool, ToolStreamEvent } from '@wrongstack/core';\nimport { buildChildEnv, compileGlob } from '@wrongstack/core';\nimport { capSubject, compileUserRegex } from './_regex.js';\nimport { isBinaryBuffer, safeResolve } from './_util.js';\ninterface GrepInput {\n pattern: string;\n path?: string | undefined;\n glob?: string | undefined;\n output_mode?: 'content' | 'files_with_matches' | 'count' | undefined;\n context_lines?: number | undefined;\n case_insensitive?: boolean | undefined;\n limit?: number | undefined;\n}\n\ninterface GrepOutput {\n matches: string[];\n count: number;\n truncated: boolean;\n used: 'rg' | 'native';\n}\n\nconst DEFAULT_IGNORE = ['node_modules', '.git', 'dist', 'build', '.next', 'coverage'];\nconst NATIVE_SCAN_CONCURRENCY = 32;\n\nexport const grepTool: Tool<GrepInput, GrepOutput> = {\n name: 'grep',\n category: 'Search',\n description:\n 'Search across files using a regular expression. This is one of the primary code search tools. ' +\n 'Prefers ripgrep for speed and features when available.',\n usageHint:\n 'POWERFUL CODE SEARCH TOOL:\\n\\n' +\n '- `pattern` is a regular expression.\\n' +\n '- Use `output_mode: \"content\"` (default) to get matching lines with context.\\n' +\n '- Use `\"files_with_matches\"` when you only need the list of files.\\n' +\n '- Use `\"count\"` for quick statistics.\\n' +\n '- `glob` and `path` let you narrow the search scope significantly.\\n' +\n '- Always prefer this over `bash grep` when searching code.',\n permission: 'auto',\n mutating: false,\n capabilities: ['fs.read'],\n icon: 'search',\n maxOutputBytes: 131_072,\n timeoutMs: 10_000,\n inputSchema: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Regular expression pattern to search for in file contents.',\n },\n path: {\n type: 'string',\n description: 'Limit search to this directory or file (relative to project root).',\n },\n glob: {\n type: 'string',\n description: 'Glob filter for which files to include (e.g. \"**/*.ts\", \"src/**\").',\n },\n output_mode: {\n type: 'string',\n enum: ['content', 'files_with_matches', 'count'],\n description: 'Return style: detailed matches, just file list, or count only.',\n },\n context_lines: {\n type: 'integer',\n description: 'How many lines of surrounding context to include with each match.',\n },\n case_insensitive: {\n type: 'boolean',\n description: 'Ignore case when matching.',\n },\n limit: {\n type: 'integer',\n description: 'Maximum number of matches to return.',\n },\n },\n required: ['pattern'],\n },\n async execute(input, ctx, opts) {\n let final: GrepOutput | undefined;\n const executeStream = grepTool.executeStream;\n if (!executeStream) throw new Error('grepTool: stream execution unavailable');\n for await (const ev of executeStream(input, ctx, opts)) {\n if (ev.type === 'final') final = ev.output;\n }\n if (!final) throw new Error('grep: stream ended without final event');\n return final;\n },\n async *executeStream(input, ctx, opts): AsyncGenerator<ToolStreamEvent<GrepOutput>> {\n if (!input?.pattern) throw new Error('grep: pattern is required');\n const base = input.path ? safeResolve(input.path, ctx) : ctx.cwd;\n const mode = input.output_mode ?? 'content';\n const limit = Math.max(1, Math.min(input.limit ?? 200, 2000));\n const validation = compileUserRegex(input.pattern, input.case_insensitive ? 'i' : '');\n if (!validation.ok) {\n throw new Error(`grep: ${validation.reason}`);\n }\n\n const rgAvailable = await detectRg(opts.signal);\n if (rgAvailable) {\n try {\n yield* runRgStream(input, base, mode, limit, opts.signal);\n return;\n } catch {\n // fall through to native\n }\n }\n yield { type: 'log', text: 'Falling back to native grep…' };\n const out = await runNative(input, base, mode, limit, opts.signal);\n yield { type: 'final', output: out };\n },\n};\n\nasync function detectRg(signal: AbortSignal): Promise<boolean> {\n return new Promise((resolve) => {\n try {\n const p = spawn('rg', ['--version'], { env: buildChildEnv(), stdio: 'ignore', signal, windowsHide: true });\n p.on('error', () => resolve(false));\n p.on('close', (code) => resolve(code === 0));\n } catch {\n resolve(false);\n }\n });\n}\n\nasync function* runRgStream(\n input: GrepInput,\n base: string,\n mode: 'content' | 'files_with_matches' | 'count',\n limit: number,\n signal: AbortSignal,\n): AsyncGenerator<ToolStreamEvent<GrepOutput>> {\n const args: string[] = ['--no-heading'];\n if (input.case_insensitive) args.push('-i');\n if (mode === 'files_with_matches') args.push('-l');\n if (mode === 'count') args.push('-c');\n if (mode === 'content') {\n args.push('-n');\n if (input.context_lines) args.push('-C', String(input.context_lines));\n }\n for (const ignored of DEFAULT_IGNORE) {\n args.push('--glob', `!${ignored}/**`, '--glob', `!**/${ignored}/**`);\n }\n if (input.glob) args.push('--glob', input.glob);\n args.push('--', input.pattern, base);\n\n const matches: string[] = [];\n let buf = '';\n let totalLines = 0;\n let totalCount = 0;\n let batchSinceFlush = 0;\n const FLUSH_AT = 16; // yield a partial_output every 16 matches\n // Cap on the in-progress line buffer. Without this, a single huge \"line\"\n // (e.g. a file with no newlines under a symlink) plus a fast producer\n // would let `buf` grow unbounded. 1 MB comfortably holds any realistic\n // grep hit; beyond that we kill the child and surface a truncation.\n const MAX_BUF_BYTES = 1_000_000;\n let bufOverflow = false;\n\n const child = spawn('rg', args, { signal, env: buildChildEnv(), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });\n\n type Chunk = { kind: 'out' | 'close' | 'error'; data: string };\n const queue: Chunk[] = [];\n let waiter: (() => void) | undefined;\n const wake = () => {\n if (waiter) {\n const w = waiter;\n waiter = undefined;\n w();\n }\n };\n child.stdout?.on('data', (c) => {\n queue.push({ kind: 'out', data: c.toString() });\n wake();\n });\n child.on('error', (e) => {\n queue.push({ kind: 'error', data: e.message });\n wake();\n });\n child.on('close', () => {\n queue.push({ kind: 'close', data: '' });\n wake();\n });\n\n let pendingBatch: string[] = [];\n let errored = false;\n for (;;) {\n while (queue.length === 0) {\n await new Promise<void>((r) => {\n waiter = r;\n });\n }\n const c = expectDefined(queue.shift());\n if (c.kind === 'error') {\n errored = true;\n continue;\n }\n if (c.kind === 'close') break;\n buf += c.data;\n // Guard against a pathological producer (e.g. matching a huge binary\n // without newlines) pinning memory. Kill the child and mark the result\n // truncated; whatever we already captured stays intact.\n if (buf.length > MAX_BUF_BYTES && !bufOverflow) {\n bufOverflow = true;\n buf = buf.slice(-MAX_BUF_BYTES);\n try {\n child.kill('SIGTERM');\n } catch {\n /* ignore */\n }\n }\n const idx = buf.lastIndexOf('\\n');\n if (idx === -1) continue;\n const ready = buf.slice(0, idx);\n buf = buf.slice(idx + 1);\n for (const line of ready.split('\\n')) {\n if (!line) continue;\n totalLines++;\n if (mode === 'count') totalCount += parseRgCountLine(line);\n if (matches.length < limit) {\n matches.push(line);\n pendingBatch.push(line);\n batchSinceFlush++;\n }\n }\n if (batchSinceFlush >= FLUSH_AT) {\n yield {\n type: 'partial_output',\n text: pendingBatch.join('\\n'),\n data: { matches_so_far: matches.length },\n };\n pendingBatch = [];\n batchSinceFlush = 0;\n }\n }\n\n if (buf.trim()) {\n for (const line of buf.split('\\n')) {\n if (!line) continue;\n totalLines++;\n if (mode === 'count') totalCount += parseRgCountLine(line);\n if (matches.length < limit) {\n matches.push(line);\n pendingBatch.push(line);\n }\n }\n }\n if (pendingBatch.length > 0) {\n yield {\n type: 'partial_output',\n text: pendingBatch.join('\\n'),\n data: { matches_so_far: matches.length },\n };\n }\n if (errored) throw new Error('rg: spawn error');\n\n yield {\n type: 'final',\n output: {\n matches,\n count: mode === 'count' ? totalCount : totalLines,\n truncated: totalLines > limit || bufOverflow,\n used: 'rg',\n },\n };\n}\n\nfunction parseRgCountLine(line: string): number {\n const idx = line.lastIndexOf(':');\n if (idx === -1) return 0;\n const n = Number.parseInt(line.slice(idx + 1), 10);\n return Number.isFinite(n) ? n : 0;\n}\n\nasync function runNative(\n input: GrepInput,\n base: string,\n mode: 'content' | 'files_with_matches' | 'count',\n limit: number,\n signal: AbortSignal,\n): Promise<GrepOutput> {\n const flags = input.case_insensitive ? 'i' : '';\n const compiled = compileUserRegex(input.pattern, flags);\n if (!compiled.ok) {\n throw new Error(`grep: ${compiled.reason}`);\n }\n const re = compiled.regex;\n const globRe = input.glob ? compileGlob(input.glob) : null;\n const matches: string[] = [];\n const fileMatches = new Map<string, number>();\n let total = 0;\n let stopped = false;\n\n const scanFile = async (full: string, name: string): Promise<void> => {\n if (stopped || signal.aborted) return;\n if (globRe && !globRe.test(name) && !globRe.test(full)) return;\n if (globRe) globRe.lastIndex = 0;\n try {\n const stat = await fs.stat(full);\n if (stat.size > 1_000_000 || stopped || signal.aborted) return;\n const head = await fs.readFile(full);\n if (isBinaryBuffer(head) || stopped || signal.aborted) return;\n const text = head.toString('utf8');\n const lines = text.split(/\\r?\\n/);\n let fileHits = 0;\n for (let i = 0; i < lines.length; i++) {\n if (stopped || signal.aborted) break;\n const ln = capSubject(lines[i] ?? '');\n re.lastIndex = 0;\n if (re.test(ln)) {\n fileHits++;\n total++;\n if (mode === 'content' && matches.length < limit) {\n matches.push(`${full}:${i + 1}:${ln}`);\n }\n }\n }\n if (fileHits > 0) {\n fileMatches.set(full, fileHits);\n if (mode === 'files_with_matches' && matches.length < limit) {\n matches.push(full);\n }\n if (mode === 'count' && matches.length < limit) {\n matches.push(`${full}:${fileHits}`);\n }\n }\n if (matches.length >= limit) stopped = true;\n } catch {\n // skip read errors\n }\n };\n\n const walk = async (dir: string): Promise<void> => {\n if (stopped || signal.aborted) return;\n let entries: import('node:fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n const files: Array<{ full: string; name: string }> = [];\n for (const e of entries) {\n if (stopped) return;\n if (DEFAULT_IGNORE.includes(e.name)) continue;\n // Skip symlinks entirely. fs.Dirent.isDirectory/isFile return the\n // symlink's TYPE without resolving, but following the link into\n // arbitrary places (e.g. ~/.ssh) is the security concern. Tools\n // that genuinely need to traverse symlinks should opt in explicitly.\n if (e.isSymbolicLink()) continue;\n const full = path.join(dir, e.name);\n if (e.isDirectory()) {\n await walk(full);\n } else if (e.isFile()) {\n files.push({ full, name: e.name });\n }\n }\n await mapWithConcurrency(files, NATIVE_SCAN_CONCURRENCY, ({ full, name }) => scanFile(full, name));\n };\n await walk(base);\n\n return {\n matches,\n count: total,\n truncated: stopped,\n used: 'native',\n };\n}\n\nasync function mapWithConcurrency<T>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T) => Promise<void>,\n): Promise<void> {\n if (items.length === 0) return;\n let next = 0;\n const workerCount = Math.min(Math.max(1, concurrency), items.length);\n const workers = Array.from({ length: workerCount }, async () => {\n for (;;) {\n const idx = next++;\n if (idx >= items.length) return;\n const item = items[idx];\n if (item !== undefined) await fn(item);\n }\n });\n await Promise.all(workers);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/_concurrency.ts","../src/_regex.ts","../src/_util.ts","../src/grep.ts"],"names":["resolve","stat","path2"],"mappings":";;;;;;;;;AAcA,eAAsB,kBAAA,CACpB,KAAA,EACA,KAAA,EACA,EAAA,EACc;AACd,EAAA,IAAI,KAAA,CAAM,MAAA,KAAW,CAAA,EAAG,OAAO,EAAC;AAChC,EAAA,MAAM,cAAA,GAAiB,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,IAAI,KAAA,GAAQ,CAAA,EAAG,KAAA,CAAM,MAAM,CAAC,CAAA;AACpE,EAAA,MAAM,OAAA,GAAe,IAAI,KAAA,CAAM,KAAA,CAAM,MAAM,CAAA;AAC3C,EAAA,IAAI,SAAA,GAAY,CAAA;AAEhB,EAAA,MAAM,SAAS,YAA2B;AACxC,IAAA,OAAO,IAAA,EAAM;AACX,MAAA,MAAM,CAAA,GAAI,SAAA,EAAA;AACV,MAAA,IAAI,CAAA,IAAK,MAA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AG,IAAI,CAAA;AAAA,EAC/E,CAAA;AACA,EAAA,MAAM,KAAK,IAAI,CAAA;AAEf,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,KAAA,EAAO,KAAA;AAAA,IACP,SAAA,EAAW,OAAA;AAAA,IACX,IAAA,EAAM;AAAA,GACR;AACF","file":"grep.js","sourcesContent":["/**\n * Bounded-concurrency async map.\n *\n * Runs `fn` over `items` with at most `limit` in-flight promises. Order of\n * results matches input order. Errors reject the returned promise on the first\n * failure — the remaining in-flight work is not awaited; this matches\n * `Promise.all` semantics for callers that want fail-fast behavior.\n *\n * Lives here (rather than imported from `@wrongstack/bench`) because:\n * 1. tools sits below bench in the dependency graph — bench is a consumer of\n * tools, never the other way around.\n * 2. The semantics used by grep/glob are deliberately simple (fail-fast,\n * no cancellation, no progress) and don't need bench's richer options.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n if (items.length === 0) return [];\n const effectiveLimit = Math.max(1, Math.min(limit | 0, items.length));\n const results: R[] = new Array(items.length);\n let nextIndex = 0;\n\n const worker = async (): Promise<void> => {\n while (true) {\n const i = nextIndex++;\n if (i >= items.length) return;\n results[i] = await fn(items[i] as T);\n }\n };\n\n await Promise.all(Array.from({ length: effectiveLimit }, worker));\n return results;\n}\n","/**\n * Compile a user-supplied regex with conservative bounds against ReDoS.\n *\n * Node's regex engine (V8) is backtracking-based and cannot interrupt a\n * synchronous match — a pattern like `(a+)+$` against a sufficiently long\n * line will pin a worker for seconds. The executor's outer `timeoutMs` only\n * fires between async boundaries, so a long regex eval inside a sync loop\n * is uninterruptible.\n *\n * We can't fully prevent ReDoS without an alternative engine (re2-wasm), but\n * we can sharply limit the blast radius:\n *\n * 1. Cap pattern length — practically all legitimate user patterns are\n * under 256 characters. A 4 KB pattern is almost certainly malicious\n * or a copy-paste accident.\n * 2. Reject patterns containing the most obvious super-linear structures.\n * This is a coarse filter (false-positives are likely; we accept that\n * for hostile-input contexts).\n *\n * Callers should additionally bound the *subject* length (e.g. by capping\n * line size before matching).\n */\n\nconst MAX_PATTERN_LEN = 256;\n\n// Heuristics for catastrophic-backtracking constructs. Not exhaustive; bias\n// toward false-positives in tools that accept LLM-generated input.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n // (a+)+, (.*)+, etc — nested quantifier on a group with internal quantifier\n /(\\([^)]*[+*][^)]*\\))[+*]/,\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/,\n // Adjacent quantifiers: a++ a*+\n /[+*]{2,}/,\n // Quantifier on alternation with length 2+\n /\\([^|)]+\\|[^)]+\\)[+*][+*]/,\n // Greedy quantifier inside lookahead/lookbehind — (?!.*a+)\n /[([][^)\\]]*[+*][^)\\]]*[)\\]][^)]*\\?\\??/,\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking — rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n\n/**\n * Truncate a subject line to a safe length for synchronous regex eval.\n * The cap is conservative; tools that need exact-line matching against very\n * long lines should use ripgrep externally rather than the native walker.\n */\nexport const MAX_SUBJECT_LEN = 64 * 1024;\n\nexport function capSubject(line: string): string {\n return line.length > MAX_SUBJECT_LEN ? line.slice(0, MAX_SUBJECT_LEN) : line;\n}\n","import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import { expectDefined } from '@wrongstack/core';\nimport { spawn } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { Tool, ToolStreamEvent } from '@wrongstack/core';\nimport { buildChildEnv, compileGlob } from '@wrongstack/core';\nimport { mapWithConcurrency } from './_concurrency.js';\nimport { capSubject, compileUserRegex } from './_regex.js';\nimport { isBinaryBuffer, safeResolve } from './_util.js';\ninterface GrepInput {\n pattern: string;\n path?: string | undefined;\n glob?: string | undefined;\n output_mode?: 'content' | 'files_with_matches' | 'count' | undefined;\n context_lines?: number | undefined;\n case_insensitive?: boolean | undefined;\n limit?: number | undefined;\n}\n\ninterface GrepOutput {\n matches: string[];\n count: number;\n truncated: boolean;\n used: 'rg' | 'native';\n}\n\nconst DEFAULT_IGNORE = ['node_modules', '.git', 'dist', 'build', '.next', 'coverage'];\nconst NATIVE_SCAN_CONCURRENCY = 32;\nconst NATIVE_READ_CHUNK_BYTES = 64 * 1024;\nconst NATIVE_MAX_FILE_BYTES = 1_000_000;\n\nexport const grepTool: Tool<GrepInput, GrepOutput> = {\n name: 'grep',\n category: 'Search',\n description:\n 'Search across files using a regular expression. This is one of the primary code search tools. ' +\n 'Prefers ripgrep for speed and features when available.',\n usageHint:\n 'POWERFUL CODE SEARCH TOOL:\\n\\n' +\n '- `pattern` is a regular expression.\\n' +\n '- Use `output_mode: \"content\"` (default) to get matching lines with context.\\n' +\n '- Use `\"files_with_matches\"` when you only need the list of files.\\n' +\n '- Use `\"count\"` for quick statistics.\\n' +\n '- `glob` and `path` let you narrow the search scope significantly.\\n' +\n '- Always prefer this over `bash grep` when searching code.',\n permission: 'auto',\n mutating: false,\n capabilities: ['fs.read'],\n icon: 'search',\n maxOutputBytes: 131_072,\n timeoutMs: 10_000,\n inputSchema: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Regular expression pattern to search for in file contents.',\n },\n path: {\n type: 'string',\n description: 'Limit search to this directory or file (relative to project root).',\n },\n glob: {\n type: 'string',\n description: 'Glob filter for which files to include (e.g. \"**/*.ts\", \"src/**\").',\n },\n output_mode: {\n type: 'string',\n enum: ['content', 'files_with_matches', 'count'],\n description: 'Return style: detailed matches, just file list, or count only.',\n },\n context_lines: {\n type: 'integer',\n description: 'How many lines of surrounding context to include with each match.',\n },\n case_insensitive: {\n type: 'boolean',\n description: 'Ignore case when matching.',\n },\n limit: {\n type: 'integer',\n description: 'Maximum number of matches to return.',\n },\n },\n required: ['pattern'],\n },\n async execute(input, ctx, opts) {\n let final: GrepOutput | undefined;\n const executeStream = grepTool.executeStream;\n if (!executeStream) throw new Error('grepTool: stream execution unavailable');\n for await (const ev of executeStream(input, ctx, opts)) {\n if (ev.type === 'final') final = ev.output;\n }\n if (!final) throw new Error('grep: stream ended without final event');\n return final;\n },\n async *executeStream(input, ctx, opts): AsyncGenerator<ToolStreamEvent<GrepOutput>> {\n if (!input?.pattern) throw new Error('grep: pattern is required');\n const base = input.path ? safeResolve(input.path, ctx) : ctx.cwd;\n const mode = input.output_mode ?? 'content';\n const limit = Math.max(1, Math.min(input.limit ?? 200, 2000));\n const validation = compileUserRegex(input.pattern, input.case_insensitive ? 'i' : '');\n if (!validation.ok) {\n throw new Error(`grep: ${validation.reason}`);\n }\n\n const rgAvailable = await detectRg(opts.signal);\n if (rgAvailable) {\n try {\n yield* runRgStream(input, base, mode, limit, opts.signal);\n return;\n } catch {\n // fall through to native\n }\n }\n yield { type: 'log', text: 'Falling back to native grep…' };\n const out = await runNative(input, base, mode, limit, opts.signal);\n yield { type: 'final', output: out };\n },\n};\n\nasync function detectRg(signal: AbortSignal): Promise<boolean> {\n return new Promise((resolve) => {\n try {\n const p = spawn('rg', ['--version'], { env: buildChildEnv(), stdio: 'ignore', signal, windowsHide: true });\n p.on('error', () => resolve(false));\n p.on('close', (code) => resolve(code === 0));\n } catch {\n resolve(false);\n }\n });\n}\n\nasync function* runRgStream(\n input: GrepInput,\n base: string,\n mode: 'content' | 'files_with_matches' | 'count',\n limit: number,\n signal: AbortSignal,\n): AsyncGenerator<ToolStreamEvent<GrepOutput>> {\n const args: string[] = ['--no-heading'];\n if (input.case_insensitive) args.push('-i');\n if (mode === 'files_with_matches') args.push('-l');\n if (mode === 'count') args.push('-c');\n if (mode === 'content') {\n args.push('-n');\n if (input.context_lines) args.push('-C', String(input.context_lines));\n }\n for (const ignored of DEFAULT_IGNORE) {\n args.push('--glob', `!${ignored}/**`, '--glob', `!**/${ignored}/**`);\n }\n if (input.glob) args.push('--glob', input.glob);\n args.push('--', input.pattern, base);\n\n const matches: string[] = [];\n let buf = '';\n let totalLines = 0;\n let totalCount = 0;\n let batchSinceFlush = 0;\n const FLUSH_AT = 16; // yield a partial_output every 16 matches\n // Cap on the in-progress line buffer. Without this, a single huge \"line\"\n // (e.g. a file with no newlines under a symlink) plus a fast producer\n // would let `buf` grow unbounded. 1 MB comfortably holds any realistic\n // grep hit; beyond that we kill the child and surface a truncation.\n const MAX_BUF_BYTES = 1_000_000;\n let bufOverflow = false;\n\n const child = spawn('rg', args, { signal, env: buildChildEnv(), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });\n\n type Chunk = { kind: 'out' | 'close' | 'error'; data: string };\n const queue: Chunk[] = [];\n let waiter: (() => void) | undefined;\n const wake = () => {\n if (waiter) {\n const w = waiter;\n waiter = undefined;\n w();\n }\n };\n child.stdout?.on('data', (c) => {\n queue.push({ kind: 'out', data: c.toString() });\n wake();\n });\n child.on('error', (e) => {\n queue.push({ kind: 'error', data: e.message });\n wake();\n });\n child.on('close', () => {\n queue.push({ kind: 'close', data: '' });\n wake();\n });\n\n let pendingBatch: string[] = [];\n let errored = false;\n for (;;) {\n while (queue.length === 0) {\n await new Promise<void>((r) => {\n waiter = r;\n });\n }\n const c = expectDefined(queue.shift());\n if (c.kind === 'error') {\n errored = true;\n continue;\n }\n if (c.kind === 'close') break;\n buf += c.data;\n // Guard against a pathological producer (e.g. matching a huge binary\n // without newlines) pinning memory. Kill the child and mark the result\n // truncated; whatever we already captured stays intact.\n if (buf.length > MAX_BUF_BYTES && !bufOverflow) {\n bufOverflow = true;\n buf = buf.slice(-MAX_BUF_BYTES);\n try {\n child.kill('SIGTERM');\n } catch {\n /* ignore */\n }\n }\n const idx = buf.lastIndexOf('\\n');\n if (idx === -1) continue;\n const ready = buf.slice(0, idx);\n buf = buf.slice(idx + 1);\n for (const line of ready.split('\\n')) {\n if (!line) continue;\n totalLines++;\n if (mode === 'count') totalCount += parseRgCountLine(line);\n if (matches.length < limit) {\n matches.push(line);\n pendingBatch.push(line);\n batchSinceFlush++;\n }\n }\n if (batchSinceFlush >= FLUSH_AT) {\n yield {\n type: 'partial_output',\n text: pendingBatch.join('\\n'),\n data: { matches_so_far: matches.length },\n };\n pendingBatch = [];\n batchSinceFlush = 0;\n }\n }\n\n if (buf.trim()) {\n for (const line of buf.split('\\n')) {\n if (!line) continue;\n totalLines++;\n if (mode === 'count') totalCount += parseRgCountLine(line);\n if (matches.length < limit) {\n matches.push(line);\n pendingBatch.push(line);\n }\n }\n }\n if (pendingBatch.length > 0) {\n yield {\n type: 'partial_output',\n text: pendingBatch.join('\\n'),\n data: { matches_so_far: matches.length },\n };\n }\n if (errored) throw new Error('rg: spawn error');\n\n yield {\n type: 'final',\n output: {\n matches,\n count: mode === 'count' ? totalCount : totalLines,\n truncated: totalLines > limit || bufOverflow,\n used: 'rg',\n },\n };\n}\n\nfunction parseRgCountLine(line: string): number {\n const idx = line.lastIndexOf(':');\n if (idx === -1) return 0;\n const n = Number.parseInt(line.slice(idx + 1), 10);\n return Number.isFinite(n) ? n : 0;\n}\n\nasync function runNative(\n input: GrepInput,\n base: string,\n mode: 'content' | 'files_with_matches' | 'count',\n limit: number,\n signal: AbortSignal,\n): Promise<GrepOutput> {\n const flags = input.case_insensitive ? 'i' : '';\n const compiled = compileUserRegex(input.pattern, flags);\n if (!compiled.ok) {\n throw new Error(`grep: ${compiled.reason}`);\n }\n const re = compiled.regex;\n const globRe = input.glob ? compileGlob(input.glob) : null;\n const matches: string[] = [];\n const countOnlyFirstHit = mode === 'count' && limit === 1;\n const maxBytes = mode === 'content' ? NATIVE_MAX_FILE_BYTES : Math.min(NATIVE_MAX_FILE_BYTES, 256 * 1024);\n let total = 0;\n let stopped = false;\n\n const scanFile = async (full: string, name: string): Promise<void> => {\n if (stopped || signal.aborted) return;\n if (globRe && !globRe.test(name) && !globRe.test(full)) return;\n if (globRe) globRe.lastIndex = 0;\n\n try {\n const stat = await fs.stat(full);\n if (!stat.isFile() || stat.size > maxBytes || stopped || signal.aborted) return;\n\n const file = await fs.open(full, 'r');\n try {\n let bytesReadTotal = 0;\n let lineNumber = 0;\n let fileHits = 0;\n let leftover = '';\n let binaryChecked = false;\n const buffer = Buffer.allocUnsafe(Math.min(NATIVE_READ_CHUNK_BYTES, maxBytes));\n\n while (!stopped && !signal.aborted && bytesReadTotal < maxBytes) {\n const remaining = maxBytes - bytesReadTotal;\n const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, remaining), null);\n if (bytesRead === 0) break;\n const chunk = buffer.subarray(0, bytesRead);\n if (!binaryChecked) {\n binaryChecked = true;\n if (isBinaryBuffer(chunk)) return;\n }\n bytesReadTotal += bytesRead;\n const text = leftover + chunk.toString('utf8');\n const lines = text.split(/\\r?\\n/);\n leftover = lines.pop() ?? '';\n\n for (const rawLine of lines) {\n if (stopped || signal.aborted) break;\n lineNumber++;\n const ln = capSubject(rawLine);\n re.lastIndex = 0;\n if (!re.test(ln)) continue;\n\n fileHits++;\n total++;\n\n if (mode === 'content') {\n if (matches.length < limit) matches.push(`${full}:${lineNumber}:${ln}`);\n } else if (mode === 'files_with_matches') {\n if (fileHits === 1 && matches.length < limit) matches.push(full);\n break;\n } else if (fileHits === 1 && matches.length < limit) {\n matches.push(`${full}:${countOnlyFirstHit ? 1 : 0}`);\n }\n\n if (countOnlyFirstHit || (mode !== 'content' && matches.length >= limit)) {\n stopped = true;\n break;\n }\n }\n\n if (mode === 'files_with_matches' && fileHits > 0) break;\n }\n\n if (!stopped && !signal.aborted && leftover.length > 0) {\n lineNumber++;\n const ln = capSubject(leftover);\n re.lastIndex = 0;\n if (re.test(ln)) {\n fileHits++;\n total++;\n if (mode === 'content') {\n if (matches.length < limit) matches.push(`${full}:${lineNumber}:${ln}`);\n } else if (mode === 'files_with_matches') {\n if (matches.length < limit) matches.push(full);\n } else if (matches.length < limit) {\n matches.push(`${full}:${countOnlyFirstHit ? 1 : fileHits}`);\n }\n }\n }\n\n if (fileHits > 0) {\n if (mode === 'count') {\n const idx = matches.findIndex((entry) => entry.startsWith(`${full}:`));\n if (idx !== -1) matches[idx] = `${full}:${fileHits}`;\n }\n if (mode === 'files_with_matches' && matches.length >= limit) stopped = true;\n }\n\n if (mode === 'content' && matches.length >= limit) stopped = true;\n if (mode === 'count' && matches.length >= limit && (countOnlyFirstHit || mode !== 'count')) stopped = true;\n } finally {\n await file.close();\n }\n } catch {\n // skip read errors\n }\n };\n\n const walk = async (dir: string): Promise<void> => {\n if (stopped || signal.aborted) return;\n let entries: import('node:fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n const files: Array<{ full: string; name: string }> = [];\n const subdirs: string[] = [];\n for (const e of entries) {\n if (stopped) return;\n if (DEFAULT_IGNORE.includes(e.name)) continue;\n if (e.isSymbolicLink()) continue;\n const full = path.join(dir, e.name);\n if (e.isDirectory()) {\n subdirs.push(full);\n } else if (e.isFile()) {\n files.push({ full, name: e.name });\n }\n }\n await mapWithConcurrency(files, NATIVE_SCAN_CONCURRENCY, ({ full, name }) => scanFile(full, name));\n await mapWithConcurrency(subdirs, Math.min(16, NATIVE_SCAN_CONCURRENCY), walk);\n };\n await walk(base);\n\n return {\n matches,\n count: total,\n truncated: stopped,\n used: 'native',\n };\n}\n"]}
|