reasonally 0.2.0 → 0.4.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.
@@ -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,23 @@
1
+ import { bashTool } from "./bash.js";
2
+ import { editTool, readTool, writeTool } from "./files.js";
3
+ import { planTool } from "./plan.js";
4
+ import { findTool, grepTool } from "./search.js";
5
+ import { taskTool } from "./task.js";
6
+ import { todoTool } from "./todo.js";
7
+ /** The built-in tools, in the order the model sees them. */
8
+ export const BUILTIN_TOOLS = [
9
+ readTool,
10
+ editTool,
11
+ writeTool,
12
+ bashTool,
13
+ grepTool,
14
+ findTool,
15
+ todoTool,
16
+ taskTool,
17
+ planTool,
18
+ ];
19
+ /** The `tools` array for a chat request. */
20
+ export const toolSchemas = (tools) => tools.map((t) => ({
21
+ type: "function",
22
+ function: { name: t.name, description: t.description, parameters: t.parameters },
23
+ }));
@@ -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
+ }
@@ -0,0 +1,101 @@
1
+ import { stringArg, ToolInputError } from "./types.js";
2
+ /** The tool the agent presents its plan with, in Plan mode. The loop answers it (see loop.ts). */
3
+ export const PLAN_TOOL = "present_plan";
4
+ export const MAX_PLAN_CHARS = 20_000;
5
+ /** One line for the transcript, the same in every app. */
6
+ export const PLAN_OUTCOME_LABELS = {
7
+ "approved-ask": "Plan approved · ask before edits",
8
+ "approved-auto": "Plan approved · auto-accept edits",
9
+ "sent-back": "Plan sent back",
10
+ "not-approved": "Plan not approved",
11
+ stopped: "Stopped",
12
+ };
13
+ /** The plan's title: its first heading, or else its first line, as plain text. */
14
+ export function planTitle(plan) {
15
+ const lines = plan.split("\n").map((l) => l.trim());
16
+ const line = lines.find((l) => /^#{1,6}\s/.test(l)) ?? lines.find(Boolean) ?? "";
17
+ const plain = line
18
+ .replace(/^#{1,6}\s+/, "")
19
+ .replace(/^(?:[-*+]|\d+[.)])\s+/, "")
20
+ .replace(/[*_`]/g, "")
21
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
22
+ .trim();
23
+ return plain.length > 80 ? `${plain.slice(0, 79)}…` : plain || "Plan";
24
+ }
25
+ export const planTool = {
26
+ name: PLAN_TOOL,
27
+ description: "Plan mode only: show the user your plan and ask them to approve it. Write it in Markdown: " +
28
+ "a short title (# …), the goal in a sentence or two, numbered steps naming the files each " +
29
+ "touches, and how you'll check the result. Keep it short enough to read in a minute. Call it " +
30
+ "once, when the plan is complete, as the last call in your reply. The user may approve it " +
31
+ "(you then carry it out), edit it, or send it back with what to change.",
32
+ parameters: {
33
+ type: "object",
34
+ properties: {
35
+ plan: { type: "string", description: "The plan, in Markdown." },
36
+ },
37
+ required: ["plan"],
38
+ additionalProperties: false,
39
+ },
40
+ async prepare(args) {
41
+ const plan = stringArg(args, "plan").trim();
42
+ if (!plan)
43
+ throw new ToolInputError("`plan` is empty. Write the plan in Markdown.");
44
+ if (plan.length > MAX_PLAN_CHARS) {
45
+ throw new ToolInputError(`The plan is ${plan.length.toLocaleString("en-US")} characters; keep it under ` +
46
+ `${MAX_PLAN_CHARS.toLocaleString("en-US")}. Summarize the steps instead of including code.`);
47
+ }
48
+ return {
49
+ kind: "meta",
50
+ paths: [],
51
+ title: "Plan",
52
+ preview: plan,
53
+ // The loop shows the plan and waits for the user's answer instead of running this.
54
+ run: async () => ({ output: plan, summary: "Plan" }),
55
+ };
56
+ },
57
+ };
58
+ /**
59
+ * The `plan` string so far from a tool call's streaming arguments (`{"plan": "# Add a…`), or null
60
+ * before it starts. Escapes are decoded; an escape cut off at the end is left out until it's whole.
61
+ */
62
+ export function partialPlan(args) {
63
+ const key = /"plan"\s*:\s*"/.exec(args);
64
+ if (!key)
65
+ return null;
66
+ let out = "";
67
+ for (let i = key.index + key[0].length; i < args.length; i++) {
68
+ const c = args[i];
69
+ if (c === '"')
70
+ return out;
71
+ if (c !== "\\") {
72
+ out += c;
73
+ continue;
74
+ }
75
+ const next = args[i + 1];
76
+ if (next === undefined)
77
+ return out;
78
+ if (next === "u") {
79
+ const hex = args.slice(i + 2, i + 6);
80
+ if (hex.length < 4)
81
+ return out;
82
+ if (/^[0-9a-fA-F]{4}$/.test(hex))
83
+ out += String.fromCharCode(parseInt(hex, 16));
84
+ i += 5;
85
+ continue;
86
+ }
87
+ const simple = {
88
+ n: "\n",
89
+ t: "\t",
90
+ r: "\r",
91
+ b: "\b",
92
+ f: "\f",
93
+ '"': '"',
94
+ "\\": "\\",
95
+ "/": "/",
96
+ };
97
+ out += simple[next] ?? next;
98
+ i++;
99
+ }
100
+ return out;
101
+ }