reasonally 0.1.0 → 0.3.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 +143 -5
- package/dist/agent/accumulate.js +146 -0
- package/dist/agent/client.js +174 -0
- package/dist/agent/compact.js +79 -0
- package/dist/agent/cost.js +22 -0
- package/dist/agent/loop-constants.js +3 -0
- package/dist/agent/loop.js +559 -0
- package/dist/agent/mcp-config.js +72 -0
- package/dist/agent/mcp.js +194 -0
- package/dist/agent/permissions.js +116 -0
- package/dist/agent/prompt.js +98 -0
- package/dist/agent/session.js +196 -0
- package/dist/agent/sse.js +46 -0
- package/dist/agent/tools/bash.js +176 -0
- package/dist/agent/tools/diff.js +33 -0
- package/dist/agent/tools/files.js +270 -0
- package/dist/agent/tools/index.js +21 -0
- package/dist/agent/tools/paths.js +43 -0
- package/dist/agent/tools/search.js +288 -0
- package/dist/agent/tools/task.js +42 -0
- package/dist/agent/tools/todo.js +59 -0
- package/dist/agent/tools/types.js +57 -0
- package/dist/agent/types.js +2 -0
- package/dist/api.js +5 -1
- package/dist/browser/command.js +93 -0
- package/dist/browser/guards.js +138 -0
- package/dist/browser/pairing.js +123 -0
- package/dist/browser/protocol.js +172 -0
- package/dist/browser/server.js +157 -0
- package/dist/browser/sessions.js +478 -0
- package/dist/catalog.js +12 -0
- package/dist/cli.js +43 -3
- package/dist/config.js +17 -4
- package/dist/tui/app.js +869 -0
- package/dist/tui/args.js +32 -0
- package/dist/tui/commands.js +38 -0
- package/dist/tui/components.js +375 -0
- package/dist/tui/format.js +116 -0
- package/dist/tui/node-version.js +7 -0
- package/dist/tui/start.js +135 -0
- package/dist/tui/theme.js +36 -0
- package/package.json +11 -3
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { tildePath } from "./paths.js";
|
|
3
|
+
import { optionalInt, stringArg, truncateMiddle } from "./types.js";
|
|
4
|
+
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
5
|
+
const MAX_TIMEOUT_MS = 600_000;
|
|
6
|
+
const MAX_OUTPUT_CHARS = 30_000;
|
|
7
|
+
/** Time between asking a command to stop and forcing it. */
|
|
8
|
+
const KILL_GRACE_MS = 2_000;
|
|
9
|
+
const isWindows = process.platform === "win32";
|
|
10
|
+
/** The shell commands run in: the user's own on macOS/Linux, PowerShell on Windows. */
|
|
11
|
+
export function shellFor(env) {
|
|
12
|
+
if (isWindows) {
|
|
13
|
+
return {
|
|
14
|
+
file: "powershell.exe",
|
|
15
|
+
args: (cmd) => ["-NoProfile", "-NonInteractive", "-Command", cmd],
|
|
16
|
+
name: "PowerShell",
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
const file = env.SHELL || "/bin/sh";
|
|
20
|
+
return { file, args: (cmd) => ["-c", cmd], name: file.split("/").pop() ?? "sh" };
|
|
21
|
+
}
|
|
22
|
+
/** Our API key never reaches commands; pagers and prompts that would wait forever are off. */
|
|
23
|
+
export function commandEnv(env) {
|
|
24
|
+
const out = {
|
|
25
|
+
...env,
|
|
26
|
+
PAGER: "cat",
|
|
27
|
+
GIT_PAGER: "cat",
|
|
28
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
29
|
+
};
|
|
30
|
+
delete out.REASONALLY_API_KEY;
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
/** Stops a command and everything it started (it runs in its own process group). */
|
|
34
|
+
export function killTree(child, signal = "SIGTERM") {
|
|
35
|
+
if (child.pid === undefined)
|
|
36
|
+
return;
|
|
37
|
+
try {
|
|
38
|
+
if (isWindows) {
|
|
39
|
+
spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }).on("error", () => { });
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
process.kill(-child.pid, signal);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// already gone
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007]*(?:\u0007|\u001b\\)/g;
|
|
50
|
+
export const stripAnsi = (text) => text.replace(ANSI, "");
|
|
51
|
+
/** Runs one command to completion, a timeout, or `signal`. Output is stdout and stderr together. */
|
|
52
|
+
export function runCommand(command, opts) {
|
|
53
|
+
const started = Date.now();
|
|
54
|
+
const shell = shellFor(opts.env);
|
|
55
|
+
return new Promise((resolve) => {
|
|
56
|
+
let output = "";
|
|
57
|
+
let timedOut = false;
|
|
58
|
+
let aborted = false;
|
|
59
|
+
let settled = false;
|
|
60
|
+
const child = spawn(shell.file, shell.args(command), {
|
|
61
|
+
cwd: opts.cwd,
|
|
62
|
+
env: opts.env,
|
|
63
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
64
|
+
detached: !isWindows,
|
|
65
|
+
windowsHide: true,
|
|
66
|
+
});
|
|
67
|
+
// Keep a little more than the cap while running; truncate once at the end.
|
|
68
|
+
const append = (chunk) => {
|
|
69
|
+
output += chunk.toString("utf8");
|
|
70
|
+
if (output.length > MAX_OUTPUT_CHARS * 4) {
|
|
71
|
+
output = truncateMiddle(output, MAX_OUTPUT_CHARS * 2);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
child.stdout?.on("data", append);
|
|
75
|
+
child.stderr?.on("data", append);
|
|
76
|
+
let forceTimer;
|
|
77
|
+
const stop = () => {
|
|
78
|
+
killTree(child, "SIGTERM");
|
|
79
|
+
forceTimer = setTimeout(() => killTree(child, "SIGKILL"), KILL_GRACE_MS);
|
|
80
|
+
forceTimer.unref();
|
|
81
|
+
};
|
|
82
|
+
const timer = setTimeout(() => {
|
|
83
|
+
timedOut = true;
|
|
84
|
+
stop();
|
|
85
|
+
}, opts.timeoutMs);
|
|
86
|
+
const onAbort = () => {
|
|
87
|
+
aborted = true;
|
|
88
|
+
stop();
|
|
89
|
+
};
|
|
90
|
+
if (opts.signal.aborted)
|
|
91
|
+
onAbort();
|
|
92
|
+
opts.signal.addEventListener("abort", onAbort, { once: true });
|
|
93
|
+
const finish = (exitCode) => {
|
|
94
|
+
if (settled)
|
|
95
|
+
return;
|
|
96
|
+
settled = true;
|
|
97
|
+
clearTimeout(timer);
|
|
98
|
+
opts.signal.removeEventListener("abort", onAbort);
|
|
99
|
+
// Something it started in the background may still hold the pipes open: stop listening.
|
|
100
|
+
child.stdout?.destroy();
|
|
101
|
+
child.stderr?.destroy();
|
|
102
|
+
resolve({
|
|
103
|
+
output: truncateMiddle(stripAnsi(output), MAX_OUTPUT_CHARS),
|
|
104
|
+
exitCode,
|
|
105
|
+
timedOut,
|
|
106
|
+
aborted,
|
|
107
|
+
ms: Date.now() - started,
|
|
108
|
+
});
|
|
109
|
+
};
|
|
110
|
+
child.on("error", (error) => {
|
|
111
|
+
output += `\n${error.message}`;
|
|
112
|
+
finish(null);
|
|
113
|
+
});
|
|
114
|
+
// Give the pipes a moment to drain after the shell itself exits.
|
|
115
|
+
child.on("exit", (code, signal) => {
|
|
116
|
+
setTimeout(() => finish(code ?? (signal ? null : 0)), 50);
|
|
117
|
+
});
|
|
118
|
+
child.on("close", (code) => finish(code));
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
const seconds = (ms) => `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)}s`;
|
|
122
|
+
export const bashTool = {
|
|
123
|
+
name: "bash",
|
|
124
|
+
description: "Run a shell command in the project folder and get its output (stdout and stderr together, " +
|
|
125
|
+
"trimmed if long). Each call starts fresh in the project folder: `cd` doesn't carry over. " +
|
|
126
|
+
"Nothing is typed into it, so avoid commands that wait for input, and don't start servers or " +
|
|
127
|
+
"watchers that never exit. Default timeout 2 minutes (max 10).",
|
|
128
|
+
parameters: {
|
|
129
|
+
type: "object",
|
|
130
|
+
properties: {
|
|
131
|
+
command: { type: "string", description: "The command line to run." },
|
|
132
|
+
timeout_ms: { type: "integer", description: "Timeout in milliseconds (default 120000)." },
|
|
133
|
+
},
|
|
134
|
+
required: ["command"],
|
|
135
|
+
additionalProperties: false,
|
|
136
|
+
},
|
|
137
|
+
async prepare(args, ctx) {
|
|
138
|
+
const command = stringArg(args, "command");
|
|
139
|
+
const timeoutMs = optionalInt(args, "timeout_ms", 1000, MAX_TIMEOUT_MS) ?? DEFAULT_TIMEOUT_MS;
|
|
140
|
+
const firstLine = command.split("\n")[0];
|
|
141
|
+
const short = firstLine.length > 80 ? `${firstLine.slice(0, 77)}…` : firstLine;
|
|
142
|
+
return {
|
|
143
|
+
kind: "exec",
|
|
144
|
+
paths: [ctx.cwd],
|
|
145
|
+
command,
|
|
146
|
+
title: `Run ${short}${command.includes("\n") ? " …" : ""}`,
|
|
147
|
+
preview: `$ ${command}\n\nin ${tildePath(ctx.cwd, ctx.home)}`,
|
|
148
|
+
async run() {
|
|
149
|
+
const result = await runCommand(command, {
|
|
150
|
+
cwd: ctx.cwd,
|
|
151
|
+
env: ctx.env,
|
|
152
|
+
signal: ctx.signal,
|
|
153
|
+
timeoutMs,
|
|
154
|
+
});
|
|
155
|
+
const status = result.aborted
|
|
156
|
+
? "stopped"
|
|
157
|
+
: result.timedOut
|
|
158
|
+
? `timed out after ${seconds(timeoutMs)}`
|
|
159
|
+
: result.exitCode === 0
|
|
160
|
+
? "done"
|
|
161
|
+
: `exit ${result.exitCode ?? "?"}`;
|
|
162
|
+
const tail = result.aborted
|
|
163
|
+
? "[Stopped by the user.]"
|
|
164
|
+
: result.timedOut
|
|
165
|
+
? `[Timed out after ${seconds(timeoutMs)} and was stopped.]`
|
|
166
|
+
: `[Exit code ${result.exitCode ?? "unknown"}]`;
|
|
167
|
+
return {
|
|
168
|
+
output: `${result.output.trimEnd() || "(no output)"}\n${tail}`,
|
|
169
|
+
summary: `Ran ${short} · ${status} (${seconds(result.ms)})`,
|
|
170
|
+
isError: result.exitCode !== 0,
|
|
171
|
+
detail: result.output,
|
|
172
|
+
};
|
|
173
|
+
},
|
|
174
|
+
};
|
|
175
|
+
},
|
|
176
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { structuredPatch } from "diff";
|
|
2
|
+
/** Hunks wider than this are summarized, so a huge rewrite doesn't flood the screen. */
|
|
3
|
+
const MAX_PREVIEW_LINES = 400;
|
|
4
|
+
export function fileDiff(before, after) {
|
|
5
|
+
const patch = structuredPatch("a", "b", before, after, undefined, undefined, { context: 3 });
|
|
6
|
+
let added = 0;
|
|
7
|
+
let removed = 0;
|
|
8
|
+
const lines = [];
|
|
9
|
+
for (const hunk of patch.hunks) {
|
|
10
|
+
lines.push(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`);
|
|
11
|
+
for (const line of hunk.lines) {
|
|
12
|
+
if (line.startsWith("\\"))
|
|
13
|
+
continue; // ""
|
|
14
|
+
if (line.startsWith("+"))
|
|
15
|
+
added++;
|
|
16
|
+
else if (line.startsWith("-"))
|
|
17
|
+
removed++;
|
|
18
|
+
lines.push(line);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const text = lines.length > MAX_PREVIEW_LINES
|
|
22
|
+
? [
|
|
23
|
+
...lines.slice(0, MAX_PREVIEW_LINES),
|
|
24
|
+
`… ${lines.length - MAX_PREVIEW_LINES} more diff lines`,
|
|
25
|
+
].join("\n")
|
|
26
|
+
: lines.join("\n");
|
|
27
|
+
return { added, removed, text };
|
|
28
|
+
}
|
|
29
|
+
/** The whole of a new file as added lines. */
|
|
30
|
+
export function newFileDiff(content) {
|
|
31
|
+
return fileDiff("", content);
|
|
32
|
+
}
|
|
33
|
+
export const diffStat = (d) => `+${d.added} −${d.removed}`;
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { mkdir, open, readdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { diffStat, fileDiff, newFileDiff } from "./diff.js";
|
|
4
|
+
import { displayPath, resolvePath } from "./paths.js";
|
|
5
|
+
import { optionalBool, optionalInt, stringArg, ToolInputError, } from "./types.js";
|
|
6
|
+
const DEFAULT_LINES = 2000;
|
|
7
|
+
const MAX_LINE_CHARS = 2000;
|
|
8
|
+
const MAX_FILE_BYTES = 20 * 1024 * 1024;
|
|
9
|
+
const MAX_DIR_ENTRIES = 1000;
|
|
10
|
+
const errorResult = (output, summary = output) => ({
|
|
11
|
+
output,
|
|
12
|
+
summary,
|
|
13
|
+
isError: true,
|
|
14
|
+
});
|
|
15
|
+
/** "1 line", "3 lines". */
|
|
16
|
+
export const count = (n, one, many = `${one}s`) => `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
|
|
17
|
+
const statOrNull = (path) => stat(path).catch(() => null);
|
|
18
|
+
/** A NUL byte in the first 8 KB means it isn't text. */
|
|
19
|
+
async function isBinary(path) {
|
|
20
|
+
const handle = await open(path, "r");
|
|
21
|
+
try {
|
|
22
|
+
const buffer = Buffer.alloc(8192);
|
|
23
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
24
|
+
return buffer.subarray(0, bytesRead).includes(0);
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
await handle.close();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export const readTool = {
|
|
31
|
+
name: "read",
|
|
32
|
+
description: "Read a text file, with line numbers, or list a folder. Long files are read 2000 lines at a " +
|
|
33
|
+
"time: use offset and limit for the rest. Read a file before editing or overwriting it.",
|
|
34
|
+
parameters: {
|
|
35
|
+
type: "object",
|
|
36
|
+
properties: {
|
|
37
|
+
path: { type: "string", description: "File or folder, relative to the project or absolute." },
|
|
38
|
+
offset: { type: "integer", description: "First line to read, starting at 1." },
|
|
39
|
+
limit: { type: "integer", description: `How many lines to read (default ${DEFAULT_LINES}).` },
|
|
40
|
+
},
|
|
41
|
+
required: ["path"],
|
|
42
|
+
additionalProperties: false,
|
|
43
|
+
},
|
|
44
|
+
async prepare(args, ctx) {
|
|
45
|
+
const path = await resolvePath(stringArg(args, "path"), ctx.cwd, ctx.home);
|
|
46
|
+
const offset = optionalInt(args, "offset", 1, Number.MAX_SAFE_INTEGER) ?? 1;
|
|
47
|
+
const limit = optionalInt(args, "limit", 1, 100_000) ?? DEFAULT_LINES;
|
|
48
|
+
const shown = displayPath(path, ctx.cwd, ctx.home);
|
|
49
|
+
return {
|
|
50
|
+
kind: "read",
|
|
51
|
+
paths: [path],
|
|
52
|
+
title: `Read ${shown}`,
|
|
53
|
+
async run() {
|
|
54
|
+
const info = await statOrNull(path);
|
|
55
|
+
if (!info)
|
|
56
|
+
return errorResult(`${shown} doesn't exist.`);
|
|
57
|
+
if (info.isDirectory()) {
|
|
58
|
+
const entries = await readdir(path, { withFileTypes: true });
|
|
59
|
+
const names = entries
|
|
60
|
+
.map((e) => (e.isDirectory() ? `${e.name}/` : e.name))
|
|
61
|
+
.sort((a, b) => a.localeCompare(b));
|
|
62
|
+
const listed = names.slice(0, MAX_DIR_ENTRIES);
|
|
63
|
+
const more = names.length - listed.length;
|
|
64
|
+
return {
|
|
65
|
+
output: (listed.join("\n") || "(empty folder)") +
|
|
66
|
+
(more > 0 ? `\n[… ${more} more entries]` : ""),
|
|
67
|
+
summary: `Listed ${shown} (${count(names.length, "entry", "entries")})`,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
if (info.size > MAX_FILE_BYTES) {
|
|
71
|
+
return errorResult(`${shown} is ${Math.round(info.size / 1024 / 1024)} MB, too large to read. Search it with grep instead.`, `${shown} is too large to read`);
|
|
72
|
+
}
|
|
73
|
+
if (await isBinary(path)) {
|
|
74
|
+
return errorResult(`${shown} is a binary file (${info.size} bytes).`);
|
|
75
|
+
}
|
|
76
|
+
const text = await readFile(path, "utf8");
|
|
77
|
+
ctx.files.record(path, info.mtimeMs);
|
|
78
|
+
if (text === "")
|
|
79
|
+
return { output: "(empty file)", summary: `Read ${shown} (empty)` };
|
|
80
|
+
const lines = text.replace(/\r?\n$/, "").split(/\r?\n/);
|
|
81
|
+
const start = Math.min(offset, lines.length);
|
|
82
|
+
const slice = lines.slice(start - 1, start - 1 + limit);
|
|
83
|
+
const end = start - 1 + slice.length;
|
|
84
|
+
const width = String(end).length;
|
|
85
|
+
const body = slice
|
|
86
|
+
.map((line, i) => {
|
|
87
|
+
const clipped = line.length > MAX_LINE_CHARS ? `${line.slice(0, MAX_LINE_CHARS)} [line cut]` : line;
|
|
88
|
+
return `${String(start + i).padStart(width)}\t${clipped}`;
|
|
89
|
+
})
|
|
90
|
+
.join("\n");
|
|
91
|
+
const partial = start > 1 || end < lines.length;
|
|
92
|
+
return {
|
|
93
|
+
output: partial
|
|
94
|
+
? `${body}\n\n[Lines ${start}–${end} of ${lines.length}. Use offset to read more.]`
|
|
95
|
+
: body,
|
|
96
|
+
summary: partial
|
|
97
|
+
? `Read ${shown} (lines ${start}–${end} of ${lines.length})`
|
|
98
|
+
: `Read ${shown} (${count(lines.length, "line")})`,
|
|
99
|
+
};
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
/** Refuses to change a file the agent hasn't seen, or that changed since it read it. */
|
|
105
|
+
function requireFresh(path, shown, mtimeMs, ctx) {
|
|
106
|
+
const state = ctx.files.check(path, mtimeMs);
|
|
107
|
+
if (state === "unread") {
|
|
108
|
+
throw new ToolInputError(`Read ${shown} before changing it, so you don't overwrite what you haven't seen.`);
|
|
109
|
+
}
|
|
110
|
+
if (state === "changed") {
|
|
111
|
+
throw new ToolInputError(`${shown} changed since you last read it. Read it again first.`);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** Writes, unless the file changed while the user was looking at the approval. */
|
|
115
|
+
async function writeChecked(path, shown, content, expectedMtime, ctx) {
|
|
116
|
+
const now = await statOrNull(path);
|
|
117
|
+
if ((now?.mtimeMs ?? null) !== expectedMtime) {
|
|
118
|
+
return errorResult(`${shown} changed while waiting for approval, so it wasn't written. Read it again and redo the change.`, `${shown} changed meanwhile; not written`);
|
|
119
|
+
}
|
|
120
|
+
await mkdir(dirname(path), { recursive: true });
|
|
121
|
+
await writeFile(path, content);
|
|
122
|
+
const after = await stat(path);
|
|
123
|
+
ctx.files.record(path, after.mtimeMs);
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
export const writeTool = {
|
|
127
|
+
name: "write",
|
|
128
|
+
description: "Create a file, or replace a whole file. Prefer `edit` for changes to an existing file. " +
|
|
129
|
+
"Folders are created as needed. An existing file must be read first.",
|
|
130
|
+
parameters: {
|
|
131
|
+
type: "object",
|
|
132
|
+
properties: {
|
|
133
|
+
path: { type: "string", description: "File path, relative to the project or absolute." },
|
|
134
|
+
content: { type: "string", description: "The complete new content." },
|
|
135
|
+
},
|
|
136
|
+
required: ["path", "content"],
|
|
137
|
+
additionalProperties: false,
|
|
138
|
+
},
|
|
139
|
+
async prepare(args, ctx) {
|
|
140
|
+
const path = await resolvePath(stringArg(args, "path"), ctx.cwd, ctx.home);
|
|
141
|
+
if (typeof args.content !== "string")
|
|
142
|
+
throw new ToolInputError("`content` must be a string.");
|
|
143
|
+
const content = args.content;
|
|
144
|
+
const shown = displayPath(path, ctx.cwd, ctx.home);
|
|
145
|
+
const info = await statOrNull(path);
|
|
146
|
+
if (info?.isDirectory())
|
|
147
|
+
throw new ToolInputError(`${shown} is a folder.`);
|
|
148
|
+
if (info)
|
|
149
|
+
requireFresh(path, shown, info.mtimeMs, ctx);
|
|
150
|
+
const before = info ? await readFile(path, "utf8") : null;
|
|
151
|
+
const diff = before === null ? newFileDiff(content) : fileDiff(before, content);
|
|
152
|
+
return {
|
|
153
|
+
kind: "edit",
|
|
154
|
+
paths: [path],
|
|
155
|
+
title: `${before === null ? "Create" : "Write"} ${shown}`,
|
|
156
|
+
preview: diff.text,
|
|
157
|
+
async run() {
|
|
158
|
+
const failed = await writeChecked(path, shown, content, info?.mtimeMs ?? null, ctx);
|
|
159
|
+
if (failed)
|
|
160
|
+
return failed;
|
|
161
|
+
return {
|
|
162
|
+
output: before === null ? `Created ${shown}.` : `Wrote ${shown}.`,
|
|
163
|
+
summary: before === null
|
|
164
|
+
? `Created ${shown} (${count(diff.added, "line")})`
|
|
165
|
+
: `Wrote ${shown} (${diffStat(diff)})`,
|
|
166
|
+
detail: diff.text,
|
|
167
|
+
};
|
|
168
|
+
},
|
|
169
|
+
};
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
const occurrences = (text, search) => {
|
|
173
|
+
let count = 0;
|
|
174
|
+
for (let i = text.indexOf(search); i !== -1; i = text.indexOf(search, i + search.length))
|
|
175
|
+
count++;
|
|
176
|
+
return count;
|
|
177
|
+
};
|
|
178
|
+
/** Replaces `oldText` with `newText`: exactly once, or everywhere with `replaceAll`. */
|
|
179
|
+
export function applyEdit(content, oldText, newText, replaceAll) {
|
|
180
|
+
if (oldText === newText)
|
|
181
|
+
return { ok: false, error: "old_string and new_string are the same." };
|
|
182
|
+
let search = oldText;
|
|
183
|
+
let replacement = newText;
|
|
184
|
+
let count = occurrences(content, search);
|
|
185
|
+
// Files with Windows line endings: the model writes "\n".
|
|
186
|
+
if (count === 0 &&
|
|
187
|
+
content.includes("\r\n") &&
|
|
188
|
+
oldText.includes("\n") &&
|
|
189
|
+
!oldText.includes("\r")) {
|
|
190
|
+
search = oldText.replaceAll("\n", "\r\n");
|
|
191
|
+
replacement = newText.replaceAll("\n", "\r\n");
|
|
192
|
+
count = occurrences(content, search);
|
|
193
|
+
}
|
|
194
|
+
if (count === 0) {
|
|
195
|
+
return {
|
|
196
|
+
ok: false,
|
|
197
|
+
error: "old_string wasn't found. It must match the file exactly, including whitespace and " +
|
|
198
|
+
"indentation. Read the file again if you're unsure what it contains.",
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
if (count > 1 && !replaceAll) {
|
|
202
|
+
return {
|
|
203
|
+
ok: false,
|
|
204
|
+
error: `old_string appears ${count} times. Include more surrounding lines to make it unique, or set replace_all to change every one.`,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
if (replaceAll)
|
|
208
|
+
return { ok: true, content: content.split(search).join(replacement), count };
|
|
209
|
+
const at = content.indexOf(search);
|
|
210
|
+
return {
|
|
211
|
+
ok: true,
|
|
212
|
+
content: content.slice(0, at) + replacement + content.slice(at + search.length),
|
|
213
|
+
count,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
export const editTool = {
|
|
217
|
+
name: "edit",
|
|
218
|
+
description: "Change part of an existing file by replacing an exact piece of text. old_string must match " +
|
|
219
|
+
"the file exactly (whitespace included) and appear once, unless replace_all is set. Read the " +
|
|
220
|
+
"file first.",
|
|
221
|
+
parameters: {
|
|
222
|
+
type: "object",
|
|
223
|
+
properties: {
|
|
224
|
+
path: { type: "string", description: "File path, relative to the project or absolute." },
|
|
225
|
+
old_string: { type: "string", description: "The exact text to replace." },
|
|
226
|
+
new_string: { type: "string", description: "The text to put in its place." },
|
|
227
|
+
replace_all: { type: "boolean", description: "Replace every occurrence (default false)." },
|
|
228
|
+
},
|
|
229
|
+
required: ["path", "old_string", "new_string"],
|
|
230
|
+
additionalProperties: false,
|
|
231
|
+
},
|
|
232
|
+
async prepare(args, ctx) {
|
|
233
|
+
const path = await resolvePath(stringArg(args, "path"), ctx.cwd, ctx.home);
|
|
234
|
+
const oldText = stringArg(args, "old_string");
|
|
235
|
+
if (typeof args.new_string !== "string") {
|
|
236
|
+
throw new ToolInputError("`new_string` must be a string.");
|
|
237
|
+
}
|
|
238
|
+
const replaceAll = optionalBool(args, "replace_all");
|
|
239
|
+
const shown = displayPath(path, ctx.cwd, ctx.home);
|
|
240
|
+
const info = await statOrNull(path);
|
|
241
|
+
if (!info)
|
|
242
|
+
throw new ToolInputError(`${shown} doesn't exist. Use write to create it.`);
|
|
243
|
+
if (info.isDirectory())
|
|
244
|
+
throw new ToolInputError(`${shown} is a folder.`);
|
|
245
|
+
requireFresh(path, shown, info.mtimeMs, ctx);
|
|
246
|
+
const before = await readFile(path, "utf8");
|
|
247
|
+
const outcome = applyEdit(before, oldText, args.new_string, replaceAll);
|
|
248
|
+
if (!outcome.ok)
|
|
249
|
+
throw new ToolInputError(outcome.error);
|
|
250
|
+
const diff = fileDiff(before, outcome.content);
|
|
251
|
+
return {
|
|
252
|
+
kind: "edit",
|
|
253
|
+
paths: [path],
|
|
254
|
+
title: `Edit ${shown}`,
|
|
255
|
+
preview: diff.text,
|
|
256
|
+
async run() {
|
|
257
|
+
const failed = await writeChecked(path, shown, outcome.content, info.mtimeMs, ctx);
|
|
258
|
+
if (failed)
|
|
259
|
+
return failed;
|
|
260
|
+
return {
|
|
261
|
+
output: outcome.count > 1
|
|
262
|
+
? `Edited ${shown} (${outcome.count} replacements).`
|
|
263
|
+
: `Edited ${shown}.`,
|
|
264
|
+
summary: `Edited ${shown} (${diffStat(diff)})`,
|
|
265
|
+
detail: diff.text,
|
|
266
|
+
};
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
},
|
|
270
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { bashTool } from "./bash.js";
|
|
2
|
+
import { editTool, readTool, writeTool } from "./files.js";
|
|
3
|
+
import { findTool, grepTool } from "./search.js";
|
|
4
|
+
import { taskTool } from "./task.js";
|
|
5
|
+
import { todoTool } from "./todo.js";
|
|
6
|
+
/** The built-in tools, in the order the model sees them. */
|
|
7
|
+
export const BUILTIN_TOOLS = [
|
|
8
|
+
readTool,
|
|
9
|
+
editTool,
|
|
10
|
+
writeTool,
|
|
11
|
+
bashTool,
|
|
12
|
+
grepTool,
|
|
13
|
+
findTool,
|
|
14
|
+
todoTool,
|
|
15
|
+
taskTool,
|
|
16
|
+
];
|
|
17
|
+
/** The `tools` array for a chat request. */
|
|
18
|
+
export const toolSchemas = (tools) => tools.map((t) => ({
|
|
19
|
+
type: "function",
|
|
20
|
+
function: { name: t.name, description: t.description, parameters: t.parameters },
|
|
21
|
+
}));
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { realpath } from "node:fs/promises";
|
|
2
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { isInside } from "../permissions.js";
|
|
4
|
+
/**
|
|
5
|
+
* An absolute path with symlinks followed, so a link inside the project that points elsewhere is
|
|
6
|
+
* judged by where it really leads. For paths that don't exist yet (a new file), the nearest
|
|
7
|
+
* existing folder is resolved and the rest appended.
|
|
8
|
+
*/
|
|
9
|
+
export async function resolvePath(input, cwd, home) {
|
|
10
|
+
const expanded = input === "~"
|
|
11
|
+
? home
|
|
12
|
+
: input.startsWith(`~${sep}`) || input.startsWith("~/")
|
|
13
|
+
? join(home, input.slice(2))
|
|
14
|
+
: input;
|
|
15
|
+
const absolute = isAbsolute(expanded) ? resolve(expanded) : resolve(cwd, expanded);
|
|
16
|
+
const missing = [];
|
|
17
|
+
let current = absolute;
|
|
18
|
+
for (;;) {
|
|
19
|
+
try {
|
|
20
|
+
const real = await realpath(current);
|
|
21
|
+
return missing.length ? join(real, ...missing.reverse()) : real;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
const parent = dirname(current);
|
|
25
|
+
if (parent === current)
|
|
26
|
+
return absolute;
|
|
27
|
+
missing.push(basename(current));
|
|
28
|
+
current = parent;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** `~/…` for paths in the home folder, else the path as is. */
|
|
33
|
+
export function tildePath(path, home) {
|
|
34
|
+
if (path === home)
|
|
35
|
+
return "~";
|
|
36
|
+
return isInside(path, home) ? `~${sep}${relative(home, path)}` : path;
|
|
37
|
+
}
|
|
38
|
+
/** How a path is shown: relative inside the project, `~/…` in the home folder, else absolute. */
|
|
39
|
+
export function displayPath(path, cwd, home) {
|
|
40
|
+
if (isInside(path, cwd))
|
|
41
|
+
return relative(cwd, path) || ".";
|
|
42
|
+
return tildePath(path, home);
|
|
43
|
+
}
|