@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,133 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { promises as fs } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { isProtectedWrite, resolvePermissionPath } from '../extension/permission-modes/paths.ts';
5
+ import { writeUnlinkedFile } from './write-file.ts';
6
+ import { MAX_MEMORY_NOTE, memoryPath, readMemory, writeMemory } from './memory-store.ts';
7
+ import type { Args, Tool, ToolContext, ToolResult } from '../types/index.ts';
8
+
9
+ /** Persistent project-local memory and checkpoints, with optional host delegation. */
10
+ export function createAdvancedTools(): Tool<Args>[] {
11
+ return [
12
+ makeTool('memory', 'Read, write, or append project-local agent memory', {
13
+ action: 'string', content: 'string?',
14
+ }, async (a, c) => {
15
+ if (!['read', 'write', 'append'].includes(String(a.action))) return { success: false, error: 'action must be read, write, or append' };
16
+ const file = memoryPath(c.workingDirectory);
17
+ const write = a.action !== 'read';
18
+ const permitted = () => !c.signal?.aborted && c.canAccessMemory?.(file, write) !== false;
19
+ if (!permitted()) return { success: false, error: 'Project memory is not permitted' };
20
+ if (write && (typeof a.content !== 'string' || a.content.length > MAX_MEMORY_NOTE)) {
21
+ return { success: false, error: `content must be a string of at most ${MAX_MEMORY_NOTE} characters` };
22
+ }
23
+ const data = await readMemory(c.workingDirectory, file);
24
+ if (!permitted()) return { success: false, error: 'Project memory is not permitted' };
25
+ if (!write) return { success: true, output: data.entries.join('\n') };
26
+ await writeMemory(c.workingDirectory, data, a.action === 'write' ? [a.content as string] : [...data.entries, a.content as string], permitted);
27
+ return { success: true, output: `Memory ${a.action} complete` };
28
+ }),
29
+ makeTool('checkpoint', 'Create or list file-content recovery checkpoints', {
30
+ action: 'string', label: 'string?', paths: 'array?',
31
+ }, async (a, c) => {
32
+ const dir = await stateDir(c, 'checkpoints');
33
+ await fs.mkdir(dir, { recursive: true });
34
+ if (a.action === 'list') {
35
+ const files = (await fs.readdir(dir)).filter((f) => f.endsWith('.json')).sort();
36
+ const checkpoints = await Promise.all(files.map((f) => readJson(checkedStatePath(dir, f), null)));
37
+ return { success: true, output: checkpoints.map((p: any) => `${p.id} ${p.label} (${p.files.length} files)`).join('\n') };
38
+ }
39
+ if (a.action !== 'create') return { success: false, error: 'action must be create or list' };
40
+ const targets = Array.isArray(a.paths) ? a.paths as string[] : [];
41
+ if (!targets.length) return { success: false, error: 'paths must contain files to capture' };
42
+ const files: Array<{ path: string; content: string }> = [];
43
+ for (const input of targets) {
44
+ const file = await safeFile(c, input);
45
+ const stat = await fs.stat(file);
46
+ if (!stat.isFile()) return { success: false, error: `${input} is not a file` };
47
+ files.push({ path: path.relative(c.workingDirectory, file), content: (await fs.readFile(file)).toString('base64') });
48
+ }
49
+ const checkpoint = {
50
+ id: randomUUID(),
51
+ label: typeof a.label === 'string' ? a.label : 'checkpoint',
52
+ createdAt: new Date().toISOString(),
53
+ files,
54
+ };
55
+ await writeJson(checkedStatePath(dir, `${checkpoint.id}.json`), checkpoint);
56
+ return { success: true, output: checkpoint.id, metadata: { fileCount: files.length } };
57
+ }),
58
+ makeTool('subagent', 'Delegate a task to a host-provided specialized agent', {
59
+ task: 'string',
60
+ }, async (a, c) => {
61
+ if (!c.delegateAgent) return { success: false, error: 'Agent delegation is unavailable in this context' };
62
+ return { success: true, output: await c.delegateAgent(a.task as string) };
63
+ }),
64
+ ];
65
+ }
66
+
67
+ function makeTool(
68
+ name: string,
69
+ description: string,
70
+ shape: Record<string, string>,
71
+ execute: (args: Args, context: ToolContext) => Promise<ToolResult>,
72
+ ): Tool<Args> {
73
+ return {
74
+ name, description,
75
+ parameters: {
76
+ type: 'object',
77
+ properties: Object.fromEntries(Object.entries(shape).map(([k, type]) => [
78
+ k, type.startsWith('array') ? { type: 'array', items: { type: 'string' } } : { type: type.replace('?', '') },
79
+ ])),
80
+ required: Object.entries(shape).filter(([, type]) => !type.endsWith('?')).map(([k]) => k),
81
+ additionalProperties: false,
82
+ },
83
+ validate: (value): value is Args => value !== null && typeof value === 'object' && !Array.isArray(value) &&
84
+ Object.entries(shape).every(([k, type]) => {
85
+ const v = (value as Args)[k];
86
+ return (type.endsWith('?') && v === undefined) ||
87
+ (type.startsWith('array') ? Array.isArray(v) && v.every((item) => typeof item === 'string') :
88
+ typeof v === type.replace('?', ''));
89
+ }),
90
+ execute,
91
+ };
92
+ }
93
+
94
+ async function stateDir(context: ToolContext, name: string): Promise<string> {
95
+ const root = await fs.realpath(context.workingDirectory);
96
+ const dir = path.join(root, '.pi', name);
97
+ const rel = path.relative(root, dir);
98
+ if (rel.startsWith('..') || path.isAbsolute(rel)) throw new Error('Invalid state directory');
99
+ return checkedStatePath(root, path.relative(root, dir));
100
+ }
101
+
102
+ function checkedStatePath(root: string, name: string): string {
103
+ const target = path.join(root, name);
104
+ if (isProtectedWrite(target) || resolvePermissionPath(root, target) !== target) throw new Error('Unsafe project state path');
105
+ return target;
106
+ }
107
+
108
+ async function safeFile(context: ToolContext, input: string): Promise<string> {
109
+ const root = await fs.realpath(context.workingDirectory);
110
+ const target = path.resolve(root, input);
111
+ const rel = path.relative(root, target);
112
+ if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) throw new Error('Path is outside the working directory');
113
+ const real = await fs.realpath(target);
114
+ const realRel = path.relative(root, real);
115
+ if (realRel === '..' || realRel.startsWith(`..${path.sep}`) || path.isAbsolute(realRel)) throw new Error('Path is outside the working directory');
116
+ return real;
117
+ }
118
+
119
+ async function readJson<T>(file: string, fallback: T): Promise<T> {
120
+ try {
121
+ const stat = await fs.lstat(file);
122
+ if (!stat.isFile() || stat.nlink !== 1) throw new Error('Unsafe project state file');
123
+ return JSON.parse(await fs.readFile(file, 'utf8')) as T;
124
+ } catch (error) {
125
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return fallback;
126
+ throw error;
127
+ }
128
+ }
129
+
130
+ async function writeJson(file: string, data: unknown): Promise<void> {
131
+ await fs.mkdir(path.dirname(file), { recursive: true });
132
+ await writeUnlinkedFile(file, `${JSON.stringify(data, null, 2)}\n`);
133
+ }
@@ -0,0 +1,379 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { promises as fs } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createUndoJournal, type UndoJournal } from './undo-journal.ts';
5
+ import { isProtectedWrite } from '../extension/permission-modes/paths.ts';
6
+ import { atomicReplace } from './filesystem.ts';
7
+ import { writeUnlinkedFile } from './write-file.ts';
8
+ import { createTodoDefinition } from './todo.ts';
9
+ import type {
10
+ AgentToolDefinition,
11
+ AskQuestion,
12
+ AskUserFn,
13
+ Args,
14
+ Tool,
15
+ ToolContext,
16
+ ToolResult,
17
+ UndoEntry,
18
+ } from '../types/index.ts';
19
+
20
+ /** In-memory agent helpers; undo only restores files unchanged since its own edit. */
21
+ export function createAgentTools(options: { askUser?: AskUserFn; journal?: UndoJournal } = {}): Tool<Args>[] {
22
+ const journal = options.journal ?? createUndoJournal();
23
+ const undoStack = journal.entries;
24
+ const definitions: AgentToolDefinition[] = [
25
+ createTodoDefinition(),
26
+ ...(options.askUser ? [{
27
+ name: 'ask_user',
28
+ description:
29
+ 'Ask 1–4 structured questions when a decision materially changes the outcome and cannot be discovered from the repository. Not for permission, progress, or whether to proceed.',
30
+ promptGuideline:
31
+ 'Do not ask for things you can discover by reading files or running commands, and do not ask for permission to proceed with what was already requested.',
32
+ shape: {},
33
+ parameters: {
34
+ type: 'object',
35
+ properties: {
36
+ questions: {
37
+ type: 'array',
38
+ minItems: 1,
39
+ maxItems: 4,
40
+ items: {
41
+ type: 'object',
42
+ properties: {
43
+ id: { type: 'string' },
44
+ header: { type: 'string' },
45
+ question: { type: 'string' },
46
+ multiSelect: { type: 'boolean' },
47
+ options: {
48
+ type: 'array',
49
+ minItems: 2,
50
+ maxItems: 4,
51
+ items: {
52
+ type: 'object',
53
+ properties: {
54
+ label: { type: 'string' },
55
+ description: { type: 'string' },
56
+ recommended: { type: 'boolean' },
57
+ },
58
+ required: ['label', 'description'],
59
+ additionalProperties: false,
60
+ },
61
+ },
62
+ },
63
+ required: ['id', 'header', 'question', 'multiSelect', 'options'],
64
+ additionalProperties: false,
65
+ },
66
+ },
67
+ },
68
+ required: ['questions'],
69
+ additionalProperties: false,
70
+ },
71
+ execute: async (a: Args) => {
72
+ const questions = a.questions;
73
+ if (
74
+ !Array.isArray(questions) ||
75
+ questions.length < 1 ||
76
+ questions.length > 4 ||
77
+ questions.some((q) => !isAskQuestion(q))
78
+ ) {
79
+ return { success: false, error: 'questions must contain 1–4 valid structured questions' };
80
+ }
81
+ return {
82
+ success: true,
83
+ output: JSON.stringify(await options.askUser!(questions as AskQuestion[])),
84
+ };
85
+ },
86
+ }] : []),
87
+ {
88
+ name: 'plan',
89
+ description:
90
+ 'Format an ordered implementation plan before a large multi-file change. Returns numbered text only; does not store or track anything — use todo for tracking.',
91
+ promptGuideline:
92
+ 'Use only before changes spanning several files; skip it for small or single-file edits.',
93
+ shape: { steps: 'array' },
94
+ execute: async (a) => ({
95
+ success: true,
96
+ output: (a.steps as string[]).map((step, i) => `${i + 1}. ${step}`).join('\n'),
97
+ }),
98
+ },
99
+ {
100
+ name: 'apply_patch',
101
+ description:
102
+ 'Replace exact text in existing files. Each edit: path, oldText (must match exactly once, whitespace included), newText. Max one edit per file per call — for multiple changes in one file, use a larger oldText or separate calls. All-or-nothing: if any edit fails, none are applied. Cannot create files. Not a unified diff.',
103
+ promptGuideline:
104
+ 'Prefer apply_patch over edit/write for changes to existing files so they can be undone. Include enough surrounding context in oldText to make it unique.',
105
+ shape: { edits: 'array' },
106
+ arrayItems: {
107
+ type: 'object',
108
+ properties: {
109
+ path: { type: 'string', description: 'File path relative to the working directory' },
110
+ oldText: {
111
+ type: 'string',
112
+ description: 'Exact existing text to replace; must match exactly once',
113
+ },
114
+ newText: { type: 'string', description: 'Replacement text' },
115
+ },
116
+ required: ['path', 'oldText', 'newText'],
117
+ additionalProperties: false,
118
+ },
119
+ execute: async (a, c) => {
120
+ const edits = a.edits as Array<Record<string, unknown>>;
121
+ if (edits.length === 0) return { success: false, error: 'At least one edit is required' };
122
+
123
+ // Phase 1: validate + resolve sab kuch, disk pe kuch likhne se pehle
124
+ const resolved: Array<{ path: string; file: string; oldText: string; newText: string }> =
125
+ [];
126
+ const seen = new Map<string, string>(); // fileKey -> pehla path jo is file ko point karta hai
127
+ try {
128
+ for (const edit of edits) {
129
+ if (
130
+ typeof edit.path !== 'string' ||
131
+ typeof edit.oldText !== 'string' ||
132
+ typeof edit.newText !== 'string'
133
+ )
134
+ throw new Error('Each edit requires path, oldText, and newText strings');
135
+ if (!edit.oldText) throw new Error(`oldText must not be empty (${edit.path})`);
136
+ const file = await safeFile(c, edit.path);
137
+ const st = await fs.stat(file, { bigint: true });
138
+ if (!st.isFile() || st.nlink !== 1n) throw new Error(`Not a regular single-link file: ${edit.path}`);
139
+ // ino 0 kuch filesystems pe aata hai (unreliable) → tab real path fallback
140
+ const key = st.ino !== 0n ? `${st.dev}:${st.ino}` : file;
141
+ const prev = seen.get(key);
142
+ if (prev !== undefined)
143
+ throw new Error(
144
+ `"${prev}" and "${edit.path}" refer to the same file; only one edit per file is allowed per apply_patch call`,
145
+ );
146
+ seen.set(key, edit.path);
147
+ resolved.push({ path: edit.path, file, oldText: edit.oldText, newText: edit.newText });
148
+ }
149
+ } catch (error) {
150
+ return { success: false, error: error instanceof Error ? error.message : 'Patch failed' };
151
+ }
152
+
153
+ // Phase 2: write karo + undo ke liye record rakho
154
+ const pending: UndoEntry[] = [];
155
+ const operationId = randomUUID();
156
+ try {
157
+ for (const edit of resolved) {
158
+ const original = await fs.readFile(edit.file);
159
+ const text = original.toString('utf8');
160
+ if (!Buffer.from(text, 'utf8').equals(original))
161
+ throw new Error(`${edit.path} is not valid UTF-8; apply_patch cannot edit it safely`);
162
+ const at = text.indexOf(edit.oldText);
163
+ if (at < 0) throw new Error(`Match not found in ${edit.path}`);
164
+ if (text.indexOf(edit.oldText, at + 1) >= 0)
165
+ throw new Error(`Match is not unique in ${edit.path}`);
166
+ const updated = text.slice(0, at) + edit.newText + text.slice(at + edit.oldText.length);
167
+ await writeUnlinkedFile(edit.file, updated);
168
+ pending.push({
169
+ id: operationId,
170
+ file: edit.file,
171
+ before: original,
172
+ afterHash: hash(Buffer.from(updated)),
173
+ });
174
+ }
175
+ } catch (error) {
176
+ // Is call ke completed edits restore karo, sirf agar content abhi bhi hamara hai
177
+ for (const entry of pending.reverse()) {
178
+ try {
179
+ if (hash(await fs.readFile(entry.file)) === entry.afterHash) {
180
+ if (entry.before) await writeUnlinkedFile(entry.file, entry.before);
181
+ else await fs.rm(entry.file);
182
+ }
183
+ } catch {
184
+ // rollback best-effort hai; ek file fail ho toh baaki continue
185
+ }
186
+ }
187
+ return { success: false, error: error instanceof Error ? error.message : 'Patch failed' };
188
+ }
189
+ journal.record(c, pending);
190
+ return {
191
+ success: true,
192
+ output: `Applied ${pending.length} edit(s)`,
193
+ metadata: { operationIds: [operationId] },
194
+ };
195
+ },
196
+ },
197
+ {
198
+ name: 'undo',
199
+ description:
200
+ 'Revert the most recent tracked Honeycomb file operation (all files in it). Each call reverts one operation; call again to go further back. Refuses if any affected file changed since that patch.',
201
+ promptGuideline:
202
+ 'Use when the user asks to revert, or when your own last patch was wrong. If undo refuses, fix forward with apply_patch instead. Cannot undo shell commands or untracked changes.',
203
+ shape: {},
204
+ execute: async (_a, c) => {
205
+ const key = journal.select(c);
206
+ if (!undoStack.length)
207
+ return { success: false, error: 'No agent edits are available to undo' };
208
+ const lastId = undoStack[undoStack.length - 1].id;
209
+ const entries = undoStack.filter((entry) => entry.id === lastId);
210
+ const preflight = async (): Promise<ToolResult | undefined> => {
211
+ if (!journal.current(key) || undoStack.at(-1)?.id !== lastId || c.signal?.aborted ||
212
+ (c.checkUndo && !c.checkUndo(entries))) return { success: false, error: 'Restore is no longer permitted' };
213
+ for (const entry of entries) {
214
+ let current: Buffer;
215
+ try {
216
+ if (isProtectedWrite(entry.file) || await safeFile(c, entry.file) !== entry.file) return { success: false, error: 'Restore path is no longer safe' };
217
+ const stat = await fs.lstat(entry.file);
218
+ if (!stat.isFile() || stat.nlink !== 1) return { success: false, error: `Cannot undo: ${entry.file} is not a regular single-link file` };
219
+ current = await fs.readFile(entry.file);
220
+ } catch {
221
+ return { success: false, error: `Cannot undo: ${entry.file} is missing` };
222
+ }
223
+ if (hash(current) !== entry.afterHash)
224
+ return {
225
+ success: false,
226
+ error: `Cannot undo: ${entry.file} changed since the agent edit`,
227
+ };
228
+ }
229
+ };
230
+ const blocked = await preflight();
231
+ if (blocked) return blocked;
232
+ if (c.checkUndo && !await c.confirmDestructive?.('rewind last file operation', entries.map(entry => `${entry.before === null ? 'Remove' : 'Restore'}: ${entry.file}`).join('\n'))) return { success: false, error: 'Restore was not approved' };
233
+ const stale = await preflight();
234
+ if (stale) return stale;
235
+ const restored: { entry: UndoEntry; previous: Buffer; mode: number }[] = [];
236
+ const inspect = async (file: string, expected: string) => {
237
+ const stat = await fs.lstat(file);
238
+ if (!stat.isFile() || stat.nlink !== 1 || await safeFile(c, file) !== file) throw new Error('Unsafe path');
239
+ const bytes = await fs.readFile(file);
240
+ if (hash(bytes) !== expected) throw new Error('File changed');
241
+ return { bytes, mode: stat.mode };
242
+ };
243
+ try {
244
+ for (const entry of [...entries].reverse()) {
245
+ const { bytes, mode } = await inspect(entry.file, entry.afterHash);
246
+ const validate = async () => {
247
+ if (!journal.current(key) || c.signal?.aborted || (c.checkUndo && !c.checkUndo(entries))) throw new Error('Permission changed');
248
+ if ((await inspect(entry.file, entry.afterHash)).mode !== mode) throw new Error('File mode changed');
249
+ };
250
+ if (entry.before === null) { await validate(); await fs.unlink(entry.file); }
251
+ else await atomicReplace(entry.file, entry.before, mode, validate);
252
+ restored.push({ entry, previous: bytes, mode });
253
+ }
254
+ } catch {
255
+ let remaining = restored.length;
256
+ for (const { entry, previous, mode } of restored.reverse()) {
257
+ if (!entry.before) continue;
258
+ try {
259
+ if (c.checkUndo && !c.checkUndo(entries)) continue;
260
+ const validate = async () => {
261
+ if (c.checkUndo && !c.checkUndo(entries)) throw new Error('Permission changed');
262
+ if ((await inspect(entry.file, hash(entry.before!))).mode !== mode) throw new Error('File mode changed');
263
+ };
264
+ await validate();
265
+ await atomicReplace(entry.file, previous, mode, validate);
266
+ remaining--;
267
+ } catch { /* Do not overwrite a file changed after restore. */ }
268
+ }
269
+ return { success: false, error: remaining ? `Restore failed; ${remaining} file(s) could not be rolled back. Inspect the affected files.` : 'Restore failed; no restored changes remain.' };
270
+ } finally {
271
+ journal.invalidateSnapshots?.(c, entries.map(entry => entry.file));
272
+ }
273
+ while (undoStack.length && undoStack.at(-1)?.id === lastId) undoStack.pop();
274
+ return { success: true, output: `Undid ${entries.length} edit(s)` };
275
+ },
276
+ },
277
+ ];
278
+ return definitions.map(({ name, description, promptGuideline, shape, execute, arrayItems, parameters }) =>
279
+ tool(name, description, shape, execute, promptGuideline, arrayItems, parameters),
280
+ );
281
+ }
282
+
283
+ function tool(
284
+ name: string,
285
+ description: string,
286
+ shape: Record<string, string>,
287
+ execute: (args: Args, context: ToolContext) => Promise<ToolResult>,
288
+ promptGuideline?: string,
289
+ arrayItems?: Record<string, unknown>,
290
+ parameters?: Record<string, unknown>,
291
+ ): Tool<Args> {
292
+ return {
293
+ name,
294
+ description,
295
+ ...(promptGuideline ? { promptSnippet: description, promptGuidelines: [promptGuideline] } : {}),
296
+ parameters: parameters ?? {
297
+ type: 'object',
298
+ properties: Object.fromEntries(
299
+ Object.entries(shape).map(([k, type]) => [
300
+ k,
301
+ type === 'array'
302
+ ? { type: 'array', items: arrayItems ?? { type: 'string' } }
303
+ : { type: type.replace('?', '') },
304
+ ]),
305
+ ),
306
+ required: Object.entries(shape)
307
+ .filter(([, type]) => !type.endsWith('?'))
308
+ .map(([k]) => k),
309
+ additionalProperties: false,
310
+ },
311
+ validate: (value): value is Args => parameters
312
+ ? value !== null && typeof value === 'object' && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype
313
+ : validateArgs(value, shape, arrayItems),
314
+ execute,
315
+ };
316
+ }
317
+
318
+ function isAskQuestion(value: unknown): value is AskQuestion {
319
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
320
+ const q = value as Record<string, unknown>;
321
+ return typeof q.id === 'string' && typeof q.header === 'string' && typeof q.question === 'string' &&
322
+ typeof q.multiSelect === 'boolean' && Array.isArray(q.options) && q.options.length >= 2 && q.options.length <= 4 &&
323
+ q.options.every((option) => {
324
+ if (!option || typeof option !== 'object' || Array.isArray(option)) return false;
325
+ const o = option as Record<string, unknown>;
326
+ return typeof o.label === 'string' && typeof o.description === 'string' &&
327
+ (o.recommended === undefined || typeof o.recommended === 'boolean');
328
+ });
329
+ }
330
+
331
+ function validateArgs(
332
+ value: unknown,
333
+ shape: Record<string, string>,
334
+ arrayItems?: Record<string, unknown>,
335
+ ): value is Args {
336
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
337
+ const args = value as Args;
338
+ return Object.entries(shape).every(([key, type]) => {
339
+ const item = args[key];
340
+ if (type.endsWith('?') && item === undefined) return true;
341
+ if (type !== 'array') return typeof item === type.replace('?', '');
342
+ if (!Array.isArray(item)) return false;
343
+ if (!arrayItems) return item.every((entry) => typeof entry === 'string');
344
+ const properties = arrayItems.properties as Record<string, { type?: string }>;
345
+ return item.every(
346
+ (entry) =>
347
+ entry !== null &&
348
+ typeof entry === 'object' &&
349
+ !Array.isArray(entry) &&
350
+ Object.entries(properties).every(
351
+ ([key, schema]) => typeof (entry as Args)[key] === schema.type,
352
+ ),
353
+ );
354
+ });
355
+ }
356
+
357
+ async function safeFile(context: ToolContext, input: string): Promise<string> {
358
+ const root = await fs.realpath(context.workingDirectory);
359
+ const target = path.resolve(root, input);
360
+ const rel = path.relative(root, target);
361
+ if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel))
362
+ throw new Error('Path is outside the working directory');
363
+ let real: string;
364
+ try {
365
+ real = await fs.realpath(target);
366
+ } catch (error) {
367
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
368
+ throw new Error(`File not found: ${input}`);
369
+ throw error;
370
+ }
371
+ const realRel = path.relative(root, real);
372
+ if (realRel === '..' || realRel.startsWith(`..${path.sep}`) || path.isAbsolute(realRel))
373
+ throw new Error('Path is outside the working directory');
374
+ return real;
375
+ }
376
+
377
+ function hash(value: Buffer): string {
378
+ return createHash('sha256').update(value).digest('hex');
379
+ }
@@ -0,0 +1,80 @@
1
+ import { BI_CONFIG } from '../config/index.ts';
2
+ import { loadProjectConfig } from '../config/project.ts';
3
+ import { CONFIG_LIMITS, OUTPUT_TRUNCATION_MARKER } from '../config/limits.ts';
4
+ import type { DispatchResult, ToolCall, ToolContext } from '../types/index.ts';
5
+ import { ToolRegistry } from './registry.ts';
6
+
7
+ export class ToolDispatcher {
8
+ constructor(
9
+ private readonly registry: ToolRegistry,
10
+ private readonly maxOutputChars = BI_CONFIG.output.maxChars,
11
+ ) {
12
+ if (!Number.isInteger(maxOutputChars) || maxOutputChars < CONFIG_LIMITS.minOutputChars ||
13
+ maxOutputChars > CONFIG_LIMITS.maxOutputChars) {
14
+ throw new Error(`output.maxChars must be an integer from ${CONFIG_LIMITS.minOutputChars} to ${CONFIG_LIMITS.maxOutputChars}`);
15
+ }
16
+ }
17
+
18
+ async dispatch(call: ToolCall, context: ToolContext): Promise<DispatchResult> {
19
+ if (context.signal?.aborted) {
20
+ return { success: false, error: 'Tool execution was cancelled', errorCode: 'OPERATION_CANCELLED' };
21
+ }
22
+ const tool = this.registry.get(call.name);
23
+ if (!tool) return { success: false, error: `Unknown tool: ${call.name}`, errorCode: 'TOOL_NOT_FOUND' };
24
+ if (!isArguments(call.arguments) || (tool.validate && !tool.validate(call.arguments))) {
25
+ return { success: false, error: `Invalid arguments for tool: ${call.name}`, errorCode: 'INVALID_ARGUMENTS' };
26
+ }
27
+
28
+ try {
29
+ const projectConfig = await loadProjectConfig(context.workingDirectory);
30
+ if (context.signal?.aborted) {
31
+ return { success: false, error: 'Tool execution was cancelled', errorCode: 'OPERATION_CANCELLED' };
32
+ }
33
+ const toolContext = { ...context, projectConfig };
34
+ const result = normalizeResult(await tool.execute(call.arguments, toolContext));
35
+ return limitOutput(result, projectConfig.output?.maxChars ?? this.maxOutputChars);
36
+ } catch (error) {
37
+ if (context.signal?.aborted) {
38
+ return { success: false, error: 'Tool execution was cancelled', errorCode: 'OPERATION_CANCELLED' };
39
+ }
40
+ return {
41
+ success: false,
42
+ error: error instanceof Error ? error.message : 'Tool execution failed',
43
+ errorCode: 'EXECUTION_FAILED',
44
+ };
45
+ }
46
+ }
47
+
48
+ async dispatchSequential(calls: ToolCall[], context: ToolContext): Promise<DispatchResult[]> {
49
+ const results: DispatchResult[] = [];
50
+ for (const call of calls) {
51
+ if (context.signal?.aborted) {
52
+ results.push({ success: false, error: 'Tool execution was cancelled', errorCode: 'OPERATION_CANCELLED' });
53
+ break;
54
+ }
55
+ results.push(await this.dispatch(call, context));
56
+ }
57
+ return results;
58
+ }
59
+ }
60
+
61
+ function isArguments(value: unknown): value is Record<string, unknown> {
62
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
63
+ }
64
+
65
+ function normalizeResult(value: unknown): DispatchResult {
66
+ if (!value || typeof value !== 'object' || typeof (value as { success?: unknown }).success !== 'boolean') {
67
+ return { success: false, error: 'Tool returned an invalid result', errorCode: 'INTERNAL_ERROR' };
68
+ }
69
+ return value as DispatchResult;
70
+ }
71
+
72
+ function limitOutput(result: DispatchResult, maxChars: number): DispatchResult {
73
+ if (typeof result.output !== 'string' || result.output.length <= maxChars) return result;
74
+ const contentLimit = maxChars - OUTPUT_TRUNCATION_MARKER.length;
75
+ let content = result.output.slice(0, contentLimit);
76
+ if (content.length > 0 && /[\uD800-\uDBFF]/u.test(content[content.length - 1])) {
77
+ content = content.slice(0, -1);
78
+ }
79
+ return { ...result, output: content + OUTPUT_TRUNCATION_MARKER };
80
+ }
@@ -0,0 +1,15 @@
1
+ import { constants, promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { isWithin } from '../extension/permission-modes/paths.ts';
4
+
5
+ /** Resolve only installed executables outside the active project. */
6
+ export async function resolveExternalExecutable(input: unknown, cwd: string): Promise<string | undefined> {
7
+ if (typeof input !== 'string' || !path.isAbsolute(input) || input.includes('\0')) return;
8
+ try {
9
+ const root = await fs.realpath(cwd);
10
+ const executable = await fs.realpath(input);
11
+ if (isWithin(root, executable) || isWithin(path.resolve(cwd), path.resolve(input)) || !(await fs.stat(executable)).isFile()) return;
12
+ await fs.access(executable, constants.X_OK);
13
+ return executable;
14
+ } catch { return undefined; }
15
+ }