@mumbrane/arrakis 0.0.0-stage → 0.2.0
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.
- package/README.md +74 -2
- package/bin/arrakis.js +7 -0
- package/index.js +8 -0
- package/package.json +37 -4
- package/src/agent.js +135 -0
- package/src/cli.js +247 -0
- package/src/client.js +90 -0
- package/src/config.js +60 -0
- package/src/permissions.js +17 -0
- package/src/prompt.js +81 -0
- package/src/session.js +141 -0
- package/src/tools.js +377 -0
- package/src/ui.js +173 -0
- package/src/version.js +3 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Modes: 'ask' prompts for each write/command; 'yolo' allows everything;
|
|
2
|
+
// 'deny' refuses anything that needs permission (non-interactive default).
|
|
3
|
+
export class Permissions {
|
|
4
|
+
constructor({ ui, mode = 'ask', allow = [] }) {
|
|
5
|
+
this.ui = ui;
|
|
6
|
+
this.mode = mode;
|
|
7
|
+
this.allowed = new Set(allow);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
async check(toolName, preview) {
|
|
11
|
+
if (this.mode === 'yolo' || this.allowed.has(toolName)) return true;
|
|
12
|
+
if (this.mode === 'deny') return false;
|
|
13
|
+
const answer = await this.ui.confirm(preview);
|
|
14
|
+
if (answer === 'always') this.allowed.add(toolName);
|
|
15
|
+
return answer !== 'no';
|
|
16
|
+
}
|
|
17
|
+
}
|
package/src/prompt.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { HOME_DIR } from './config.js';
|
|
5
|
+
|
|
6
|
+
const INSTRUCTION_FILES = ['ARRAKIS.md', 'AGENTS.md'];
|
|
7
|
+
|
|
8
|
+
function findUp(start, name) {
|
|
9
|
+
let dir = start;
|
|
10
|
+
while (true) {
|
|
11
|
+
if (fs.existsSync(path.join(dir, name))) return dir;
|
|
12
|
+
const parent = path.dirname(dir);
|
|
13
|
+
if (parent === dir) return null;
|
|
14
|
+
dir = parent;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Instruction files from the global config dir, then from the filesystem root
|
|
19
|
+
// down to the working directory (closer files come later and take precedence).
|
|
20
|
+
export function loadProjectInstructions(cwd) {
|
|
21
|
+
const found = [];
|
|
22
|
+
for (const name of INSTRUCTION_FILES) {
|
|
23
|
+
const global = path.join(HOME_DIR, name);
|
|
24
|
+
if (fs.existsSync(global)) found.push(global);
|
|
25
|
+
}
|
|
26
|
+
const chain = [];
|
|
27
|
+
let dir = cwd;
|
|
28
|
+
while (true) {
|
|
29
|
+
for (const name of INSTRUCTION_FILES) {
|
|
30
|
+
const f = path.join(dir, name);
|
|
31
|
+
if (fs.existsSync(f)) {
|
|
32
|
+
chain.unshift(f);
|
|
33
|
+
break; // one file per directory; ARRAKIS.md wins over AGENTS.md
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const parent = path.dirname(dir);
|
|
37
|
+
if (parent === dir || dir === os.homedir()) break;
|
|
38
|
+
dir = parent;
|
|
39
|
+
}
|
|
40
|
+
return [...found, ...chain].map((file) => {
|
|
41
|
+
let text = '';
|
|
42
|
+
try {
|
|
43
|
+
text = fs.readFileSync(file, 'utf8').slice(0, 40000);
|
|
44
|
+
} catch {}
|
|
45
|
+
return { file, text };
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function buildSystemPrompt({ cwd, model }) {
|
|
50
|
+
const git = findUp(cwd, '.git');
|
|
51
|
+
const instructions = loadProjectInstructions(cwd).filter((i) => i.text.trim());
|
|
52
|
+
let prompt = `You are Arrakis, a coding agent built by Mumbrane that runs in the user's terminal. You help with software engineering: reading and changing code, running commands, debugging, and explaining.
|
|
53
|
+
|
|
54
|
+
# Environment
|
|
55
|
+
- Working directory: ${cwd}
|
|
56
|
+
- Git repository: ${git ? `yes (root: ${git})` : 'no'}
|
|
57
|
+
- Platform: ${process.platform} (${os.release()})
|
|
58
|
+
- Date: ${new Date().toISOString().slice(0, 10)}
|
|
59
|
+
- Model: ${model}
|
|
60
|
+
|
|
61
|
+
# How to work
|
|
62
|
+
- Understand before changing: use list_files, grep and read_file to find and read the relevant code.
|
|
63
|
+
- Make focused changes with edit_file. Read a file before editing it and copy old_string exactly, including indentation.
|
|
64
|
+
- Use write_file only for new files or full rewrites.
|
|
65
|
+
- Verify your work when you can: run the tests, the build, or the program with bash.
|
|
66
|
+
- Each bash call starts fresh in the working directory; use "cd dir && cmd" when needed. Commands get no stdin, so avoid interactive programs, editors and watch modes.
|
|
67
|
+
- Do what was asked. Don't make unrelated changes, add files nobody asked for, or commit unless told to.
|
|
68
|
+
- If the user denies a tool call, don't retry it; ask how they want to proceed.
|
|
69
|
+
- Never print or exfiltrate secrets such as API keys or tokens.
|
|
70
|
+
|
|
71
|
+
# Style
|
|
72
|
+
- Be concise and direct. Lead with the answer or result; skip preamble.
|
|
73
|
+
- Reference code as path:line.
|
|
74
|
+
- When done, say briefly what changed and anything left unverified.`;
|
|
75
|
+
|
|
76
|
+
if (instructions.length) {
|
|
77
|
+
prompt += `\n\n# Project instructions\nThese come from instruction files the user wrote. Follow them.\n`;
|
|
78
|
+
for (const { file, text } of instructions) prompt += `\n## ${file}\n${text.trim()}\n`;
|
|
79
|
+
}
|
|
80
|
+
return prompt;
|
|
81
|
+
}
|
package/src/session.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Sessions are append-only JSONL event logs in ~/.arrakis/sessions/<id>.jsonl.
|
|
2
|
+
// Each event is written (and flushed) as it happens, so a crash loses at most
|
|
3
|
+
// the line being written. Resuming replays the log to rebuild the conversation.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import { SESSIONS_DIR } from './config.js';
|
|
8
|
+
import { VERSION } from './version.js';
|
|
9
|
+
|
|
10
|
+
function newId() {
|
|
11
|
+
const d = new Date();
|
|
12
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
13
|
+
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}-${crypto.randomBytes(2).toString('hex')}`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function readEvents(file) {
|
|
17
|
+
const events = [];
|
|
18
|
+
for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
|
|
19
|
+
if (!line.trim()) continue;
|
|
20
|
+
try {
|
|
21
|
+
events.push(JSON.parse(line));
|
|
22
|
+
} catch {
|
|
23
|
+
// A torn final line from a crash: skip it.
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return events;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class Session {
|
|
30
|
+
constructor({ id, file, meta, messages = [] }) {
|
|
31
|
+
this.id = id;
|
|
32
|
+
this.file = file;
|
|
33
|
+
this.meta = meta;
|
|
34
|
+
this.messages = messages;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
static create({ cwd, model }) {
|
|
38
|
+
fs.mkdirSync(SESSIONS_DIR, { recursive: true });
|
|
39
|
+
const id = newId();
|
|
40
|
+
const file = path.join(SESSIONS_DIR, `${id}.jsonl`);
|
|
41
|
+
const meta = { type: 'meta', id, cwd, model, version: VERSION, created: new Date().toISOString() };
|
|
42
|
+
const session = new Session({ id, file, meta });
|
|
43
|
+
session.append(meta);
|
|
44
|
+
return session;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
static load(idOrPrefix) {
|
|
48
|
+
const file = findSessionFile(idOrPrefix);
|
|
49
|
+
const events = readEvents(file);
|
|
50
|
+
const meta = events.find((e) => e.type === 'meta') ?? { id: path.basename(file, '.jsonl') };
|
|
51
|
+
let messages = [];
|
|
52
|
+
for (const e of events) {
|
|
53
|
+
if (e.type === 'message') messages.push(e.message);
|
|
54
|
+
else if (e.type === 'compact') messages = e.messages;
|
|
55
|
+
else if (e.type === 'clear') messages = [];
|
|
56
|
+
}
|
|
57
|
+
const session = new Session({ id: meta.id, file, meta, messages });
|
|
58
|
+
session.repair();
|
|
59
|
+
return session;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
static latest(cwd) {
|
|
63
|
+
const s = listSessions().find((x) => x.cwd === cwd);
|
|
64
|
+
return s ? Session.load(s.id) : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
append(event) {
|
|
68
|
+
const line = JSON.stringify({ ...event, t: event.t ?? Date.now() }) + '\n';
|
|
69
|
+
const fd = fs.openSync(this.file, 'a', 0o600);
|
|
70
|
+
try {
|
|
71
|
+
fs.writeSync(fd, line);
|
|
72
|
+
fs.fsyncSync(fd);
|
|
73
|
+
} finally {
|
|
74
|
+
fs.closeSync(fd);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
add(message) {
|
|
79
|
+
this.messages.push(message);
|
|
80
|
+
this.append({ type: 'message', message });
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
compact(summary, keepFrom) {
|
|
84
|
+
this.messages = [
|
|
85
|
+
{ role: 'user', content: `[Summary of the earlier conversation, written when the context was compacted]\n\n${summary}` },
|
|
86
|
+
{ role: 'assistant', content: 'Understood. I have the summary and will continue from there.' },
|
|
87
|
+
...this.messages.slice(keepFrom),
|
|
88
|
+
];
|
|
89
|
+
this.append({ type: 'compact', messages: this.messages });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Every assistant tool call needs a matching tool result, or the API rejects
|
|
93
|
+
// the history. After an interrupt or crash, fill in the missing ones.
|
|
94
|
+
repair() {
|
|
95
|
+
for (let i = this.messages.length - 1; i >= 0; i--) {
|
|
96
|
+
const m = this.messages[i];
|
|
97
|
+
if (m.role !== 'assistant' || !m.tool_calls?.length) continue;
|
|
98
|
+
const answered = new Set(this.messages.slice(i + 1).filter((x) => x.role === 'tool').map((x) => x.tool_call_id));
|
|
99
|
+
const missing = m.tool_calls.filter((c) => !answered.has(c.id));
|
|
100
|
+
if (!missing.length) break;
|
|
101
|
+
// Tool results must directly follow their assistant message.
|
|
102
|
+
const fill = missing.map((c) => ({ role: 'tool', tool_call_id: c.id, content: 'Interrupted: this tool call did not finish.' }));
|
|
103
|
+
let at = i + 1;
|
|
104
|
+
while (at < this.messages.length && this.messages[at].role === 'tool') at++;
|
|
105
|
+
this.messages.splice(at, 0, ...fill);
|
|
106
|
+
this.append({ type: 'compact', messages: this.messages });
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function findSessionFile(idOrPrefix) {
|
|
113
|
+
const exact = path.join(SESSIONS_DIR, `${idOrPrefix}.jsonl`);
|
|
114
|
+
if (fs.existsSync(exact)) return exact;
|
|
115
|
+
const matches = fs.existsSync(SESSIONS_DIR) ? fs.readdirSync(SESSIONS_DIR).filter((f) => f.startsWith(idOrPrefix) && f.endsWith('.jsonl')) : [];
|
|
116
|
+
if (matches.length === 1) return path.join(SESSIONS_DIR, matches[0]);
|
|
117
|
+
if (matches.length > 1) throw new Error(`Session id "${idOrPrefix}" is ambiguous (${matches.length} matches).`);
|
|
118
|
+
throw new Error(`No session "${idOrPrefix}". List sessions with: arrakis sessions`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function listSessions() {
|
|
122
|
+
if (!fs.existsSync(SESSIONS_DIR)) return [];
|
|
123
|
+
const out = [];
|
|
124
|
+
for (const f of fs.readdirSync(SESSIONS_DIR)) {
|
|
125
|
+
if (!f.endsWith('.jsonl')) continue;
|
|
126
|
+
const file = path.join(SESSIONS_DIR, f);
|
|
127
|
+
const events = readEvents(file);
|
|
128
|
+
const meta = events.find((e) => e.type === 'meta') ?? {};
|
|
129
|
+
const firstUser = events.find((e) => e.type === 'message' && e.message.role === 'user');
|
|
130
|
+
const count = events.filter((e) => e.type === 'message').length;
|
|
131
|
+
out.push({
|
|
132
|
+
id: meta.id ?? f.replace(/\.jsonl$/, ''),
|
|
133
|
+
cwd: meta.cwd,
|
|
134
|
+
model: meta.model,
|
|
135
|
+
updated: fs.statSync(file).mtimeMs,
|
|
136
|
+
messages: count,
|
|
137
|
+
title: typeof firstUser?.message.content === 'string' ? firstUser.message.content.replace(/\s+/g, ' ').slice(0, 70) : '',
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return out.sort((a, b) => b.updated - a.updated);
|
|
141
|
+
}
|
package/src/tools.js
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
4
|
+
|
|
5
|
+
const MAX_OUTPUT = 30000;
|
|
6
|
+
const SKIP_DIRS = new Set(['.git', 'node_modules', '.hg', '.svn', '__pycache__', '.venv', 'venv', '.DS_Store']);
|
|
7
|
+
|
|
8
|
+
export function truncate(text, max = MAX_OUTPUT) {
|
|
9
|
+
if (text.length <= max) return text;
|
|
10
|
+
const half = Math.floor(max / 2);
|
|
11
|
+
return `${text.slice(0, half)}\n\n… [${text.length - max} characters truncated] …\n\n${text.slice(-half)}`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function resolvePath(ctx, p) {
|
|
15
|
+
if (!p || typeof p !== 'string') throw new Error('path is required');
|
|
16
|
+
if (p.startsWith('~/')) p = path.join(process.env.HOME || '', p.slice(2));
|
|
17
|
+
return path.resolve(ctx.cwd, p);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function rel(ctx, p) {
|
|
21
|
+
const r = path.relative(ctx.cwd, p);
|
|
22
|
+
return r && !r.startsWith('..') ? r : p;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function* walk(dir) {
|
|
26
|
+
let entries;
|
|
27
|
+
try {
|
|
28
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
29
|
+
} catch {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
33
|
+
for (const e of entries) {
|
|
34
|
+
if (SKIP_DIRS.has(e.name)) continue;
|
|
35
|
+
const full = path.join(dir, e.name);
|
|
36
|
+
if (e.isDirectory()) yield* walk(full);
|
|
37
|
+
else if (e.isFile()) yield full;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function globToRegExp(glob) {
|
|
42
|
+
if (!glob.includes('/')) glob = `**/${glob}`;
|
|
43
|
+
let re = '';
|
|
44
|
+
let braces = 0;
|
|
45
|
+
for (let i = 0; i < glob.length; i++) {
|
|
46
|
+
const ch = glob[i];
|
|
47
|
+
if (ch === '*') {
|
|
48
|
+
if (glob[i + 1] === '*') {
|
|
49
|
+
if (glob[i + 2] === '/') {
|
|
50
|
+
re += '(?:.*/)?';
|
|
51
|
+
i += 2;
|
|
52
|
+
} else {
|
|
53
|
+
re += '.*';
|
|
54
|
+
i += 1;
|
|
55
|
+
}
|
|
56
|
+
} else re += '[^/]*';
|
|
57
|
+
} else if (ch === '?') re += '[^/]';
|
|
58
|
+
else if (ch === '{') { braces++; re += '(?:'; }
|
|
59
|
+
else if (ch === '}' && braces) { braces--; re += ')'; }
|
|
60
|
+
else if (ch === ',' && braces) re += '|';
|
|
61
|
+
else re += ch.replace(/[.+^$()|[\]\\]/g, '\\$&');
|
|
62
|
+
}
|
|
63
|
+
return new RegExp(`^${re}$`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function isBinary(buf) {
|
|
67
|
+
const n = Math.min(buf.length, 8000);
|
|
68
|
+
for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
let rgAvailable;
|
|
73
|
+
function hasRipgrep() {
|
|
74
|
+
if (rgAvailable === undefined) {
|
|
75
|
+
const r = spawnSync('rg', ['--version'], { stdio: 'ignore' });
|
|
76
|
+
rgAvailable = r.status === 0;
|
|
77
|
+
}
|
|
78
|
+
return rgAvailable;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function runProcess(cmd, args, { cwd, signal, timeoutMs, shell = false }) {
|
|
82
|
+
return new Promise((resolve) => {
|
|
83
|
+
const child = spawn(cmd, args, { cwd, shell, detached: true, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ARRAKIS: '1' } });
|
|
84
|
+
let out = '';
|
|
85
|
+
let size = 0;
|
|
86
|
+
let timedOut = false;
|
|
87
|
+
let aborted = false;
|
|
88
|
+
const add = (d) => {
|
|
89
|
+
size += d.length;
|
|
90
|
+
if (size < 2_000_000) out += d.toString();
|
|
91
|
+
};
|
|
92
|
+
child.stdout.on('data', add);
|
|
93
|
+
child.stderr.on('data', add);
|
|
94
|
+
const kill = () => {
|
|
95
|
+
try {
|
|
96
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
97
|
+
} catch {
|
|
98
|
+
child.kill('SIGKILL');
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
const timer = timeoutMs ? setTimeout(() => { timedOut = true; kill(); }, timeoutMs) : null;
|
|
102
|
+
const onAbort = () => { aborted = true; kill(); };
|
|
103
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
104
|
+
child.on('error', (err) => {
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
signal?.removeEventListener('abort', onAbort);
|
|
107
|
+
resolve({ out: '', code: -1, error: err });
|
|
108
|
+
});
|
|
109
|
+
child.on('close', (code) => {
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
signal?.removeEventListener('abort', onAbort);
|
|
112
|
+
resolve({ out, code, timedOut, aborted });
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function diffPreview(oldStr, newStr, maxLines = 24) {
|
|
118
|
+
const lines = [];
|
|
119
|
+
for (const l of oldStr.split('\n')) lines.push({ sign: '-', text: l });
|
|
120
|
+
for (const l of newStr.split('\n')) lines.push({ sign: '+', text: l });
|
|
121
|
+
const shown = lines.slice(0, maxLines);
|
|
122
|
+
if (lines.length > maxLines) shown.push({ sign: ' ', text: `… ${lines.length - maxLines} more lines` });
|
|
123
|
+
return shown;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export const TOOLS = [
|
|
127
|
+
{
|
|
128
|
+
name: 'read_file',
|
|
129
|
+
description: 'Read a text file. Returns lines prefixed with line numbers. Use offset/limit for large files. Reading a directory lists its entries.',
|
|
130
|
+
parameters: {
|
|
131
|
+
type: 'object',
|
|
132
|
+
properties: {
|
|
133
|
+
path: { type: 'string', description: 'File path, absolute or relative to the working directory' },
|
|
134
|
+
offset: { type: 'integer', description: '1-based line to start from (default 1)' },
|
|
135
|
+
limit: { type: 'integer', description: 'Max lines to return (default 2000)' },
|
|
136
|
+
},
|
|
137
|
+
required: ['path'],
|
|
138
|
+
},
|
|
139
|
+
summary: (a) => a.path,
|
|
140
|
+
run(a, ctx) {
|
|
141
|
+
const p = resolvePath(ctx, a.path);
|
|
142
|
+
const stat = fs.statSync(p);
|
|
143
|
+
if (stat.isDirectory()) {
|
|
144
|
+
const entries = fs.readdirSync(p, { withFileTypes: true }).map((e) => (e.isDirectory() ? `${e.name}/` : e.name));
|
|
145
|
+
return entries.sort().join('\n') || '(empty directory)';
|
|
146
|
+
}
|
|
147
|
+
const buf = fs.readFileSync(p);
|
|
148
|
+
if (isBinary(buf)) return `${rel(ctx, p)} is a binary file (${stat.size} bytes).`;
|
|
149
|
+
const lines = buf.toString('utf8').split('\n');
|
|
150
|
+
const offset = Math.max(1, a.offset || 1);
|
|
151
|
+
const limit = Math.max(1, a.limit || 2000);
|
|
152
|
+
const slice = lines.slice(offset - 1, offset - 1 + limit);
|
|
153
|
+
const body = slice.map((l, i) => `${offset + i}\t${l.length > 2000 ? l.slice(0, 2000) + '…' : l}`).join('\n');
|
|
154
|
+
const more = offset - 1 + limit < lines.length ? `\n… (${lines.length - (offset - 1 + limit)} more lines; use offset to read further)` : '';
|
|
155
|
+
return (body || '(empty file)') + more;
|
|
156
|
+
},
|
|
157
|
+
},
|
|
158
|
+
{
|
|
159
|
+
name: 'write_file',
|
|
160
|
+
description: 'Create a new file or completely overwrite an existing one. Prefer edit_file for changes to existing files.',
|
|
161
|
+
parameters: {
|
|
162
|
+
type: 'object',
|
|
163
|
+
properties: {
|
|
164
|
+
path: { type: 'string', description: 'File path' },
|
|
165
|
+
content: { type: 'string', description: 'Full file content' },
|
|
166
|
+
},
|
|
167
|
+
required: ['path', 'content'],
|
|
168
|
+
},
|
|
169
|
+
needsPermission: true,
|
|
170
|
+
summary: (a) => a.path,
|
|
171
|
+
preview(a, ctx) {
|
|
172
|
+
const p = resolvePath(ctx, a.path);
|
|
173
|
+
const exists = fs.existsSync(p);
|
|
174
|
+
const lines = String(a.content ?? '').split('\n');
|
|
175
|
+
return {
|
|
176
|
+
title: `${exists ? 'Overwrite' : 'Create'} ${rel(ctx, p)} (${lines.length} lines)`,
|
|
177
|
+
lines: lines.slice(0, 16).map((text) => ({ sign: '+', text })).concat(lines.length > 16 ? [{ sign: ' ', text: `… ${lines.length - 16} more lines` }] : []),
|
|
178
|
+
};
|
|
179
|
+
},
|
|
180
|
+
run(a, ctx) {
|
|
181
|
+
const p = resolvePath(ctx, a.path);
|
|
182
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
183
|
+
const content = String(a.content ?? '');
|
|
184
|
+
fs.writeFileSync(p, content);
|
|
185
|
+
return `Wrote ${content.split('\n').length} lines to ${rel(ctx, p)}`;
|
|
186
|
+
},
|
|
187
|
+
},
|
|
188
|
+
{
|
|
189
|
+
name: 'edit_file',
|
|
190
|
+
description: 'Replace exact text in a file. old_string must match the file exactly (including whitespace) and be unique unless replace_all is true. Read the file first.',
|
|
191
|
+
parameters: {
|
|
192
|
+
type: 'object',
|
|
193
|
+
properties: {
|
|
194
|
+
path: { type: 'string', description: 'File path' },
|
|
195
|
+
old_string: { type: 'string', description: 'Exact text to replace' },
|
|
196
|
+
new_string: { type: 'string', description: 'Replacement text' },
|
|
197
|
+
replace_all: { type: 'boolean', description: 'Replace every occurrence (default false)' },
|
|
198
|
+
},
|
|
199
|
+
required: ['path', 'old_string', 'new_string'],
|
|
200
|
+
},
|
|
201
|
+
needsPermission: true,
|
|
202
|
+
summary: (a) => a.path,
|
|
203
|
+
preview(a, ctx) {
|
|
204
|
+
return { title: `Edit ${rel(ctx, resolvePath(ctx, a.path))}`, lines: diffPreview(String(a.old_string ?? ''), String(a.new_string ?? '')) };
|
|
205
|
+
},
|
|
206
|
+
validate(a, ctx) {
|
|
207
|
+
const p = resolvePath(ctx, a.path);
|
|
208
|
+
if (!fs.existsSync(p)) throw new Error(`${a.path} does not exist. Use write_file to create it.`);
|
|
209
|
+
if (!a.old_string) throw new Error('old_string must not be empty. Use write_file to create or overwrite a file.');
|
|
210
|
+
if (a.old_string === a.new_string) throw new Error('old_string and new_string are identical.');
|
|
211
|
+
const text = fs.readFileSync(p, 'utf8');
|
|
212
|
+
const count = text.split(a.old_string).length - 1;
|
|
213
|
+
if (count === 0) throw new Error('old_string was not found in the file. Read the file and copy the exact text, including indentation.');
|
|
214
|
+
if (count > 1 && !a.replace_all) throw new Error(`old_string matches ${count} places. Include more surrounding lines to make it unique, or set replace_all.`);
|
|
215
|
+
return { p, text, count };
|
|
216
|
+
},
|
|
217
|
+
run(a, ctx) {
|
|
218
|
+
const { p, text, count } = this.validate(a, ctx);
|
|
219
|
+
const updated = a.replace_all ? text.split(a.old_string).join(a.new_string) : text.replace(a.old_string, () => a.new_string);
|
|
220
|
+
fs.writeFileSync(p, updated);
|
|
221
|
+
return `Edited ${rel(ctx, p)} (${a.replace_all ? count : 1} replacement${count > 1 && a.replace_all ? 's' : ''})`;
|
|
222
|
+
},
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
name: 'bash',
|
|
226
|
+
description: 'Run a shell command in the working directory and return its combined stdout/stderr. Each call starts fresh in the working directory. No stdin: avoid interactive commands.',
|
|
227
|
+
parameters: {
|
|
228
|
+
type: 'object',
|
|
229
|
+
properties: {
|
|
230
|
+
command: { type: 'string', description: 'The command to run' },
|
|
231
|
+
timeout_ms: { type: 'integer', description: 'Timeout in milliseconds (default 120000, max 600000)' },
|
|
232
|
+
},
|
|
233
|
+
required: ['command'],
|
|
234
|
+
},
|
|
235
|
+
needsPermission: true,
|
|
236
|
+
summary: (a) => a.command,
|
|
237
|
+
preview: (a) => ({ title: 'Run command', lines: String(a.command).split('\n').map((text) => ({ sign: '$', text })) }),
|
|
238
|
+
async run(a, ctx) {
|
|
239
|
+
const timeoutMs = Math.min(Math.max(a.timeout_ms || 120000, 1000), 600000);
|
|
240
|
+
const shell = fs.existsSync('/bin/bash') ? '/bin/bash' : true;
|
|
241
|
+
const { out, code, timedOut, aborted, error } = await runProcess(String(a.command), [], { cwd: ctx.cwd, signal: ctx.signal, timeoutMs, shell });
|
|
242
|
+
if (error) throw error;
|
|
243
|
+
let result = truncate(out.trimEnd()) || '(no output)';
|
|
244
|
+
if (timedOut) result += `\n[timed out after ${timeoutMs / 1000}s]`;
|
|
245
|
+
else if (aborted) result += '\n[interrupted by user]';
|
|
246
|
+
else if (code !== 0) result += `\n[exit code ${code}]`;
|
|
247
|
+
return result;
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
{
|
|
251
|
+
name: 'grep',
|
|
252
|
+
description: 'Search file contents with a regular expression. Returns matching lines as path:line:text. Skips .git and node_modules.',
|
|
253
|
+
parameters: {
|
|
254
|
+
type: 'object',
|
|
255
|
+
properties: {
|
|
256
|
+
pattern: { type: 'string', description: 'Regular expression' },
|
|
257
|
+
path: { type: 'string', description: 'File or directory to search (default: working directory)' },
|
|
258
|
+
glob: { type: 'string', description: 'Only search files matching this glob, e.g. "*.ts"' },
|
|
259
|
+
ignore_case: { type: 'boolean', description: 'Case-insensitive search' },
|
|
260
|
+
},
|
|
261
|
+
required: ['pattern'],
|
|
262
|
+
},
|
|
263
|
+
summary: (a) => `${a.pattern}${a.glob ? ` (${a.glob})` : ''}`,
|
|
264
|
+
async run(a, ctx) {
|
|
265
|
+
const root = resolvePath(ctx, a.path || '.');
|
|
266
|
+
const limit = 200;
|
|
267
|
+
if (hasRipgrep()) {
|
|
268
|
+
const args = ['-n', '--no-heading', '--color', 'never', '--max-columns', '400'];
|
|
269
|
+
if (a.ignore_case) args.push('-i');
|
|
270
|
+
if (a.glob) args.push('-g', a.glob);
|
|
271
|
+
args.push('-e', a.pattern);
|
|
272
|
+
if (root !== ctx.cwd) args.push(rel(ctx, root));
|
|
273
|
+
const { out, code } = await runProcess('rg', args, { cwd: ctx.cwd, signal: ctx.signal, timeoutMs: 60000 });
|
|
274
|
+
if (code === 1) return 'No matches.';
|
|
275
|
+
if (code !== 0) throw new Error(out.trim() || `rg exited with code ${code}`);
|
|
276
|
+
const lines = out.trimEnd().split('\n');
|
|
277
|
+
return lines.slice(0, limit).join('\n') + (lines.length > limit ? `\n… (${lines.length - limit} more matches)` : '');
|
|
278
|
+
}
|
|
279
|
+
const re = new RegExp(a.pattern, a.ignore_case ? 'i' : '');
|
|
280
|
+
const globRe = a.glob ? globToRegExp(a.glob) : null;
|
|
281
|
+
const files = fs.statSync(root).isFile() ? [root] : walk(root);
|
|
282
|
+
const results = [];
|
|
283
|
+
let total = 0;
|
|
284
|
+
for (const f of files) {
|
|
285
|
+
if (globRe && !globRe.test(path.relative(root, f).split(path.sep).join('/'))) continue;
|
|
286
|
+
let buf;
|
|
287
|
+
try {
|
|
288
|
+
if (fs.statSync(f).size > 2_000_000) continue;
|
|
289
|
+
buf = fs.readFileSync(f);
|
|
290
|
+
} catch {
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
if (isBinary(buf)) continue;
|
|
294
|
+
const lines = buf.toString('utf8').split('\n');
|
|
295
|
+
for (let i = 0; i < lines.length; i++) {
|
|
296
|
+
if (re.test(lines[i])) {
|
|
297
|
+
total++;
|
|
298
|
+
if (results.length < limit) results.push(`${rel(ctx, f)}:${i + 1}:${lines[i].slice(0, 400)}`);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (!total) return 'No matches.';
|
|
303
|
+
return results.join('\n') + (total > limit ? `\n… (${total - limit} more matches)` : '');
|
|
304
|
+
},
|
|
305
|
+
},
|
|
306
|
+
{
|
|
307
|
+
name: 'list_files',
|
|
308
|
+
description: 'Find files by glob pattern, e.g. "**/*.py" or "src/**/*.ts". Skips .git and node_modules.',
|
|
309
|
+
parameters: {
|
|
310
|
+
type: 'object',
|
|
311
|
+
properties: {
|
|
312
|
+
pattern: { type: 'string', description: 'Glob pattern (default "**/*")' },
|
|
313
|
+
path: { type: 'string', description: 'Directory to search (default: working directory)' },
|
|
314
|
+
},
|
|
315
|
+
},
|
|
316
|
+
summary: (a) => a.pattern || '**/*',
|
|
317
|
+
run(a, ctx) {
|
|
318
|
+
const root = resolvePath(ctx, a.path || '.');
|
|
319
|
+
const re = globToRegExp(a.pattern || '**/*');
|
|
320
|
+
const limit = 500;
|
|
321
|
+
const results = [];
|
|
322
|
+
let total = 0;
|
|
323
|
+
for (const f of walk(root)) {
|
|
324
|
+
const r = path.relative(root, f).split(path.sep).join('/');
|
|
325
|
+
if (!re.test(r)) continue;
|
|
326
|
+
total++;
|
|
327
|
+
if (results.length < limit) results.push(rel(ctx, f));
|
|
328
|
+
}
|
|
329
|
+
if (!total) return 'No files found.';
|
|
330
|
+
return results.join('\n') + (total > limit ? `\n… (${total - limit} more files)` : '');
|
|
331
|
+
},
|
|
332
|
+
},
|
|
333
|
+
];
|
|
334
|
+
|
|
335
|
+
export const toolSchemas = () =>
|
|
336
|
+
TOOLS.map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.parameters } }));
|
|
337
|
+
|
|
338
|
+
export const findTool = (name) => TOOLS.find((t) => t.name === name);
|
|
339
|
+
|
|
340
|
+
// Run one tool call from the model. Always returns a string for the tool message.
|
|
341
|
+
export async function executeToolCall(call, ctx) {
|
|
342
|
+
const tool = findTool(call.function?.name);
|
|
343
|
+
if (!tool) return `Error: unknown tool "${call.function?.name}". Available: ${TOOLS.map((t) => t.name).join(', ')}`;
|
|
344
|
+
let args;
|
|
345
|
+
try {
|
|
346
|
+
args = call.function.arguments ? JSON.parse(call.function.arguments) : {};
|
|
347
|
+
} catch {
|
|
348
|
+
return `Error: tool arguments were not valid JSON: ${String(call.function.arguments).slice(0, 200)}`;
|
|
349
|
+
}
|
|
350
|
+
ctx.ui.toolStart(tool.name, safe(() => tool.summary?.(args)) ?? '');
|
|
351
|
+
try {
|
|
352
|
+
if (tool.validate) tool.validate(args, ctx);
|
|
353
|
+
if (tool.needsPermission) {
|
|
354
|
+
const preview = safe(() => tool.preview?.(args, ctx));
|
|
355
|
+
const allowed = await ctx.permissions.check(tool.name, preview);
|
|
356
|
+
if (!allowed) {
|
|
357
|
+
ctx.ui.toolResult('Denied', true);
|
|
358
|
+
return 'Permission denied: the user declined this tool call. Do not retry it; ask the user how to proceed.';
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
const result = String(await tool.run(args, ctx));
|
|
362
|
+
ctx.ui.toolResult(result);
|
|
363
|
+
return truncate(result);
|
|
364
|
+
} catch (err) {
|
|
365
|
+
const msg = `Error: ${err.message}`;
|
|
366
|
+
ctx.ui.toolResult(msg, true);
|
|
367
|
+
return msg;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function safe(fn) {
|
|
372
|
+
try {
|
|
373
|
+
return fn();
|
|
374
|
+
} catch {
|
|
375
|
+
return undefined;
|
|
376
|
+
}
|
|
377
|
+
}
|