@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,236 @@
1
+ import path from 'node:path';
2
+ import { lstatSync, readdirSync } from 'node:fs';
3
+ import { isProtectedWrite, isWithin, resolvePermissionPath } from './paths.ts';
4
+ import { classifyShell } from './shell.ts';
5
+ import { shellForTool } from '../../tools/shells.ts';
6
+ import { validGrepArgs } from '../../tools/grep.ts';
7
+ import { isMcpResourceTool, validMcpResourceArgs } from './mcp-resources.ts';
8
+ import { validNotebookEdit } from '../../tools/notebook.ts';
9
+ import { validLspArgs } from '../../tools/lsp.ts';
10
+ import { parseWebUrl, validWebFetchArgs } from '../../tools/web-fetch.ts';
11
+ import { validWebSearchArgs } from '../../tools/web-search.ts';
12
+ import { validTodoArgs } from '../../tools/todo.ts';
13
+ import { imageMime } from '../../tools/image-read.ts';
14
+
15
+ export type Decision = { action: 'allow' | 'ask' | 'deny'; reason: string; source?: 'rule' | 'default' | 'boundary' };
16
+ export interface PermissionRules { allow?: string[]; ask?: string[]; deny?: string[] }
17
+ const result = (action: Decision['action'], reason: string, source: Decision['source'] = 'boundary'): Decision => ({ action, reason, source });
18
+
19
+ /** Directory operations can affect protected descendants even when the parent is ordinary. */
20
+ function containsProtectedDescendant(cwd: string, target: string): boolean {
21
+ const pending = [resolvePermissionPath(cwd, target)];
22
+ let visited = 0;
23
+ while (pending.length) {
24
+ if (++visited > 10000) throw new Error('Directory too large to classify');
25
+ const current = pending.pop()!;
26
+ let stat;
27
+ try { stat = lstatSync(current); } catch (error) {
28
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
29
+ throw error;
30
+ }
31
+ if (!stat.isDirectory() || stat.isSymbolicLink()) continue;
32
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
33
+ const child = path.join(current, entry.name);
34
+ if (isProtectedWrite(child)) return true;
35
+ if (entry.isDirectory() && !entry.isSymbolicLink()) pending.push(child);
36
+ }
37
+ }
38
+ return false;
39
+ }
40
+
41
+ function globExpression(glob: string): RegExp {
42
+ const pattern = [...glob].map(c => c === '*' ? '.*' : c === '?' ? '.' : c.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')).join('');
43
+ return new RegExp(`^${pattern}$`, 's');
44
+ }
45
+
46
+ function matchesRule(tool: string, args: Record<string, unknown>, rule: string, cwd: string): boolean {
47
+ const split = rule.indexOf(':');
48
+ if (split < 1 || rule.slice(0, split) !== tool) return false;
49
+ if (tool === 'web_fetch') return globExpression(rule.slice(split + 1)).test(parseWebUrl(args.url)?.href ?? '');
50
+ if (tool === 'web_search') return globExpression(rule.slice(split + 1)).test(String(args.query));
51
+ if (isMcpResourceTool(tool)) {
52
+ const matches = globExpression(rule.slice(split + 1));
53
+ return [args.server, args.uri].some(value => typeof value === 'string' && matches.test(value));
54
+ }
55
+ if (['bash', 'powershell', 'background', 'terminal'].includes(tool)) {
56
+ const pattern = globExpression(rule.slice(split + 1));
57
+ return [args.command, args.input].some(value => typeof value === 'string' && pattern.test(value));
58
+ }
59
+ const values = [args.path, args.source, args.destination, ...(Array.isArray(args.edits) ? args.edits.map(edit => edit && typeof edit === 'object' ? (edit as Record<string, unknown>).path : undefined) : [])];
60
+ if (!values.some(value => typeof value === 'string')) values.push(JSON.stringify(args));
61
+ const rulePath = rule.slice(split + 1);
62
+ const patterns = [rulePath];
63
+ try {
64
+ const wildcard = rulePath.search(/[*?]/);
65
+ const prefix = wildcard < 0 ? rulePath : rulePath.slice(0, wildcard);
66
+ const base = wildcard < 0 ? prefix : prefix.endsWith('/') ? prefix.slice(0, -1) || '/' : path.dirname(prefix);
67
+ const suffix = wildcard < 0 ? '' : rulePath.slice(base === '.' ? 0 : base.length);
68
+ const resolved = resolvePermissionPath(cwd, base) + suffix;
69
+ patterns.push(resolved, path.relative(resolvePermissionPath(cwd, '.'), resolved));
70
+ } catch { /* Invalid paths are rejected by the path checks below. */ }
71
+ const expressions = patterns.map(globExpression);
72
+ const matches = (value: string) => expressions.some(expression => expression.test(value));
73
+ return values.some(value => {
74
+ if (typeof value !== 'string') return false;
75
+ if (matches(value)) return true;
76
+ try {
77
+ const root = resolvePermissionPath(cwd, '.');
78
+ const lexical = path.resolve(cwd, value);
79
+ const resolved = resolvePermissionPath(cwd, value);
80
+ return [lexical, resolved, path.relative(cwd, lexical), path.relative(root, resolved)].some(matches);
81
+ } catch { return false; }
82
+ });
83
+ }
84
+
85
+ function matchesWriteAllow(cwd: string, tool: string, target: string, rules: string[]): boolean {
86
+ try {
87
+ const root = resolvePermissionPath(cwd, '.');
88
+ const resolved = resolvePermissionPath(cwd, target);
89
+ if (!isWithin(root, resolved)) return false;
90
+ const relative = path.relative(root, resolved);
91
+ return rules.some(rule => {
92
+ if (!rule.startsWith(`${tool}:`)) return false;
93
+ const pattern = rule.slice(tool.length + 1).replace(/^(?:\.\/)+/, '');
94
+ return globExpression(pattern).test(path.isAbsolute(pattern) ? resolved : relative);
95
+ });
96
+ } catch {
97
+ return false;
98
+ }
99
+ }
100
+
101
+ /** Mode gate only: the tool's own validation and authorization still run. */
102
+ export function decidePermission(mode: string, toolName: string, input: unknown, cwd: string, rules: PermissionRules = {}): Decision {
103
+ if (!input || typeof input !== 'object' || Array.isArray(input) || typeof cwd !== 'string' || !cwd)
104
+ return result('deny', 'Invalid tool arguments or working directory');
105
+ const args = input as Record<string, unknown>;
106
+ if (isMcpResourceTool(toolName)) {
107
+ if (!validMcpResourceArgs(toolName, args)) return result('deny', 'MCP resource calls require a server and valid resource arguments');
108
+ if (mode === 'plan' || mode === 'dontAsk') return result('deny', 'This mode blocks MCP resource calls');
109
+ if (rules.deny?.some(rule => matchesRule(toolName, args, rule, cwd))) return result('deny', 'Denied by permission rule', 'rule');
110
+ return result('ask', 'MCP resources require one-time approval');
111
+ }
112
+ if (toolName === 'notebook_edit' && !validNotebookEdit(args)) return result('deny', 'Invalid notebook edit arguments');
113
+ const writes: Record<string, string[]> = { write: ['path'], edit: ['path'], notebook_edit: ['path'], mkdir: ['path'], delete: ['path'], copy: ['destination'], move: ['source', 'destination'] };
114
+ const readTools = ['read', 'ls', 'grep', 'find', 'glob'];
115
+ if (toolName === 'web_search' && !validWebSearchArgs(args)) return result('deny', 'Invalid web search query');
116
+ if (toolName === 'web_fetch' && !validWebFetchArgs(args)) return result('deny', 'Web fetch requires a public HTTPS URL without credentials or a custom port');
117
+ if (toolName === 'lsp' && !validLspArgs(args)) return result('deny', 'Invalid LSP arguments');
118
+ const readPath = toolName === 'lsp' ? args.path : readTools.includes(toolName)
119
+ ? (args.path === undefined && toolName !== 'read' ? '.' : args.path) : undefined;
120
+ const writePaths: unknown[] = (writes[toolName] ?? []).map(field => args[field]);
121
+ const readPaths: unknown[] = readPath === undefined ? [] : [readPath];
122
+ if (readTools.includes(toolName) && readPath === undefined) return result('deny', 'Missing read path');
123
+ if (toolName === 'copy') readPaths.push(args.source);
124
+ if (toolName === 'apply_patch') {
125
+ if (!Array.isArray(args.edits) || !args.edits.length) return result('deny', 'Invalid patch edits');
126
+ for (const edit of args.edits) {
127
+ if (!edit || typeof edit !== 'object' || Array.isArray(edit)) return result('deny', 'Invalid patch edit');
128
+ writePaths.push((edit as Record<string, unknown>).path);
129
+ }
130
+ }
131
+ let outside = false, sensitive = false;
132
+ const check = (target: unknown, write: boolean, workspaceOnly: boolean): Decision | undefined => {
133
+ if (typeof target !== 'string' || !target || target.includes('\0')) return result('deny', 'Invalid path');
134
+ try {
135
+ const root = resolvePermissionPath(cwd, '.');
136
+ const lexical = path.resolve(cwd, target);
137
+ // The filesystem and patch tools resolve relative inputs from the real cwd.
138
+ // Glob, LSP and notebook edits first check the logical workspace path.
139
+ const logicalRoot = ['glob', 'lsp', 'notebook_edit'].includes(toolName);
140
+ const base = workspaceOnly && !logicalRoot ? root : path.resolve(cwd);
141
+ const candidate = path.resolve(base, target);
142
+ if (workspaceOnly && !isWithin(base, candidate)) return result('deny', 'Path is outside the working directory');
143
+ const resolved = resolvePermissionPath(base, candidate);
144
+ if (workspaceOnly && !isWithin(root, resolved)) return result('deny', 'Path is outside the working directory');
145
+ if (isProtectedWrite(lexical) || isProtectedWrite(candidate) || isProtectedWrite(resolved)) {
146
+ if (write) return result('deny', 'Protected path');
147
+ sensitive = true;
148
+ }
149
+ if (!workspaceOnly && (!isWithin(root, lexical) || !isWithin(root, resolved))) outside = true;
150
+ } catch { return result('deny', 'Unable to resolve path safely'); }
151
+ };
152
+ for (const target of writePaths) { const failure = check(target, true, true); if (failure) return failure; }
153
+ for (const target of readPaths) { const failure = check(target, false, true); if (failure) return failure; }
154
+ const image = toolName === 'read' && !!imageMime(args.path);
155
+ if (image && (sensitive || args.offset !== undefined || args.limit !== undefined)) return result('deny', 'Images require a non-protected path without a line range');
156
+ if (sensitive && ['glob', 'lsp'].includes(toolName)) return result('deny', `${toolName === 'glob' ? 'Glob' : 'LSP'} requires a non-protected workspace path`);
157
+ if (['delete', 'move', 'copy'].includes(toolName)) {
158
+ const target = toolName === 'delete' ? args.path : args.source;
159
+ try {
160
+ if (typeof target !== 'string' || containsProtectedDescendant(cwd, target)) return result('deny', 'Directory contains protected paths');
161
+ } catch { return result('deny', 'Unable to classify directory safely'); }
162
+ }
163
+ if (toolName === 'terminal' && !(typeof args.input === 'string'
164
+ ? args.command === undefined && typeof args.processId === 'string' && !!args.processId
165
+ : args.input === undefined && args.processId === undefined && typeof args.command === 'string'))
166
+ return result('deny', 'Invalid terminal arguments');
167
+ const shellTool = ['bash', 'powershell', 'background', 'terminal'].includes(toolName);
168
+ const backend = shellTool ? shellForTool(toolName) : undefined;
169
+ const powershell = toolName === 'powershell' || backend === 'powershell';
170
+ let shellUnknown = false;
171
+ if (powershell && typeof args.command === 'string') {
172
+ shellUnknown = true;
173
+ } else if (shellTool && typeof args.command === 'string') {
174
+ const shell = classifyShell(args.command, cwd);
175
+ if (shell.kind === 'deny') return result('deny', shell.reason);
176
+ if (shell.kind === 'unknown') shellUnknown = true;
177
+ else for (const operand of shell.paths) { const failure = check(operand, false, false); if (failure) return failure; }
178
+ } else if (shellTool && toolName !== 'terminal') return result('deny', 'Missing command');
179
+ if (toolName === 'write' && typeof args.content !== 'string') return result('deny', 'Invalid write content');
180
+ if (toolName === 'plan_note' && typeof args.content !== 'string') return result('deny', 'Invalid plan note content');
181
+ if (toolName === 'apply_patch' && (args.edits as unknown[]).some(edit => {
182
+ const item = edit as Record<string, unknown>;
183
+ return typeof item.oldText !== 'string' || typeof item.newText !== 'string';
184
+ })) return result('deny', 'Invalid patch edit');
185
+ if (toolName === 'edit') {
186
+ const pairs = Array.isArray(args.edits) ? args.edits : [args];
187
+ if (!pairs.length || pairs.some(item => !item || typeof item !== 'object' ||
188
+ !(typeof ((item as Record<string, unknown>).old_str ?? (item as Record<string, unknown>).oldText) === 'string' &&
189
+ typeof ((item as Record<string, unknown>).new_str ?? (item as Record<string, unknown>).newText) === 'string'))) return result('deny', 'Invalid edit arguments');
190
+ }
191
+ if (toolName === 'grep' && !validGrepArgs(args)) return result('deny', 'Supply exactly one literal query or regex pattern and valid filters');
192
+ if (toolName === 'glob' && (typeof args.pattern !== 'string' || !args.pattern || args.pattern.length > 256)) return result('deny', 'Invalid glob pattern');
193
+ if (toolName === 'find' && typeof (args.name ?? args.pattern) !== 'string') return result('deny', 'Invalid find pattern');
194
+ if (toolName === 'read' && ['offset', 'limit'].some(key => args[key] !== undefined && (typeof args[key] !== 'number' || !Number.isInteger(args[key]) || (args[key] as number) < 1))) return result('deny', 'Invalid read range');
195
+ if (toolName === 'git_commit' && (typeof args.message !== 'string' || !args.message.trim() || args.message.includes('\0'))) return result('deny', 'Invalid commit message');
196
+ if (toolName === 'git_branch' && args.name !== undefined && typeof args.name !== 'string') return result('deny', 'Invalid branch name');
197
+ if (toolName === 'git_diff' && args.staged !== undefined && typeof args.staged !== 'boolean') return result('deny', 'Invalid diff arguments');
198
+ if (toolName === 'git_log' && args.limit !== undefined && (typeof args.limit !== 'number' || !Number.isInteger(args.limit) || args.limit < 1 || args.limit > 100)) return result('deny', 'Invalid log limit');
199
+ if (toolName === 'process' && typeof args.processId !== 'string') return result('deny', 'Invalid process ID');
200
+ if (toolName === 'todo' && !validTodoArgs(args)) return result('deny', 'Invalid todo action or fields');
201
+ if (toolName === 'plan' && (!Array.isArray(args.steps) || args.steps.some(step => typeof step !== 'string'))) return result('deny', 'Invalid plan steps');
202
+ if (toolName === 'goal_report' && (!['continue', 'completed', 'blocked'].includes(String(args.status)) || typeof args.summary !== 'string' || !args.summary.trim())) return result('deny', 'Invalid goal report');
203
+ if (toolName === 'ask_user' && (!Array.isArray(args.questions) || !args.questions.length)) return result('deny', 'Invalid questions');
204
+ const listBranches = toolName === 'git_branch' && args.name === undefined;
205
+ if (mode === 'plan' && !listBranches && ![...readTools, 'git_status', 'git_diff', 'git_log', 'goal_report', 'todo', 'plan', 'ask_user', 'plan_note'].includes(toolName))
206
+ return result('deny', 'Plan mode blocks mutation, execution and delegation');
207
+ const matches = (items?: string[]) => items?.some(rule =>
208
+ matchesRule(toolName, readPath === undefined ? args : { ...args, path: readPath }, rule, cwd) ||
209
+ (!!backend && backend !== toolName && typeof args.command === 'string' && matchesRule(backend, args, rule, cwd))) ?? false;
210
+ if (matches(rules.deny)) return result('deny', 'Denied by permission rule', 'rule');
211
+ if (image) return mode === 'dontAsk' ? result('deny', 'No prompts mode blocks image attachments') : result('ask', 'Attaching an image requires one-time approval');
212
+ if (toolName === 'web_search') return mode === 'dontAsk'
213
+ ? result('deny', 'No prompts mode blocks web search')
214
+ : result('ask', 'Tavily web search requires one-time approval');
215
+ if (toolName === 'web_fetch') return mode === 'dontAsk'
216
+ ? result('deny', 'No prompts mode blocks web fetch')
217
+ : result('ask', 'Public web fetch requires one-time approval');
218
+ if (toolName === 'lsp' && rules.deny?.some(rule => matchesRule('read', { path: args.path }, rule, cwd))) return result('deny', 'LSP source file is restricted by read policy');
219
+ if (matches(rules.ask)) return result(mode === 'dontAsk' ? 'deny' : 'ask', 'Requires approval by permission rule', 'rule');
220
+ if (shellUnknown) return result(mode === 'dontAsk' ? 'deny' : 'ask', 'Unclassified shell command requires approval');
221
+ if (sensitive || outside) return result(mode === 'dontAsk' ? 'deny' : 'ask', 'Sensitive or outside path requires approval');
222
+ // Recursive grep reads every file, including credentials nested below the root.
223
+ if (toolName === 'grep') return result(mode === 'dontAsk' ? 'deny' : 'ask', 'Recursive search may read sensitive files');
224
+ if (mode === 'dontAsk' && toolName === 'ask_user') return result('deny', 'No prompts mode blocks interactive questions');
225
+ if (toolName === 'plan_note') return mode === 'plan' ? result('allow', 'Session plan note') : result('deny', 'Plan note is available only in Plan mode');
226
+ if (listBranches || [...readTools, 'git_status', 'git_diff', 'git_log', 'goal_report', 'todo', 'plan', 'ask_user', 'process'].includes(toolName)) return result('allow', 'Read or session bookkeeping');
227
+ const ordinaryEdit = ['write', 'edit', 'mkdir', 'apply_patch', 'copy', 'move'].includes(toolName);
228
+ if (ordinaryEdit && writePaths.length === 1 && readPaths.length === 0 && rules.allow &&
229
+ matchesWriteAllow(cwd, toolName, writePaths[0] as string, rules.allow)) {
230
+ return result('allow', 'Allowed by trusted user rule', 'rule');
231
+ }
232
+ if (ordinaryEdit && ['acceptEdits', 'auto'].includes(mode)) return result('allow', 'Project edit', 'default');
233
+ if (mode === 'bypassPermissions' && (ordinaryEdit || toolName === 'delete' || (shellTool && typeof args.command === 'string'))) return result('allow', 'Bypass mode', 'default');
234
+ if (mode === 'dontAsk') return result('deny', 'Permission requires confirmation');
235
+ return result('ask', 'Permission requires confirmation', 'default');
236
+ }
@@ -0,0 +1,104 @@
1
+ import type { PreviewLine } from '../../tui/permission-dialog.ts';
2
+ import { literal } from '../../tui/text.ts';
3
+ import { parseWebUrl } from '../../tools/web-fetch.ts';
4
+ import { isMcpResourceTool } from './mcp-resources.ts';
5
+ import { shellForTool } from '../../tools/shells.ts';
6
+ import { imageMime } from '../../tools/image-read.ts';
7
+
8
+ const MAX_FILE_PREVIEW = 12_000;
9
+ const actions = new Map([
10
+ ['read', 'Read file?'], ['edit', 'Edit file?'], ['write', 'Write file?'], ['apply_patch', 'Apply patch?'],
11
+ ['delete', 'Delete path?'], ['copy', 'Copy path?'], ['move', 'Move path?'], ['mkdir', 'Create directory?'],
12
+ ]);
13
+
14
+ function previewText(value: string, color?: PreviewLine['color'], prefix = ''): PreviewLine {
15
+ const clipped = value.length > MAX_FILE_PREVIEW;
16
+ const text = value.slice(0, MAX_FILE_PREVIEW).split('\n').map(line => prefix + line).join('\n');
17
+ return { text: clipped ? `${text}\n[preview truncated]` : text, color };
18
+ }
19
+
20
+ export function previewToolCall(toolName: string, input: Record<string, unknown>): { title: string; preview: PreviewLine[] } {
21
+ if (['bash', 'powershell', 'background', 'terminal'].includes(toolName)) {
22
+ if (typeof input.command === 'string') return {
23
+ title: shellForTool(toolName) === 'powershell'
24
+ ? (toolName === 'background' ? 'Start a background PowerShell command?' : 'Run PowerShell command?')
25
+ : (toolName === 'background' ? 'Start a background command?' : 'Run shell command?'),
26
+ preview: [{ text: input.command }],
27
+ };
28
+ if (toolName === 'terminal' && typeof input.input === 'string') return {
29
+ title: 'Send input to terminal?',
30
+ preview: [{ text: `Process: ${literal(String(input.processId))}`, color: 'dim' }, { text: input.input }],
31
+ };
32
+ }
33
+ if (toolName === 'git_add' && Array.isArray(input.paths)) return {
34
+ title: 'Stage Git paths?', preview: input.paths.map(value => ({ text: literal(String(value)) })),
35
+ };
36
+ if (toolName === 'git_checkout' && typeof input.branch === 'string') return {
37
+ title: 'Switch Git branch?', preview: [{ text: literal(input.branch) }],
38
+ };
39
+ if (toolName === 'git_branch' && typeof input.name === 'string') return {
40
+ title: 'Create Git branch?', preview: [{ text: literal(input.name) }],
41
+ };
42
+ if (toolName === 'git_commit' && typeof input.message === 'string') return {
43
+ title: 'Commit staged changes?', preview: [previewText(input.message)],
44
+ };
45
+ if (toolName === 'delete' && typeof input.path === 'string') return {
46
+ title: 'Delete path recursively?', preview: [{ text: `Path: ${literal(input.path)}` }],
47
+ };
48
+ const title = actions.get(toolName) ?? `Allow ${literal(toolName)}?`;
49
+ const preview: PreviewLine[] = [];
50
+ for (const [key, name] of [['path', 'Path'], ['source', 'From'], ['destination', 'To']] as const) {
51
+ const value = input[key];
52
+ if (typeof value === 'string') preview.push({ text: `${name}: ${literal(value)}` });
53
+ }
54
+ if (isMcpResourceTool(toolName)) {
55
+ const read = toolName === 'read_mcp_resource';
56
+ return {
57
+ title: read ? 'Read an MCP resource?' : toolName === 'list_mcp_resource_templates' ? 'List MCP resource templates?' : 'List MCP resources?',
58
+ preview: [{ text: `Server: ${literal(String(input.server))}` },
59
+ ...(read ? [{ text: `URI: ${literal(String(input.uri))}` }] : input.cursor ? [{ text: 'Request the next page.' }] : []),
60
+ { text: read ? 'Pi may return text or images to the model, or save binary content to a temporary file.' : 'Resource metadata goes to the model.' }],
61
+ };
62
+ }
63
+ if (toolName === 'web_search') return {
64
+ title: 'Search the web with Tavily?',
65
+ preview: [{ text: `Query: ${literal(String(input.query))}` },
66
+ { text: 'Tavily receives the query. Returned results go to the model.' }],
67
+ };
68
+ if (toolName === 'web_fetch') return {
69
+ title: 'Fetch a public web page?',
70
+ preview: [{ text: `GET ${literal(parseWebUrl(input.url)?.href ?? '')}` },
71
+ { text: 'The site receives this URL (including its query) and your network address. Returned text goes to the model.' }],
72
+ };
73
+ if (toolName === 'read' && imageMime(input.path)) return {
74
+ title: 'Attach this image to the model?',
75
+ preview: [...preview, { text: 'Image bytes may be sent to the selected provider and recorded in the session. Review the file for sensitive content first.' }],
76
+ };
77
+ if (toolName === 'lsp') return {
78
+ title: 'Run a local language server query?',
79
+ preview: [...preview, { text: `Action: ${literal(String(input.action))} (${literal(String(input.language_id))})` },
80
+ ...(typeof input.line === 'number' ? [{ text: `Position: ${input.line}:${input.character} (zero-based UTF-16)` }] : []),
81
+ { text: 'The selected server runs with your local user permissions and receives the workspace path and file contents.' }],
82
+ };
83
+ if (toolName === 'notebook_edit') return {
84
+ title: 'Edit notebook cell source?',
85
+ preview: [...preview, { text: `Cell index: ${Number(input.cell_index)} (zero-based)` },
86
+ previewText(String(input.old_source), 'toolDiffRemoved', '- '),
87
+ previewText(String(input.new_source), 'toolDiffAdded', '+ ')],
88
+ };
89
+ if (toolName === 'write' && typeof input.content === 'string') preview.push(previewText(input.content, 'toolDiffAdded', '+ '));
90
+ if (toolName === 'apply_patch' || toolName === 'edit') {
91
+ const edits = Array.isArray(input.edits) ? input.edits : [input];
92
+ for (const edit of edits.slice(0, 10)) {
93
+ if (!edit || typeof edit !== 'object') continue;
94
+ if (typeof edit.path === 'string' && edit !== input) preview.push({ text: `Path: ${literal(edit.path)}` });
95
+ const before = edit.old_str ?? edit.oldText, after = edit.new_str ?? edit.newText;
96
+ if (edit.replace_all === true || input.replace_all === true) preview.push({ text: 'Replace all matches', color: 'warning' });
97
+ if (typeof before === 'string') preview.push(previewText(before, 'toolDiffRemoved', '- '));
98
+ if (typeof after === 'string') preview.push(previewText(after, 'toolDiffAdded', '+ '));
99
+ }
100
+ if (edits.length > 10) preview.push({ text: `[${edits.length - 10} additional edits not shown]`, color: 'warning' });
101
+ }
102
+ if (!preview.length) preview.push(previewText(JSON.stringify(input, null, 2)));
103
+ return { title, preview };
104
+ }
@@ -0,0 +1,67 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import type { PermissionRules } from './policy.ts';
5
+ import { resolvePermissionPath } from './paths.ts';
6
+
7
+ const groups = ['allow', 'ask', 'deny'] as const;
8
+ export function validateRules(value: unknown, trusted: boolean): PermissionRules & { defaultMode?: string } {
9
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('configuration must be an object');
10
+ const input = value as Record<string, unknown>;
11
+ for (const key of Object.keys(input)) if (![...groups, 'defaultMode'].includes(key)) throw new Error(`unknown rule field: ${key}`);
12
+ const result: PermissionRules = {};
13
+ for (const key of groups) {
14
+ const list = input[key]; if (list === undefined) continue;
15
+ if (!Array.isArray(list) || list.length > 100 || list.some(x => typeof x !== 'string' || x.length > 500 || !/^[a-zA-Z0-9_]+:.+/.test(x))) throw new Error(`invalid ${key} rules`);
16
+ if (key === 'allow' && !trusted) throw new Error('project configuration cannot define allow rules');
17
+ result[key] = list as string[];
18
+ }
19
+ if (input.defaultMode !== undefined) {
20
+ if (!trusted || !['default','acceptEdits','plan','auto'].includes(String(input.defaultMode))) throw new Error('invalid or untrusted defaultMode');
21
+ (result as PermissionRules & { defaultMode?: string }).defaultMode = String(input.defaultMode);
22
+ }
23
+ return result;
24
+ }
25
+ function readRulesFile(root: string, relativePath: string): unknown {
26
+ let file = resolvePermissionPath(root, '.');
27
+ for (const component of relativePath.split('/')) {
28
+ file = path.join(file, component);
29
+ if (lstatSync(file).isSymbolicLink()) {
30
+ throw new Error('permission rules path contains a symbolic link');
31
+ }
32
+ }
33
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
34
+ try {
35
+ const stat = fstatSync(fd);
36
+ if (!stat.isFile() || stat.nlink !== 1) {
37
+ throw new Error('permission rules must be a regular file with one link');
38
+ }
39
+ return JSON.parse(readFileSync(fd, 'utf8'));
40
+ } finally {
41
+ closeSync(fd);
42
+ }
43
+ }
44
+
45
+ export function loadPermissionRules(cwd: string, report: (message: string) => void = console.warn) {
46
+ if (typeof cwd !== 'string' || !cwd) return { rules: {} as PermissionRules, groups: [], defaultMode: undefined as string | undefined, invalid: true };
47
+ let invalid = false;
48
+ const load = (root: string, relativePath: string, trusted: boolean) => {
49
+ try {
50
+ return validateRules(readRulesFile(root, relativePath), trusted);
51
+ } catch (error) {
52
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
53
+ invalid = true;
54
+ report(`Invalid permission rules ${path.join(root, relativePath)}: ${String(error)}`);
55
+ }
56
+ return {};
57
+ }
58
+ };
59
+ const user = load(os.homedir(), '.pi/agent/permission-modes.json', true);
60
+ const project = load(cwd, '.pi/permission-modes.json', false);
61
+ return {
62
+ rules: { allow: user.allow, ask: [...(user.ask ?? []), ...(project.ask ?? [])], deny: [...(user.deny ?? []), ...(project.deny ?? [])] },
63
+ groups: [{ label: 'User', rules: user }, { label: 'Project', rules: project }],
64
+ defaultMode: user.defaultMode,
65
+ invalid,
66
+ };
67
+ }
@@ -0,0 +1,183 @@
1
+ import { homedir } from 'node:os';
2
+ import path from 'node:path';
3
+ import { isProtectedWrite, resolvePermissionPath } from './paths.ts';
4
+
5
+ export type ShellClassification =
6
+ | { kind: 'read'; paths: string[] }
7
+ | { kind: 'unknown' }
8
+ | { kind: 'deny'; reason: string };
9
+
10
+ /** Parse a deliberately small shell subset. No expansion or shell operators are accepted. */
11
+ function words(command: string): string[] | undefined {
12
+ const result: string[] = [];
13
+ let word = '', started = false, quote: 'single' | 'double' | undefined;
14
+ for (let i = 0; i < command.length; i++) {
15
+ const ch = command[i]!;
16
+ if (quote === 'single') {
17
+ if (ch === "'") quote = undefined; else word += ch;
18
+ started = true;
19
+ } else if (quote === 'double') {
20
+ if (ch === '"') quote = undefined;
21
+ else if ('$`\\'.includes(ch)) return undefined;
22
+ else word += ch;
23
+ started = true;
24
+ } else if (ch === "'" || ch === '"') {
25
+ quote = ch === "'" ? 'single' : 'double'; started = true;
26
+ } else if (' \t'.includes(ch)) {
27
+ if (started) { result.push(word); word = ''; started = false; }
28
+ } else if ('\n\r;&|<>$`(){}*?[]~\\'.includes(ch)) return undefined;
29
+ else { word += ch; started = true; }
30
+ }
31
+ if (quote) return undefined;
32
+ if (started) result.push(word);
33
+ return result;
34
+ }
35
+
36
+ /** Only remember literal standalone commands, or a literal command following an absolute cd. */
37
+ export function rememberedShellCommand(command: string, cwd: string): { command: string; cwd: string } | undefined {
38
+ const literal = (value: string) => !!value && !value.includes('#') && !!words(value)?.length;
39
+ if (literal(command)) return { command, cwd };
40
+ // The only supported chain changes directory with the shell builtin; no other
41
+ // command in the chain can alter the subsequent command's context.
42
+ const match = /^cd (\/[a-zA-Z0-9_./-]+) && (.+)$/.exec(command);
43
+ if (!match || path.resolve(match[1]!) !== match[1] || !literal(match[2]!)) return undefined;
44
+ return { command: match[2]!, cwd: match[1]! };
45
+ }
46
+
47
+ /** Tokenize command words and separators for hard-denial detection only. */
48
+ function tokenize(command: string): { segments: string[][]; nested: string[]; outputs: string[]; links: string[] } | undefined {
49
+ const segments: string[][] = [[]];
50
+ const nested: string[] = [], outputs: string[] = [], links: string[] = [];
51
+ let word = '', started = false, complex = false, output = false, quote: 'single' | 'double' | undefined;
52
+ const flush = () => { if (started) { if (output) { outputs.push(word); output = false; } else segments[segments.length - 1]!.push(word); word = ''; started = false; } };
53
+ for (let i = 0; i < command.length; i++) {
54
+ const ch = command[i]!;
55
+ if (quote === 'single') {
56
+ if (ch === "'") quote = undefined; else word += ch;
57
+ started = true; continue;
58
+ }
59
+ if (ch === "'" && !quote) { quote = 'single'; started = true; continue; }
60
+ if (ch === '"') { quote = quote === 'double' ? undefined : 'double'; started = true; continue; }
61
+ if (ch === '\\') {
62
+ if (++i >= command.length) return undefined;
63
+ word += command[i]!; started = true; complex = true; continue;
64
+ }
65
+ if (ch === '$' || ch === '`') {
66
+ // Expansions are never used as evidence of safety. Inspect straightforward
67
+ // substitutions separately for hard denials; all such calls remain unknown.
68
+ complex = true; started = true;
69
+ if (ch === '$' && command[i + 1] === '(') {
70
+ let depth = 1, end = i + 2;
71
+ for (; end < command.length && depth; end++) {
72
+ if (command[end] === '(') depth++;
73
+ else if (command[end] === ')') depth--;
74
+ }
75
+ if (depth) return undefined;
76
+ nested.push(command.slice(i + 2, end - 1)); i = end - 1;
77
+ } else if (ch === '`') {
78
+ const end = command.indexOf('`', i + 1);
79
+ if (end < 0) return undefined;
80
+ nested.push(command.slice(i + 1, end)); i = end;
81
+ }
82
+ word += '?'; continue;
83
+ }
84
+ if (!quote && /[\s;&|<>]/.test(ch)) {
85
+ flush();
86
+ if (!/[ \t]/.test(ch)) {
87
+ complex = true;
88
+ if (ch === '>') { output = true; if (command[i + 1] === '>') i++; }
89
+ if (';&|\n\r'.includes(ch)) {
90
+ if (output) return undefined;
91
+ if (segments[segments.length - 1]!.length) {
92
+ const doubled = command[i + 1] === ch && (ch === '&' || ch === '|');
93
+ links.push(doubled ? ch + ch : ch);
94
+ segments.push([]);
95
+ }
96
+ if (command[i + 1] === ch && (ch === '&' || ch === '|')) i++;
97
+ }
98
+ }
99
+ continue;
100
+ }
101
+ if (!quote && '(){}*?[]~'.includes(ch)) complex = true;
102
+ word += ch; started = true;
103
+ }
104
+ if (quote) return undefined;
105
+ flush();
106
+ if (output) return undefined;
107
+ return { segments, nested, outputs, links };
108
+ }
109
+
110
+ function hardDenial(command: string, cwd: string, depth = 0): string | undefined {
111
+ if (depth > 8) return undefined;
112
+ const parsed = tokenize(command);
113
+ if (!parsed) return undefined;
114
+ for (const nested of parsed.nested) {
115
+ const denial = hardDenial(nested, cwd, depth + 1);
116
+ if (denial) return denial;
117
+ }
118
+ for (const target of parsed.outputs) {
119
+ try {
120
+ const lexical = path.resolve(cwd, target);
121
+ const real = resolvePermissionPath(cwd, target);
122
+ if (lexical === '/dev' || lexical.startsWith('/dev/') || real === '/dev' || real.startsWith('/dev/') || isProtectedWrite(lexical) || isProtectedWrite(real)) return 'protected output destination is blocked';
123
+ } catch { return 'unable to resolve output destination safely'; }
124
+ }
125
+ for (let i = 0; i < parsed.links.length; i++) {
126
+ const source = parsed.segments[i]?.[0]?.split('/').pop();
127
+ const dest = parsed.segments[i + 1]?.[0]?.split('/').pop();
128
+ if (parsed.links[i] === '|' && ['curl', 'wget'].includes(source ?? '') && ['sh', 'bash', 'dash', 'zsh', 'ksh'].includes(dest ?? '')) return 'remote script piped to shell is blocked';
129
+ }
130
+ for (const segment of parsed.segments) {
131
+ let commandIndex = 0;
132
+ while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(segment[commandIndex] ?? '')) commandIndex++;
133
+ if (['env', 'command', 'exec'].includes(segment[commandIndex]?.split('/').pop() ?? '')) {
134
+ commandIndex++;
135
+ while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(segment[commandIndex] ?? '')) commandIndex++;
136
+ }
137
+ const commandWords = segment.slice(commandIndex);
138
+ const name = commandWords[0]?.split('/').pop();
139
+ if (name === 'sudo') return 'sudo is blocked';
140
+ if (name && ['sh', 'bash', 'dash', 'zsh', 'ksh'].includes(name)) {
141
+ const index = commandWords.findIndex((value, i) => i > 0 && /^-[^-]*c/.test(value));
142
+ if (index >= 0 && commandWords[index + 1]) {
143
+ const denial = hardDenial(commandWords[index + 1]!, cwd, depth + 1);
144
+ if (denial) return denial;
145
+ }
146
+ }
147
+ if (name === 'find' && commandWords.some(value => ['-delete', '-exec', '-execdir', '-ok', '-okdir', '-fprint', '-fprint0', '-fprintf'].includes(value))) return 'mutating find operation cannot be safely classified';
148
+ if (name && ['rm', 'mv', 'cp', 'touch', 'mkdir', 'rmdir', 'truncate', 'shred', 'chmod', 'chown', 'tee'].includes(name)) {
149
+ for (const operand of commandWords.slice(1).filter((value) => !value.startsWith('-'))) {
150
+ try {
151
+ const lexical = path.resolve(cwd, operand);
152
+ const real = resolvePermissionPath(cwd, operand);
153
+ if (isProtectedWrite(lexical) || isProtectedWrite(real) || lexical.startsWith('/dev/') || real.startsWith('/dev/')) return 'protected write destination is blocked';
154
+ } catch { /* The policy rejects unclassified commands. */ }
155
+ }
156
+ }
157
+ if (name === 'git' && commandWords.includes('push') && commandWords.some((v) => /^-[^-]*f/.test(v) || v === '--force' || v.startsWith('--force=') || v === '--force-with-lease' || v.startsWith('--force-with-lease='))) return 'force push is blocked';
158
+ if (name === 'rm' && commandWords.some((v) => v === '--recursive' || (/^-[^-]*[rR]/.test(v))) && commandWords.slice(1).some((v) => v === '~' || path.resolve(cwd, v) === '/' || path.resolve(cwd, v) === homedir())) return 'recursive root or home deletion is blocked';
159
+ }
160
+ return undefined;
161
+ }
162
+
163
+ /** Classification alone never authorizes execution; callers must also validate paths. */
164
+ export function classifyShell(command: unknown, cwd = process.cwd()): ShellClassification {
165
+ if (typeof command !== 'string') return { kind: 'unknown' };
166
+ const denial = hardDenial(command, cwd);
167
+ if (denial) return { kind: 'deny', reason: denial };
168
+ const parts = words(command);
169
+ if (!parts?.length) return { kind: 'unknown' };
170
+ const executable = parts[0]!.split('/').pop();
171
+ if (executable === 'sudo') return { kind: 'deny', reason: 'sudo is blocked' };
172
+ // Do not recognize executables through a path or rely on the shell's PATH for scripts.
173
+ if (parts[0] !== executable) return { kind: 'unknown' };
174
+ const operands = parts.slice(1);
175
+ if (executable === 'pwd' && operands.length === 0) return { kind: 'read', paths: [] };
176
+ if (executable === 'grep' && operands.length >= 2 && operands.every((x) => x.length > 0 && !x.startsWith('-'))) {
177
+ return { kind: 'read', paths: operands.slice(1) };
178
+ }
179
+ if ((executable === 'cat' || executable === 'head' || executable === 'tail') && operands.length > 0 && operands.every((x) => x.length > 0 && !x.startsWith('-'))) {
180
+ return { kind: 'read', paths: operands };
181
+ }
182
+ return { kind: 'unknown' };
183
+ }
@@ -0,0 +1,6 @@
1
+ export const MODE_ENTRY = 'bi.permission-mode';
2
+ export function restorePermissionMode(entries: readonly unknown[]): string | undefined {
3
+ const entry=[...entries].reverse().find((x:any)=>x?.type==='custom'&&x.customType===MODE_ENTRY) as {data?: {mode?: unknown}} | undefined;
4
+ const mode=entry?.data?.mode;
5
+ return typeof mode === 'string' && ['default','acceptEdits','plan','auto','dontAsk','bypassPermissions'].includes(mode)?mode:undefined;
6
+ }
@@ -0,0 +1,25 @@
1
+ import { lstat, mkdir, readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { resolvePermissionPath } from './permission-modes/paths.ts';
4
+ import { writeUnlinkedFile } from '../tools/write-file.ts';
5
+
6
+ /** Preserve project settings while optionally enabling Pi's quieter startup by default. */
7
+ export async function ensureQuietStartup(cwd: string, autoEnable = true): Promise<void> {
8
+ if (!autoEnable) return;
9
+ const root = resolvePermissionPath(cwd, '.');
10
+ const settingsDir = join(root, '.pi');
11
+ const settingsPath = join(settingsDir, 'settings.json');
12
+ try { if (resolvePermissionPath(root, settingsPath) !== settingsPath) return; } catch { return; }
13
+ let settings: Record<string, unknown> = {};
14
+ try {
15
+ const stat = await lstat(settingsPath);
16
+ if (!stat.isFile() || stat.nlink !== 1) return;
17
+ settings = JSON.parse(await readFile(settingsPath, 'utf8'));
18
+ if (!settings || typeof settings !== 'object' || Array.isArray(settings)) return;
19
+ if (Object.hasOwn(settings, 'quietStartup')) return;
20
+ } catch (error) {
21
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return;
22
+ }
23
+ await mkdir(settingsDir, { recursive: true });
24
+ await writeUnlinkedFile(settingsPath, `${JSON.stringify({ ...settings, quietStartup: true }, null, 2)}\n`);
25
+ }