@phren/agent 0.3.20 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/agent-loop/index.js +113 -19
  2. package/dist/agent-loop/stream.js +3 -1
  3. package/dist/attach-images.js +57 -0
  4. package/dist/commands/info.js +6 -2
  5. package/dist/commands/model.js +55 -13
  6. package/dist/commands/session.js +79 -18
  7. package/dist/commands.js +9 -2
  8. package/dist/config.js +45 -0
  9. package/dist/context/clear-tool-results.js +43 -0
  10. package/dist/context/compactor.js +8 -2
  11. package/dist/context/usage.js +26 -0
  12. package/dist/cost.js +10 -3
  13. package/dist/headless.js +41 -0
  14. package/dist/index.js +180 -56
  15. package/dist/mcp-client.js +38 -1
  16. package/dist/mcp-prompts.js +94 -0
  17. package/dist/multi/child-entry.js +3 -1
  18. package/dist/multi/spawner.js +27 -15
  19. package/dist/permissions/allowlist.js +19 -4
  20. package/dist/permissions/checker.js +37 -20
  21. package/dist/permissions/kernel-sandbox.js +32 -10
  22. package/dist/permissions/rules.js +173 -0
  23. package/dist/permissions/shell-classify.js +173 -0
  24. package/dist/plan.js +6 -2
  25. package/dist/repl.js +16 -1
  26. package/dist/session/persist.js +9 -4
  27. package/dist/settings.js +14 -0
  28. package/dist/structured-output.js +85 -0
  29. package/dist/system-prompt.js +117 -14
  30. package/dist/tools/apply-patch.js +15 -1
  31. package/dist/tools/edit-file.js +8 -1
  32. package/dist/tools/file-state.js +88 -0
  33. package/dist/tools/glob.js +53 -35
  34. package/dist/tools/grep.js +139 -53
  35. package/dist/tools/lint-test.js +24 -0
  36. package/dist/tools/read-file.js +2 -0
  37. package/dist/tools/registry.js +8 -1
  38. package/dist/tools/search-support.js +141 -0
  39. package/dist/tools/shell.js +3 -1
  40. package/dist/tools/spawn-agent.js +15 -3
  41. package/dist/tools/syntax-check.js +116 -0
  42. package/dist/tools/write-file.js +11 -3
  43. package/dist/tui/components/App.js +5 -4
  44. package/dist/tui/components/Banner.js +1 -1
  45. package/dist/tui/components/ListPicker.js +32 -0
  46. package/dist/tui/ink-entry.js +57 -16
  47. package/dist/user-hooks.js +26 -4
  48. package/package.json +3 -2
@@ -0,0 +1,88 @@
1
+ /**
2
+ * What the model has seen of each file, so the write tools can refuse to work
3
+ * from a stale picture.
4
+ *
5
+ * read_file records a file's state; a successful edit, write or patch records
6
+ * the state it left behind. Before writing, the tools check the file on disk
7
+ * against that record:
8
+ *
9
+ * - changed since the model last saw it (the user, a formatter or a shell
10
+ * command touched it): refused, so a whole-file write can't silently drop
11
+ * the other change and an edit is not planned against old text;
12
+ * - an existing file the model never read: write_file refuses to overwrite
13
+ * it. Edits and patch hunks are allowed, because their old text has to
14
+ * match the file exactly, which already grounds them in its contents.
15
+ *
16
+ * One record per process, which is one session: subagents are separate
17
+ * processes with their own records, so a child that changes a file the
18
+ * parent has read makes the parent read it again.
19
+ */
20
+ import { createHash } from "crypto";
21
+ import * as fs from "fs";
22
+ import * as path from "path";
23
+ const records = new Map();
24
+ function key(filePath) {
25
+ const abs = path.resolve(filePath);
26
+ try {
27
+ return fs.realpathSync(abs);
28
+ }
29
+ catch {
30
+ return abs;
31
+ }
32
+ }
33
+ function hashOf(content) {
34
+ return createHash("sha256").update(content).digest("hex");
35
+ }
36
+ /** Remember the file as it is on disk now (after a read or a write). */
37
+ export function recordFileState(filePath) {
38
+ try {
39
+ const stat = fs.statSync(filePath);
40
+ if (!stat.isFile())
41
+ return;
42
+ records.set(key(filePath), { mtimeMs: stat.mtimeMs, size: stat.size, hash: hashOf(fs.readFileSync(filePath)) });
43
+ }
44
+ catch {
45
+ records.delete(key(filePath));
46
+ }
47
+ }
48
+ /** Forget a file the tools deleted. */
49
+ export function forgetFileState(filePath) {
50
+ records.delete(key(filePath));
51
+ }
52
+ /**
53
+ * Why the file must not be written now, or null when it may be. `requireRead`
54
+ * is for whole-file overwrites.
55
+ */
56
+ export function staleFileError(filePath, opts = {}) {
57
+ if (process.env.PHREN_AGENT_FILE_GUARD === "off")
58
+ return null;
59
+ let stat;
60
+ try {
61
+ stat = fs.statSync(filePath);
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ if (!stat.isFile())
67
+ return null;
68
+ const k = key(filePath);
69
+ const seen = records.get(k);
70
+ if (!seen) {
71
+ return opts.requireRead
72
+ ? `${filePath} already exists and has not been read in this session. Read it with read_file first; to change part of it, use edit_file.`
73
+ : null;
74
+ }
75
+ if (stat.mtimeMs === seen.mtimeMs && stat.size === seen.size)
76
+ return null;
77
+ // Touched but maybe not changed (a formatter that found nothing to do).
78
+ const hash = hashOf(fs.readFileSync(filePath));
79
+ if (hash === seen.hash) {
80
+ records.set(k, { mtimeMs: stat.mtimeMs, size: stat.size, hash });
81
+ return null;
82
+ }
83
+ return `${filePath} changed on disk since you last read or wrote it (by the user, a formatter or a command). Read it again with read_file before changing it; nothing was written.`;
84
+ }
85
+ /** Test seam: forget everything. */
86
+ export function resetFileState() {
87
+ records.clear();
88
+ }
@@ -1,6 +1,37 @@
1
- import * as fs from "fs";
2
- import * as path from "path";
3
1
  import { validatePath } from "../permissions/sandbox.js";
2
+ import { ripgrepPath, runRipgrep, walkTree } from "./search-support.js";
3
+ const MAX_RESULTS = 500;
4
+ const MAX_WALK_FILES = 10000;
5
+ /** Stop reading `rg --files` here; the notice then says "more than". */
6
+ const MAX_RG_FILES = 100000;
7
+ /** Every file under `root` that ripgrep lists (.gitignore applied, hidden files included, not .git or node_modules), or null without ripgrep. */
8
+ async function listWithRipgrep(root, pattern, signal) {
9
+ const rg = ripgrepPath();
10
+ if (!rg)
11
+ return null;
12
+ const matches = [];
13
+ let total = 0;
14
+ let capped = false;
15
+ try {
16
+ await runRipgrep(rg, ["--files", "--hidden", "--no-require-git", "--glob", "!.git", "--glob", "!node_modules", "--sort", "path"], root, (line) => {
17
+ const rel = line.replace(/^\.[\\/]/, "");
18
+ if (!matchGlob(pattern, rel))
19
+ return false;
20
+ total++;
21
+ if (matches.length < MAX_RESULTS)
22
+ matches.push(rel);
23
+ if (total >= MAX_RG_FILES) {
24
+ capped = true;
25
+ return true;
26
+ }
27
+ return false;
28
+ }, signal);
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ return { matches, total, capped };
34
+ }
4
35
  /** Simple glob matching without external dependencies. Supports * and ** patterns. */
5
36
  function matchGlob(pattern, filePath) {
6
37
  // Normalize path separators
@@ -34,34 +65,9 @@ function matchGlob(pattern, filePath) {
34
65
  }
35
66
  return new RegExp(`^${regex}$`).test(f);
36
67
  }
37
- function walkDir(dir, base, results, maxResults) {
38
- if (results.length >= maxResults)
39
- return;
40
- let entries;
41
- try {
42
- entries = fs.readdirSync(dir, { withFileTypes: true });
43
- }
44
- catch {
45
- return;
46
- }
47
- for (const entry of entries) {
48
- if (results.length >= maxResults)
49
- return;
50
- if (entry.name.startsWith(".") || entry.name === "node_modules")
51
- continue;
52
- const full = path.join(dir, entry.name);
53
- const rel = path.relative(base, full);
54
- if (entry.isDirectory()) {
55
- walkDir(full, base, results, maxResults);
56
- }
57
- else {
58
- results.push(rel);
59
- }
60
- }
61
- }
62
68
  export const globTool = {
63
69
  name: "glob",
64
- description: "Find files by glob pattern. Use to discover project structure, locate files by extension or name. Examples: '**/*.ts', 'src/**/*.test.js', '**/config.*'. Skips node_modules and dotfiles.",
70
+ description: "Find files by glob pattern. Use to discover project structure, locate files by extension or name. Examples: '**/*.ts', 'src/**/*.test.js', '**/config.*'. Honours .gitignore, includes hidden files such as .github (not .git).",
65
71
  input_schema: {
66
72
  type: "object",
67
73
  properties: {
@@ -70,20 +76,32 @@ export const globTool = {
70
76
  },
71
77
  required: ["pattern"],
72
78
  },
73
- async execute(input) {
79
+ async execute(input, signal) {
74
80
  const pattern = input.pattern;
75
81
  const searchPath = input.path || process.cwd();
76
- const maxResults = 500;
77
82
  // Defense-in-depth: validate search path against sandbox
78
83
  const pathResult = validatePath(searchPath, process.cwd(), []);
79
84
  if (!pathResult.ok) {
80
85
  return { output: `Path outside sandbox: ${pathResult.error}`, is_error: true };
81
86
  }
82
- const allFiles = [];
83
- walkDir(searchPath, searchPath, allFiles, 10000);
84
- const matches = allFiles.filter((f) => matchGlob(pattern, f)).slice(0, maxResults);
87
+ let matches;
88
+ let note = "";
89
+ const listed = await listWithRipgrep(pathResult.resolved, pattern, signal);
90
+ if (listed) {
91
+ matches = listed.matches;
92
+ if (listed.total > matches.length)
93
+ note = `showing the first ${matches.length} of ${listed.capped ? "more than " : ""}${listed.total} matches; narrow the pattern or path`;
94
+ }
95
+ else {
96
+ const walked = walkTree(searchPath, MAX_WALK_FILES, (rel) => matchGlob(pattern, rel));
97
+ matches = walked.files.slice(0, MAX_RESULTS);
98
+ if (walked.truncated)
99
+ note = `searched the first ${MAX_WALK_FILES} files; narrow the path or pattern`;
100
+ else if (walked.files.length > MAX_RESULTS)
101
+ note = `showing the first ${MAX_RESULTS} of ${walked.files.length} matches; narrow the pattern or path`;
102
+ }
85
103
  if (matches.length === 0)
86
- return { output: "No files found." };
87
- return { output: matches.join("\n") };
104
+ return { output: note ? `No files found (${note}).` : "No files found." };
105
+ return { output: note ? `${matches.join("\n")}\n\n(${note})` : matches.join("\n") };
88
106
  },
89
107
  };
@@ -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].slice(0, 200) });
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: true." },
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"] ?? true;
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 || "i");
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 files = [];
152
- walkDir(searchPath, files, 5000);
153
- // File type filter
154
- if (fileType) {
155
- const exts = FILE_TYPE_EXTENSIONS[fileType] ?? [`.${fileType}`];
156
- const filtered = files.filter((f) => exts.some((ext) => f.endsWith(ext)));
157
- files.length = 0;
158
- files.push(...filtered);
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
- return { output: output.join(outputMode === "content" ? "\n\n" : "\n") };
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
  };
@@ -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
@@ -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();
@@ -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
  }