@preapexis/honeycomb 0.0.0-stage → 1.1.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.
Files changed (97) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +443 -2
  3. package/bin/bee.js +18 -0
  4. package/package.json +66 -4
  5. package/plan/tools/tool-parity.md +61 -0
  6. package/src/commands/btw.ts +95 -0
  7. package/src/commands/claude-migrate.ts +63 -0
  8. package/src/commands/diff.ts +119 -0
  9. package/src/commands/discovery.ts +112 -0
  10. package/src/commands/doctor.ts +80 -0
  11. package/src/commands/goal/index.ts +254 -0
  12. package/src/commands/goal/report.ts +66 -0
  13. package/src/commands/goal/state.ts +74 -0
  14. package/src/commands/hooks.ts +38 -0
  15. package/src/commands/index.ts +13 -0
  16. package/src/commands/init.ts +66 -0
  17. package/src/commands/memory.ts +70 -0
  18. package/src/commands/plan.ts +36 -0
  19. package/src/commands/review-report.ts +23 -0
  20. package/src/commands/review.ts +21 -0
  21. package/src/commands/rewind-history.ts +40 -0
  22. package/src/commands/security-review.ts +138 -0
  23. package/src/commands/simplify.ts +21 -0
  24. package/src/commands/stats.ts +125 -0
  25. package/src/commands/tasks.ts +87 -0
  26. package/src/commands/verify.ts +21 -0
  27. package/src/commands/worktree.ts +138 -0
  28. package/src/config/bi.config.json +77 -0
  29. package/src/config/index.ts +47 -0
  30. package/src/config/limits.ts +12 -0
  31. package/src/config/path-rules.ts +19 -0
  32. package/src/config/project.ts +133 -0
  33. package/src/extension/ask-user.ts +52 -0
  34. package/src/extension/index.ts +4 -0
  35. package/src/extension/lsp-install.ts +95 -0
  36. package/src/extension/lsp-menu.ts +90 -0
  37. package/src/extension/permission-modes/index.ts +337 -0
  38. package/src/extension/permission-modes/mcp-resources.ts +21 -0
  39. package/src/extension/permission-modes/metadata.ts +18 -0
  40. package/src/extension/permission-modes/paths.ts +44 -0
  41. package/src/extension/permission-modes/plan-note.ts +58 -0
  42. package/src/extension/permission-modes/policy.ts +236 -0
  43. package/src/extension/permission-modes/preview.ts +104 -0
  44. package/src/extension/permission-modes/rules.ts +67 -0
  45. package/src/extension/permission-modes/shell.ts +183 -0
  46. package/src/extension/permission-modes/state.ts +6 -0
  47. package/src/extension/quiet-startup.ts +25 -0
  48. package/src/extension/register-tools.ts +312 -0
  49. package/src/extension/scoped-rules.ts +91 -0
  50. package/src/extension/system-instruction.ts +74 -0
  51. package/src/index.ts +71 -0
  52. package/src/tools/advanced.ts +133 -0
  53. package/src/tools/agent.ts +379 -0
  54. package/src/tools/dispatcher.ts +80 -0
  55. package/src/tools/executable.ts +15 -0
  56. package/src/tools/execution.ts +289 -0
  57. package/src/tools/filesystem.ts +662 -0
  58. package/src/tools/git.ts +196 -0
  59. package/src/tools/glob.ts +81 -0
  60. package/src/tools/grep.ts +203 -0
  61. package/src/tools/image-read.ts +71 -0
  62. package/src/tools/index.ts +52 -0
  63. package/src/tools/lsp-client.ts +104 -0
  64. package/src/tools/lsp.ts +172 -0
  65. package/src/tools/memory-store.ts +77 -0
  66. package/src/tools/notebook.ts +169 -0
  67. package/src/tools/registry.ts +31 -0
  68. package/src/tools/shells.ts +63 -0
  69. package/src/tools/todo.ts +119 -0
  70. package/src/tools/undo-journal.ts +46 -0
  71. package/src/tools/web-fetch.ts +119 -0
  72. package/src/tools/web-search.ts +76 -0
  73. package/src/tools/write-file.ts +14 -0
  74. package/src/tui/editor.ts +65 -0
  75. package/src/tui/footer-stats.ts +35 -0
  76. package/src/tui/header.ts +81 -0
  77. package/src/tui/index.ts +124 -0
  78. package/src/tui/mascot.ts +59 -0
  79. package/src/tui/permission-dialog.ts +94 -0
  80. package/src/tui/permission-rules.ts +64 -0
  81. package/src/tui/tasks-panel.ts +84 -0
  82. package/src/tui/text.ts +55 -0
  83. package/src/tui/tool-renderer.ts +42 -0
  84. package/src/tui/working-feedback.ts +220 -0
  85. package/src/types/agent.ts +54 -0
  86. package/src/types/common.ts +1 -0
  87. package/src/types/execution.ts +24 -0
  88. package/src/types/index.ts +4 -0
  89. package/src/types/tools.ts +61 -0
  90. package/themes/catppuccin-mocha.json +80 -0
  91. package/themes/github-dark.json +80 -0
  92. package/themes/honeycomb-dark.json +81 -0
  93. package/themes/honeycomb-light.json +81 -0
  94. package/themes/tokyo-day.json +80 -0
  95. package/themes/tokyo-night.json +80 -0
  96. package/themes/vercel-black.json +80 -0
  97. package/themes/vercel-light.json +80 -0
@@ -0,0 +1,662 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { promises as fs } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { MAX_UNDO_FILE_BYTES, type UndoJournal } from './undo-journal.ts';
5
+ import { writeUnlinkedFile } from './write-file.ts';
6
+ import { createGlobTool } from './glob.ts';
7
+ import { createGrepTool } from './grep.ts';
8
+ import { createNotebookTool } from './notebook.ts';
9
+ import { imageMime, readImage } from './image-read.ts';
10
+ import { BI_CONFIG } from '../config/index.ts';
11
+ import { CONFIG_LIMITS } from '../config/limits.ts';
12
+ import type { Args, Tool, ToolContext } from '../types/index.ts';
13
+
14
+ const READ_LINE_TRUNCATION_MARKER = '... [truncated]';
15
+
16
+ interface FileSnapshot {
17
+ size: number;
18
+ mtimeMs: number;
19
+ sha256: string;
20
+ }
21
+
22
+ /**
23
+ * Creates the Phase 2 filesystem tools. All paths are relative to the active
24
+ * working directory, and resolved paths (including symlinks) must stay inside it.
25
+ */
26
+ export function createFileSystemTools(options: {
27
+ journal?: UndoJournal;
28
+ defaultReadLimit?: number;
29
+ maxReadLineLength?: number;
30
+ maxGrepMatches?: number;
31
+ } = {}): Tool<Args>[] {
32
+ const defaultReadLimit = options.defaultReadLimit ?? BI_CONFIG.filesystem.defaultReadLimit;
33
+ const maxReadLineLength = options.maxReadLineLength ?? BI_CONFIG.filesystem.maxReadLineLength;
34
+ const maxGrepMatches = options.maxGrepMatches ?? BI_CONFIG.filesystem.maxGrepMatches;
35
+ if (!Number.isInteger(defaultReadLimit) || defaultReadLimit < 1 || defaultReadLimit > CONFIG_LIMITS.maxReadLimit) {
36
+ throw new Error(`filesystem.defaultReadLimit must be an integer from 1 to ${CONFIG_LIMITS.maxReadLimit}`);
37
+ }
38
+ if (!Number.isInteger(maxReadLineLength) || maxReadLineLength < READ_LINE_TRUNCATION_MARKER.length ||
39
+ maxReadLineLength > CONFIG_LIMITS.maxReadLineLength) {
40
+ throw new Error(`filesystem.maxReadLineLength must be an integer from ${READ_LINE_TRUNCATION_MARKER.length} to ${CONFIG_LIMITS.maxReadLineLength}`);
41
+ }
42
+ if (!Number.isInteger(maxGrepMatches) || maxGrepMatches < 1 || maxGrepMatches > CONFIG_LIMITS.maxGrepMatches) {
43
+ throw new Error(`filesystem.maxGrepMatches must be an integer from 1 to ${CONFIG_LIMITS.maxGrepMatches}`);
44
+ }
45
+ const snapshots = new Map<string, Map<string, FileSnapshot>>();
46
+ if (options.journal) options.journal.invalidateSnapshots = (ctx, files) => {
47
+ const saved = snapshots.get(ctx.sessionId);
48
+ for (const file of files) saved?.delete(file);
49
+ };
50
+ return [
51
+ tool('read', 'Read UTF-8 text by line range, or attach a small local PNG/JPEG after approval. Text offset is 1-indexed; omit offset and limit for images.', {
52
+ path: 'string', offset: 'number?', limit: 'number?',
53
+ }, async (a, c) => {
54
+ const offset = a.offset === undefined ? 1 : a.offset as number;
55
+ const limit = a.limit === undefined
56
+ ? c.projectConfig?.filesystem?.defaultReadLimit ?? defaultReadLimit
57
+ : a.limit as number;
58
+ const lineLength = c.projectConfig?.filesystem?.maxReadLineLength ?? maxReadLineLength;
59
+ if (!Number.isInteger(offset) || offset < 1) {
60
+ return { success: false, error: 'read: "offset" must be a positive integer (1-indexed)' };
61
+ }
62
+ if (!Number.isInteger(limit) || limit < 1) {
63
+ return { success: false, error: 'read: "limit" must be a positive integer' };
64
+ }
65
+ const requested = stringArg(a, 'path');
66
+ const file = await resolvePath(c, requested);
67
+ if (imageMime(requested)) {
68
+ if (a.offset !== undefined || a.limit !== undefined) return { success: false, error: 'Omit offset and limit when reading images' };
69
+ return readImage(requested, file, c);
70
+ }
71
+ const bytes = await fs.readFile(file);
72
+ const stat = await fs.stat(file);
73
+ const sessionSnapshots = snapshotsForSession(snapshots, c);
74
+ const text = bytes.toString('utf8');
75
+ const lines = splitReadLines(text);
76
+ const start = offset - 1;
77
+ if (start >= lines.length && (lines.length > 0 || a.offset !== undefined)) {
78
+ return { success: false, error: `read: offset ${offset} is beyond end of file (${lines.length} lines total)` };
79
+ }
80
+ const selected = lines.slice(start, start + limit);
81
+ let output = selected.map((line) => `${truncateReadLine(line.text, lineLength)}${line.ending}`).join('');
82
+ const end = start + selected.length;
83
+ if (start > 0 || end < lines.length) {
84
+ const separator = output.endsWith('\n') || output.endsWith('\r') ? '\n' : '\n\n';
85
+ output += `${separator}Showing lines ${offset}-${end} of ${lines.length}...`;
86
+ }
87
+ sessionSnapshots.set(file, snapshot(stat, bytes));
88
+ return { success: true, output };
89
+ }),
90
+ tool('write', 'Create or overwrite a UTF-8 text file', { path: 'string', content: 'string' }, async (a, c) => {
91
+ const file = await resolvePath(c, stringArg(a, 'path'), true);
92
+ await fs.mkdir(path.dirname(file), { recursive: true });
93
+ const content = stringArg(a, 'content');
94
+ let before: Buffer | null | undefined;
95
+ if (options.journal && Buffer.byteLength(content) <= MAX_UNDO_FILE_BYTES) {
96
+ try {
97
+ const stat = await fs.lstat(file);
98
+ if (stat.isFile() && stat.nlink === 1 && stat.size <= MAX_UNDO_FILE_BYTES) before = await fs.readFile(file);
99
+ } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') before = null; }
100
+ }
101
+ await writeUnlinkedFile(file, content);
102
+ options.journal?.record(c, before === undefined || before?.includes(0) ? [] : [{
103
+ id: randomUUID(), file, before, afterHash: sha256(Buffer.from(content)),
104
+ }]);
105
+ return { success: true, output: `Wrote ${file}` };
106
+ }),
107
+ createEditTool(snapshots, options.journal),
108
+ ...(options.journal ? [createNotebookTool({
109
+ journal: options.journal,
110
+ readHash: (ctx, file) => snapshots.get(ctx.sessionId)?.get(file)?.sha256,
111
+ atomicReplace,
112
+ })] : []),
113
+ tool('ls', 'List directory entries', { path: 'string?' }, async (a, c) => {
114
+ const dir = await resolvePath(c, optionalString(a, 'path') ?? '.');
115
+ const entries = await fs.readdir(dir, { withFileTypes: true });
116
+ return { success: true, output: entries.map((e) => `${e.isDirectory() ? 'dir' : 'file'} ${e.name}`).join('\n') };
117
+ }),
118
+ tool('find', 'Find files and directories by name substring', { path: 'string?', name: 'string' }, async (a, c) => {
119
+ const root = await resolvePath(c, optionalString(a, 'path') ?? '.');
120
+ const name = stringArg(a, 'name');
121
+ const matches: string[] = [];
122
+ const walk = async (dir: string): Promise<void> => {
123
+ for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
124
+ const full = path.join(dir, entry.name);
125
+ if (entry.name.includes(name)) matches.push(path.relative(root, full));
126
+ if (entry.isDirectory() && !entry.isSymbolicLink()) await walk(full);
127
+ }
128
+ };
129
+ await walk(root);
130
+ return { success: true, output: matches.join('\n') };
131
+ }),
132
+ createGlobTool(),
133
+ createGrepTool(maxGrepMatches, resolvePath),
134
+ tool('mkdir', 'Create a directory', { path: 'string' }, async (a, c) => {
135
+ const dir = await resolvePath(c, stringArg(a, 'path'), true);
136
+ await fs.mkdir(dir, { recursive: true });
137
+ return { success: true, output: `Created ${dir}` };
138
+ }),
139
+ tool('delete', 'Delete a file or directory (requires approval)', { path: 'string' }, async (a, c) => {
140
+ const target = await resolvePath(c, stringArg(a, 'path'));
141
+ if (!c.confirmDestructive || !(await c.confirmDestructive('delete', target))) {
142
+ return { success: false, error: 'Deletion was not approved' };
143
+ }
144
+ await fs.rm(target, { recursive: true, force: false });
145
+ return { success: true, output: `Deleted ${target}` };
146
+ }),
147
+ tool('move', 'Move or rename a file or directory', { source: 'string', destination: 'string' }, async (a, c) => {
148
+ const source = await resolvePath(c, stringArg(a, 'source'));
149
+ const destination = await resolvePath(c, stringArg(a, 'destination'), true);
150
+ await fs.mkdir(path.dirname(destination), { recursive: true });
151
+ await fs.rename(source, destination);
152
+ return { success: true, output: `Moved ${source} to ${destination}` };
153
+ }),
154
+ tool('copy', 'Copy a file or directory', { source: 'string', destination: 'string' }, async (a, c) => {
155
+ const source = await resolvePath(c, stringArg(a, 'source'));
156
+ const destination = await resolvePath(c, stringArg(a, 'destination'), true);
157
+ await fs.cp(source, destination, { recursive: true, errorOnExist: true, force: false });
158
+ return { success: true, output: `Copied ${source} to ${destination}` };
159
+ }),
160
+ ];
161
+ }
162
+
163
+ function createEditTool(snapshots: Map<string, Map<string, FileSnapshot>>, journal?: UndoJournal): Tool<Args> {
164
+ return {
165
+ name: 'edit',
166
+ description: 'Replace exact text in a file that was read in this session. Read the file first; edits fail if it has not been read or has changed since reading. old_str must be unique unless replace_all is true; add more context if it is ambiguous. Use replace_all for intentional renames and edits for multiple non-overlapping changes in one file. Each edit matches the original file content. In mixed-ending files, inserted newlines use the first newline style found; untouched line endings are preserved.',
167
+ parameters: {
168
+ type: 'object',
169
+ properties: {
170
+ path: { type: 'string' },
171
+ old_str: { type: 'string' },
172
+ new_str: { type: 'string' },
173
+ replace_all: { type: 'boolean', default: false },
174
+ edits: {
175
+ type: 'array',
176
+ minItems: 1,
177
+ items: {
178
+ type: 'object',
179
+ properties: {
180
+ old_str: { type: 'string' },
181
+ new_str: { type: 'string' },
182
+ replace_all: { type: 'boolean', default: false },
183
+ },
184
+ required: ['old_str', 'new_str'],
185
+ additionalProperties: false,
186
+ },
187
+ },
188
+ },
189
+ required: ['path'],
190
+ additionalProperties: false,
191
+ },
192
+ validate: (args): args is Args => {
193
+ if (!isRecord(args)) return false;
194
+ const normalized = normalizeLegacyParams(args);
195
+ if (!normalized.error) {
196
+ Object.assign(args, normalized.args);
197
+ delete args.oldText;
198
+ delete args.newText;
199
+ }
200
+ return true;
201
+ },
202
+ execute: (args, context) => executeEdit(args, context, snapshots, journal),
203
+ };
204
+ }
205
+
206
+ interface TextEdit {
207
+ oldText: string;
208
+ newText: string;
209
+ replaceAll: boolean;
210
+ }
211
+
212
+ function normalizeLegacyParams(args: Args): { args: Args; error?: string } {
213
+ const hasLegacy = Object.hasOwn(args, 'oldText') || Object.hasOwn(args, 'newText');
214
+ if (!hasLegacy) return { args };
215
+ if (Object.hasOwn(args, 'old_str') || Object.hasOwn(args, 'new_str')) {
216
+ return { args, error: 'edit: do not mix legacy oldText/newText with old_str/new_str' };
217
+ }
218
+ const normalized: Args = { ...args, old_str: args.oldText, new_str: args.newText };
219
+ delete normalized.oldText;
220
+ delete normalized.newText;
221
+ return { args: normalized };
222
+ }
223
+
224
+ async function executeEdit(
225
+ input: Args,
226
+ context: ToolContext,
227
+ snapshots: Map<string, Map<string, FileSnapshot>>,
228
+ journal?: UndoJournal,
229
+ ) {
230
+ const normalized = normalizeLegacyParams(input);
231
+ if (normalized.error) return { success: false, error: normalized.error };
232
+ const args = normalized.args;
233
+ const inputPath = args.path;
234
+ if (typeof inputPath !== 'string' || inputPath.length === 0) {
235
+ return { success: false, error: 'edit: "path" must be a non-empty string' };
236
+ }
237
+ if (args.replace_all !== undefined && typeof args.replace_all !== 'boolean') {
238
+ return { success: false, error: 'edit: "replace_all" must be a boolean' };
239
+ }
240
+
241
+ const hasSingle = Object.hasOwn(args, 'old_str') || Object.hasOwn(args, 'new_str');
242
+ const hasEdits = Object.hasOwn(args, 'edits');
243
+ if (hasSingle && hasEdits) {
244
+ return { success: false, error: 'edit: provide either old_str/new_str or edits, not both' };
245
+ }
246
+ if (!hasSingle && !hasEdits) {
247
+ return { success: false, error: 'edit: provide old_str/new_str or a non-empty edits array' };
248
+ }
249
+
250
+ let edits: TextEdit[];
251
+ const defaultReplaceAll = args.replace_all === true;
252
+ if (hasEdits) {
253
+ if (!Array.isArray(args.edits)) return { success: false, error: 'edit: "edits" must be an array' };
254
+ if (args.edits.length === 0) return { success: false, error: 'edit: "edits" must not be empty' };
255
+ edits = [];
256
+ for (let index = 0; index < args.edits.length; index++) {
257
+ const item = args.edits[index];
258
+ if (!isRecord(item)) return editFailure(index, 'must be an object');
259
+ if (typeof item.old_str !== 'string' || typeof item.new_str !== 'string') {
260
+ return editFailure(index, 'must include string "old_str" and "new_str" values');
261
+ }
262
+ if (item.replace_all !== undefined && typeof item.replace_all !== 'boolean') {
263
+ return editFailure(index, '"replace_all" must be a boolean');
264
+ }
265
+ edits.push({
266
+ oldText: item.old_str,
267
+ newText: item.new_str,
268
+ replaceAll: item.replace_all === undefined ? defaultReplaceAll : item.replace_all,
269
+ });
270
+ }
271
+ } else {
272
+ if (typeof args.old_str !== 'string' || typeof args.new_str !== 'string') {
273
+ return { success: false, error: 'edit: old_str and new_str must both be strings' };
274
+ }
275
+ edits = [{ oldText: args.old_str, newText: args.new_str, replaceAll: defaultReplaceAll }];
276
+ }
277
+
278
+ let file: string;
279
+ try {
280
+ file = await resolvePath(context, inputPath);
281
+ } catch (error) {
282
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
283
+ return { success: false, error: `edit: file not found: ${inputPath}` };
284
+ }
285
+ return { success: false, error: `edit: ${errorMessage(error)}` };
286
+ }
287
+
288
+ const sessionSnapshots = snapshotsForSession(snapshots, context);
289
+ const previousSnapshot = sessionSnapshots.get(file);
290
+ if (!previousSnapshot) {
291
+ return { success: false, error: `edit: ${inputPath} has not been read in this session` };
292
+ }
293
+
294
+ let stat;
295
+ let bytes: Buffer;
296
+ try {
297
+ stat = await fs.stat(file);
298
+ if (!stat.isFile()) return { success: false, error: `edit: ${inputPath} is not a regular file` };
299
+ bytes = await fs.readFile(file);
300
+ } catch (error) {
301
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
302
+ return { success: false, error: `edit: file not found: ${inputPath}` };
303
+ }
304
+ return { success: false, error: `edit: cannot read ${inputPath}: ${errorMessage(error)}` };
305
+ }
306
+
307
+ if (stat.size !== previousSnapshot.size || stat.mtimeMs !== previousSnapshot.mtimeMs) {
308
+ const currentHash = sha256(bytes);
309
+ if (currentHash !== previousSnapshot.sha256) {
310
+ return { success: false, error: `edit: ${inputPath} has changed since it was read` };
311
+ }
312
+ sessionSnapshots.set(file, snapshot(stat, bytes));
313
+ }
314
+
315
+ const hasBom = bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;
316
+ const textBytes = hasBom ? bytes.subarray(3) : bytes;
317
+ if (textBytes.includes(0)) return { success: false, error: `edit: ${inputPath} is a binary file` };
318
+ let original: string;
319
+ try {
320
+ original = new TextDecoder('utf-8', { fatal: true }).decode(textBytes);
321
+ } catch {
322
+ return { success: false, error: `edit: ${inputPath} is not valid UTF-8` };
323
+ }
324
+ if (/[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(original)) {
325
+ return { success: false, error: `edit: ${inputPath} is a binary file` };
326
+ }
327
+
328
+ // For mixed-ending files, replacement snippets use the first newline sequence found.
329
+ // The original content is never normalized, so all untouched line endings stay unchanged.
330
+ const lineEnding = original.match(/\r\n|\n|\r/)?.[0] ?? '\n';
331
+ const replacements: Array<{ editIndex: number; start: number; end: number; text: string }> = [];
332
+ for (let index = 0; index < edits.length; index++) {
333
+ const edit = edits[index];
334
+ if (edit.oldText.length === 0) return editFailure(index, 'old_str must not be empty');
335
+ if (edit.oldText === edit.newText) return editFailure(index, 'old_str and new_str must be different');
336
+ const oldText = normalizeLineEndings(edit.oldText, lineEnding);
337
+ const newText = normalizeLineEndings(edit.newText, lineEnding);
338
+ if (oldText === newText) return editFailure(index, 'old_str and new_str must be different');
339
+ const positions = findOccurrences(original, oldText);
340
+ if (positions.length === 0) return editFailure(index, `old_str was not found in ${inputPath}`);
341
+ if (positions.length > 1 && !edit.replaceAll) {
342
+ const lineNumbers = positions.map((position) => lineNumberAt(original, position));
343
+ return editFailure(index,
344
+ `old_str matches ${positions.length} times on lines ${lineNumbers.join(', ')}; add more context or set replace_all to true`);
345
+ }
346
+ for (const start of edit.replaceAll ? positions : [positions[0]]) {
347
+ replacements.push({ editIndex: index, start, end: start + oldText.length, text: newText });
348
+ }
349
+ }
350
+
351
+ replacements.sort((a, b) => a.start - b.start || a.end - b.end);
352
+ let previous = replacements[0];
353
+ for (let index = 1; index < replacements.length; index++) {
354
+ const current = replacements[index];
355
+ if (current.start < previous.end) {
356
+ return {
357
+ success: false,
358
+ error: `edit: edit ${previous.editIndex + 1} overlaps edit ${current.editIndex + 1}; edits must target non-overlapping original text`,
359
+ };
360
+ }
361
+ if (current.end > previous.end) previous = current;
362
+ }
363
+
364
+ let updated = '';
365
+ let cursor = 0;
366
+ for (const replacement of replacements) {
367
+ updated += original.slice(cursor, replacement.start) + replacement.text;
368
+ cursor = replacement.end;
369
+ }
370
+ updated += original.slice(cursor);
371
+
372
+ const outputBytes = Buffer.concat([hasBom ? Buffer.from([0xef, 0xbb, 0xbf]) : Buffer.alloc(0), Buffer.from(updated, 'utf8')]);
373
+ try {
374
+ await atomicReplace(file, outputBytes, stat.mode);
375
+ } catch (error) {
376
+ return { success: false, error: `edit: could not write ${inputPath}: ${errorMessage(error)}` };
377
+ }
378
+ journal?.record(context, stat.nlink !== 1 || outputBytes.length > MAX_UNDO_FILE_BYTES ? [] : [{ id: randomUUID(), file, before: bytes, afterHash: sha256(outputBytes) }]);
379
+ sessionSnapshots.set(file, snapshot(await fs.stat(file), outputBytes));
380
+
381
+ const diff = unifiedDiff(original, updated, inputPath);
382
+ return {
383
+ success: true,
384
+ output: `${replacements.length} replacement${replacements.length === 1 ? '' : 's'} in ${inputPath}\n${diff}`,
385
+ };
386
+ }
387
+
388
+ function editFailure(index: number, reason: string) {
389
+ return { success: false, error: `edit: edit ${index + 1} failed: ${reason}` };
390
+ }
391
+
392
+ function normalizeLineEndings(text: string, lineEnding: string): string {
393
+ return text.replace(/\r\n|\r|\n/g, lineEnding);
394
+ }
395
+
396
+ function findOccurrences(text: string, needle: string): number[] {
397
+ const positions: number[] = [];
398
+ let position = 0;
399
+ while ((position = text.indexOf(needle, position)) !== -1) {
400
+ positions.push(position);
401
+ position += needle.length;
402
+ }
403
+ return positions;
404
+ }
405
+
406
+ function lineNumberAt(text: string, position: number): number {
407
+ let line = 1;
408
+ for (let index = 0; index < position; index++) if (text[index] === '\n') line++;
409
+ return line;
410
+ }
411
+
412
+ export async function atomicReplace(file: string, contents: Buffer, mode: number, validate?: () => Promise<void>): Promise<void> {
413
+ const target = await fs.realpath(file);
414
+ if (validate && target !== file) throw new Error('Replace target changed');
415
+ const temp = path.join(path.dirname(target), `.${path.basename(target)}.${process.pid}.${randomUUID()}.tmp`);
416
+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
417
+ try {
418
+ handle = await fs.open(temp, 'wx', mode & 0o7777);
419
+ await handle.writeFile(contents);
420
+ await handle.sync();
421
+ await handle.close();
422
+ handle = undefined;
423
+ await fs.chmod(temp, mode & 0o7777);
424
+ await validate?.();
425
+ await fs.rename(temp, target);
426
+ } catch (error) {
427
+ if (handle) await handle.close().catch(() => undefined);
428
+ await fs.rm(temp, { force: true }).catch(() => undefined);
429
+ throw error;
430
+ }
431
+ }
432
+
433
+ interface DiffLine {
434
+ type: ' ' | '+' | '-';
435
+ text: string;
436
+ }
437
+
438
+ function unifiedDiff(before: string, after: string, filePath: string): string {
439
+ const oldLines = diffLines(before);
440
+ const newLines = diffLines(after);
441
+ const operations = lineDiff(oldLines, newLines);
442
+ const changed = operations.flatMap((operation, index) => operation.type === ' ' ? [] : [index]);
443
+ if (changed.length === 0) return `--- a/${filePath}\n+++ b/${filePath}\n(no textual diff)`;
444
+
445
+ const ranges: Array<{ start: number; end: number }> = [];
446
+ for (const index of changed) {
447
+ const start = Math.max(0, index - 3);
448
+ const end = Math.min(operations.length, index + 4);
449
+ const last = ranges[ranges.length - 1];
450
+ if (last && start <= last.end) last.end = Math.max(last.end, end);
451
+ else ranges.push({ start, end });
452
+ }
453
+
454
+ const output = [`--- a/${filePath}`, `+++ b/${filePath}`];
455
+ for (const range of ranges) {
456
+ const rangeOps = operations.slice(range.start, range.end);
457
+ const oldCount = rangeOps.filter((operation) => operation.type !== '+').length;
458
+ const newCount = rangeOps.filter((operation) => operation.type !== '-').length;
459
+ const oldBefore = operations.slice(0, range.start).filter((operation) => operation.type !== '+').length;
460
+ const newBefore = operations.slice(0, range.start).filter((operation) => operation.type !== '-').length;
461
+ const oldStart = oldBefore + (oldCount === 0 ? 0 : 1);
462
+ const newStart = newBefore + (newCount === 0 ? 0 : 1);
463
+ output.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`);
464
+ for (const operation of rangeOps) output.push(`${operation.type}${operation.text}`);
465
+ }
466
+
467
+ const maxLines = 100;
468
+ if (output.length > maxLines) return [...output.slice(0, maxLines), '... diff truncated ...'].join('\n');
469
+ const rendered = output.join('\n');
470
+ const maxCharacters = 12_000;
471
+ return rendered.length > maxCharacters
472
+ ? `${rendered.slice(0, maxCharacters)}\n... diff truncated ...`
473
+ : rendered;
474
+ }
475
+
476
+ function diffLines(text: string): string[] {
477
+ if (text.length === 0) return [];
478
+ const lines = text.replace(/\r\n|\r/g, '\n').split('\n');
479
+ if (lines[lines.length - 1] === '') lines.pop();
480
+ return lines;
481
+ }
482
+
483
+ function lineDiff(oldLines: string[], newLines: string[]): DiffLine[] {
484
+ const oldLength = oldLines.length;
485
+ const newLength = newLines.length;
486
+ const width = newLength + 1;
487
+ if ((oldLength + 1) * width > 1_000_000) return coarseLineDiff(oldLines, newLines);
488
+ const table = new Uint32Array((oldLength + 1) * width);
489
+ for (let oldIndex = oldLength - 1; oldIndex >= 0; oldIndex--) {
490
+ for (let newIndex = newLength - 1; newIndex >= 0; newIndex--) {
491
+ const cell = oldIndex * width + newIndex;
492
+ table[cell] = oldLines[oldIndex] === newLines[newIndex]
493
+ ? table[(oldIndex + 1) * width + newIndex + 1] + 1
494
+ : Math.max(table[(oldIndex + 1) * width + newIndex], table[oldIndex * width + newIndex + 1]);
495
+ }
496
+ }
497
+
498
+ const operations: DiffLine[] = [];
499
+ let oldIndex = 0;
500
+ let newIndex = 0;
501
+ while (oldIndex < oldLength && newIndex < newLength) {
502
+ if (oldLines[oldIndex] === newLines[newIndex]) {
503
+ operations.push({ type: ' ', text: oldLines[oldIndex++] });
504
+ newIndex++;
505
+ } else if (table[(oldIndex + 1) * width + newIndex] >= table[oldIndex * width + newIndex + 1]) {
506
+ operations.push({ type: '-', text: oldLines[oldIndex++] });
507
+ } else {
508
+ operations.push({ type: '+', text: newLines[newIndex++] });
509
+ }
510
+ }
511
+ while (oldIndex < oldLength) operations.push({ type: '-', text: oldLines[oldIndex++] });
512
+ while (newIndex < newLength) operations.push({ type: '+', text: newLines[newIndex++] });
513
+ return operations;
514
+ }
515
+
516
+ function coarseLineDiff(oldLines: string[], newLines: string[]): DiffLine[] {
517
+ let prefix = 0;
518
+ while (prefix < oldLines.length && prefix < newLines.length && oldLines[prefix] === newLines[prefix]) prefix++;
519
+ let suffix = 0;
520
+ while (suffix < oldLines.length - prefix && suffix < newLines.length - prefix &&
521
+ oldLines[oldLines.length - suffix - 1] === newLines[newLines.length - suffix - 1]) suffix++;
522
+ return [
523
+ ...oldLines.slice(0, prefix).map((text): DiffLine => ({ type: ' ', text })),
524
+ ...oldLines.slice(prefix, oldLines.length - suffix).map((text): DiffLine => ({ type: '-', text })),
525
+ ...newLines.slice(prefix, newLines.length - suffix).map((text): DiffLine => ({ type: '+', text })),
526
+ ...oldLines.slice(oldLines.length - suffix).map((text): DiffLine => ({ type: ' ', text })),
527
+ ];
528
+ }
529
+
530
+ function errorMessage(error: unknown): string {
531
+ return error instanceof Error ? error.message : String(error);
532
+ }
533
+
534
+ function snapshotsForSession(
535
+ snapshots: Map<string, Map<string, FileSnapshot>>,
536
+ context: ToolContext,
537
+ ): Map<string, FileSnapshot> {
538
+ if (typeof context.sessionId !== 'string' || !context.sessionId) {
539
+ throw new Error('File tracking unavailable: Pi session ID is missing; refusing to use a tool-call ID');
540
+ }
541
+ let sessionSnapshots = snapshots.get(context.sessionId);
542
+ if (!sessionSnapshots) {
543
+ sessionSnapshots = new Map();
544
+ snapshots.set(context.sessionId, sessionSnapshots);
545
+ }
546
+ return sessionSnapshots;
547
+ }
548
+
549
+ function snapshot(stat: { size: number; mtimeMs: number }, bytes: Buffer): FileSnapshot {
550
+ return { size: stat.size, mtimeMs: stat.mtimeMs, sha256: sha256(bytes) };
551
+ }
552
+
553
+ function sha256(bytes: Buffer): string {
554
+ return createHash('sha256').update(bytes).digest('hex');
555
+ }
556
+
557
+ function splitReadLines(text: string): Array<{ text: string; ending: string }> {
558
+ const lines: Array<{ text: string; ending: string }> = [];
559
+ let start = 0;
560
+ for (let index = 0; index < text.length; index++) {
561
+ if (text[index] !== '\r' && text[index] !== '\n') continue;
562
+ const ending = text[index] === '\r' && text[index + 1] === '\n' ? '\r\n' : text[index];
563
+ lines.push({ text: text.slice(start, index), ending });
564
+ if (ending.length === 2) index++;
565
+ start = index + 1;
566
+ }
567
+ if (start < text.length) lines.push({ text: text.slice(start), ending: '' });
568
+ return lines;
569
+ }
570
+
571
+ function truncateReadLine(line: string, maxLineLength: number): string {
572
+ let index = 0;
573
+ let characters = 0;
574
+ while (index < line.length && characters <= maxLineLength) {
575
+ const codePoint = line.codePointAt(index)!;
576
+ index += codePoint > 0xffff ? 2 : 1;
577
+ characters++;
578
+ }
579
+ if (characters <= maxLineLength) return line;
580
+
581
+ const markerLength = [...READ_LINE_TRUNCATION_MARKER].length;
582
+ const maxContentLength = maxLineLength - markerLength;
583
+ index = 0;
584
+ characters = 0;
585
+ while (index < line.length && characters < maxContentLength) {
586
+ const codePoint = line.codePointAt(index)!;
587
+ index += codePoint > 0xffff ? 2 : 1;
588
+ characters++;
589
+ }
590
+ return `${line.slice(0, index)}${READ_LINE_TRUNCATION_MARKER}`;
591
+ }
592
+
593
+ function tool(
594
+ name: string,
595
+ description: string,
596
+ shape: Record<string, string>,
597
+ execute: (args: Args, context: ToolContext) => Promise<{ success: boolean; output?: string; error?: string }>,
598
+ ): Tool<Args> {
599
+ return {
600
+ name, description,
601
+ parameters: {
602
+ type: 'object',
603
+ properties: Object.fromEntries(Object.entries(shape).map(([key, type]) => [key, { type: type.replace('?', '') }])),
604
+ required: Object.entries(shape).filter(([, type]) => !type.endsWith('?')).map(([key]) => key),
605
+ additionalProperties: false,
606
+ },
607
+ validate: (args): args is Args => isRecord(args) && Object.entries(shape).every(([key, type]) =>
608
+ (type.endsWith('?') && args[key] === undefined) || typeof args[key] === type.replace('?', '')),
609
+ execute,
610
+ };
611
+ }
612
+
613
+ function isRecord(value: unknown): value is Args {
614
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
615
+ }
616
+
617
+ function stringArg(args: Args, key: string): string {
618
+ if (typeof args[key] !== 'string') throw new TypeError(`"${key}" must be a string`);
619
+ return args[key] as string;
620
+ }
621
+
622
+ function optionalString(args: Args, key: string): string | undefined {
623
+ const value = args[key];
624
+ if (value === undefined) return undefined;
625
+ if (typeof value !== 'string') throw new TypeError(`"${key}" must be a string`);
626
+ return value;
627
+ }
628
+
629
+ async function resolvePath(context: ToolContext, input: string, allowMissing = false): Promise<string> {
630
+ const root = await fs.realpath(context.workingDirectory);
631
+ const candidate = path.resolve(root, input);
632
+ if (!inside(root, candidate)) throw new Error('Path is outside the working directory');
633
+ let resolved: string;
634
+ try {
635
+ resolved = await fs.realpath(candidate);
636
+ } catch (error) {
637
+ if (!allowMissing || (error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
638
+ let ancestor = path.dirname(candidate);
639
+ const suffix = [path.basename(candidate)];
640
+ while (true) {
641
+ try {
642
+ const realAncestor = await fs.realpath(ancestor);
643
+ if (!inside(root, realAncestor)) throw new Error('Path is outside the working directory');
644
+ resolved = path.join(realAncestor, ...suffix.reverse());
645
+ break;
646
+ } catch (ancestorError) {
647
+ if ((ancestorError as NodeJS.ErrnoException).code !== 'ENOENT') throw ancestorError;
648
+ const parent = path.dirname(ancestor);
649
+ if (parent === ancestor) throw new Error('No existing parent directory found');
650
+ suffix.push(path.basename(ancestor));
651
+ ancestor = parent;
652
+ }
653
+ }
654
+ }
655
+ if (!inside(root, resolved)) throw new Error('Path is outside the working directory');
656
+ return resolved;
657
+ }
658
+
659
+ function inside(root: string, candidate: string): boolean {
660
+ const relative = path.relative(root, candidate);
661
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
662
+ }