@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.
- package/LICENSE +15 -0
- package/README.md +443 -2
- package/bin/bee.js +18 -0
- package/package.json +66 -4
- package/plan/tools/tool-parity.md +61 -0
- package/src/commands/btw.ts +95 -0
- package/src/commands/claude-migrate.ts +63 -0
- package/src/commands/diff.ts +119 -0
- package/src/commands/discovery.ts +112 -0
- package/src/commands/doctor.ts +80 -0
- package/src/commands/goal/index.ts +254 -0
- package/src/commands/goal/report.ts +66 -0
- package/src/commands/goal/state.ts +74 -0
- package/src/commands/hooks.ts +38 -0
- package/src/commands/index.ts +13 -0
- package/src/commands/init.ts +66 -0
- package/src/commands/memory.ts +70 -0
- package/src/commands/plan.ts +36 -0
- package/src/commands/review-report.ts +23 -0
- package/src/commands/review.ts +21 -0
- package/src/commands/rewind-history.ts +40 -0
- package/src/commands/security-review.ts +138 -0
- package/src/commands/simplify.ts +21 -0
- package/src/commands/stats.ts +125 -0
- package/src/commands/tasks.ts +87 -0
- package/src/commands/verify.ts +21 -0
- package/src/commands/worktree.ts +138 -0
- package/src/config/bi.config.json +77 -0
- package/src/config/index.ts +47 -0
- package/src/config/limits.ts +12 -0
- package/src/config/path-rules.ts +19 -0
- package/src/config/project.ts +133 -0
- package/src/extension/ask-user.ts +52 -0
- package/src/extension/index.ts +4 -0
- package/src/extension/lsp-install.ts +95 -0
- package/src/extension/lsp-menu.ts +90 -0
- package/src/extension/permission-modes/index.ts +337 -0
- package/src/extension/permission-modes/mcp-resources.ts +21 -0
- package/src/extension/permission-modes/metadata.ts +18 -0
- package/src/extension/permission-modes/paths.ts +44 -0
- package/src/extension/permission-modes/plan-note.ts +58 -0
- package/src/extension/permission-modes/policy.ts +236 -0
- package/src/extension/permission-modes/preview.ts +104 -0
- package/src/extension/permission-modes/rules.ts +67 -0
- package/src/extension/permission-modes/shell.ts +183 -0
- package/src/extension/permission-modes/state.ts +6 -0
- package/src/extension/quiet-startup.ts +25 -0
- package/src/extension/register-tools.ts +312 -0
- package/src/extension/scoped-rules.ts +91 -0
- package/src/extension/system-instruction.ts +74 -0
- package/src/index.ts +71 -0
- package/src/tools/advanced.ts +133 -0
- package/src/tools/agent.ts +379 -0
- package/src/tools/dispatcher.ts +80 -0
- package/src/tools/executable.ts +15 -0
- package/src/tools/execution.ts +289 -0
- package/src/tools/filesystem.ts +662 -0
- package/src/tools/git.ts +196 -0
- package/src/tools/glob.ts +81 -0
- package/src/tools/grep.ts +203 -0
- package/src/tools/image-read.ts +71 -0
- package/src/tools/index.ts +52 -0
- package/src/tools/lsp-client.ts +104 -0
- package/src/tools/lsp.ts +172 -0
- package/src/tools/memory-store.ts +77 -0
- package/src/tools/notebook.ts +169 -0
- package/src/tools/registry.ts +31 -0
- package/src/tools/shells.ts +63 -0
- package/src/tools/todo.ts +119 -0
- package/src/tools/undo-journal.ts +46 -0
- package/src/tools/web-fetch.ts +119 -0
- package/src/tools/web-search.ts +76 -0
- package/src/tools/write-file.ts +14 -0
- package/src/tui/editor.ts +65 -0
- package/src/tui/footer-stats.ts +35 -0
- package/src/tui/header.ts +81 -0
- package/src/tui/index.ts +124 -0
- package/src/tui/mascot.ts +59 -0
- package/src/tui/permission-dialog.ts +94 -0
- package/src/tui/permission-rules.ts +64 -0
- package/src/tui/tasks-panel.ts +84 -0
- package/src/tui/text.ts +55 -0
- package/src/tui/tool-renderer.ts +42 -0
- package/src/tui/working-feedback.ts +220 -0
- package/src/types/agent.ts +54 -0
- package/src/types/common.ts +1 -0
- package/src/types/execution.ts +24 -0
- package/src/types/index.ts +4 -0
- package/src/types/tools.ts +61 -0
- package/themes/catppuccin-mocha.json +80 -0
- package/themes/github-dark.json +80 -0
- package/themes/honeycomb-dark.json +81 -0
- package/themes/honeycomb-light.json +81 -0
- package/themes/tokyo-day.json +80 -0
- package/themes/tokyo-night.json +80 -0
- package/themes/vercel-black.json +80 -0
- package/themes/vercel-light.json +80 -0
package/src/tools/git.ts
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { BI_CONFIG } from '../config/index.ts';
|
|
5
|
+
import { isProtectedWrite, resolvePermissionPath } from '../extension/permission-modes/paths.ts';
|
|
6
|
+
import type { Args, Tool, ToolContext, ToolResult } from '../types/index.ts';
|
|
7
|
+
|
|
8
|
+
const execFileAsync = promisify(execFile);
|
|
9
|
+
// Read operations must not refresh the on-disk index or invoke repo-configured helpers.
|
|
10
|
+
const readOnlyFlags = ['--no-optional-locks', '--no-pager', '-c', 'core.fsmonitor=false', '-c', 'core.untrackedCache=false'];
|
|
11
|
+
|
|
12
|
+
export async function disableWorktreeFilters(context: ToolContext, timeout = 30_000, env?: NodeJS.ProcessEnv): Promise<string[]> {
|
|
13
|
+
try {
|
|
14
|
+
const { stdout } = await execFileAsync('git', [...readOnlyFlags, 'config', '--null', '--name-only', '--get-regexp', '^filter\\..*\\.(clean|smudge|process|required)$'], {
|
|
15
|
+
cwd: context.workingDirectory, signal: context.signal, timeout, env,
|
|
16
|
+
});
|
|
17
|
+
return [...new Set(stdout.split('\0').filter(Boolean))].flatMap(key => {
|
|
18
|
+
if (!/^filter\.[^=\r\n]+\.(clean|smudge|process|required)$/.test(key)) throw new Error('Invalid Git filter key');
|
|
19
|
+
return ['-c', `${key}=${key.endsWith('.required') ? 'false' : ''}`];
|
|
20
|
+
});
|
|
21
|
+
} catch (error) {
|
|
22
|
+
if ((error as { code?: unknown }).code === 1) return [];
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function readGitStatus(context: ToolContext, args: string[], timeout = 30_000): Promise<ToolResult> {
|
|
28
|
+
return runGit(context, [...readOnlyFlags, ...await disableWorktreeFilters(context, timeout), 'status', ...args, '--ignore-submodules=all'], timeout);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Git tools use execFile (never a shell) and run only in the active directory. */
|
|
32
|
+
export function createGitTools(options: { defaultLogLimit?: number } = {}): Tool<Args>[] {
|
|
33
|
+
const defaultLogLimit = options.defaultLogLimit ?? BI_CONFIG.git.defaultLogLimit;
|
|
34
|
+
if (!Number.isInteger(defaultLogLimit) || defaultLogLimit < 1 || defaultLogLimit > 100) {
|
|
35
|
+
throw new Error('git.defaultLogLimit must be an integer from 1 to 100');
|
|
36
|
+
}
|
|
37
|
+
return [
|
|
38
|
+
gitTool('git_status', 'Show working tree status', {}, async (_a, c) =>
|
|
39
|
+
readGitStatus(c, ['--short', '--branch'])),
|
|
40
|
+
gitTool('git_diff', 'Show working tree diff', { staged: 'boolean?' }, async (a, c) =>
|
|
41
|
+
runDiff(c, a.staged === true)),
|
|
42
|
+
gitTool('git_log', 'Show recent commit history; the default limit comes from configuration.', { limit: 'number?' }, async (a, c) => {
|
|
43
|
+
const limit = a.limit === undefined
|
|
44
|
+
? c.projectConfig?.git?.defaultLogLimit ?? defaultLogLimit
|
|
45
|
+
: a.limit as number;
|
|
46
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
|
|
47
|
+
return { success: false, error: 'limit must be an integer from 1 to 100' };
|
|
48
|
+
}
|
|
49
|
+
return runGit(c, [...readOnlyFlags, 'log', `-${limit}`, '--oneline', '--decorate']);
|
|
50
|
+
}),
|
|
51
|
+
gitTool('git_commit', 'Create a commit from staged changes', { message: 'string' }, async (a, c) => {
|
|
52
|
+
const message = a.message as string;
|
|
53
|
+
if (!message.trim()) return { success: false, error: 'Commit message must not be empty' };
|
|
54
|
+
if (!await approve(c, 'git commit', message)) return { success: false, error: 'Commit was not approved' };
|
|
55
|
+
return runGit(c, ['commit', '-m', message]);
|
|
56
|
+
}),
|
|
57
|
+
gitTool('git_branch', 'List branches or create a branch', { name: 'string?' }, async (a, c) => {
|
|
58
|
+
if (typeof a.name !== 'string') return runGit(c, [...readOnlyFlags, 'branch', '--list']);
|
|
59
|
+
if (!validRef(a.name)) return { success: false, error: 'Invalid branch name' };
|
|
60
|
+
if (!await approve(c, 'create git branch', a.name)) return { success: false, error: 'Branch creation was not approved' };
|
|
61
|
+
return runGit(c, ['branch', '--', a.name]);
|
|
62
|
+
}),
|
|
63
|
+
gitTool('git_checkout', 'Switch to an existing branch', { branch: 'string' }, async (a, c) => {
|
|
64
|
+
const branch = a.branch as string;
|
|
65
|
+
if (!validRef(branch)) return { success: false, error: 'Invalid branch name' };
|
|
66
|
+
if (!await approve(c, 'git checkout', branch)) return { success: false, error: 'Checkout was not approved' };
|
|
67
|
+
return runGit(c, ['checkout', branch]);
|
|
68
|
+
}),
|
|
69
|
+
gitTool('git_add', 'Stage paths for commit', { paths: 'array' }, async (a, c) => {
|
|
70
|
+
const paths = a.paths as string[];
|
|
71
|
+
if (!paths.length || paths.some((p) => !p || p.includes('\0'))) {
|
|
72
|
+
return { success: false, error: 'paths must contain at least one valid path' };
|
|
73
|
+
}
|
|
74
|
+
if (!await approve(c, 'git add', paths.join(', '))) return { success: false, error: 'Staging was not approved' };
|
|
75
|
+
return runGit(c, ['add', '--', ...paths]);
|
|
76
|
+
}),
|
|
77
|
+
];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function runDiff(context: ToolContext, staged: boolean, selection?: { list: true } | { paths: string[] }): Promise<ToolResult> {
|
|
81
|
+
try {
|
|
82
|
+
const options = { cwd: context.workingDirectory, env: { ...process.env, GIT_NO_LAZY_FETCH: '1' }, encoding: 'utf8' as const, timeout: 30_000, maxBuffer: 10 * 1024 * 1024, signal: context.signal };
|
|
83
|
+
const rootOutput = await execFileAsync('git', [...readOnlyFlags, 'rev-parse', '--show-toplevel'], options);
|
|
84
|
+
const root = rootOutput.stdout.replace(/\n$/, '');
|
|
85
|
+
const filters = staged ? [] : await disableWorktreeFilters(context);
|
|
86
|
+
const listing = selection && 'list' in selection;
|
|
87
|
+
const paths = selection && 'paths' in selection ? selection.paths : [];
|
|
88
|
+
const args = [...readOnlyFlags, ...filters, '--literal-pathspecs', '-C', root, 'diff', '--raw', '-z', ...(listing ? [] : ['--patch']), '--no-color', '--no-ext-diff', '--no-textconv', '--ignore-submodules=all', ...(staged ? ['--cached'] : []), '--', ...paths];
|
|
89
|
+
const { stdout, stderr } = await execFileAsync('git', args, options);
|
|
90
|
+
if (!stdout) return listing ? { success: true, metadata: { files: [], root } } : { success: true, output: stderr.trimEnd() };
|
|
91
|
+
|
|
92
|
+
let cursor = 0;
|
|
93
|
+
let sensitive = false;
|
|
94
|
+
const files: { status: string; paths: string[] }[] = [];
|
|
95
|
+
try {
|
|
96
|
+
while (cursor < stdout.length && stdout[cursor] !== '\0') {
|
|
97
|
+
const end = stdout.indexOf('\0', cursor);
|
|
98
|
+
if (end < 0) throw new Error('Cannot identify diff paths');
|
|
99
|
+
const header = stdout.slice(cursor, end);
|
|
100
|
+
const match = /^:\d{6} \d{6} [0-9a-f]+ [0-9a-f]+ ([ACDMRTUXB])\d*$/.exec(header);
|
|
101
|
+
if (!match) throw new Error('Cannot identify diff paths');
|
|
102
|
+
cursor = end + 1;
|
|
103
|
+
const count = match[1] === 'R' || match[1] === 'C' ? 2 : 1;
|
|
104
|
+
const names: string[] = [];
|
|
105
|
+
for (let i = 0; i < count; i++) {
|
|
106
|
+
const pathEnd = stdout.indexOf('\0', cursor);
|
|
107
|
+
if (pathEnd < 0 || pathEnd === cursor) throw new Error('Cannot identify diff paths');
|
|
108
|
+
const name = stdout.slice(cursor, pathEnd);
|
|
109
|
+
if (selection && name.includes('\uFFFD')) throw new Error('Unsupported Git filename encoding');
|
|
110
|
+
names.push(name);
|
|
111
|
+
const target = path.resolve(root, name);
|
|
112
|
+
try {
|
|
113
|
+
if (isProtectedWrite(target) || isProtectedWrite(resolvePermissionPath(root, target))) sensitive = true;
|
|
114
|
+
} catch { sensitive = true; }
|
|
115
|
+
cursor = pathEnd + 1;
|
|
116
|
+
}
|
|
117
|
+
files.push({ status: match[1]!, paths: names });
|
|
118
|
+
}
|
|
119
|
+
if (listing ? cursor !== stdout.length : stdout[cursor] !== '\0') throw new Error('Cannot identify diff paths');
|
|
120
|
+
} catch {
|
|
121
|
+
if (listing || selection) throw new Error('Cannot safely classify diff paths');
|
|
122
|
+
sensitive = true;
|
|
123
|
+
const separator = stdout.indexOf('\0\0');
|
|
124
|
+
if (separator < 0) throw new Error('Cannot safely separate diff output');
|
|
125
|
+
cursor = separator + 1;
|
|
126
|
+
}
|
|
127
|
+
if (sensitive && !await context.confirmSensitiveRead?.('The diff contains sensitive paths or its paths could not be classified.')) {
|
|
128
|
+
return { success: false, error: 'Sensitive diff was not approved' };
|
|
129
|
+
}
|
|
130
|
+
if (listing) return { success: true, metadata: { files, root } };
|
|
131
|
+
return { success: true, output: [stdout.slice(cursor + 1).trimEnd(), stderr.trimEnd()].filter(Boolean).join('\n') };
|
|
132
|
+
} catch (error) {
|
|
133
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
134
|
+
return { success: false, error: `Unable to inspect Git diff: ${message}` };
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function runGit(context: ToolContext, args: string[], timeout = 30_000): Promise<ToolResult> {
|
|
139
|
+
try {
|
|
140
|
+
const { stdout, stderr } = await execFileAsync('git', args, {
|
|
141
|
+
cwd: context.workingDirectory,
|
|
142
|
+
...(args[0] === '--no-optional-locks' ? { env: { ...process.env, GIT_NO_LAZY_FETCH: '1' } } : {}),
|
|
143
|
+
encoding: 'utf8',
|
|
144
|
+
timeout,
|
|
145
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
146
|
+
signal: context.signal,
|
|
147
|
+
});
|
|
148
|
+
return { success: true, output: [stdout.trimEnd(), stderr.trimEnd()].filter(Boolean).join('\n') };
|
|
149
|
+
} catch (error) {
|
|
150
|
+
const e = error as Error & { stdout?: string; stderr?: string; code?: number | string };
|
|
151
|
+
return {
|
|
152
|
+
success: false,
|
|
153
|
+
output: [e.stdout, e.stderr].filter(Boolean).join('\n'),
|
|
154
|
+
error: e.message,
|
|
155
|
+
metadata: { exitCode: e.code },
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function approve(context: ToolContext, operation: string, target: string): Promise<boolean> {
|
|
161
|
+
return !!context.confirmDestructive && context.confirmDestructive(operation, target);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function validRef(value: string): boolean {
|
|
165
|
+
return value.length > 0 && !value.startsWith('-') && !value.includes('\0');
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function gitTool(
|
|
169
|
+
name: string,
|
|
170
|
+
description: string,
|
|
171
|
+
shape: Record<string, string>,
|
|
172
|
+
execute: (args: Args, context: ToolContext) => Promise<ToolResult>,
|
|
173
|
+
): Tool<Args> {
|
|
174
|
+
return {
|
|
175
|
+
name,
|
|
176
|
+
description,
|
|
177
|
+
parameters: {
|
|
178
|
+
type: 'object',
|
|
179
|
+
properties: Object.fromEntries(Object.entries(shape).map(([key, type]) => [
|
|
180
|
+
key,
|
|
181
|
+
type === 'array' ? { type: 'array', items: { type: 'string' } } : { type: type.replace('?', '') },
|
|
182
|
+
])),
|
|
183
|
+
required: Object.entries(shape).filter(([, type]) => !type.endsWith('?')).map(([key]) => key),
|
|
184
|
+
additionalProperties: false,
|
|
185
|
+
},
|
|
186
|
+
validate: (value): value is Args => {
|
|
187
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
188
|
+
const args = value as Args;
|
|
189
|
+
return Object.entries(shape).every(([key, type]) =>
|
|
190
|
+
(type.endsWith('?') && args[key] === undefined) ||
|
|
191
|
+
(type === 'array' ? Array.isArray(args[key]) && (args[key] as unknown[]).every((v) => typeof v === 'string') :
|
|
192
|
+
typeof args[key] === type.replace('?', '')));
|
|
193
|
+
},
|
|
194
|
+
execute,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { promises as fs } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { isProtectedWrite, isWithin } from '../extension/permission-modes/paths.ts';
|
|
4
|
+
import { decidePermission } from '../extension/permission-modes/policy.ts';
|
|
5
|
+
import { loadPermissionRules } from '../extension/permission-modes/rules.ts';
|
|
6
|
+
import { literal } from '../tui/text.ts';
|
|
7
|
+
import type { Args, Tool } from '../types/index.ts';
|
|
8
|
+
|
|
9
|
+
const MAX_PATTERN = 256;
|
|
10
|
+
const MAX_ENTRIES = 20_000;
|
|
11
|
+
const MAX_MATCHES = 200;
|
|
12
|
+
|
|
13
|
+
function validPattern(value: unknown): value is string {
|
|
14
|
+
return typeof value === 'string' && value.length > 0 && value.length <= MAX_PATTERN &&
|
|
15
|
+
!/[\\:[\]{}()!\p{Cc}]/u.test(value) && value.split('/').every(part =>
|
|
16
|
+
part && part !== '.' && part !== '..' && (!part.includes('**') || part === '**'));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function excluded(workspace: string, target: string): boolean {
|
|
20
|
+
return isProtectedWrite(target) || path.relative(workspace, target).split(path.sep)
|
|
21
|
+
.some(part => ['.pi', '.bi'].includes(part.toLowerCase()));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function createGlobTool(): Tool<Args> {
|
|
25
|
+
return {
|
|
26
|
+
name: 'glob',
|
|
27
|
+
description: 'List workspace files by relative path pattern (*, ?, **). Skips symlinks and protected paths.',
|
|
28
|
+
parameters: {
|
|
29
|
+
type: 'object', additionalProperties: false, required: ['pattern'],
|
|
30
|
+
properties: {
|
|
31
|
+
pattern: { type: 'string', minLength: 1, maxLength: MAX_PATTERN },
|
|
32
|
+
path: { type: 'string', minLength: 1, description: 'Optional workspace search directory' },
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
validate: (args): args is Args => !!args && typeof args === 'object' && !Array.isArray(args) &&
|
|
36
|
+
Object.keys(args).every(key => key === 'pattern' || key === 'path') && validPattern((args as Args).pattern) &&
|
|
37
|
+
((args as Args).path === undefined || (typeof (args as Args).path === 'string' && !!(args as Args).path)),
|
|
38
|
+
async execute(args, ctx) {
|
|
39
|
+
const pattern = args.pattern as string;
|
|
40
|
+
const lexicalWorkspace = path.resolve(ctx.workingDirectory);
|
|
41
|
+
const requested = path.resolve(lexicalWorkspace, args.path as string ?? '.');
|
|
42
|
+
if (!isWithin(lexicalWorkspace, requested) || excluded(lexicalWorkspace, requested)) {
|
|
43
|
+
return { success: false, error: 'Glob requires a non-protected search root inside the workspace' };
|
|
44
|
+
}
|
|
45
|
+
const workspace = await fs.realpath(lexicalWorkspace);
|
|
46
|
+
const root = path.join(workspace, path.relative(lexicalWorkspace, requested));
|
|
47
|
+
if (excluded(workspace, root) || await fs.realpath(root) !== root) {
|
|
48
|
+
return { success: false, error: 'Glob cannot search protected or symlinked directories' };
|
|
49
|
+
}
|
|
50
|
+
const config = loadPermissionRules(ctx.workingDirectory, () => {});
|
|
51
|
+
if (config.invalid || decidePermission('default', 'glob', { pattern, path: requested }, ctx.workingDirectory, config.rules).action === 'deny') {
|
|
52
|
+
return { success: false, error: 'Glob search denied by permission rules' };
|
|
53
|
+
}
|
|
54
|
+
const filterRules = !!(config.rules.deny?.length || config.rules.ask?.length);
|
|
55
|
+
const matches: string[] = [];
|
|
56
|
+
const pending = [root];
|
|
57
|
+
let scanned = 0;
|
|
58
|
+
let limited = false;
|
|
59
|
+
while (pending.length && !limited) {
|
|
60
|
+
ctx.signal?.throwIfAborted();
|
|
61
|
+
const dir = pending.pop()!;
|
|
62
|
+
if (await fs.realpath(dir) !== dir) continue;
|
|
63
|
+
for await (const entry of await fs.opendir(dir)) {
|
|
64
|
+
ctx.signal?.throwIfAborted();
|
|
65
|
+
if (scanned++ === MAX_ENTRIES) { limited = true; break; }
|
|
66
|
+
const full = path.join(dir, entry.name);
|
|
67
|
+
if (entry.isSymbolicLink() || excluded(workspace, full)) continue;
|
|
68
|
+
const relative = path.relative(root, full).split(path.sep).join('/');
|
|
69
|
+
if (!entry.isDirectory() && (!entry.isFile() || !path.posix.matchesGlob(relative, pattern))) continue;
|
|
70
|
+
// A search-root approval is not approval to disclose a separately restricted child.
|
|
71
|
+
if (filterRules && decidePermission('default', 'glob', { pattern, path: full }, ctx.workingDirectory, config.rules).action !== 'allow') continue;
|
|
72
|
+
if (entry.isDirectory()) pending.push(full);
|
|
73
|
+
else matches.push(relative);
|
|
74
|
+
if (matches.length >= MAX_MATCHES) { limited = true; break; }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const output = matches.sort().map(name => literal(name)).join('\n');
|
|
78
|
+
return { success: true, output: limited ? `${output}${output ? '\n' : ''}... Glob reached its scan or match limit.` : output };
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { once } from 'node:events';
|
|
3
|
+
import { promises as fs } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { createInterface } from 'node:readline';
|
|
6
|
+
import { CONFIG_LIMITS, OUTPUT_TRUNCATION_MARKER } from '../config/limits.ts';
|
|
7
|
+
import type { Args, Tool, ToolContext } from '../types/index.ts';
|
|
8
|
+
import { resolveExternalExecutable } from './executable.ts';
|
|
9
|
+
|
|
10
|
+
const modes = ['content', 'files_with_matches', 'count'] as const;
|
|
11
|
+
type OutputMode = typeof modes[number];
|
|
12
|
+
const MAX_CONTEXT = 10;
|
|
13
|
+
const properties = {
|
|
14
|
+
query: { type: 'string', description: 'Literal text to search for' },
|
|
15
|
+
pattern: { type: 'string', description: 'ripgrep regular expression' },
|
|
16
|
+
path: { type: 'string', description: 'Workspace file or directory (default: current directory)' },
|
|
17
|
+
glob: { type: 'string', description: 'ripgrep file glob, e.g. *.{ts,tsx}' },
|
|
18
|
+
type: { type: 'string', description: 'ripgrep file type, e.g. ts' },
|
|
19
|
+
'-i': { type: 'boolean', description: 'Case-insensitive matching' },
|
|
20
|
+
output_mode: { enum: modes, description: 'Matching lines (default), filenames only, or matching line counts per file' },
|
|
21
|
+
context: { type: 'integer', minimum: 0, maximum: MAX_CONTEXT, description: 'Surrounding lines per match; content mode only' },
|
|
22
|
+
};
|
|
23
|
+
type GrepArgs = Args & { query?: string; pattern?: string; path?: string; glob?: string; type?: string; '-i'?: boolean; output_mode?: OutputMode; context?: number };
|
|
24
|
+
|
|
25
|
+
export function validGrepArgs(input: unknown): input is GrepArgs {
|
|
26
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) return false;
|
|
27
|
+
const args = input as GrepArgs;
|
|
28
|
+
return (args.query !== undefined) !== (args.pattern !== undefined) &&
|
|
29
|
+
Object.entries(args).every(([key, value]) => {
|
|
30
|
+
if (!Object.hasOwn(properties, key)) return false;
|
|
31
|
+
if (key === '-i') return typeof value === 'boolean';
|
|
32
|
+
if (key === 'output_mode') return modes.includes(value as OutputMode);
|
|
33
|
+
if (key === 'context') return (args.output_mode === undefined || args.output_mode === 'content') &&
|
|
34
|
+
typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= MAX_CONTEXT;
|
|
35
|
+
return typeof value === 'string' && !value.includes('\0');
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function findRipgrep(cwd: string): Promise<string> {
|
|
40
|
+
const { getAgentDir } = await import('@earendil-works/pi-coding-agent');
|
|
41
|
+
const dirs = [path.join(getAgentDir(), 'bin'), ...(process.env.PATH ?? '').split(path.delimiter)];
|
|
42
|
+
for (const dir of dirs) {
|
|
43
|
+
if (!path.isAbsolute(dir)) continue;
|
|
44
|
+
const exe = await resolveExternalExecutable(path.join(dir, process.platform === 'win32' ? 'rg.exe' : 'rg'), cwd);
|
|
45
|
+
if (exe) return exe;
|
|
46
|
+
}
|
|
47
|
+
throw new Error('ripgrep (rg) is required for regex or filtered searches. Install it in Pi’s bin directory or on PATH.');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
class SearchOutput {
|
|
51
|
+
private rows: string[] = [];
|
|
52
|
+
private size = 0;
|
|
53
|
+
truncated = false;
|
|
54
|
+
hits = 0;
|
|
55
|
+
|
|
56
|
+
constructor(readonly mode: OutputMode, readonly limit: number) {}
|
|
57
|
+
|
|
58
|
+
get full() { return this.truncated || this.hits >= this.limit; }
|
|
59
|
+
|
|
60
|
+
add(line: string) {
|
|
61
|
+
if (this.truncated) return;
|
|
62
|
+
const remaining = CONFIG_LIMITS.maxOutputChars - OUTPUT_TRUNCATION_MARKER.length - this.size;
|
|
63
|
+
if (line.length >= remaining) {
|
|
64
|
+
this.rows.push(line.slice(0, Math.max(0, remaining - 1)).replace(/[\uD800-\uDBFF]$/u, ''));
|
|
65
|
+
this.truncated = true;
|
|
66
|
+
} else {
|
|
67
|
+
this.rows.push(line);
|
|
68
|
+
this.size += line.length + 1;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
format() {
|
|
73
|
+
if (this.hits === this.limit) this.add(`... Search stopped at the configured limit of ${this.limit} ${this.mode === 'content' ? 'matches' : 'files'}.`);
|
|
74
|
+
return this.rows.join('\n') + (this.truncated ? OUTPUT_TRUNCATION_MARKER : '');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Keep the original literal search's traversal of hidden and ignored files.
|
|
79
|
+
async function literalSearch(root: string, file: string | undefined, query: string, context: number, result: SearchOutput, signal?: AbortSignal) {
|
|
80
|
+
async function searchFile(full: string) {
|
|
81
|
+
let text: string;
|
|
82
|
+
try { text = await fs.readFile(full, { encoding: 'utf8', signal }); }
|
|
83
|
+
catch { signal?.throwIfAborted(); return; }
|
|
84
|
+
const name = path.relative(root, full);
|
|
85
|
+
const lines = text.split('\n');
|
|
86
|
+
if (result.mode !== 'content') {
|
|
87
|
+
let count = 0;
|
|
88
|
+
for (const line of lines) {
|
|
89
|
+
if (!line.includes(query)) continue;
|
|
90
|
+
count++;
|
|
91
|
+
if (result.mode === 'files_with_matches') break;
|
|
92
|
+
}
|
|
93
|
+
if (count) {
|
|
94
|
+
result.hits++;
|
|
95
|
+
result.add(result.mode === 'count' ? `${name}:${count}` : name);
|
|
96
|
+
}
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const matches = new Set<number>();
|
|
100
|
+
for (let i = 0; i < lines.length && matches.size < result.limit - result.hits; i++) {
|
|
101
|
+
if (lines[i].includes(query)) matches.add(i);
|
|
102
|
+
}
|
|
103
|
+
let next = 0;
|
|
104
|
+
for (const index of matches) {
|
|
105
|
+
for (let i = Math.max(next, index - context); i <= Math.min(lines.length - 1, index + context); i++) {
|
|
106
|
+
if (!matches.has(i) && lines[i].includes(query)) break; // Beyond the match cap, do not emit more matches as context.
|
|
107
|
+
const sep = matches.has(i) ? ':' : '-';
|
|
108
|
+
result.add(`${name}${sep}${i + 1}${sep}${lines[i]}`);
|
|
109
|
+
if (result.truncated) return;
|
|
110
|
+
next = i + 1;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
result.hits += matches.size;
|
|
114
|
+
}
|
|
115
|
+
async function walk(dir: string) {
|
|
116
|
+
for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
|
|
117
|
+
signal?.throwIfAborted();
|
|
118
|
+
if (result.full) return;
|
|
119
|
+
const full = path.join(dir, entry.name);
|
|
120
|
+
if (entry.isDirectory()) await walk(full);
|
|
121
|
+
else if (entry.isFile()) await searchFile(full);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (file) await searchFile(file);
|
|
125
|
+
else await walk(root);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
type RgText = { text: string } | { bytes: string };
|
|
129
|
+
function decode(field: RgText) {
|
|
130
|
+
return 'text' in field ? field.text : Buffer.from(field.bytes, 'base64').toString('utf8');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function rgSearch(ctx: ToolContext, root: string, file: string | undefined, args: GrepArgs, result: SearchOutput) {
|
|
134
|
+
const exe = await findRipgrep(ctx.workingDirectory);
|
|
135
|
+
const flags = ['--no-config', '--json'];
|
|
136
|
+
const context = args.context ?? 0;
|
|
137
|
+
if (context) flags.push('--context', String(context));
|
|
138
|
+
if (result.mode === 'files_with_matches') flags.push('--max-count', '1');
|
|
139
|
+
if (args.query !== undefined) flags.push('--fixed-strings');
|
|
140
|
+
if (args['-i']) flags.push('--ignore-case');
|
|
141
|
+
if (args.glob !== undefined) flags.push('--glob', args.glob);
|
|
142
|
+
if (args.type !== undefined) flags.push('--type', args.type);
|
|
143
|
+
flags.push('-e', args.pattern ?? args.query!, '--', file ? `.${path.sep}${path.basename(file)}` : '.');
|
|
144
|
+
ctx.signal?.throwIfAborted();
|
|
145
|
+
const child = spawn(exe, flags, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, signal: ctx.signal });
|
|
146
|
+
let diagnostic = '';
|
|
147
|
+
child.stderr.setEncoding('utf8').on('data', (chunk: string) => { diagnostic += chunk.slice(0, 4096 - diagnostic.length); });
|
|
148
|
+
const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
149
|
+
async function collect() {
|
|
150
|
+
let trailing = context;
|
|
151
|
+
for await (const line of lines) {
|
|
152
|
+
const { type, data } = JSON.parse(line);
|
|
153
|
+
if (result.full) {
|
|
154
|
+
if (result.truncated || type !== 'context' || trailing === 0) break;
|
|
155
|
+
trailing--;
|
|
156
|
+
}
|
|
157
|
+
if (result.mode === 'content' && (type === 'match' || type === 'context')) {
|
|
158
|
+
const sep = type === 'match' ? ':' : '-';
|
|
159
|
+
if (type === 'match') result.hits++;
|
|
160
|
+
result.add(`${path.normalize(decode(data.path))}${sep}${data.line_number}${sep}${decode(data.lines).replace(/\r?\n$/, '')}`);
|
|
161
|
+
} else if (result.mode === 'files_with_matches' && type === 'match') {
|
|
162
|
+
result.hits++;
|
|
163
|
+
result.add(path.normalize(decode(data.path)));
|
|
164
|
+
} else if (result.mode === 'count' && type === 'end' && data.stats.matched_lines > 0) {
|
|
165
|
+
result.hits++;
|
|
166
|
+
result.add(`${path.normalize(decode(data.path))}:${data.stats.matched_lines}`);
|
|
167
|
+
}
|
|
168
|
+
if (result.full && (!trailing || result.truncated)) break;
|
|
169
|
+
}
|
|
170
|
+
if (result.full) child.kill();
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
const [[code]] = await Promise.all([once(child, 'close'), collect()]);
|
|
174
|
+
ctx.signal?.throwIfAborted();
|
|
175
|
+
if (!result.full && code !== 0 && code !== 1) throw new Error(diagnostic.trim() || `ripgrep exited with code ${code}`);
|
|
176
|
+
} finally {
|
|
177
|
+
lines.close();
|
|
178
|
+
if (child.exitCode === null && child.signalCode === null) child.kill();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function createGrepTool(defaultLimit: number, resolvePath: (ctx: ToolContext, input: string) => Promise<string>): Tool<GrepArgs> {
|
|
183
|
+
return {
|
|
184
|
+
name: 'grep',
|
|
185
|
+
description: 'Search file contents with a literal query or regex pattern. Defaults to path:line:text; also supports nearby context, filenames, or per-file matching line counts.',
|
|
186
|
+
parameters: { type: 'object', properties, additionalProperties: false },
|
|
187
|
+
validate: validGrepArgs,
|
|
188
|
+
async execute(args, ctx) {
|
|
189
|
+
const target = await resolvePath(ctx, args.path ?? '.');
|
|
190
|
+
const stat = await fs.stat(target);
|
|
191
|
+
if (!stat.isFile() && !stat.isDirectory()) throw new Error('grep requires a regular file or directory');
|
|
192
|
+
const file = stat.isFile() ? target : undefined;
|
|
193
|
+
const root = file ? path.dirname(file) : target;
|
|
194
|
+
const result = new SearchOutput(args.output_mode ?? 'content', ctx.projectConfig?.filesystem?.maxGrepMatches ?? defaultLimit);
|
|
195
|
+
if (args.query !== undefined && args.glob === undefined && args.type === undefined && !args['-i']) {
|
|
196
|
+
await literalSearch(root, file, args.query, args.context ?? 0, result, ctx.signal);
|
|
197
|
+
} else {
|
|
198
|
+
await rgSearch(ctx, root, file, args, result);
|
|
199
|
+
}
|
|
200
|
+
return { success: true, output: result.format() };
|
|
201
|
+
},
|
|
202
|
+
};
|
|
203
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { constants, promises as fs } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import type { ToolContext, ToolResult } from '../types/index.ts';
|
|
4
|
+
import { isProtectedWrite, isWithin } from '../extension/permission-modes/paths.ts';
|
|
5
|
+
|
|
6
|
+
const MAX_BYTES = 2 * 1024 * 1024;
|
|
7
|
+
const MAX_DIMENSION = 4096;
|
|
8
|
+
const pngHeader = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
|
9
|
+
|
|
10
|
+
export function imageMime(input: unknown): 'image/png' | 'image/jpeg' | undefined {
|
|
11
|
+
if (typeof input !== 'string') return;
|
|
12
|
+
const extension = path.extname(input).toLowerCase();
|
|
13
|
+
if (extension === '.png') return 'image/png';
|
|
14
|
+
if (extension === '.jpg' || extension === '.jpeg') return 'image/jpeg';
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function dimensions(bytes: Buffer, mimeType: NonNullable<ReturnType<typeof imageMime>>) {
|
|
18
|
+
if (mimeType === 'image/png') {
|
|
19
|
+
if (bytes.length < 33 || !bytes.subarray(0, 8).equals(pngHeader) || bytes.readUInt32BE(8) !== 13 || bytes.toString('ascii', 12, 16) !== 'IHDR') return;
|
|
20
|
+
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
|
|
21
|
+
}
|
|
22
|
+
if (bytes.length < 4 || bytes.readUInt16BE(0) !== 0xffd8) return;
|
|
23
|
+
let i = 2;
|
|
24
|
+
while (i < bytes.length && bytes[i++] === 0xff) {
|
|
25
|
+
while (bytes[i] === 0xff) i++;
|
|
26
|
+
const marker = bytes[i++];
|
|
27
|
+
if (marker === 0xda || marker === 0xd9 || i + 2 > bytes.length) return;
|
|
28
|
+
const length = bytes.readUInt16BE(i);
|
|
29
|
+
if (length < 2 || i + length > bytes.length) return;
|
|
30
|
+
if ([0xc0, 0xc1, 0xc2].includes(marker) && length >= 8) {
|
|
31
|
+
return { width: bytes.readUInt16BE(i + 5), height: bytes.readUInt16BE(i + 3) };
|
|
32
|
+
}
|
|
33
|
+
i += length;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function readImage(input: string, resolved: string, ctx: ToolContext): Promise<ToolResult> {
|
|
38
|
+
const mimeType = imageMime(input)!;
|
|
39
|
+
const root = await fs.realpath(ctx.workingDirectory);
|
|
40
|
+
if (!isWithin(root, resolved) || isProtectedWrite(resolved) || path.resolve(root, input) !== resolved || await fs.realpath(resolved) !== resolved) {
|
|
41
|
+
return { success: false, error: 'Image reads require a non-protected path without symlinks inside the workspace' };
|
|
42
|
+
}
|
|
43
|
+
if (ctx.authorizeImage && !ctx.authorizeImage()) return { success: false, error: 'Image attachment was not approved or the selected model cannot accept images' };
|
|
44
|
+
ctx.signal?.throwIfAborted();
|
|
45
|
+
const file = await fs.open(resolved, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
46
|
+
try {
|
|
47
|
+
const stat = await file.stat();
|
|
48
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_BYTES) {
|
|
49
|
+
return { success: false, error: 'Image reads require a regular single-link file of at most 2 MiB' };
|
|
50
|
+
}
|
|
51
|
+
const buffer = Buffer.alloc(stat.size + 1);
|
|
52
|
+
let length = 0;
|
|
53
|
+
while (length < buffer.length) {
|
|
54
|
+
ctx.signal?.throwIfAborted();
|
|
55
|
+
const { bytesRead } = await file.read(buffer, length, buffer.length - length, length);
|
|
56
|
+
if (!bytesRead) break;
|
|
57
|
+
length += bytesRead;
|
|
58
|
+
}
|
|
59
|
+
if (length !== stat.size || await fs.realpath(resolved) !== resolved) {
|
|
60
|
+
return { success: false, error: 'Image changed while reading' };
|
|
61
|
+
}
|
|
62
|
+
const bytes = buffer.subarray(0, length);
|
|
63
|
+
const size = dimensions(bytes, mimeType);
|
|
64
|
+
if (!size?.width || !size.height || size.width > MAX_DIMENSION || size.height > MAX_DIMENSION) {
|
|
65
|
+
return { success: false, error: 'Expected a PNG or JPEG with matching headers and dimensions of at most 4096 × 4096' };
|
|
66
|
+
}
|
|
67
|
+
ctx.signal?.throwIfAborted();
|
|
68
|
+
if (ctx.imageApprovalCurrent?.() === false) return { success: false, error: 'Image approval is no longer valid' };
|
|
69
|
+
return { success: true, output: `Read image (${mimeType}, ${size.width} × ${size.height}).`, image: { type: 'image', mimeType, data: bytes.toString('base64') } };
|
|
70
|
+
} finally { await file.close(); }
|
|
71
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { createAdvancedTools } from './advanced.ts';
|
|
2
|
+
import { createAgentTools } from './agent.ts';
|
|
3
|
+
import { BI_CONFIG, type BiConfig } from '../config/index.ts';
|
|
4
|
+
import type { AskUserFn } from '../types/index.ts';
|
|
5
|
+
import { ToolDispatcher } from './dispatcher.ts';
|
|
6
|
+
import { createExecutionTools } from './execution.ts';
|
|
7
|
+
import { createFileSystemTools } from './filesystem.ts';
|
|
8
|
+
import { createGitTools } from './git.ts';
|
|
9
|
+
import { createLspTool } from './lsp.ts';
|
|
10
|
+
import { createWebFetchTool } from './web-fetch.ts';
|
|
11
|
+
import { createWebSearchTool } from './web-search.ts';
|
|
12
|
+
import { createUndoJournal } from './undo-journal.ts';
|
|
13
|
+
import { ToolRegistry } from './registry.ts';
|
|
14
|
+
|
|
15
|
+
/** Build a registry containing the configured tool groups. */
|
|
16
|
+
export function createToolSystem(options: { askUser?: AskUserFn; config?: BiConfig } = {}) {
|
|
17
|
+
const registry = new ToolRegistry();
|
|
18
|
+
const config = options.config ?? BI_CONFIG;
|
|
19
|
+
if (!Number.isInteger(config.execution.timeoutMs) || config.execution.timeoutMs < 1) {
|
|
20
|
+
throw new Error('execution.timeoutMs must be a positive integer');
|
|
21
|
+
}
|
|
22
|
+
const execution = createExecutionTools(undefined, {
|
|
23
|
+
timeoutMs: config.execution.timeoutMs,
|
|
24
|
+
maxOutputChars: config.output.maxChars,
|
|
25
|
+
});
|
|
26
|
+
const journal = config.toolGroups.agent ? createUndoJournal() : undefined;
|
|
27
|
+
const tools = [
|
|
28
|
+
...(config.toolGroups.filesystem ? createFileSystemTools({ ...config.filesystem, journal }) : []),
|
|
29
|
+
...(config.toolGroups.execution ? execution.tools : []),
|
|
30
|
+
...(config.toolGroups.git ? createGitTools(config.git) : []),
|
|
31
|
+
...(config.toolGroups.agent ? createAgentTools({ ...options, journal }) : []),
|
|
32
|
+
...(config.toolGroups.advanced ? [...createAdvancedTools(), createLspTool(), createWebFetchTool(), createWebSearchTool()] : []),
|
|
33
|
+
];
|
|
34
|
+
for (const tool of tools) registry.register(tool);
|
|
35
|
+
return {
|
|
36
|
+
registry,
|
|
37
|
+
dispatcher: new ToolDispatcher(registry, config.output.maxChars),
|
|
38
|
+
processManager: execution.processManager,
|
|
39
|
+
journal,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export * from '../types/index.ts';
|
|
44
|
+
export { ToolRegistry } from './registry.ts';
|
|
45
|
+
export { ToolDispatcher } from './dispatcher.ts';
|
|
46
|
+
export { createFileSystemTools } from './filesystem.ts';
|
|
47
|
+
export { createExecutionTools, ProcessManager } from './execution.ts';
|
|
48
|
+
export { createGitTools } from './git.ts';
|
|
49
|
+
export { createAgentTools } from './agent.ts';
|
|
50
|
+
export { createAdvancedTools } from './advanced.ts';
|
|
51
|
+
export { BI_CONFIG } from '../config/index.ts';
|
|
52
|
+
export type { BiConfig } from '../config/index.ts';
|