-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathpre-tool-use.ts
More file actions
473 lines (436 loc) · 19.5 KB
/
Copy pathpre-tool-use.ts
File metadata and controls
473 lines (436 loc) · 19.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
#!/usr/bin/env node
import { existsSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
import { fileURLToPath } from "node:url";
import { dirname } from "node:path";
import { readStdin } from "../utils/stdin.js";
import { loadConfig } from "../config.js";
import { DeeplakeApi } from "../deeplake-api.js";
import { sqlStr, sqlLike } from "../utils/sql.js";
import { type GrepParams, parseBashGrep, handleGrepDirect } from "./grep-direct.js";
import { log as _log } from "../utils/debug.js";
const log = (msg: string) => _log("pre", msg);
const MEMORY_PATH = join(homedir(), ".deeplake", "memory");
const TILDE_PATH = "~/.deeplake/memory";
const HOME_VAR_PATH = "$HOME/.deeplake/memory";
const __bundleDir = dirname(fileURLToPath(import.meta.url));
const SHELL_BUNDLE = existsSync(join(__bundleDir, "shell", "deeplake-shell.js"))
? join(__bundleDir, "shell", "deeplake-shell.js")
: join(__bundleDir, "..", "shell", "deeplake-shell.js");
// All commands supported by just-bash + shell control flow
const SAFE_BUILTINS = new Set([
// filesystem
"cat", "ls", "cp", "mv", "rm", "rmdir", "mkdir", "touch", "ln", "chmod",
"stat", "readlink", "du", "tree", "file",
// text processing
"grep", "egrep", "fgrep", "rg", "sed", "awk", "cut", "tr", "sort", "uniq",
"wc", "head", "tail", "tac", "rev", "nl", "fold", "expand", "unexpand",
"paste", "join", "comm", "column", "diff", "strings", "split",
// search
"find", "xargs", "which",
// data formats
"jq", "yq", "xan", "base64", "od",
// archives
"tar", "gzip", "gunzip", "zcat",
// hashing
"md5sum", "sha1sum", "sha256sum",
// output/io
"echo", "printf", "tee", "cat",
// path/env
"pwd", "cd", "basename", "dirname", "env", "printenv", "hostname", "whoami",
// misc
"date", "seq", "expr", "sleep", "timeout", "time", "true", "false", "test",
"alias", "unalias", "history", "help", "clear",
// shell control flow
"for", "while", "do", "done", "if", "then", "else", "fi", "case", "esac",
]);
function isSafe(cmd: string): boolean {
// Reject command/process substitution before checking tokens
if (/\$\(|`|<\(/.test(cmd)) return false;
// Strip quoted strings before splitting on pipes — prevents splitting
// inside jq expressions like 'select(.type) | .content'
const stripped = cmd.replace(/'[^']*'/g, "''").replace(/"[^"]*"/g, '""');
const stages = stripped.split(/\||;|&&|\|\||\n/);
for (const stage of stages) {
const firstToken = stage.trim().split(/\s+/)[0] ?? "";
if (firstToken && !SAFE_BUILTINS.has(firstToken)) return false;
}
return true;
}
interface PreToolUseInput {
session_id: string;
tool_name: string;
tool_input: Record<string, unknown>;
tool_use_id: string;
}
function touchesMemory(p: string): boolean {
return p.includes(MEMORY_PATH) || p.includes(TILDE_PATH) || p.includes(HOME_VAR_PATH);
}
function rewritePaths(cmd: string): string {
return cmd
.replace(new RegExp(MEMORY_PATH.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "/?", "g"), "/")
.replace(/~\/.deeplake\/memory\/?/g, "/")
.replace(/\$HOME\/.deeplake\/memory\/?/g, "/")
.replace(/"\$HOME\/.deeplake\/memory\/?"/g, '"/"');
}
function getShellCommand(toolName: string, toolInput: Record<string, unknown>): string | null {
switch (toolName) {
case "Grep": {
const p = toolInput.path as string | undefined;
if (p && touchesMemory(p)) {
const pattern = toolInput.pattern as string ?? "";
const flags: string[] = ["-r"];
if (toolInput["-i"]) flags.push("-i");
if (toolInput["-n"]) flags.push("-n");
return `grep ${flags.join(" ")} '${pattern}' /`;
}
break;
}
case "Read": {
const fp = toolInput.file_path as string | undefined;
if (fp && touchesMemory(fp)) {
const virtualPath = rewritePaths(fp) || "/";
return `cat ${virtualPath}`;
}
break;
}
case "Bash": {
const cmd = toolInput.command as string | undefined;
if (!cmd || !touchesMemory(cmd)) break;
{
const rewritten = rewritePaths(cmd);
if (!isSafe(rewritten)) {
log(`unsafe command blocked: ${rewritten}`);
return null;
}
return rewritten;
}
break;
}
case "Glob": {
const p = toolInput.path as string | undefined;
if (p && touchesMemory(p)) {
return `ls /`;
}
break;
}
}
return null;
}
// ── Output helper ────────────────────────────────────────────────────────────
function emitResult(command: string, description: string): void {
console.log(JSON.stringify({
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "allow",
updatedInput: { command, description },
},
}));
}
// ── Grep parameter extraction (Claude Code specific) ─────────────────────────
/** Extract grep parameters from Grep tool input or Bash grep command. */
function extractGrepParams(
toolName: string,
toolInput: Record<string, unknown>,
shellCmd: string,
): GrepParams | null {
if (toolName === "Grep") {
const outputMode = (toolInput.output_mode as string) ?? "files_with_matches";
return {
pattern: (toolInput.pattern as string) ?? "",
targetPath: rewritePaths((toolInput.path as string) ?? "") || "/",
ignoreCase: !!toolInput["-i"],
wordMatch: false,
filesOnly: outputMode === "files_with_matches",
countOnly: outputMode === "count",
lineNumber: !!toolInput["-n"],
invertMatch: false,
fixedString: false,
};
}
if (toolName === "Bash") return parseBashGrep(shellCmd);
return null;
}
async function main(): Promise<void> {
const input = await readStdin<PreToolUseInput>();
log(`hook fired: tool=${input.tool_name} input=${JSON.stringify(input.tool_input)}`);
const cmd = (input.tool_input.command as string) ?? "";
const shellCmd = getShellCommand(input.tool_name, input.tool_input);
// Also check non-Bash tools (Read/Write/Edit/Glob/Grep) that touch memory but didn't get a shellCmd
const toolPath = (input.tool_input.file_path ?? input.tool_input.path ?? "") as string;
if (!shellCmd && (touchesMemory(cmd) || touchesMemory(toolPath))) {
// Instead of denying (which triggers alarm loops in Claude Code), return
// an "allow" with guidance that tells the agent to retry with bash.
// Uses stdout so the agent sees it as output (not a fatal error), but
// prefixed with [RETRY] to signal it should try again differently.
const guidance = "[RETRY REQUIRED] The command you tried is not available for ~/.deeplake/memory/. " +
"This virtual filesystem only supports bash builtins: cat, ls, grep, echo, jq, head, tail, sed, awk, wc, sort, find, etc. " +
"python, python3, node, and curl are NOT available. " +
"You MUST rewrite your command using only the bash tools listed above and try again. " +
"For example, to parse JSON use: cat file.json | jq '.key'. To count keys: cat file.json | jq 'keys | length'.";
// Only auto-convert when the user is clearly trying to READ a memory
// file with an unsupported interpreter (python, node, ruby, perl).
// curl/wget and anything with shell metacharacters fall through to the
// RETRY guidance below — converting them would hide actual intent.
const isReadLike = /^(?:python3?|node|deno|bun|ruby|perl)\b/.test(cmd.trim());
const hasShellMeta = /[$`;|&<>()\\]/.test(cmd);
if (isReadLike && !hasShellMeta) {
const pathMatch = cmd.match(/~\/\.deeplake\/memory\/[\w./_-]+/)
|| toolPath.match(/~\/\.deeplake\/memory\/[\w./_-]+/);
const memPath = pathMatch ? pathMatch[0] : "";
const cleanPath = memPath ? rewritePaths(memPath) : "";
if (cleanPath && !cleanPath.endsWith("/")) {
log(`unsupported command on file, converting to read: ${cleanPath}`);
console.log(JSON.stringify({
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "allow",
updatedInput: {
command: `cat '${cleanPath.replace(/'/g, "'\\''")}'`,
description: "[DeepLake] converted unsupported command to file read",
},
},
}));
return;
}
}
log(`unsupported command, returning guidance: ${cmd}`);
console.log(JSON.stringify({
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "allow",
updatedInput: {
command: `echo ${JSON.stringify(guidance)}`,
description: "[DeepLake] unsupported command — rewrite using bash builtins",
},
},
}));
return;
}
if (!shellCmd) return;
// ── Fast path: handle Read and Grep directly via SQL (no shell spawn) ──
const config = loadConfig();
if (config) {
const table = process.env["DEEPLAKE_TABLE"] ?? "memory";
const sessionsTable = process.env["DEEPLAKE_SESSIONS_TABLE"] ?? "sessions";
const api = new DeeplakeApi(config.token, config.apiUrl, config.orgId, config.workspaceId, table);
try {
// ── Grep (Grep tool or Bash grep) — single SQL query ──
const grepParams = extractGrepParams(input.tool_name, input.tool_input, shellCmd);
if (grepParams) {
log(`direct grep: pattern=${grepParams.pattern} path=${grepParams.targetPath}`);
const result = await handleGrepDirect(api, table, sessionsTable, grepParams);
if (result !== null) {
emitResult(`echo ${JSON.stringify(result)}`, `[DeepLake direct] grep ${grepParams.pattern}`);
return;
}
}
// ── Read file: Read tool, or Bash cat/head/tail ──
{
let virtualPath: string | null = null;
let lineLimit = 0; // 0 = all lines
let fromEnd = false; // true = tail
if (input.tool_name === "Read") {
virtualPath = rewritePaths((input.tool_input.file_path as string) ?? "");
} else if (input.tool_name === "Bash") {
// cat <file> [2>...] [| grep ... | head -N] or [| head -N]
// Strip stderr redirect (2>/dev/null, 2>&1, etc.) and optional grep -v pipe
const catCmd = shellCmd.replace(/\s+2>\S+/g, "").trim();
const catPipeHead = catCmd.match(/^cat\s+(\S+?)\s*(?:\|[^|]*)*\|\s*head\s+(?:-n?\s*)?(-?\d+)\s*$/);
if (catPipeHead) { virtualPath = catPipeHead[1]; lineLimit = Math.abs(parseInt(catPipeHead[2], 10)); }
// cat <file>
if (!virtualPath) {
const catMatch = catCmd.match(/^cat\s+(\S+)\s*$/);
if (catMatch) virtualPath = catMatch[1];
}
// head [-n] N <file>
if (!virtualPath) {
const headMatch = shellCmd.match(/^head\s+(?:-n\s*)?(-?\d+)\s+(\S+)\s*$/) ??
shellCmd.match(/^head\s+(\S+)\s*$/);
if (headMatch) {
if (headMatch[2]) { virtualPath = headMatch[2]; lineLimit = Math.abs(parseInt(headMatch[1], 10)); }
else { virtualPath = headMatch[1]; lineLimit = 10; }
}
}
// tail [-n] N <file>
if (!virtualPath) {
const tailMatch = shellCmd.match(/^tail\s+(?:-n\s*)?(-?\d+)\s+(\S+)\s*$/) ??
shellCmd.match(/^tail\s+(\S+)\s*$/);
if (tailMatch) {
fromEnd = true;
if (tailMatch[2]) { virtualPath = tailMatch[2]; lineLimit = Math.abs(parseInt(tailMatch[1], 10)); }
else { virtualPath = tailMatch[1]; lineLimit = 10; }
}
}
// wc -l <file>
if (!virtualPath) {
const wcMatch = shellCmd.match(/^wc\s+-l\s+(\S+)\s*$/);
if (wcMatch) { virtualPath = wcMatch[1]; lineLimit = -1; } // -1 = count mode
}
}
if (virtualPath && !virtualPath.endsWith("/")) {
log(`direct read: ${virtualPath}`);
let content: string | null = null;
if (virtualPath.startsWith("/sessions/")) {
// Session files live in the sessions table — skip memory
try {
const sessionRows = await api.query(
`SELECT message::text AS content FROM "${sessionsTable}" WHERE path = '${sqlStr(virtualPath)}' LIMIT 1`
);
if (sessionRows.length > 0 && sessionRows[0]["content"]) {
content = sessionRows[0]["content"] as string;
}
} catch { /* fall through to shell */ }
} else {
// Memory table (summaries, notes, etc.)
const rows = await api.query(
`SELECT summary FROM "${table}" WHERE path = '${sqlStr(virtualPath)}' LIMIT 1`
);
if (rows.length > 0 && rows[0]["summary"]) {
content = rows[0]["summary"] as string;
} else if (virtualPath === "/index.md") {
// Virtual index — generate from all entries in memory table
// Try companion memory table first (has descriptions), fall back to primary
const memTable = table.endsWith("_sessions")
? table.replace(/_sessions$/, "_memory") : table;
let idxRows: Record<string, unknown>[] = [];
try {
idxRows = await api.query(
`SELECT path, description, creation_date FROM "${memTable}" ORDER BY path LIMIT 500`
);
} catch { /* companion table may not exist */ }
if (idxRows.length === 0) {
idxRows = await api.query(
`SELECT path, description, creation_date FROM "${table}" ORDER BY path LIMIT 500`
);
}
const lines = ["# Memory Index", "", `${idxRows.length} entries:`, ""];
for (const r of idxRows) {
const p = r["path"] as string;
const desc = (r["description"] as string || "").slice(0, 100);
const date = (r["creation_date"] as string || "").slice(0, 10);
lines.push(`- [${p}](${p}) ${date} ${desc}`);
}
content = lines.join("\n");
}
}
if (content !== null) {
if (lineLimit === -1) {
const count = content.split("\n").length;
emitResult(`echo ${JSON.stringify(`${count} ${virtualPath}`)}`, `[DeepLake direct] wc -l ${virtualPath}`);
return;
}
if (lineLimit > 0) {
const lines = content.split("\n");
content = fromEnd ? lines.slice(-lineLimit).join("\n") : lines.slice(0, lineLimit).join("\n");
}
const label = lineLimit > 0 ? (fromEnd ? `tail -${lineLimit}` : `head -${lineLimit}`) : "cat";
emitResult(`echo ${JSON.stringify(content)}`, `[DeepLake direct] ${label} ${virtualPath}`);
return;
}
}
}
// ── ls: Bash ls or Glob tool ──
{
let lsDir: string | null = null;
let longFormat = false;
if (input.tool_name === "Glob") {
lsDir = rewritePaths((input.tool_input.path as string) ?? "") || "/";
} else if (input.tool_name === "Bash") {
const lsMatch = shellCmd.match(/^ls\s+(?:-([a-zA-Z]+)\s+)?(\S+)?\s*$/);
if (lsMatch) {
lsDir = lsMatch[2] ?? "/";
longFormat = (lsMatch[1] ?? "").includes("l");
}
}
if (lsDir) {
const dir = lsDir.replace(/\/+$/, "") || "/";
log(`direct ls: ${dir}`);
// Query the right table(s) based on path
const isSessionDir = dir === "/sessions" || dir.startsWith("/sessions/");
const isRoot = dir === "/";
const lsQueries: Promise<Record<string, unknown>[]>[] = [];
if (!isSessionDir) {
lsQueries.push(api.query(
`SELECT path, size_bytes FROM "${table}" WHERE path LIKE '${sqlLike(dir === "/" ? "" : dir)}/%' ORDER BY path`
).catch(() => []));
}
if (isSessionDir || isRoot) {
lsQueries.push(api.query(
`SELECT path, size_bytes FROM "${sessionsTable}" WHERE path LIKE '${sqlLike(dir === "/" ? "" : dir)}/%' ORDER BY path`
).catch(() => []));
}
const rows = (await Promise.all(lsQueries)).flat();
const entries = new Map<string, { isDir: boolean; size: number }>();
const prefix = dir === "/" ? "/" : dir + "/";
for (const row of rows) {
const p = row["path"] as string;
if (!p.startsWith(prefix) && dir !== "/") continue;
const rest = dir === "/" ? p.slice(1) : p.slice(prefix.length);
const slash = rest.indexOf("/");
const name = slash === -1 ? rest : rest.slice(0, slash);
if (!name) continue;
const existing = entries.get(name);
if (slash !== -1) {
if (!existing) entries.set(name, { isDir: true, size: 0 });
} else {
entries.set(name, { isDir: false, size: (row["size_bytes"] as number) ?? 0 });
}
}
const lines: string[] = [];
for (const [name, info] of [...entries].sort((a, b) => a[0].localeCompare(b[0]))) {
if (longFormat) {
const type = info.isDir ? "drwxr-xr-x" : "-rw-r--r--";
const size = String(info.isDir ? 0 : info.size).padStart(6);
lines.push(`${type} 1 user user ${size} ${name}${info.isDir ? "/" : ""}`);
} else {
lines.push(name + (info.isDir ? "/" : ""));
}
}
emitResult(`echo ${JSON.stringify(lines.join("\n") || "(empty directory)")}`, `[DeepLake direct] ls ${dir}`);
return;
}
}
// ── find <dir> -name '<pattern>' ──
if (input.tool_name === "Bash") {
const findMatch = shellCmd.match(/^find\s+(\S+)\s+(?:-type\s+\S+\s+)?-name\s+'([^']+)'/);
if (findMatch) {
const dir = findMatch[1].replace(/\/+$/, "") || "/";
const namePattern = sqlLike(findMatch[2]).replace(/\*/g, "%").replace(/\?/g, "_");
log(`direct find: ${dir} -name '${findMatch[2]}'`);
const isSessionDir = dir === "/sessions" || dir.startsWith("/sessions/");
const findTable = isSessionDir ? sessionsTable : table;
const rows = await api.query(
`SELECT path FROM "${findTable}" WHERE path LIKE '${sqlLike(dir === "/" ? "" : dir)}/%' AND filename LIKE '${namePattern}' ORDER BY path`
);
let result = rows.map(r => r["path"] as string).join("\n") || "";
// Handle piped wc -l
if (/\|\s*wc\s+-l\s*$/.test(shellCmd)) {
result = String(rows.length);
}
emitResult(`echo ${JSON.stringify(result || "(no matches)")}`, `[DeepLake direct] find ${dir}`);
return;
}
}
} catch (e: any) {
log(`direct query failed, falling back to shell: ${e.message}`);
}
}
// ── Slow path: rewrite to virtual shell (for Bash, Glob, or when direct fails) ──
log(`intercepted → rewriting to shell: ${shellCmd}`);
const rewrittenCommand = `node "${SHELL_BUNDLE}" -c "${shellCmd.replace(/"/g, '\\"')}"`;
const output: Record<string, unknown> = {
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "allow",
updatedInput: {
command: rewrittenCommand,
description: `[DeepLake] ${shellCmd}`,
},
},
};
log(`rewritten: ${rewrittenCommand}`);
console.log(JSON.stringify(output));
}
main().catch((e) => { log(`fatal: ${e.message}`); process.exit(0); });