xonecas.io
64875
Mc

mini-coder / commit d966c5d

feat: drop glob/grep tools and add one-shot exit

- Remove glob and grep tools (src/tools/glob.ts, grep.ts, ignore.ts,
  scan-path.ts + tests); agents use shell for file discovery/search
- Remove hookEnvForGlob/hookEnvForGrep from hooks.ts and HOOKABLE_TOOLS
- Remove glob/grep renderers, commonPrefix, stripHashlinePrefix from
  tool-render.ts
- Exit after processUserInput when a prompt arg is provided (one-shot)
- Update schema descriptions in insert.ts, replace.ts, read.ts
- Update docs: README, tool-hooks.md, mini-coder.1.md, custom-commands.md
- Update SKILL.md and system-prompt.ts to reflect removed tools

xonecas2026-03-14 d966c5dec3ba3e49b61a7a962dc1e676be32f3c5 parent 705e288

24 files changed

.agents/skills/mini-coder/SKILL.md+3−3
@@ -14,7 +14,7 @@ mini-coder is a small, fast CLI coding agent built with Bun and TypeScript.
1414 | `src/agent/` | Core agent loop, session runner, subagent runner, system prompt builder |
1515 | `src/cli/` | CLI commands, custom commands, agents/skills loaders, input/output rendering |
1616 | `src/llm-api/` | Provider abstraction, turn streaming, model metadata |
17-| `src/tools/` | All tools (read, replace, insert, create, glob, grep, shell, subagent, exa, …) |
17+| `src/tools/` | All tools (read, replace, insert, create, shell, subagent, exa, …) |
1818 | `src/session/` | Session manager and SQLite DB repositories |
1919 | `src/mcp/` | MCP client integration |
2020 | `.agents/` | Local config: agents, commands, skills, hooks |
@@ -47,9 +47,9 @@ All config lives under `.agents/` (or `~/.agents/` globally). Local wins over gl
4747
4848 ## Tools
4949
50-Every tool is declared in `src/agent/tools.ts`. Core tools: `read`, `glob`, `grep`, `replace`, `insert`, `create`, `shell`, `subagent`, `webSearch`, `webContent`.
50+Every tool is declared in `src/agent/tools.ts`. Core tools: `read`, `replace`, `insert`, `create`, `shell`, `subagent`, `webSearch`, `webContent`.
5151
52-Hooks in `.agents/hooks/` fire after any of the 7 hookable tools: `glob`, `grep`, `read`, `create`, `replace`, `insert`, `shell`. The repo currently uses `post-create`, `post-insert`, and `post-replace` to auto-format changed files.
52+Hooks in `.agents/hooks/` fire after any of the 5 hookable tools: `read`, `create`, `replace`, `insert`, `shell`. The repo currently uses `post-create`, `post-insert`, and `post-replace` to auto-format changed files.
5353
5454
5555 ## Testing
README.md+1−3
@@ -28,8 +28,6 @@ My toolkit is lean on purpose — every tool earns its spot, no passengers:
2828
2929 | Tool | What it does |
3030 | --------------- | ----------------------------------------------------------- |
31-| 🔍 `glob` | Find files by pattern across your project |
32-| 🧲 `grep` | Search file contents with regex |
3331 | 📖 `read` | Read files (with line-range support) |
3432 | 📝 `create` | Create a new file or fully overwrite an existing file |
3533 | ✏️ `replace` | Replace or delete lines using hashline anchors |
@@ -166,7 +164,7 @@ src/
166164 agent/ # Main REPL loop + tool registry
167165 cli/ # Input, output, slash commands, markdown rendering
168166 llm-api/ # Provider factory + streaming turn logic
169- tools/ # glob, grep, read, create, replace, insert, shell, subagent
167+ tools/ # read, create, replace, insert, shell, subagent
170168 # + webSearch, webContent, hashline anchors, diffs, hooks, snapshots
171169 mcp/ # MCP server connections
172170 session/ # SQLite-backed session & history management
TODO.md+3−3
@@ -11,9 +11,9 @@
1111
1212 ## Lean and mean idea
1313
14-Drop the suabgent tool completly, prefer using the shell tool to mimic the subagent behaviour. Ensure we still support our subagents features like commands in new processes and subagent types. Update the mini-coder skill to be a guide explaining how to use mc via shell tool. Revise our cli interface to ensure support. When mc is called with a prompt, make it exit after the loop. Like a one shot.
15-Drop glob and grep tools. the agents can use shell for these.
16-Do an extensive pass to cleanup tests, dead code and anything else that might have been related to our removals.
14+When mc is called with a prompt, make it exit after the loop. Like a one shot. ✅
15+Drop glob and grep tools — done. ✅
16+Cleanup pass — done. ✅
1717
1818 ---
1919
docs/custom-commands.md+3−3
@@ -59,7 +59,7 @@ model: zen/claude-haiku-4-5
5959
6060 Search the codebase for: $ARGUMENTS
6161
62-Use glob, grep, and read tools to explore thoroughly. Report all
62+Use shell, read, and other tools to explore thoroughly. Report all
6363 relevant files, key code snippets with line numbers, and a short summary.
6464 Be exhaustive but concise. No edits — read only.
6565 ```
@@ -113,11 +113,11 @@ lightweight tasks regardless of what the session is currently set to.
113113
114114 ```md
115115 ---
116-description: Quick grep for a symbol
116+description: Quick symbol search
117117 model: zen/claude-haiku-4-5
118118 ---
119119
120-Find all usages of $ARGUMENTS across the codebase using grep and glob.
120+Find all usages of $ARGUMENTS across the codebase using shell.
121121 List each occurrence with file path and line number. No explanations needed.
122122 ```
123123
docs/mini-coder.1.md+0−2
@@ -103,8 +103,6 @@ Inside the interactive session, the following slash commands are available:
103103
104104 ## BUILT-IN TOOLS
105105 The agent has access to the following tools:
106-* **glob**: Discover files by glob pattern across the project.
107-* **grep**: Search file contents using regular expressions.
108106 * **read**: Read file contents with line-range pagination support.
109107 * **create**: Write a new file or completely overwrite an existing one.
110108 * **replace**: Replace or delete targeted lines using hashline anchors.
docs/tool-hooks.md+0−14
@@ -19,8 +19,6 @@ Local hooks take precedence over global ones. The filename must match `post-<too
1919
2020 | Tool | Hook filename |
2121 |---|---|
22-| `glob` | `post-glob` |
23-| `grep` | `post-grep` |
2422 | `read` | `post-read` |
2523 | `create` | `post-create` |
2624 | `replace` | `post-replace` |
@@ -77,18 +75,6 @@ Plus tool-specific variables:
7775 | `STDOUT` | Captured standard output |
7876 | `STDERR` | Captured standard error |
7977
80-### `post-glob`
81-
82-| Variable | Description |
83-|---|---|
84-| `PATTERN` | The glob pattern that was searched |
85-
86-### `post-grep`
87-
88-| Variable | Description |
89-|---|---|
90-| `PATTERN` | The regex pattern that was searched |
91-
9278 ### `post-read`
9379
9480 | Variable | Description |
package.json+0−1
@@ -25,7 +25,6 @@
2525 "@ai-sdk/openai-compatible": "^2.0.36",
2626 "@modelcontextprotocol/sdk": "^1.27.1",
2727 "ai": "^6.0.127",
28- "ignore": "^7.0.5",
2928 "yoctocolors": "^2.1.2",
3029 "zod": "^4.3.6"
3130 },
plan.md+102−0
@@ -0,0 +1,102 @@
1+# Plan: Lean and Mean
2+
3+## Overview
4+
5+Three changes:
6+1. **One-shot exit** — when `mc` is called with a prompt (interactive, non-subagent), exit after the agent finishes instead of dropping into the input loop.
7+2. **Drop `glob` and `grep` tools** — agents can use `shell` for these. Remove all related source, tests, hooks, and documentation.
8+3. **Cleanup pass** — dead code, orphaned helpers, stale references.
9+
10+---
11+
12+## 1. One-shot exit (`src/index.ts`)
13+
14+Currently when a prompt is provided, `processUserInput` runs and then `runInputLoop` starts anyway. Change this:
15+
16+```
17+if (args.prompt) {
18+ await runner.processUserInput(...);
19+ return; // ← exit instead of falling into runInputLoop
20+}
21+await runInputLoop(...);
22+```
23+
24+Update the `printHelp` example comment in `src/cli/args.ts` from
25+`# one-shot prompt then interactive` → `# one-shot prompt then exit`.
26+
27+---
28+
29+## 2. Drop `glob` and `grep` tools
30+
31+### Files to delete
32+- `src/tools/glob.ts`
33+- `src/tools/glob.test.ts`
34+- `src/tools/grep.ts`
35+- `src/tools/grep.test.ts`
36+- `src/tools/ignore.ts` — only consumed by glob and grep
37+- `src/tools/scan-path.ts` — only consumed by glob and grep
38+
39+### `src/agent/tools.ts`
40+- Remove imports: `GlobOutput`, `globTool`, `GrepOutput`, `grepTool`, `hookEnvForGlob`, `hookEnvForGrep`
41+- Remove `"glob"` and `"grep"` from `HOOKABLE_TOOLS`
42+- Remove `withHooks(withCwdDefault(globTool …))` entry from `buildToolSet`
43+- Remove `withHooks(withCwdDefault(grepTool …))` entry from `buildToolSet`
44+- Remove `withCwdDefault(globTool …)` and `withCwdDefault(grepTool …)` from `buildReadOnlyToolSet`
45+
46+### `src/tools/hooks.ts`
47+- Delete `hookEnvForGlob` function
48+- Delete `hookEnvForGrep` function
49+
50+### `src/agent/system-prompt.ts`
51+- Line 96: update guideline — remove `glob, grep` from the list of dedicated tools:
52+ `"Prefer dedicated tools (read, replace, insert) over shell for file operations."`
53+- Line 101: update tool output format note — remove mention of `grep` prefixing lines
54+ (only `read` adds the `line:hash|` prefix now):
55+ `` `read` prefixes every line with `line:hash|` … ``
56+
57+### `src/agent/tools.test.ts`
58+- No glob/grep-specific tests exist here, but verify the `buildReadOnlyToolSet` test no longer expects glob/grep (it currently doesn't assert on them, so it should be fine as-is).
59+
60+---
61+
62+## 3. Cleanup pass
63+
64+### `src/agent/system-prompt.ts` — SKILL.md reference
65+The skill file (`SKILL.md`) lists `glob` and `grep` as core tools; update it once the tools are removed.
66+File: `.agents/skills/mini-coder/SKILL.md` — remove `glob` and `grep` from the tools table, remove hook references for those tools.
67+
68+### `src/agent/tools.test.ts`
69+- After removing tools, confirm no lingering `"glob"` / `"grep"` name checks remain.
70+
71+### Verify no other source files import from `glob.ts`, `grep.ts`, `ignore.ts`, or `scan-path.ts`
72+- Run `knip` / `typecheck` after deletions to surface any missed references.
73+
74+---
75+
76+## 4. Verification
77+
78+```bash
79+bun run jscpd && bun run knip && bun run typecheck && bun run format && bun run lint && bun run test
80+```
81+
82+All checks must pass cleanly before closing out.
83+
84+---
85+
86+## Touch-list (ordered)
87+
88+| # | File | Action |
89+|---|------|--------|
90+| 1 | `src/index.ts` | Return after one-shot prompt instead of entering input loop |
91+| 2 | `src/cli/args.ts` | Fix help comment for prompt example |
92+| 3 | `src/tools/glob.ts` | Delete |
93+| 4 | `src/tools/glob.test.ts` | Delete |
94+| 5 | `src/tools/grep.ts` | Delete |
95+| 6 | `src/tools/grep.test.ts` | Delete |
96+| 7 | `src/tools/ignore.ts` | Delete |
97+| 8 | `src/tools/scan-path.ts` | Delete |
98+| 9 | `src/agent/tools.ts` | Remove glob/grep imports, registrations, HOOKABLE_TOOLS entries |
99+| 10 | `src/tools/hooks.ts` | Remove `hookEnvForGlob`, `hookEnvForGrep` |
100+| 11 | `src/agent/system-prompt.ts` | Update guidelines and tool-output-format text |
101+| 12 | `.agents/skills/mini-coder/SKILL.md` | Remove glob/grep from tools table and hooks list |
102+| 13 | Verify | `bun run jscpd && bun run knip && … && bun run test` |
src/agent/system-prompt.ts+2−2
@@ -93,12 +93,12 @@ Current date/time: ${sessionTimeAnchor}
9393 Guidelines:
9494 - Be concise and precise. Avoid unnecessary preamble.
9595 - Prefer small, targeted edits over large rewrites.
96-- Always read a file before editing it. Prefer dedicated tools (read, glob, grep, replace, insert) over shell for file operations.
96+- Always read a file before editing it. Prefer dedicated tools (read, replace, insert) over shell for file operations.
9797 - Make parallel tool calls when reads/searches are independent — don't wait for one to start the next.
9898 - Keep your context clean and focused on the user request.
9999
100100 # Tool output format
101-\`read\` and \`grep\` prefix every line with \`line:hash|\` (e.g. \`11:a3| code here\`). This prefix is metadata — never include it in file content you write. Use the \`line:hash\` values as anchors for \`replace\` and \`insert\`.`;
101+\`read\` prefixes every line with \`line:hash|\` (e.g. \`11:a3| code here\`). This prefix is metadata — never include it in file content you write. Use the \`line:hash\` values as anchors for \`replace\` and \`insert\`.`;
102102
103103 prompt += AUTONOMY;
104104 prompt += SAFETY;
src/agent/tools.ts+1−37
@@ -2,15 +2,9 @@ import type { ToolDef } from "../llm-api/types.ts";
22 import type { CreateToolOutput } from "../tools/create.ts";
33 import { createTool } from "../tools/create.ts";
44 import { webContentTool, webSearchTool } from "../tools/exa.ts";
5-import type { GlobOutput } from "../tools/glob.ts";
6-import { globTool } from "../tools/glob.ts";
7-import type { GrepOutput } from "../tools/grep.ts";
8-import { grepTool } from "../tools/grep.ts";
95 import {
106 createHookCache,
117 hookEnvForCreate,
12- hookEnvForGlob,
13- hookEnvForGrep,
148 hookEnvForInsert,
159 hookEnvForRead,
1610 hookEnvForReplace,
@@ -109,15 +103,7 @@ function withHooks<
109103 // ─── Tool registry ────────────────────────────────────────────────────────────
110104
111105 // Names of all local tools that support hooks (MCP tools are excluded).
112-const HOOKABLE_TOOLS = [
113- "glob",
114- "grep",
115- "read",
116- "create",
117- "replace",
118- "insert",
119- "shell",
120-];
106+const HOOKABLE_TOOLS = ["read", "create", "replace", "insert", "shell"];
121107
122108 export function buildToolSet(opts: {
123109 cwd: string;
@@ -136,26 +122,6 @@ export function buildToolSet(opts: {
136122
137123 const tools: ToolDef[] = [
138124 // Read-only: discover and inspect files
139- withHooks(
140- withCwdDefault(globTool as ToolDef, cwd) as ToolDef<
141- { cwd?: string; pattern: string },
142- GlobOutput
143- >,
144- lookupHook,
145- cwd,
146- (_, input) => hookEnvForGlob(input, cwd),
147- onHook,
148- ) as ToolDef,
149- withHooks(
150- withCwdDefault(grepTool as ToolDef, cwd) as ToolDef<
151- { cwd?: string; pattern: string },
152- GrepOutput
153- >,
154- lookupHook,
155- cwd,
156- (_, input) => hookEnvForGrep(input, cwd),
157- onHook,
158- ) as ToolDef,
159125 withHooks(
160126 withCwdDefault(readTool as ToolDef, cwd) as ToolDef<
161127 { cwd?: string; path: string },
@@ -233,8 +199,6 @@ export function buildToolSet(opts: {
233199 export function buildReadOnlyToolSet(opts: { cwd: string }): ToolDef[] {
234200 const { cwd } = opts;
235201 const tools: ToolDef[] = [
236- withCwdDefault(globTool as ToolDef, cwd),
237- withCwdDefault(grepTool as ToolDef, cwd),
238202 withCwdDefault(readTool as ToolDef, cwd),
239203 withCwdDefault(listSkillsTool as ToolDef, cwd),
240204 withCwdDefault(readSkillTool as ToolDef, cwd),
src/cli/args.ts+1−1
@@ -110,7 +110,7 @@ export function printHelp(): void {
110110 writeln(`\n${c.bold("Examples:")}`);
111111 writeln(` mc ${c.dim("# interactive session")}`);
112112 writeln(
113- ` mc "explain this codebase" ${c.dim("# one-shot prompt then interactive")}`,
113+ ` mc "explain this codebase" ${c.dim("# one-shot prompt then exit")}`,
114114 );
115115 writeln(` mc -c ${c.dim("# continue last session")}`);
116116 writeln(
src/cli/output.ts+1−1
@@ -39,7 +39,7 @@ export const G = {
3939 reply: c.cyan("◆"), // assistant reply start
4040
4141 // tool action glyphs (compact, one per line)
42- search: c.yellow("?"), // glob / grep
42+ search: c.yellow("?"), // search (shell grep/glob)
4343 read: c.dim("←"), // read file
4444 write: c.green("✎"), // edit / create file
4545 run: c.dim("$"), // shell
src/cli/tool-render.ts+0−100
@@ -4,26 +4,7 @@ import { G, writeln } from "./output.ts";
44
55 const HOME = homedir();
66
7-/** Strip the `linenum:hash| ` prefix that hashline-formatted tool outputs include. */
8-function stripHashlinePrefix(text: string): string {
9- return text.replace(/^\d+:[0-9a-f]{2}\| /, "");
10-}
11-
12-function commonPrefix(paths: string[]): string {
13- const first = paths[0];
14- if (!first) return "";
15- const parts = first.split("/");
16- let prefix = "";
17- for (let i = 0; i < parts.length - 1; i++) {
18- const candidate = `${parts.slice(0, i + 1).join("/")}/`;
19- if (paths.every((p) => p.startsWith(candidate))) prefix = candidate;
20- else break;
21- }
22- return prefix;
23-}
24-
257 function toolGlyph(name: string): string {
26- if (name === "glob" || name === "grep") return G.search;
278 if (name === "read") return G.read;
289 if (name === "create" || name === "replace" || name === "insert")
2910 return G.write;
@@ -49,21 +30,6 @@ function toolCallLine(
4930 const label = agentName ? ` ${c.dim(c.cyan(`[@${agentName}]`))}` : "";
5031 return `${G.agent}${label} ${c.dim("—")} ${short}`;
5132 }
52- if (name === "glob") {
53- const pattern = String(a.pattern ?? "");
54- const cwd = a.cwd ? String(a.cwd) : "";
55- return `${G.search} ${c.dim("glob")} ${c.bold(pattern)}${cwd ? c.dim(` in ${cwd}`) : ""}`;
56- }
57- if (name === "grep") {
58- const flags = [
59- a.include ? String(a.include) : null,
60- a.caseSensitive === false ? "i" : null,
61- ]
62- .filter(Boolean)
63- .join(" ");
64- const pattern = String(a.pattern ?? "");
65- return `${G.search} ${c.dim("grep")} ${c.bold(pattern)}${flags ? c.dim(` ${flags}`) : ""}`;
66- }
6733 if (name === "read") {
6834 const line = Number.isFinite(a.line as number) ? Number(a.line) : null;
6935 const count = Number.isFinite(a.count as number) ? Number(a.count) : null;
@@ -170,72 +136,6 @@ export function renderToolResult(
170136 return;
171137 }
172138
173- if (toolName === "glob") {
174- const r = result as { files?: string[]; truncated?: boolean };
175- if (Array.isArray(r?.files)) {
176- const files = r.files;
177- if (files.length === 0) {
178- writeln(` ${G.info} ${c.dim("no matches")}`);
179- return;
180- }
181-
182- // Show up to 12 files, grouped by top-level directory for readability
183- const show = files.slice(0, 12);
184- const rest = files.length - show.length;
185-
186- // Find common prefix to strip for cleaner display
187- const prefix = commonPrefix(show);
188- for (const f of show) {
189- const rel =
190- prefix && f.startsWith(prefix)
191- ? c.dim(prefix) + f.slice(prefix.length)
192- : f;
193- writeln(` ${c.dim("·")} ${rel}`);
194- }
195- if (rest > 0) writeln(` ${c.dim(` +${rest} more`)}`);
196- if (r.truncated) writeln(` ${c.dim(" (results capped)")}`);
197- return;
198- }
199- }
200-
201- if (toolName === "grep") {
202- const r = result as {
203- matches?: Array<{
204- file: string;
205- line: number;
206- text: string;
207- context?: Array<{ line: number; text: string; isMatch: boolean }>;
208- }>;
209- truncated?: boolean;
210- };
211- if (Array.isArray(r?.matches)) {
212- if (r.matches.length === 0) {
213- writeln(` ${G.info} ${c.dim("no matches")}`);
214- return;
215- }
216-
217- // Deduplicate by file, show file:line and match text
218- const seen = new Set<string>();
219- let shown = 0;
220- for (const m of r.matches) {
221- if (shown >= 10) break;
222- const key = m.file;
223- const fileLabel = seen.has(key)
224- ? c.dim(" ".repeat(m.file.length + 1))
225- : c.dim(`${m.file}:`);
226- seen.add(key);
227- writeln(
228- ` ${fileLabel}${c.dim(String(m.line))} ${stripHashlinePrefix(m.text).trim()}`,
229- );
230- shown++;
231- }
232- const rest = r.matches.length - shown;
233- if (rest > 0) writeln(` ${c.dim(` +${rest} more`)}`);
234- if (r.truncated) writeln(` ${c.dim(" (results capped)")}`);
235- return;
236- }
237- }
238-
239139 if (toolName === "read") {
240140 const r = result as {
241141 path: string;
src/index.ts+1−0
@@ -171,6 +171,7 @@ async function main(): Promise<void> {
171171 args.cwd,
172172 );
173173 await runner.processUserInput(resolvedText, refImages);
174+ return;
174175 }
175176
176177 await runInputLoop({
src/tools/glob.test.ts+0−57
@@ -1,57 +0,0 @@
1-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3-import { tmpdir } from "node:os";
4-import { dirname, join } from "node:path";
5-import { globTool } from "./glob.ts";
6-
7-describe("globTool", () => {
8- let root: string;
9-
10- beforeEach(() => {
11- root = mkdtempSync(join(tmpdir(), "mc-glob-test-"));
12- mkdirSync(join(root, "src"));
13- writeFileSync(join(root, ".gitignore"), "");
14- writeFileSync(join(root, "src", "a.ts"), "export const ok = true;\n");
15- writeFileSync(join(root, "src", "a.md"), "note\n");
16- });
17-
18- afterEach(() => {
19- rmSync(root, { recursive: true, force: true });
20- });
21-
22- test("normalizes absolute patterns to cwd-relative results", async () => {
23- const result = await globTool.execute({
24- cwd: root,
25- pattern: join(root, "**", "*.ts"),
26- });
27-
28- expect(result.files).toContain("src/a.ts");
29- expect(
30- result.files.every((p) => !p.startsWith("/") && !p.startsWith("..")),
31- ).toBe(true);
32- });
33-
34- test("ignores default-ignore directories outside cwd", async () => {
35- const outside = mkdtempSync(join(dirname(root), "mc-glob-outside-"));
36- mkdirSync(join(outside, ".git"));
37- writeFileSync(join(outside, "ok.txt"), "ok\n");
38- writeFileSync(join(outside, ".git", "ignored.txt"), "ignore\n");
39-
40- try {
41- const result = await globTool.execute({
42- cwd: root,
43- pattern: join(outside, "**", "*"),
44- });
45-
46- expect(
47- result.files.some((file) => file.endsWith("ok.txt")),
48- "Expected outside allowed file to be discovered",
49- ).toBe(true);
50- expect(
51- result.files.some((file) => file.endsWith(".git/ignored.txt")),
52- ).toBe(false);
53- } finally {
54- rmSync(outside, { recursive: true, force: true });
55- }
56- });
57-});
src/tools/glob.ts+0−79
@@ -1,79 +0,0 @@
1-import { resolve } from "node:path";
2-import { z } from "zod";
3-import type { ToolDef } from "../llm-api/types.ts";
4-import { loadGitignore } from "./ignore.ts";
5-import { getScannedPathInfo } from "./scan-path.ts";
6-
7-const GlobSchema = z.object({
8- pattern: z
9- .string()
10- .describe("Glob pattern to match files against, e.g. '**/*.ts'"),
11- ignore: z.array(z.string()).optional().describe("Glob patterns to exclude"),
12-});
13-
14-type GlobInput = z.infer<typeof GlobSchema> & { cwd?: string };
15-
16-export interface GlobOutput {
17- files: string[];
18- count: number;
19- truncated: boolean;
20-}
21-
22-const MAX_RESULTS = 500;
23-
24-export const globTool: ToolDef<GlobInput, GlobOutput> = {
25- name: "glob",
26- description:
27- "Find files matching a glob pattern. Returns relative paths sorted by modification time. " +
28- "Use this to discover files before reading them.",
29- schema: GlobSchema,
30- execute: async (input) => {
31- const cwd = input.cwd ?? process.cwd();
32- const defaultIgnore = [".git/**", "node_modules/**"];
33- const ignorePatterns = [...defaultIgnore, ...(input.ignore ?? [])];
34-
35- const ignoreGlobs = ignorePatterns.map((pat) => new Bun.Glob(pat));
36-
37- const ig = await loadGitignore(cwd);
38-
39- const glob = new Bun.Glob(input.pattern);
40- const matches: Array<{ path: string; mtime: number }> = [];
41-
42- for await (const file of glob.scan({ cwd, onlyFiles: true, dot: true })) {
43- const { relativePath, ignoreTargets } = getScannedPathInfo(cwd, file);
44- const firstSegment = relativePath.split("/")[0] ?? "";
45-
46- // Check if ignored by .gitignore
47- if (ignoreTargets.some((path) => ig?.ignores(path))) continue;
48-
49- // Check explicit ignore patterns
50- const ignored = ignoreTargets.some((candidate) =>
51- ignoreGlobs.some((g) => g.match(candidate) || g.match(firstSegment)),
52- );
53- if (ignored) continue;
54-
55- try {
56- const fullPath = resolve(cwd, relativePath);
57- const stat = (await Bun.file(fullPath).stat?.()) ?? null;
58- matches.push({
59- path: relativePath,
60- mtime: stat?.mtime?.getTime() ?? 0,
61- });
62- } catch {
63- matches.push({ path: relativePath, mtime: 0 });
64- }
65-
66- if (matches.length >= MAX_RESULTS + 1) break;
67- }
68-
69- const truncated = matches.length > MAX_RESULTS;
70- if (truncated) matches.pop();
71-
72- // Sort by mtime descending (most recently modified first)
73- matches.sort((a, b) => b.mtime - a.mtime);
74-
75- const files = matches.map((m) => m.path);
76-
77- return { files, count: files.length, truncated };
78- },
79-};
src/tools/grep.test.ts+0−71
@@ -1,71 +0,0 @@
1-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3-import { tmpdir } from "node:os";
4-import { dirname, join } from "node:path";
5-import { grepTool } from "./grep.ts";
6-
7-describe("grepTool", () => {
8- let root: string;
9-
10- beforeEach(() => {
11- root = mkdtempSync(join(tmpdir(), "mc-grep-test-"));
12- mkdirSync(join(root, "src"));
13- writeFileSync(join(root, ".gitignore"), "");
14- writeFileSync(join(root, "src", "notes.md"), "OpenAI auth token\n");
15- writeFileSync(
16- join(root, "src", "ignore.txt"),
17- "openai should be skipped by extension\n",
18- );
19- });
20-
21- afterEach(() => {
22- rmSync(root, { recursive: true, force: true });
23- });
24-
25- test("normalizes absolute include patterns and returns relative file paths", async () => {
26- const result = await grepTool.execute({
27- cwd: root,
28- pattern: "OpenAI",
29- include: join(root, "**", "*.md"),
30- caseSensitive: false,
31- contextLines: 2,
32- maxResults: 50,
33- });
34-
35- expect(result.matches).toHaveLength(1);
36- expect(result.matches[0]?.file).toBe("src/notes.md");
37- expect(result.matches[0]?.file.startsWith("/")).toBe(false);
38- expect(result.matches[0]?.file.startsWith("..")).toBe(false);
39- });
40-
41- test("ignores default-ignore directories outside cwd", async () => {
42- const outside = mkdtempSync(join(dirname(root), "mc-grep-outside-"));
43- mkdirSync(join(outside, ".git"));
44- writeFileSync(join(outside, "allowed.txt"), "OpenAI inside allowed\n");
45- writeFileSync(
46- join(outside, ".git", "secrets.txt"),
47- "OpenAI hidden token\n",
48- );
49-
50- try {
51- const result = await grepTool.execute({
52- cwd: root,
53- pattern: "OpenAI",
54- include: join(outside, "**", "*.txt"),
55- caseSensitive: false,
56- contextLines: 2,
57- maxResults: 50,
58- });
59-
60- expect(result.matches).toHaveLength(1);
61- expect(
62- result.matches.some((match) => match.file.endsWith("allowed.txt")),
63- ).toBe(true);
64- expect(
65- result.matches.some((match) => match.file.includes(".git/secrets.txt")),
66- ).toBe(false);
67- } finally {
68- rmSync(outside, { recursive: true, force: true });
69- }
70- });
71-});
src/tools/grep.ts+0−149
@@ -1,149 +0,0 @@
1-import { z } from "zod";
2-import type { ToolDef } from "../llm-api/types.ts";
3-import { formatHashLine } from "./hashline.ts";
4-import { loadGitignore } from "./ignore.ts";
5-import { getScannedPathInfo } from "./scan-path.ts";
6-
7-const GrepSchema = z.object({
8- pattern: z.string().describe("Regular expression to search for"),
9- include: z
10- .string()
11- .optional()
12- .describe("Glob pattern to filter files, e.g. '*.ts' or '*.{ts,tsx}'"),
13- contextLines: z
14- .number()
15- .int()
16- .min(0)
17- .max(10)
18- .optional()
19- .default(2)
20- .describe("Lines of context to include around each match"),
21- caseSensitive: z
22- .boolean()
23- .optional()
24- .default(true)
25- .describe("Case-sensitive search (default: true)"),
26- maxResults: z.number().int().min(1).max(200).optional().default(50),
27-});
28-
29-type GrepInput = z.infer<typeof GrepSchema> & { cwd?: string };
30-
31-export interface GrepMatch {
32- file: string;
33- line: number;
34- column: number;
35- text: string;
36- context: Array<{ line: number; text: string; isMatch: boolean }>;
37-}
38-
39-export interface GrepOutput {
40- matches: GrepMatch[];
41- totalMatches: number;
42- truncated: boolean;
43-}
44-
45-const DEFAULT_IGNORE = [
46- "node_modules/**",
47- ".git/**",
48- "dist/**",
49- "*.db",
50- "*.db-shm",
51- "*.db-wal",
52- "bun.lock",
53-];
54-
55-export const grepTool: ToolDef<GrepInput, GrepOutput> = {
56- name: "grep",
57- description:
58- "Search for a regex pattern across files. Returns file paths, line numbers, and context. " +
59- "Use this to find code patterns, function definitions, or specific text.",
60- schema: GrepSchema,
61- execute: async (input) => {
62- const cwd = input.cwd ?? process.cwd();
63- const flags = input.caseSensitive ? "" : "i";
64- const regex = new RegExp(input.pattern, flags);
65- const maxResults = input.maxResults ?? 50;
66- const contextLines = input.contextLines ?? 2;
67- const include = input.include ?? "**/*";
68-
69- const fileGlob = new Bun.Glob(include);
70- const ignoreGlob = DEFAULT_IGNORE.map((p) => new Bun.Glob(p));
71-
72- const allMatches: GrepMatch[] = [];
73- let truncated = false;
74- const ig = await loadGitignore(cwd);
75-
76- outer: for await (const fromPath of fileGlob.scan({
77- cwd,
78- onlyFiles: true,
79- dot: true,
80- })) {
81- const { absolute, relativePath, ignoreTargets } = getScannedPathInfo(
82- cwd,
83- fromPath,
84- );
85- const firstSegment = relativePath.split("/")[0] ?? "";
86-
87- if (ignoreTargets.some((path) => ig?.ignores(path))) continue;
88- if (
89- ignoreTargets.some((candidate) =>
90- ignoreGlob.some((g) => g.match(candidate) || g.match(firstSegment)),
91- )
92- ) {
93- continue;
94- }
95-
96- const fullPath = absolute;
97- let text: string;
98- try {
99- text = await Bun.file(fullPath).text();
100- } catch {
101- continue;
102- }
103-
104- // Skip binary-ish files
105- if (text.includes("\0")) continue;
106-
107- const lines = text.split("\n");
108-
109- for (let i = 0; i < lines.length; i++) {
110- const line = lines[i] ?? "";
111- const match = regex.exec(line);
112- if (!match) continue;
113-
114- // Gather context
115- const ctxStart = Math.max(0, i - contextLines);
116- const ctxEnd = Math.min(lines.length - 1, i + contextLines);
117- const context: GrepMatch["context"] = [];
118- for (let c = ctxStart; c <= ctxEnd; c++) {
119- context.push({
120- line: c + 1,
121- text: formatHashLine(c + 1, lines[c] ?? ""),
122- isMatch: c === i,
123- });
124- }
125-
126- allMatches.push({
127- file: relativePath,
128- line: i + 1,
129- column: match.index + 1,
130- text: formatHashLine(i + 1, line),
131- context,
132- });
133-
134- if (allMatches.length >= maxResults + 1) {
135- truncated = true;
136- break outer;
137- }
138- }
139- }
140-
141- if (truncated) allMatches.pop();
142-
143- return {
144- matches: allMatches,
145- totalMatches: allMatches.length,
146- truncated,
147- };
148- },
149-};
src/tools/hooks.ts+0−22
@@ -128,28 +128,6 @@ export function hookEnvForShell(
128128 };
129129 }
130130
131-export function hookEnvForGlob(
132- input: { pattern: string },
133- cwd: string,
134-): Record<string, string> {
135- return {
136- TOOL: "glob",
137- PATTERN: input.pattern,
138- CWD: cwd,
139- };
140-}
141-
142-export function hookEnvForGrep(
143- input: { pattern: string },
144- cwd: string,
145-): Record<string, string> {
146- return {
147- TOOL: "grep",
148- PATTERN: input.pattern,
149- CWD: cwd,
150- };
151-}
152-
153131 export function hookEnvForRead(
154132 input: { path: string },
155133 cwd: string,
src/tools/ignore.ts+0−13
@@ -1,13 +0,0 @@
1-import { join } from "node:path";
2-import ignore from "ignore";
3-
4-export async function loadGitignore(
5- cwd: string,
6-): Promise<ReturnType<typeof ignore> | null> {
7- try {
8- const gitignore = await Bun.file(join(cwd, ".gitignore")).text();
9- return ignore().add(gitignore);
10- } catch {
11- return null;
12- }
13-}
src/tools/insert.ts+2−4
@@ -6,9 +6,7 @@ import type { WriteResultMeta } from "./write-result.ts";
66
77 const InsertSchema = z.object({
88 path: z.string().describe("File path to edit (absolute or relative to cwd)"),
9- anchor: z
10- .string()
11- .describe('Anchor line from a prior read/grep, e.g. "11:a3"'),
9+ anchor: z.string().describe('Anchor line from a prior read, e.g. "11:a3"'),
1210 position: z
1311 .enum(["before", "after"])
1412 .describe('Insert the content "before" or "after" the anchor line'),
@@ -35,7 +33,7 @@ export const insertTool: ToolDef<InsertInput, InsertToolOutput> = {
3533 description:
3634 "Insert new lines before or after an anchor line in an existing file. " +
3735 "The anchor line itself is not modified. " +
38- 'Anchors come from the `read` or `grep` tools (format: "line:hash", e.g. "11:a3"). ' +
36+ 'Anchors come from the `read` tool (format: "line:hash", e.g. "11:a3"). ' +
3937 "To replace or delete lines use `replace`. To create a file use `create`.",
4038 schema: InsertSchema,
4139 execute: async (input) => {
src/tools/read.ts+1−1
@@ -53,7 +53,7 @@ export const readTool: ToolDef<ReadInput, ReadOutput> = {
5353 const size = file.size;
5454 if (size > MAX_BYTES * 5) {
5555 throw new Error(
56- `File too large (${Math.round(size / 1024)}KB). Use grep to search within it.`,
56+ `File too large (${Math.round(size / 1024)}KB). Use shell to search within it.`,
5757 );
5858 }
5959
src/tools/replace.ts+2−2
@@ -8,7 +8,7 @@ const ReplaceSchema = z.object({
88 path: z.string().describe("File path to edit (absolute or relative to cwd)"),
99 startAnchor: z
1010 .string()
11- .describe('Start anchor from a prior read/grep, e.g. "11:a3"'),
11+ .describe('Start anchor from a prior read, e.g. "11:a3"'),
1212 endAnchor: z
1313 .string()
1414 .optional()
@@ -43,7 +43,7 @@ export const replaceTool: ToolDef<ReplaceInput, ReplaceToolOutput> = {
4343 name: "replace",
4444 description:
4545 "Replace or delete a range of lines in an existing file using hashline anchors. " +
46- 'Anchors come from the `read` or `grep` tools (format: "line:hash", e.g. "11:a3"). ' +
46+ 'Anchors come from the `read` tool (format: "line:hash", e.g. "11:a3"). ' +
4747 "Provide startAnchor alone to target a single line, or add endAnchor for a range. " +
4848 "Set newContent to the replacement text, or omit it to delete the range. " +
4949 "To create a file use `create`. To insert without replacing any lines use `insert`.",
src/tools/scan-path.ts+0−45
@@ -1,45 +0,0 @@
1-import { relative, resolve, sep } from "node:path";
2-
3-interface ScanPathInfo {
4- absolute: string;
5- relativePath: string;
6- ignoreTargets: readonly string[];
7- inCwd: boolean;
8-}
9-
10-const LEADING_PARENT_SEGMENTS = /^(?:\.\.\/)+/;
11-
12-export function getScannedPathInfo(
13- cwd: string,
14- scanPath: string,
15-): ScanPathInfo {
16- const cwdAbsolute = resolve(cwd);
17- const absolute = resolve(cwdAbsolute, scanPath);
18- const relativePath = relative(cwdAbsolute, absolute).replaceAll("\\", "/");
19- const inCwd =
20- absolute === cwdAbsolute ||
21- absolute.startsWith(cwdAbsolute === sep ? sep : `${cwdAbsolute}${sep}`);
22- const ignoreTargets = getIgnoreTargets(relativePath, inCwd);
23-
24- return {
25- absolute,
26- relativePath,
27- ignoreTargets,
28- inCwd,
29- };
30-}
31-
32-function getIgnoreTargets(path: string, inCwd: boolean): string[] {
33- if (inCwd) return [path];
34-
35- const normalized = path.replace(LEADING_PARENT_SEGMENTS, "");
36- const segments = normalized.split("/").filter(Boolean);
37- if (segments.length === 0) return [normalized];
38-
39- const targets = new Set<string>([normalized]);
40- for (let i = 1; i < segments.length; i++) {
41- targets.add(segments.slice(i).join("/"));
42- }
43-
44- return [...targets];
45-}