@phren/agent 0.3.19 → 0.3.21
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/agent-loop/index.js +185 -47
- package/dist/agent-loop/stream.js +74 -66
- package/dist/agent-loop/types.js +2 -3
- package/dist/attach-images.js +57 -0
- package/dist/bin.js +7 -2
- package/dist/commands/info.js +7 -3
- package/dist/commands/model.js +55 -13
- package/dist/commands/session.js +79 -18
- package/dist/commands.js +24 -3
- package/dist/config.js +89 -10
- package/dist/context/clear-tool-results.js +43 -0
- package/dist/context/compactor.js +13 -3
- package/dist/context/pruner.js +29 -11
- package/dist/context/usage.js +26 -0
- package/dist/cost.js +68 -10
- package/dist/headless.js +47 -1
- package/dist/index.js +335 -127
- package/dist/mcp-client.js +38 -1
- package/dist/mcp-prompts.js +94 -0
- package/dist/memory/chat.js +70 -0
- package/dist/memory/context.js +1 -1
- package/dist/model-overrides.js +17 -0
- package/dist/models-list.js +73 -0
- package/dist/models.js +42 -15
- package/dist/multi/child-entry.js +18 -28
- package/dist/multi/ipc-hooks.js +34 -0
- package/dist/multi/spawner.js +49 -3
- package/dist/permissions/allowlist.js +19 -4
- package/dist/permissions/checker.js +37 -20
- package/dist/permissions/kernel-sandbox.js +32 -10
- package/dist/permissions/rules.js +173 -0
- package/dist/permissions/shell-classify.js +173 -0
- package/dist/plan.js +6 -2
- package/dist/providers/anthropic.js +119 -75
- package/dist/providers/codex.js +10 -9
- package/dist/providers/ollama.js +5 -2
- package/dist/providers/openai-compat.js +219 -92
- package/dist/providers/openrouter.js +12 -7
- package/dist/providers/resolve.js +47 -1
- package/dist/providers/retry.js +20 -7
- package/dist/providers/types.js +31 -0
- package/dist/repl.js +17 -1
- package/dist/session/persist.js +9 -4
- package/dist/session/preview.js +99 -0
- package/dist/settings.js +14 -0
- package/dist/structured-output.js +85 -0
- package/dist/system-prompt.js +117 -14
- package/dist/tools/apply-patch.js +15 -1
- package/dist/tools/edit-file.js +8 -1
- package/dist/tools/file-state.js +88 -0
- package/dist/tools/glob.js +53 -35
- package/dist/tools/grep.js +139 -53
- package/dist/tools/lint-test.js +24 -0
- package/dist/tools/read-file.js +2 -0
- package/dist/tools/registry.js +8 -1
- package/dist/tools/search-support.js +141 -0
- package/dist/tools/shell.js +266 -41
- package/dist/tools/spawn-agent.js +15 -3
- package/dist/tools/syntax-check.js +116 -0
- package/dist/tools/write-file.js +11 -3
- package/dist/tui/components/App.js +5 -4
- package/dist/tui/components/Banner.js +1 -1
- package/dist/tui/components/ListPicker.js +32 -0
- package/dist/tui/ink-entry.js +79 -15
- package/dist/user-hooks.js +26 -4
- package/package.json +3 -2
- package/dist/memory/context-flush.js +0 -24
package/dist/tools/grep.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as fs from "fs";
|
|
2
2
|
import * as path from "path";
|
|
3
3
|
import { checkSensitivePath, validatePath } from "../permissions/sandbox.js";
|
|
4
|
+
import { capLine, MAX_LINE_CHARS, ripgrepPath, runRipgrep, walkTree } from "./search-support.js";
|
|
4
5
|
function searchFile(filePath, regex, contextBefore, contextAfter) {
|
|
5
6
|
let content;
|
|
6
7
|
try {
|
|
@@ -16,7 +17,7 @@ function searchFile(filePath, regex, contextBefore, contextAfter) {
|
|
|
16
17
|
const start = Math.max(0, i - contextBefore);
|
|
17
18
|
const end = Math.min(lines.length - 1, i + contextAfter);
|
|
18
19
|
for (let j = start; j <= end; j++) {
|
|
19
|
-
matches.push({ line: j + 1, text: lines[j] });
|
|
20
|
+
matches.push({ line: j + 1, text: capLine(lines[j]) });
|
|
20
21
|
}
|
|
21
22
|
if (end < lines.length - 1)
|
|
22
23
|
matches.push({ line: -1, text: "--" });
|
|
@@ -38,32 +39,10 @@ function searchFileMultiline(filePath, regex) {
|
|
|
38
39
|
for (const match of content.matchAll(regex)) {
|
|
39
40
|
const beforeMatch = content.slice(0, match.index);
|
|
40
41
|
const lineNo = beforeMatch.split("\n").length;
|
|
41
|
-
matches.push({ line: lineNo, text: match[0]
|
|
42
|
+
matches.push({ line: lineNo, text: capLine(match[0]) });
|
|
42
43
|
}
|
|
43
44
|
return matches;
|
|
44
45
|
}
|
|
45
|
-
function walkDir(dir, results, maxFiles) {
|
|
46
|
-
if (results.length >= maxFiles)
|
|
47
|
-
return;
|
|
48
|
-
let entries;
|
|
49
|
-
try {
|
|
50
|
-
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
51
|
-
}
|
|
52
|
-
catch {
|
|
53
|
-
return;
|
|
54
|
-
}
|
|
55
|
-
for (const entry of entries) {
|
|
56
|
-
if (results.length >= maxFiles)
|
|
57
|
-
return;
|
|
58
|
-
if (entry.name.startsWith(".") || entry.name === "node_modules")
|
|
59
|
-
continue;
|
|
60
|
-
const full = path.join(dir, entry.name);
|
|
61
|
-
if (entry.isDirectory())
|
|
62
|
-
walkDir(full, results, maxFiles);
|
|
63
|
-
else
|
|
64
|
-
results.push(full);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
46
|
const FILE_TYPE_EXTENSIONS = {
|
|
68
47
|
js: [".js", ".jsx", ".mjs", ".cjs"],
|
|
69
48
|
ts: [".ts", ".tsx", ".mts", ".cts"],
|
|
@@ -80,9 +59,116 @@ const FILE_TYPE_EXTENSIONS = {
|
|
|
80
59
|
sh: [".sh", ".bash", ".zsh"],
|
|
81
60
|
sql: [".sql"],
|
|
82
61
|
};
|
|
62
|
+
const MAX_WALK_FILES = 5000;
|
|
63
|
+
/** `*.ts` style filter against a file name; `*` spans anything, the rest is literal. */
|
|
64
|
+
function globToRegex(glob) {
|
|
65
|
+
return new RegExp(`^${glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`);
|
|
66
|
+
}
|
|
67
|
+
/** Lines of one file as `N<tab>text`, with `--` between groups that do not touch. */
|
|
68
|
+
function formatRgLines(lines) {
|
|
69
|
+
const out = [];
|
|
70
|
+
let last = -2;
|
|
71
|
+
for (const l of lines) {
|
|
72
|
+
if (last >= 0 && l.line > last + 1)
|
|
73
|
+
out.push("--");
|
|
74
|
+
out.push(`${l.line}\t${l.text}`);
|
|
75
|
+
last = l.line;
|
|
76
|
+
}
|
|
77
|
+
return out.join("\n");
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Search with ripgrep's --json stream: .gitignore applies, hidden directories
|
|
81
|
+
* are searched (not .git), long lines are cut. Returns null when ripgrep
|
|
82
|
+
* cannot start, so the caller falls back to the JS walker.
|
|
83
|
+
*/
|
|
84
|
+
async function ripgrepSearch(rg, o, signal) {
|
|
85
|
+
const args = ["--json", "--hidden", "--no-require-git", "--glob", "!.git", "--glob", "!node_modules", "--max-columns", String(MAX_LINE_CHARS), "--max-columns-preview",
|
|
86
|
+
o.caseInsensitive ? "-i" : "-s"];
|
|
87
|
+
if (o.multiline)
|
|
88
|
+
args.push("-U", "--multiline-dotall");
|
|
89
|
+
if (o.outputMode === "content")
|
|
90
|
+
args.push("-A", String(o.contextA), "-B", String(o.contextB));
|
|
91
|
+
if (o.fileType) {
|
|
92
|
+
for (const ext of FILE_TYPE_EXTENSIONS[o.fileType] ?? [`.${o.fileType}`])
|
|
93
|
+
args.push("--type-add", `phren:*${ext}`);
|
|
94
|
+
args.push("--type", "phren");
|
|
95
|
+
}
|
|
96
|
+
if (o.fileGlob)
|
|
97
|
+
args.push("--glob", o.fileGlob);
|
|
98
|
+
// Run inside the search root and print relative paths; a lone file is its own root.
|
|
99
|
+
const cwd = o.isFile ? path.dirname(o.root) : o.root;
|
|
100
|
+
args.push("-e", o.pattern, "--", o.isFile ? path.basename(o.root) : ".");
|
|
101
|
+
const files = [];
|
|
102
|
+
let current = null;
|
|
103
|
+
let skipFile = false;
|
|
104
|
+
let kept = 0;
|
|
105
|
+
const wanted = o.headLimit + o.offset;
|
|
106
|
+
const onLine = (raw) => {
|
|
107
|
+
let event;
|
|
108
|
+
try {
|
|
109
|
+
event = JSON.parse(raw);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
const data = event.data ?? {};
|
|
115
|
+
if (event.type === "begin") {
|
|
116
|
+
const rel = String(data.path?.text ?? "").replace(/^\.[\\/]/, "");
|
|
117
|
+
const full = path.resolve(cwd, rel);
|
|
118
|
+
const checked = validatePath(full, process.cwd(), []);
|
|
119
|
+
skipFile = !checked.ok || checkSensitivePath(full).sensitive || checkSensitivePath(checked.resolved).sensitive;
|
|
120
|
+
current = skipFile ? null : { rel, lines: [], matches: 0 };
|
|
121
|
+
}
|
|
122
|
+
else if ((event.type === "match" || event.type === "context") && current) {
|
|
123
|
+
const text = String(data.lines?.text ?? "").replace(/\r?\n$/, "");
|
|
124
|
+
// A multiline match spans lines: number each one from the match's start.
|
|
125
|
+
text.split("\n").forEach((line, i) => current.lines.push({ line: (data.line_number ?? 0) + i, text: capLine(line) }));
|
|
126
|
+
if (event.type === "match")
|
|
127
|
+
current.matches++;
|
|
128
|
+
}
|
|
129
|
+
else if (event.type === "end" && current) {
|
|
130
|
+
if (current.matches > 0) {
|
|
131
|
+
files.push(current);
|
|
132
|
+
kept++;
|
|
133
|
+
}
|
|
134
|
+
current = null;
|
|
135
|
+
return kept >= wanted;
|
|
136
|
+
}
|
|
137
|
+
return false;
|
|
138
|
+
};
|
|
139
|
+
let run;
|
|
140
|
+
try {
|
|
141
|
+
run = await runRipgrep(rg, args, cwd, onLine, signal);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
if (signal?.aborted)
|
|
145
|
+
return { output: "Search aborted.", is_error: true };
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
// A pattern ripgrep can't parse (lookaround, backreferences) may still be a
|
|
149
|
+
// valid JavaScript regex: the JS walker gets it and reports it if not.
|
|
150
|
+
if (run.code === 2 && files.length === 0 && run.stderr.trim())
|
|
151
|
+
return null;
|
|
152
|
+
const page = files.slice(o.offset, o.offset + o.headLimit);
|
|
153
|
+
if (page.length === 0)
|
|
154
|
+
return { output: "No matches." };
|
|
155
|
+
if (o.isFile) {
|
|
156
|
+
const f = page[0];
|
|
157
|
+
if (o.outputMode === "files_with_matches")
|
|
158
|
+
return { output: o.searchPath };
|
|
159
|
+
if (o.outputMode === "count")
|
|
160
|
+
return { output: String(f.matches) };
|
|
161
|
+
return { output: `${o.searchPath}:\n${formatRgLines(f.lines)}` };
|
|
162
|
+
}
|
|
163
|
+
if (o.outputMode === "files_with_matches")
|
|
164
|
+
return { output: page.map((f) => f.rel).join("\n") };
|
|
165
|
+
if (o.outputMode === "count")
|
|
166
|
+
return { output: page.map((f) => `${f.rel}: ${f.matches}`).join("\n") };
|
|
167
|
+
return { output: page.map((f) => `${f.rel}:\n${formatRgLines(f.lines)}`).join("\n\n") };
|
|
168
|
+
}
|
|
83
169
|
export const grepTool = {
|
|
84
170
|
name: "grep",
|
|
85
|
-
description: "Search file contents by regex. Supports output modes (content, files_with_matches, count), context lines, multiline matching, file type filtering, and result pagination.",
|
|
171
|
+
description: "Search file contents by regex. Case-sensitive unless -i is set. Honours .gitignore and searches hidden directories such as .github (not .git). Supports output modes (content, files_with_matches, count), context lines, multiline matching, file type filtering, and result pagination.",
|
|
86
172
|
input_schema: {
|
|
87
173
|
type: "object",
|
|
88
174
|
properties: {
|
|
@@ -101,11 +187,11 @@ export const grepTool = {
|
|
|
101
187
|
multiline: { type: "boolean", description: "Enable multiline matching (pattern can span lines). Default: false." },
|
|
102
188
|
head_limit: { type: "number", description: "Max results to return. Default: 100." },
|
|
103
189
|
offset: { type: "number", description: "Skip first N results before applying head_limit." },
|
|
104
|
-
"-i": { type: "boolean", description: "Case insensitive search. Default:
|
|
190
|
+
"-i": { type: "boolean", description: "Case insensitive search. Default: false (case-sensitive)." },
|
|
105
191
|
},
|
|
106
192
|
required: ["pattern"],
|
|
107
193
|
},
|
|
108
|
-
async execute(input) {
|
|
194
|
+
async execute(input, signal) {
|
|
109
195
|
const pattern = input.pattern;
|
|
110
196
|
const searchPath = input.path || process.cwd();
|
|
111
197
|
const contextC = input.context ?? input["-C"] ?? 2;
|
|
@@ -117,7 +203,7 @@ export const grepTool = {
|
|
|
117
203
|
const multiline = input.multiline;
|
|
118
204
|
const headLimit = input.head_limit ?? 100;
|
|
119
205
|
const offset = input.offset ?? 0;
|
|
120
|
-
const caseInsensitive = input["-i"] ??
|
|
206
|
+
const caseInsensitive = input["-i"] ?? false;
|
|
121
207
|
const pathResult = validatePath(searchPath, process.cwd(), []);
|
|
122
208
|
if (!pathResult.ok) {
|
|
123
209
|
return { output: `Path outside sandbox: ${pathResult.error}`, is_error: true };
|
|
@@ -125,17 +211,26 @@ export const grepTool = {
|
|
|
125
211
|
if (checkSensitivePath(path.resolve(searchPath)).sensitive || checkSensitivePath(pathResult.resolved).sensitive) {
|
|
126
212
|
return { output: "Access denied: sensitive path.", is_error: true };
|
|
127
213
|
}
|
|
214
|
+
const stat = fs.statSync(pathResult.resolved, { throwIfNoEntry: false });
|
|
215
|
+
if (!stat)
|
|
216
|
+
return { output: `Path not found: ${searchPath}`, is_error: true };
|
|
217
|
+
const rg = ripgrepPath();
|
|
218
|
+
if (rg) {
|
|
219
|
+
const found = await ripgrepSearch(rg, {
|
|
220
|
+
pattern, root: pathResult.resolved, isFile: stat.isFile(), searchPath, contextA, contextB, fileGlob, fileType,
|
|
221
|
+
outputMode, multiline, headLimit, offset, caseInsensitive,
|
|
222
|
+
}, signal);
|
|
223
|
+
if (found)
|
|
224
|
+
return found;
|
|
225
|
+
}
|
|
128
226
|
let regex;
|
|
129
227
|
try {
|
|
130
228
|
const flags = (caseInsensitive ? "i" : "") + (multiline ? "gs" : "");
|
|
131
|
-
regex = new RegExp(pattern, flags
|
|
229
|
+
regex = new RegExp(pattern, flags);
|
|
132
230
|
}
|
|
133
231
|
catch {
|
|
134
232
|
return { output: `Invalid regex: ${pattern}`, is_error: true };
|
|
135
233
|
}
|
|
136
|
-
const stat = fs.statSync(pathResult.resolved, { throwIfNoEntry: false });
|
|
137
|
-
if (!stat)
|
|
138
|
-
return { output: `Path not found: ${searchPath}`, is_error: true };
|
|
139
234
|
// Single file
|
|
140
235
|
if (stat.isFile()) {
|
|
141
236
|
const results = multiline
|
|
@@ -147,25 +242,16 @@ export const grepTool = {
|
|
|
147
242
|
return { output: `${results.filter((r) => r.line > 0).length}` };
|
|
148
243
|
return { output: results.length > 0 ? `${searchPath}:\n${results.map((r) => r.line > 0 ? `${r.line}\t${r.text}` : r.text).join("\n")}` : "No matches." };
|
|
149
244
|
}
|
|
150
|
-
// Directory search
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
}
|
|
160
|
-
// Glob filter
|
|
161
|
-
if (fileGlob) {
|
|
162
|
-
const globRegex = new RegExp(fileGlob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*"));
|
|
163
|
-
const filtered = files.filter((f) => globRegex.test(path.basename(f)));
|
|
164
|
-
files.length = 0;
|
|
165
|
-
files.push(...filtered);
|
|
166
|
-
}
|
|
245
|
+
// Directory search: the JS walker, used when ripgrep is missing.
|
|
246
|
+
const exts = fileType ? (FILE_TYPE_EXTENSIONS[fileType] ?? [`.${fileType}`]) : null;
|
|
247
|
+
const globRegex = fileGlob ? globToRegex(fileGlob) : null;
|
|
248
|
+
const walked = walkTree(searchPath, MAX_WALK_FILES, (rel) => {
|
|
249
|
+
const base = path.basename(rel);
|
|
250
|
+
return (!exts || exts.some((ext) => base.endsWith(ext))) && (!globRegex || globRegex.test(base));
|
|
251
|
+
});
|
|
252
|
+
const files = walked.files.map((rel) => path.join(searchPath, rel));
|
|
253
|
+
const note = walked.truncated ? `searched the first ${files.length} files; narrow the path or glob` : "";
|
|
167
254
|
const output = [];
|
|
168
|
-
let _totalMatches = 0;
|
|
169
255
|
let skipped = 0;
|
|
170
256
|
for (const file of files) {
|
|
171
257
|
if (output.length >= headLimit + offset)
|
|
@@ -186,7 +272,6 @@ export const grepTool = {
|
|
|
186
272
|
: searchFile(checked.resolved, regex, contextB, contextA);
|
|
187
273
|
if (results.length === 0)
|
|
188
274
|
continue;
|
|
189
|
-
_totalMatches++;
|
|
190
275
|
if (skipped < offset) {
|
|
191
276
|
skipped++;
|
|
192
277
|
continue;
|
|
@@ -205,7 +290,8 @@ export const grepTool = {
|
|
|
205
290
|
}
|
|
206
291
|
}
|
|
207
292
|
if (output.length === 0)
|
|
208
|
-
return { output: "No matches." };
|
|
209
|
-
|
|
293
|
+
return { output: note ? `No matches (${note}).` : "No matches." };
|
|
294
|
+
const body = output.join(outputMode === "content" ? "\n\n" : "\n");
|
|
295
|
+
return { output: note ? `${body}\n\n(${note})` : body };
|
|
210
296
|
},
|
|
211
297
|
};
|
package/dist/tools/lint-test.js
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
import * as fs from "fs";
|
|
2
2
|
import * as path from "path";
|
|
3
|
+
/**
|
|
4
|
+
* Detect a type-check command: a package script named for it, or tsc on a
|
|
5
|
+
* TypeScript project that has it installed. Typing catches what a parse
|
|
6
|
+
* check can't, in seconds, and runs before the (usually slower) tests.
|
|
7
|
+
*/
|
|
8
|
+
export function detectTypecheckCommand(cwd) {
|
|
9
|
+
const pkgPath = path.join(cwd, "package.json");
|
|
10
|
+
if (fs.existsSync(pkgPath)) {
|
|
11
|
+
try {
|
|
12
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
13
|
+
for (const name of ["typecheck", "type-check", "check-types", "tsc"]) {
|
|
14
|
+
if (pkg.scripts?.[name])
|
|
15
|
+
return `npm run ${name}`;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
catch { /* ignore */ }
|
|
19
|
+
}
|
|
20
|
+
if (fs.existsSync(path.join(cwd, "tsconfig.json")) && fs.existsSync(path.join(cwd, "node_modules", ".bin", "tsc"))) {
|
|
21
|
+
return "npx tsc --noEmit";
|
|
22
|
+
}
|
|
23
|
+
if (fs.existsSync(path.join(cwd, "mypy.ini")))
|
|
24
|
+
return "mypy .";
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
3
27
|
/** Detect test command from project config files. */
|
|
4
28
|
export function detectTestCommand(cwd) {
|
|
5
29
|
// package.json scripts.test
|
package/dist/tools/read-file.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as fs from "fs";
|
|
2
2
|
import * as path from "path";
|
|
3
3
|
import { checkSensitivePath, validatePath } from "../permissions/sandbox.js";
|
|
4
|
+
import { recordFileState } from "./file-state.js";
|
|
4
5
|
/** Minified bundles and data files can have megabyte lines; cap each one. */
|
|
5
6
|
const MAX_LINE_CHARS = 2000;
|
|
6
7
|
export const readFileTool = {
|
|
@@ -42,6 +43,7 @@ export const readFileTool = {
|
|
|
42
43
|
is_error: true,
|
|
43
44
|
};
|
|
44
45
|
}
|
|
46
|
+
recordFileState(filePath);
|
|
45
47
|
const lines = buf.toString("utf-8").split("\n");
|
|
46
48
|
if (lines.length > 1 && lines[lines.length - 1] === "")
|
|
47
49
|
lines.pop();
|
package/dist/tools/registry.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { DIFF_MARKER } from "../multi/diff-renderer.js";
|
|
1
2
|
import { checkPermission } from "../permissions/checker.js";
|
|
2
3
|
import { askUser as defaultAskUser } from "../permissions/prompt.js";
|
|
3
4
|
import { runPreToolUseHooks, runPostToolUseHooks, } from "../user-hooks.js";
|
|
@@ -73,7 +74,13 @@ export class ToolRegistry {
|
|
|
73
74
|
const msg = err instanceof Error ? err.message : String(err);
|
|
74
75
|
result = { output: `Tool error: ${msg}`, is_error: true };
|
|
75
76
|
}
|
|
76
|
-
await runPostToolUseHooks(this.hookConfig, name, input, result.output, !!result.is_error, hookOptions);
|
|
77
|
+
const feedback = await runPostToolUseHooks(this.hookConfig, name, input, result.output, !!result.is_error, hookOptions);
|
|
78
|
+
if (feedback) {
|
|
79
|
+
// Before the TUI's diff payload, which the model never sees.
|
|
80
|
+
const note = `\n\nPostToolUse hook: ${feedback}`;
|
|
81
|
+
const at = result.output.indexOf(DIFF_MARKER);
|
|
82
|
+
result = { ...result, output: at === -1 ? result.output + note : result.output.slice(0, at) + note + result.output.slice(at) };
|
|
83
|
+
}
|
|
77
84
|
return result;
|
|
78
85
|
}
|
|
79
86
|
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { spawn } from "child_process";
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import * as path from "path";
|
|
4
|
+
/** Longest line the search tools hand back; one minified file must not flood context. */
|
|
5
|
+
export const MAX_LINE_CHARS = 500;
|
|
6
|
+
export function capLine(text, max = MAX_LINE_CHARS) {
|
|
7
|
+
return text.length > max ? `${text.slice(0, max)} ...[${text.length - max} more chars]` : text;
|
|
8
|
+
}
|
|
9
|
+
let rgCache;
|
|
10
|
+
/**
|
|
11
|
+
* Absolute path of ripgrep, or null when it is not on PATH or
|
|
12
|
+
* `PHREN_AGENT_RIPGREP=off` forces the JS walker. The PATH scan runs once.
|
|
13
|
+
*/
|
|
14
|
+
export function ripgrepPath() {
|
|
15
|
+
if (process.env.PHREN_AGENT_RIPGREP === "off")
|
|
16
|
+
return null;
|
|
17
|
+
if (rgCache !== undefined)
|
|
18
|
+
return rgCache;
|
|
19
|
+
rgCache = null;
|
|
20
|
+
const names = process.platform === "win32" ? ["rg.exe", "rg.cmd"] : ["rg"];
|
|
21
|
+
for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
|
|
22
|
+
if (!dir)
|
|
23
|
+
continue;
|
|
24
|
+
for (const name of names) {
|
|
25
|
+
const candidate = path.join(dir, name);
|
|
26
|
+
try {
|
|
27
|
+
if (fs.statSync(candidate).isFile()) {
|
|
28
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
29
|
+
return (rgCache = candidate);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
catch { /* try the next one */ }
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return rgCache;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Run ripgrep with an argument array (never a shell), feeding stdout to
|
|
39
|
+
* `onLine` one line at a time. `onLine` returns true to stop early.
|
|
40
|
+
* Rejects when ripgrep cannot start or the signal aborts.
|
|
41
|
+
*/
|
|
42
|
+
export function runRipgrep(rg, args, cwd, onLine, signal) {
|
|
43
|
+
return new Promise((resolve, reject) => {
|
|
44
|
+
const child = spawn(rg, args, { cwd, stdio: ["ignore", "pipe", "pipe"], signal, windowsHide: true });
|
|
45
|
+
let buffer = "";
|
|
46
|
+
let stderr = "";
|
|
47
|
+
let stopped = false;
|
|
48
|
+
const feed = (line) => {
|
|
49
|
+
if (stopped || line === "")
|
|
50
|
+
return;
|
|
51
|
+
if (onLine(line)) {
|
|
52
|
+
stopped = true;
|
|
53
|
+
child.kill();
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
child.stdout.setEncoding("utf8");
|
|
57
|
+
child.stdout.on("data", (chunk) => {
|
|
58
|
+
buffer += chunk;
|
|
59
|
+
let nl;
|
|
60
|
+
while ((nl = buffer.indexOf("\n")) >= 0) {
|
|
61
|
+
feed(buffer.slice(0, nl));
|
|
62
|
+
buffer = buffer.slice(nl + 1);
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
child.stderr.setEncoding("utf8");
|
|
66
|
+
child.stderr.on("data", (chunk) => { if (stderr.length < 4000)
|
|
67
|
+
stderr += chunk; });
|
|
68
|
+
child.on("error", reject);
|
|
69
|
+
child.on("close", (code) => {
|
|
70
|
+
feed(buffer);
|
|
71
|
+
resolve({ code, stderr, stopped });
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/** One simple .gitignore line as a matcher: directory names, prefixes and `*` / `?` globs. */
|
|
76
|
+
function ignoreMatcher(line) {
|
|
77
|
+
let p = line.trim();
|
|
78
|
+
if (!p || p.startsWith("#") || p.startsWith("!"))
|
|
79
|
+
return null;
|
|
80
|
+
p = p.replace(/\/+$/, "");
|
|
81
|
+
const anchored = p.includes("/");
|
|
82
|
+
p = p.replace(/^\/+/, "");
|
|
83
|
+
if (!p)
|
|
84
|
+
return null;
|
|
85
|
+
const re = new RegExp(`^${p.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "\0").replace(/\*/g, "[^/]*").replace(/\0/g, ".*").replace(/\?/g, "[^/]")}$`);
|
|
86
|
+
return anchored ? (rel) => re.test(rel) : (_rel, name) => re.test(name);
|
|
87
|
+
}
|
|
88
|
+
function readIgnore(root) {
|
|
89
|
+
let text;
|
|
90
|
+
try {
|
|
91
|
+
text = fs.readFileSync(path.join(root, ".gitignore"), "utf-8");
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return [];
|
|
95
|
+
}
|
|
96
|
+
return text.split("\n").map(ignoreMatcher).filter((m) => m !== null);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Fallback tree walk for when ripgrep is missing. Skips `.git`, node_modules
|
|
100
|
+
* and what the root .gitignore names (simple patterns only); other dotdirs
|
|
101
|
+
* such as `.github` are searched. `accept` filters files before they count
|
|
102
|
+
* against `maxFiles`.
|
|
103
|
+
*/
|
|
104
|
+
export function walkTree(root, maxFiles, accept = () => true) {
|
|
105
|
+
const ignores = readIgnore(root);
|
|
106
|
+
const files = [];
|
|
107
|
+
let truncated = false;
|
|
108
|
+
const visit = (dir, relDir) => {
|
|
109
|
+
if (truncated)
|
|
110
|
+
return;
|
|
111
|
+
let entries;
|
|
112
|
+
try {
|
|
113
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
for (const entry of entries) {
|
|
119
|
+
if (truncated)
|
|
120
|
+
return;
|
|
121
|
+
if (entry.name === ".git" || entry.name === "node_modules")
|
|
122
|
+
continue;
|
|
123
|
+
const rel = relDir ? `${relDir}/${entry.name}` : entry.name;
|
|
124
|
+
if (ignores.some((m) => m(rel, entry.name)))
|
|
125
|
+
continue;
|
|
126
|
+
if (entry.isDirectory()) {
|
|
127
|
+
visit(path.join(dir, entry.name), rel);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (!accept(rel))
|
|
131
|
+
continue;
|
|
132
|
+
if (files.length >= maxFiles) {
|
|
133
|
+
truncated = true;
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
files.push(rel);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
visit(root, "");
|
|
140
|
+
return { files, truncated };
|
|
141
|
+
}
|