xonecas.io
64875
Mc

mini-coder / commit 1e6dd05

feat: tool hooks via .agents/hooks/post-<toolname>

- Add src/tools/hooks.ts: createHookCache (session-scoped, O(1) lookup),
  runHook, and per-tool env builders
- Add src/agent/tools.ts: withHooks wrapper fires post-hook after each
  tool execute; cache built once at buildToolSet time
- Hooks discovered in <cwd>/.agents/hooks/ then ~/.agents/hooks/
- Shell hook env includes TIMED_OUT to distinguish timeouts from kills
- Add .agents/hooks/post-{create,replace,insert}: run biome lint --write
- 39 tests passing

xonecas2026-02-20 1e6dd0526a13e07e3d0e311f0edfb062eace0675 parent ca4c08d

7 files changed

.agents/hooks/post-create+2−0
@@ -0,0 +1,2 @@
1+#!/bin/bash
2+bun run lint --write "$FILEPATH" 2>/dev/null || true
.agents/hooks/post-insert+2−0
@@ -0,0 +1,2 @@
1+#!/bin/bash
2+bun run lint --write "$FILEPATH" 2>/dev/null || true
.agents/hooks/post-replace+2−0
@@ -0,0 +1,2 @@
1+#!/bin/bash
2+bun run lint --write "$FILEPATH" 2>/dev/null || true
AGENTS.md+1−0
@@ -6,3 +6,4 @@
66 - Write minimal tests, focused on our code's logic. Never test dependencies. Never use mock servers or stubs.
77 - Keep the repo pristine: no failing tests, no lint, no build issues, no `nolint:` comments.
88 - Use `bun run typecheck && bun run format && bun run lint && bun test` to check your changes.
9+- We care about performance.
src/agent/tools.ts+135−35
@@ -1,40 +1,35 @@
11 import type { ToolDef } from "../llm-api/types.ts";
2+import type { CreateOutput } from "../tools/create.ts";
23 import { createTool } from "../tools/create.ts";
4+import type { GlobOutput } from "../tools/glob.ts";
35 import { globTool } from "../tools/glob.ts";
6+import type { GrepOutput } from "../tools/grep.ts";
47 import { grepTool } from "../tools/grep.ts";
8+import {
9+ createHookCache,
10+ hookEnvForCreate,
11+ hookEnvForGlob,
12+ hookEnvForGrep,
13+ hookEnvForInsert,
14+ hookEnvForRead,
15+ hookEnvForReplace,
16+ hookEnvForShell,
17+ runHook,
18+} from "../tools/hooks.ts";
19+import type { InsertOutput } from "../tools/insert.ts";
520 import { insertTool } from "../tools/insert.ts";
21+import type { ReadOutput } from "../tools/read.ts";
622 import { readTool } from "../tools/read.ts";
23+import type { ReplaceOutput } from "../tools/replace.ts";
724 import { replaceTool } from "../tools/replace.ts";
25+import type { ShellOutput } from "../tools/shell.ts";
826 import { shellTool } from "../tools/shell.ts";
927 import { createSubagentTool } from "../tools/subagent.ts";
1028
11-// ─── Hook types ────────────────────────────────────────────────────────────────
12-
13-export type ToolHook = (toolName: string, result: unknown) => Promise<void>;
14-
15-const _hooks: ToolHook[] = [];
16-
17-export function addToolHook(hook: ToolHook): void {
18- _hooks.push(hook);
19-}
20-
21-export async function runToolHooks(
22- toolName: string,
23- result: unknown,
24-): Promise<void> {
25- for (const hook of _hooks) {
26- try {
27- await hook(toolName, result);
28- } catch {
29- // Hooks must not crash the agent
30- }
31- }
32-}
33-
34-// ─── Tool registry ────────────────────────────────────────────────────────────
29+// ─── Tool wrappers ────────────────────────────────────────────────────────────
3530
3631 /**
37- * Wrap a tool's execute function to inject a default cwd if not provided.
32+ * Inject a default cwd if not provided by the LLM.
3833 */
3934 function withCwdDefault(tool: ToolDef, cwd: string): ToolDef {
4035 const originalExecute = tool.execute;
@@ -50,8 +45,52 @@ function withCwdDefault(tool: ToolDef, cwd: string): ToolDef {
5045 };
5146 }
5247
48+type EnvBuilder<TInput, TOutput> = (
49+ result: TOutput,
50+ input: TInput,
51+) => Record<string, string>;
52+
53+/**
54+ * Wrap a tool to fire its post-hook (if one exists) after each successful execute.
55+ * Hooks are looked up via the session-scoped cache — no filesystem access per call.
56+ * Hooks are fire-and-forget; errors are always swallowed.
57+ */
58+function withHooks<TInput extends { cwd?: string }, TOutput>(
59+ tool: ToolDef<TInput, TOutput>,
60+ lookupHook: (toolName: string) => string | null,
61+ cwd: string,
62+ buildEnv: EnvBuilder<TInput, TOutput>,
63+): ToolDef<TInput, TOutput> {
64+ const originalExecute = tool.execute;
65+ return {
66+ ...tool,
67+ execute: async (input: TInput) => {
68+ const result = await originalExecute(input);
69+ const hookScript = lookupHook(tool.name);
70+ if (hookScript) {
71+ const env = buildEnv(result, input);
72+ await runHook(hookScript, env, cwd);
73+ }
74+ return result;
75+ },
76+ };
77+}
78+
79+// ─── Tool registry ────────────────────────────────────────────────────────────
80+
5381 export const MAX_SUBAGENT_DEPTH = 3;
5482
83+// Names of all local tools that support hooks (MCP tools are excluded).
84+const HOOKABLE_TOOLS = [
85+ "glob",
86+ "grep",
87+ "read",
88+ "create",
89+ "replace",
90+ "insert",
91+ "shell",
92+];
93+
5594 export function buildToolSet(opts: {
5695 cwd: string;
5796 depth?: number;
@@ -64,18 +103,77 @@ export function buildToolSet(opts: {
64103 outputTokens: number;
65104 }>;
66105 }): ToolDef[] {
106+ const { cwd } = opts;
67107 const depth = opts.depth ?? 0;
108+ const lookupHook = createHookCache(HOOKABLE_TOOLS, cwd);
109+
68110 return [
69111 // Read-only: discover and inspect files
70- withCwdDefault(globTool as ToolDef, opts.cwd),
71- withCwdDefault(grepTool as ToolDef, opts.cwd),
72- withCwdDefault(readTool as ToolDef, opts.cwd),
112+ withHooks(
113+ withCwdDefault(globTool as ToolDef, cwd) as ToolDef<
114+ { cwd?: string; pattern: string },
115+ GlobOutput
116+ >,
117+ lookupHook,
118+ cwd,
119+ (_, input) => hookEnvForGlob(input, cwd),
120+ ) as ToolDef,
121+ withHooks(
122+ withCwdDefault(grepTool as ToolDef, cwd) as ToolDef<
123+ { cwd?: string; pattern: string },
124+ GrepOutput
125+ >,
126+ lookupHook,
127+ cwd,
128+ (_, input) => hookEnvForGrep(input, cwd),
129+ ) as ToolDef,
130+ withHooks(
131+ withCwdDefault(readTool as ToolDef, cwd) as ToolDef<
132+ { cwd?: string; path: string },
133+ ReadOutput
134+ >,
135+ lookupHook,
136+ cwd,
137+ (_, input) => hookEnvForRead(input, cwd),
138+ ) as ToolDef,
73139 // Write: create/overwrite, replace/delete, insert
74- withCwdDefault(createTool as ToolDef, opts.cwd),
75- withCwdDefault(replaceTool as ToolDef, opts.cwd),
76- withCwdDefault(insertTool as ToolDef, opts.cwd),
140+ withHooks(
141+ withCwdDefault(createTool as ToolDef, cwd) as ToolDef<
142+ { cwd?: string },
143+ CreateOutput
144+ >,
145+ lookupHook,
146+ cwd,
147+ (result) => hookEnvForCreate(result, cwd),
148+ ) as ToolDef,
149+ withHooks(
150+ withCwdDefault(replaceTool as ToolDef, cwd) as ToolDef<
151+ { cwd?: string },
152+ ReplaceOutput
153+ >,
154+ lookupHook,
155+ cwd,
156+ (result) => hookEnvForReplace(result, cwd),
157+ ) as ToolDef,
158+ withHooks(
159+ withCwdDefault(insertTool as ToolDef, cwd) as ToolDef<
160+ { cwd?: string },
161+ InsertOutput
162+ >,
163+ lookupHook,
164+ cwd,
165+ (result) => hookEnvForInsert(result, cwd),
166+ ) as ToolDef,
77167 // Shell and subagent
78- withCwdDefault(shellTool as ToolDef, opts.cwd),
168+ withHooks(
169+ withCwdDefault(shellTool as ToolDef, cwd) as ToolDef<
170+ { cwd?: string; command: string },
171+ ShellOutput
172+ >,
173+ lookupHook,
174+ cwd,
175+ (result, input) => hookEnvForShell(result, input, cwd),
176+ ) as ToolDef,
79177 createSubagentTool(async (prompt) => {
80178 if (depth >= MAX_SUBAGENT_DEPTH) {
81179 throw new Error(
@@ -88,10 +186,12 @@ export function buildToolSet(opts: {
88186 ];
89187 }
90188
189+// Plan mode: read-only tools only, no hooks (hooks are a write-tool concern).
91190 export function buildReadOnlyToolSet(opts: { cwd: string }): ToolDef[] {
191+ const { cwd } = opts;
92192 return [
93- withCwdDefault(globTool as ToolDef, opts.cwd),
94- withCwdDefault(grepTool as ToolDef, opts.cwd),
95- withCwdDefault(readTool as ToolDef, opts.cwd),
193+ withCwdDefault(globTool as ToolDef, cwd),
194+ withCwdDefault(grepTool as ToolDef, cwd),
195+ withCwdDefault(readTool as ToolDef, cwd),
96196 ];
97197 }
src/tools/hooks.test.ts+110−0
@@ -0,0 +1,110 @@
1+import { afterEach, beforeEach, describe, expect, it } from "bun:test";
2+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { createHookCache, runHook } from "./hooks.ts";
6+
7+// ─── Helpers ──────────────────────────────────────────────────────────────────
8+
9+let tmpDir: string;
10+
11+beforeEach(() => {
12+ tmpDir = mkdtempSync(join(tmpdir(), "hooks-test-"));
13+});
14+
15+afterEach(() => {
16+ rmSync(tmpDir, { recursive: true, force: true });
17+});
18+
19+function makeHook(dir: string, name: string, content: string): string {
20+ const hooksDir = join(dir, ".agents", "hooks");
21+ mkdirSync(hooksDir, { recursive: true });
22+ const scriptPath = join(hooksDir, name);
23+ writeFileSync(scriptPath, content, { mode: 0o755 });
24+ return scriptPath;
25+}
26+
27+// ─── createHookCache ──────────────────────────────────────────────────────────
28+
29+describe("createHookCache", () => {
30+ it("returns null when no hook exists", () => {
31+ const lookup = createHookCache(["create"], tmpDir);
32+ expect(lookup("create")).toBeNull();
33+ });
34+
35+ it("returns the script path when an executable hook exists", () => {
36+ const scriptPath = makeHook(tmpDir, "post-create", "#!/bin/bash\necho hi");
37+ const lookup = createHookCache(["create"], tmpDir);
38+ expect(lookup("create")).toBe(scriptPath);
39+ });
40+
41+ it("returns null when the hook file exists but is not executable", () => {
42+ const hooksDir = join(tmpDir, ".agents", "hooks");
43+ mkdirSync(hooksDir, { recursive: true });
44+ writeFileSync(join(hooksDir, "post-replace"), "#!/bin/bash\necho hi", {
45+ mode: 0o644,
46+ });
47+ const lookup = createHookCache(["replace"], tmpDir);
48+ expect(lookup("replace")).toBeNull();
49+ });
50+
51+ it("returns null for an unknown tool name not in the cache", () => {
52+ makeHook(tmpDir, "post-shell", "#!/bin/bash\necho hi");
53+ const lookup = createHookCache(["shell"], tmpDir);
54+ expect(lookup("create")).toBeNull();
55+ });
56+
57+ it("resolves hooks only once — adding a script after cache creation is not visible", () => {
58+ const lookup = createHookCache(["create"], tmpDir);
59+ // Cache is already built: hook did not exist at construction time
60+ makeHook(tmpDir, "post-create", "#!/bin/bash\necho hi");
61+ expect(lookup("create")).toBeNull();
62+ });
63+});
64+
65+// ─── runHook ──────────────────────────────────────────────────────────────────
66+
67+describe("runHook", () => {
68+ it("completes without throwing when the script exits zero", async () => {
69+ const script = makeHook(tmpDir, "post-create", "#!/bin/bash\nexit 0");
70+ await expect(
71+ runHook(script, { TOOL: "create" }, tmpDir),
72+ ).resolves.toBeUndefined();
73+ });
74+
75+ it("completes without throwing when the script exits non-zero", async () => {
76+ const script = makeHook(tmpDir, "post-replace", "#!/bin/bash\nexit 1");
77+ await expect(
78+ runHook(script, { TOOL: "replace" }, tmpDir),
79+ ).resolves.toBeUndefined();
80+ });
81+
82+ it("completes without throwing when the script path does not exist", async () => {
83+ const missing = join(tmpDir, ".agents", "hooks", "post-missing");
84+ await expect(runHook(missing, {}, tmpDir)).resolves.toBeUndefined();
85+ });
86+
87+ it("passes env vars to the hook script", async () => {
88+ const outFile = join(tmpDir, "out.txt");
89+ const script = makeHook(
90+ tmpDir,
91+ "post-insert",
92+ `#!/bin/bash\necho "$FILEPATH" > "${outFile}"`,
93+ );
94+ await runHook(script, { FILEPATH: "src/foo.ts" }, tmpDir);
95+ const written = await Bun.file(outFile).text();
96+ expect(written.trim()).toBe("src/foo.ts");
97+ });
98+
99+ it("exposes TIMED_OUT env var to the hook script", async () => {
100+ const outFile = join(tmpDir, "out.txt");
101+ const script = makeHook(
102+ tmpDir,
103+ "post-shell",
104+ `#!/bin/bash\necho "$TIMED_OUT" > "${outFile}"`,
105+ );
106+ await runHook(script, { TIMED_OUT: "true" }, tmpDir);
107+ const written = await Bun.file(outFile).text();
108+ expect(written.trim()).toBe("true");
109+ });
110+});
src/tools/hooks.ts+160−0
@@ -0,0 +1,160 @@
1+import { constants, accessSync } from "node:fs";
2+import { homedir } from "node:os";
3+import { join } from "node:path";
4+
5+// ─── Hook discovery ───────────────────────────────────────────────────────────
6+
7+function isExecutable(filePath: string): boolean {
8+ try {
9+ accessSync(filePath, constants.X_OK);
10+ return true;
11+ } catch {
12+ return false;
13+ }
14+}
15+
16+function findHook(toolName: string, cwd: string): string | null {
17+ const scriptName = `post-${toolName}`;
18+ const candidates = [
19+ join(cwd, ".agents", "hooks", scriptName),
20+ join(homedir(), ".agents", "hooks", scriptName),
21+ ];
22+ for (const p of candidates) {
23+ if (isExecutable(p)) return p;
24+ }
25+ return null;
26+}
27+
28+/**
29+ * Resolve all hook scripts for the given tool names once at session start.
30+ * Returns a lookup function that is O(1) per call with no further filesystem access.
31+ */
32+export function createHookCache(
33+ toolNames: string[],
34+ cwd: string,
35+): (toolName: string) => string | null {
36+ const cache = new Map<string, string | null>();
37+ for (const name of toolNames) {
38+ cache.set(name, findHook(name, cwd));
39+ }
40+ return (toolName: string) => cache.get(toolName) ?? null;
41+}
42+
43+// ─── Hook execution ───────────────────────────────────────────────────────────
44+
45+/**
46+ * Run a hook script with the given env vars.
47+ * The script inherits the full process environment plus the provided vars.
48+ * All errors and output are silently swallowed — hooks must never crash the agent.
49+ */
50+export async function runHook(
51+ scriptPath: string,
52+ env: Record<string, string>,
53+ cwd: string,
54+): Promise<void> {
55+ try {
56+ const proc = Bun.spawn(["bash", scriptPath], {
57+ cwd,
58+ env: { ...process.env, ...env },
59+ stdout: "ignore",
60+ stderr: "ignore",
61+ });
62+ await proc.exited;
63+ } catch {
64+ // Hooks must not crash the agent
65+ }
66+}
67+
68+// ─── Env builders (one per tool) ─────────────────────────────────────────────
69+
70+export function hookEnvForCreate(
71+ result: { path: string; diff: string; created: boolean },
72+ cwd: string,
73+): Record<string, string> {
74+ return {
75+ TOOL: "create",
76+ FILEPATH: result.path,
77+ DIFF: result.diff,
78+ CREATED: String(result.created),
79+ CWD: cwd,
80+ };
81+}
82+
83+export function hookEnvForReplace(
84+ result: { path: string; diff: string; deleted: boolean },
85+ cwd: string,
86+): Record<string, string> {
87+ return {
88+ TOOL: "replace",
89+ FILEPATH: result.path,
90+ DIFF: result.diff,
91+ DELETED: String(result.deleted),
92+ CWD: cwd,
93+ };
94+}
95+
96+export function hookEnvForInsert(
97+ result: { path: string; diff: string },
98+ cwd: string,
99+): Record<string, string> {
100+ return {
101+ TOOL: "insert",
102+ FILEPATH: result.path,
103+ DIFF: result.diff,
104+ CWD: cwd,
105+ };
106+}
107+
108+export function hookEnvForShell(
109+ result: {
110+ stdout: string;
111+ stderr: string;
112+ exitCode: number;
113+ timedOut: boolean;
114+ },
115+ input: { command: string },
116+ cwd: string,
117+): Record<string, string> {
118+ return {
119+ TOOL: "shell",
120+ COMMAND: input.command,
121+ EXIT_CODE: String(result.exitCode),
122+ TIMED_OUT: String(result.timedOut),
123+ STDOUT: result.stdout,
124+ STDERR: result.stderr,
125+ CWD: cwd,
126+ };
127+}
128+
129+export function hookEnvForGlob(
130+ input: { pattern: string },
131+ cwd: string,
132+): Record<string, string> {
133+ return {
134+ TOOL: "glob",
135+ PATTERN: input.pattern,
136+ CWD: cwd,
137+ };
138+}
139+
140+export function hookEnvForGrep(
141+ input: { pattern: string },
142+ cwd: string,
143+): Record<string, string> {
144+ return {
145+ TOOL: "grep",
146+ PATTERN: input.pattern,
147+ CWD: cwd,
148+ };
149+}
150+
151+export function hookEnvForRead(
152+ input: { path: string },
153+ cwd: string,
154+): Record<string, string> {
155+ return {
156+ TOOL: "read",
157+ FILEPATH: input.path,
158+ CWD: cwd,
159+ };
160+}