-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.js
More file actions
481 lines (433 loc) · 16.4 KB
/
Copy pathtools.js
File metadata and controls
481 lines (433 loc) · 16.4 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
474
475
476
477
478
479
480
481
/**
* MERV Tool System
*
* Real, functional tools that MERV can invoke during conversations.
* Each tool has a name, description, parameter schema, and execute function.
*/
import { execSync, spawn } from "child_process";
import { readFileSync, writeFileSync, existsSync, readdirSync, statSync, mkdirSync, unlinkSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
import { request as httpRequest } from "http";
import { request as httpsRequest } from "https";
const __dirname = dirname(fileURLToPath(import.meta.url));
const MEMORY_PATH = join(__dirname, "memory.json");
const SCRATCH_DIR = join(__dirname, "scratch");
// Ensure scratch dir exists
if (!existsSync(SCRATCH_DIR)) mkdirSync(SCRATCH_DIR, { recursive: true });
// ─────────────────────────────────────────────
// TOOL DEFINITIONS
// ─────────────────────────────────────────────
export const TOOLS = [
{
name: "web_search",
description: "Search the web for current information. Use when the user asks about current events, facts you're unsure about, or anything requiring up-to-date data.",
parameters: { query: "The search query string" },
},
{
name: "fetch_url",
description: "Fetch and read the content of a web page. Use when the user provides a URL or you need to read a specific webpage.",
parameters: { url: "The URL to fetch" },
},
{
name: "run_code",
description: "Execute JavaScript or Python code and return the output. Use for calculations, data processing, or when the user asks you to run code.",
parameters: { language: "js or python", code: "The code to execute" },
},
{
name: "read_file",
description: "Read a file from the local filesystem. Use when the user asks about a file's contents.",
parameters: { path: "Absolute path to the file" },
},
{
name: "write_file",
description: "Write content to a file on the local filesystem. Use when asked to create or save files.",
parameters: { path: "Absolute path to the file", content: "The content to write" },
},
{
name: "list_directory",
description: "List files and directories at a given path.",
parameters: { path: "Absolute path to the directory" },
},
{
name: "run_command",
description: "Run a shell command and return output. Use for system tasks, git, npm, etc.",
parameters: { command: "The shell command to execute" },
},
{
name: "memory_save",
description: "Save a fact or piece of information to persistent memory. Use when the user says to remember something or when you learn important context.",
parameters: { key: "A short label for this memory", value: "The information to remember" },
},
{
name: "memory_recall",
description: "Search persistent memory for previously saved information. Use when the user references something discussed before or asks 'do you remember'.",
parameters: { query: "What to search for in memory" },
},
{
name: "memory_list",
description: "List all saved memories.",
parameters: {},
},
{
name: "get_datetime",
description: "Get the current date, time, and timezone.",
parameters: {},
},
{
name: "calculator",
description: "Evaluate a mathematical expression. Use for any math calculations.",
parameters: { expression: "The math expression to evaluate (e.g. '2 * 3.14 * 5')" },
},
];
// ─────────────────────────────────────────────
// TOOL EXECUTOR
// ─────────────────────────────────────────────
export async function executeTool(name, params) {
const start = Date.now();
let result;
try {
switch (name) {
case "web_search":
result = await webSearch(params.query);
break;
case "fetch_url":
result = await fetchUrl(params.url);
break;
case "run_code":
result = await runCode(params.language, params.code);
break;
case "read_file":
result = readFile(params.path);
break;
case "write_file":
result = writeFile(params.path, params.content);
break;
case "list_directory":
result = listDirectory(params.path);
break;
case "run_command":
result = runCommand(params.command);
break;
case "memory_save":
result = memorySave(params.key, params.value);
break;
case "memory_recall":
result = memoryRecall(params.query);
break;
case "memory_list":
result = memoryList();
break;
case "get_datetime":
result = getDatetime();
break;
case "calculator":
result = calculator(params.expression);
break;
default:
result = { error: `Unknown tool: ${name}` };
}
} catch (err) {
result = { error: err.message };
}
return { tool: name, result, duration_ms: Date.now() - start };
}
// ─────────────────────────────────────────────
// TOOL IMPLEMENTATIONS
// ─────────────────────────────────────────────
async function webSearch(query) {
if (!query) return { error: "No query provided" };
// Use DuckDuckGo HTML search (no API key needed)
const encoded = encodeURIComponent(query);
const url = `https://html.duckduckgo.com/html/?q=${encoded}`;
try {
const html = await httpsFetch(url, {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
Accept: "text/html",
});
// Parse results from DDG HTML
const results = [];
const resultRegex = /<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi;
const snippetRegex = /<a[^>]*class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi;
let match;
while ((match = resultRegex.exec(html)) !== null && results.length < 8) {
const title = match[2].replace(/<[^>]*>/g, "").trim();
let link = match[1];
// DDG wraps links in a redirect
const uddg = link.match(/uddg=([^&]*)/);
if (uddg) link = decodeURIComponent(uddg[1]);
results.push({ title, url: link, snippet: "" });
}
let i = 0;
while ((match = snippetRegex.exec(html)) !== null && i < results.length) {
results[i].snippet = match[1].replace(/<[^>]*>/g, "").trim();
i++;
}
if (results.length === 0) {
// Fallback: try to extract any useful text
const textContent = html.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
return { query, results: [], raw_excerpt: textContent.slice(0, 2000) };
}
return { query, results };
} catch (err) {
return { error: `Search failed: ${err.message}`, query };
}
}
function httpsFetch(url, headers = {}) {
return new Promise((resolve, reject) => {
const parsedUrl = new URL(url);
const options = {
hostname: parsedUrl.hostname,
port: parsedUrl.port || 443,
path: parsedUrl.pathname + parsedUrl.search,
method: "GET",
headers: {
"User-Agent": "MERV/1.0",
...headers,
},
};
const reqFn = parsedUrl.protocol === "https:" ? httpsRequest : httpRequest;
const req = reqFn(options, (res) => {
// Follow redirects
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
httpsFetch(res.headers.location, headers).then(resolve).catch(reject);
return;
}
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("end", () => resolve(data));
});
req.on("error", reject);
req.setTimeout(15000, () => { req.destroy(); reject(new Error("Request timeout")); });
req.end();
});
}
async function fetchUrl(url) {
if (!url) return { error: "No URL provided" };
try {
const html = await httpsFetch(url);
// Strip HTML tags, keep text
const text = html
.replace(/<script[\s\S]*?<\/script>/gi, "")
.replace(/<style[\s\S]*?<\/style>/gi, "")
.replace(/<[^>]*>/g, " ")
.replace(/\s+/g, " ")
.trim();
return { url, content: text.slice(0, 8000), length: text.length };
} catch (err) {
return { error: `Fetch failed: ${err.message}`, url };
}
}
async function runCode(language, code) {
if (!code) return { error: "No code provided" };
const lang = (language || "js").toLowerCase();
const timeout = 10000; // 10s max
try {
if (lang === "js" || lang === "javascript" || lang === "node") {
const filePath = join(SCRATCH_DIR, `run_${Date.now()}.js`);
writeFileSync(filePath, code);
try {
const output = execSync(`node "${filePath}"`, {
timeout,
maxBuffer: 1024 * 1024,
cwd: SCRATCH_DIR,
encoding: "utf-8",
});
return { language: "javascript", output: output.trim(), exitCode: 0 };
} finally {
try { unlinkSync(filePath); } catch {}
}
} else if (lang === "python" || lang === "py") {
const filePath = join(SCRATCH_DIR, `run_${Date.now()}.py`);
writeFileSync(filePath, code);
try {
const output = execSync(`python3 "${filePath}"`, {
timeout,
maxBuffer: 1024 * 1024,
cwd: SCRATCH_DIR,
encoding: "utf-8",
});
return { language: "python", output: output.trim(), exitCode: 0 };
} finally {
try { unlinkSync(filePath); } catch {}
}
} else {
return { error: `Unsupported language: ${lang}. Use 'js' or 'python'.` };
}
} catch (err) {
return {
language: lang,
error: err.stderr?.toString()?.trim() || err.message,
exitCode: err.status || 1,
output: err.stdout?.toString()?.trim() || "",
};
}
}
function readFile(path) {
if (!path) return { error: "No path provided" };
try {
if (!existsSync(path)) return { error: `File not found: ${path}` };
const stat = statSync(path);
if (stat.isDirectory()) return { error: `Path is a directory, use list_directory instead: ${path}` };
if (stat.size > 1024 * 1024) return { error: `File too large (${(stat.size / 1024 / 1024).toFixed(1)} MB). Max 1MB.` };
const content = readFileSync(path, "utf-8");
return { path, content, size: stat.size, lines: content.split("\n").length };
} catch (err) {
return { error: err.message };
}
}
function writeFile(path, content) {
if (!path || content === undefined) return { error: "Missing path or content" };
try {
const dir = dirname(path);
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
writeFileSync(path, content, "utf-8");
return { path, written: true, bytes: Buffer.byteLength(content) };
} catch (err) {
return { error: err.message };
}
}
function listDirectory(path) {
if (!path) return { error: "No path provided" };
try {
if (!existsSync(path)) return { error: `Directory not found: ${path}` };
const entries = readdirSync(path).map((name) => {
try {
const s = statSync(join(path, name));
return { name, type: s.isDirectory() ? "dir" : "file", size: s.size };
} catch {
return { name, type: "unknown" };
}
});
return { path, entries: entries.slice(0, 100), total: entries.length };
} catch (err) {
return { error: err.message };
}
}
function runCommand(command) {
if (!command) return { error: "No command provided" };
// Block dangerous commands
const blocked = ["rm -rf /", "mkfs", "dd if=", "> /dev/sd", ":(){ :|:& };:"];
for (const b of blocked) {
if (command.includes(b)) return { error: "Blocked: potentially destructive command." };
}
try {
const output = execSync(command, {
timeout: 15000,
maxBuffer: 1024 * 1024,
encoding: "utf-8",
shell: "/bin/zsh",
});
return { command, output: output.trim(), exitCode: 0 };
} catch (err) {
return {
command,
error: err.stderr?.toString()?.trim() || err.message,
output: err.stdout?.toString()?.trim() || "",
exitCode: err.status || 1,
};
}
}
// ─── Memory ───
function loadMemory() {
try {
if (existsSync(MEMORY_PATH)) return JSON.parse(readFileSync(MEMORY_PATH, "utf-8"));
} catch {}
return {};
}
function saveMemory(mem) {
writeFileSync(MEMORY_PATH, JSON.stringify(mem, null, 2));
}
function memorySave(key, value) {
if (!key || !value) return { error: "Missing key or value" };
const mem = loadMemory();
mem[key] = { value, saved: new Date().toISOString() };
saveMemory(mem);
return { saved: true, key, totalMemories: Object.keys(mem).length };
}
function memoryRecall(query) {
if (!query) return { error: "No query provided" };
const mem = loadMemory();
const q = query.toLowerCase();
const matches = Object.entries(mem)
.filter(([k, v]) => k.toLowerCase().includes(q) || v.value.toLowerCase().includes(q))
.map(([k, v]) => ({ key: k, value: v.value, saved: v.saved }));
return { query, matches, totalMemories: Object.keys(mem).length };
}
function memoryList() {
const mem = loadMemory();
return {
memories: Object.entries(mem).map(([k, v]) => ({ key: k, value: v.value, saved: v.saved })),
total: Object.keys(mem).length,
};
}
function getDatetime() {
const now = new Date();
return {
iso: now.toISOString(),
local: now.toLocaleString(),
date: now.toLocaleDateString(),
time: now.toLocaleTimeString(),
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
unix: Math.floor(now.getTime() / 1000),
};
}
function calculator(expression) {
if (!expression) return { error: "No expression provided" };
// Safe math eval — only allow numbers, operators, parens, math functions
const safe = expression.replace(/[^0-9+\-*/().,%^ sincotalogqrtbexpMPI\s]/g, "");
try {
// Replace common math functions
const prepared = safe
.replace(/\bsqrt\b/g, "Math.sqrt")
.replace(/\bsin\b/g, "Math.sin")
.replace(/\bcos\b/g, "Math.cos")
.replace(/\btan\b/g, "Math.tan")
.replace(/\blog\b/g, "Math.log10")
.replace(/\bln\b/g, "Math.log")
.replace(/\babs\b/g, "Math.abs")
.replace(/\bexp\b/g, "Math.exp")
.replace(/\bPI\b/g, "Math.PI")
.replace(/\^/g, "**");
// eslint-disable-next-line no-eval
const result = Function(`"use strict"; return (${prepared})`)();
return { expression, result, type: typeof result };
} catch (err) {
return { expression, error: err.message };
}
}
// ─────────────────────────────────────────────
// TOOL PROMPT BUILDER
// ─────────────────────────────────────────────
export function buildToolPrompt() {
return `You have access to the following tools. To use a tool, output a JSON block with this exact format on its own line:
[TOOL_CALL]
{"tool": "tool_name", "params": {"param1": "value1"}}
[/TOOL_CALL]
You may call multiple tools by using multiple [TOOL_CALL] blocks. After the tool results are returned, synthesize them into your final response.
IMPORTANT: Only use tools when genuinely needed. For general conversation, knowledge questions you can answer, or creative tasks, respond directly without tools.
Available tools:
${TOOLS.map((t) => `- **${t.name}**: ${t.description}\n Parameters: ${JSON.stringify(t.parameters)}`).join("\n\n")}
When you use a tool, you will receive the results in a [TOOL_RESULT] block and should incorporate them into your response.`;
}
// ─────────────────────────────────────────────
// PARSE TOOL CALLS FROM MODEL OUTPUT
// ─────────────────────────────────────────────
export function parseToolCalls(text) {
const calls = [];
const regex = /\[TOOL_CALL\]\s*\n?([\s\S]*?)\n?\[\/TOOL_CALL\]/g;
let match;
while ((match = regex.exec(text)) !== null) {
try {
const parsed = JSON.parse(match[1].trim());
if (parsed.tool) calls.push(parsed);
} catch {}
}
return calls;
}
/**
* Get the text content that isn't part of a tool call
*/
export function getTextWithoutToolCalls(text) {
return text.replace(/\[TOOL_CALL\][\s\S]*?\[\/TOOL_CALL\]/g, "").trim();
}