@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
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { Type } from 'typebox';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { createPermissionPrompter } from '../../tui/permission-dialog.ts';
|
|
5
|
+
import { registerPermissionRules, type PermissionActivity } from '../../tui/permission-rules.ts';
|
|
6
|
+
import { decidePermission } from './policy.ts';
|
|
7
|
+
import { loadPermissionRules } from './rules.ts';
|
|
8
|
+
import { isMcpResourceTool, MCP_RESOURCE_SERVER_FLAG, validMcpServerName } from './mcp-resources.ts';
|
|
9
|
+
import { MODE_ENTRY, restorePermissionMode } from './state.ts';
|
|
10
|
+
import { discardPlanNote, MAX_PLAN_BYTES, planNotePath, readPlanNote, writePlanNote } from './plan-note.ts';
|
|
11
|
+
import { previewToolCall } from './preview.ts';
|
|
12
|
+
import { classifyShell, rememberedShellCommand } from './shell.ts';
|
|
13
|
+
import { availableShellTool, executionShells, shellForTool } from '../../tools/shells.ts';
|
|
14
|
+
import { resolvePermissionPath } from './paths.ts';
|
|
15
|
+
import { readGoalState } from '../../commands/goal/state.ts';
|
|
16
|
+
import { selectedLspServer } from '../lsp-menu.ts';
|
|
17
|
+
import { WEB_FETCH_FLAG } from '../../tools/web-fetch.ts';
|
|
18
|
+
import { getTavilyKey, WEB_SEARCH_FLAG, webSearchSetupTip } from '../../tools/web-search.ts';
|
|
19
|
+
import { imageMime } from '../../tools/image-read.ts';
|
|
20
|
+
|
|
21
|
+
export type PermissionMode = 'default' | 'acceptEdits' | 'plan' | 'auto' | 'dontAsk' | 'bypassPermissions';
|
|
22
|
+
const cycle: PermissionMode[] = ['default', 'acceptEdits', 'plan', 'auto'];
|
|
23
|
+
const labels: Record<PermissionMode, string> = { default: 'Manual', acceptEdits: 'Edits', plan: 'Plan', auto: 'Auto', dontAsk: 'No prompts', bypassPermissions: 'Bypass' };
|
|
24
|
+
const planTools = new Set(['read', 'ls', 'grep', 'find', 'glob', 'git_status', 'git_diff', 'git_log', 'git_branch', 'goal_report', 'todo', 'plan', 'ask_user', 'plan_note']);
|
|
25
|
+
function canonical(value: unknown): unknown {
|
|
26
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
27
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)]));
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function approvalKey(cwd: string, tool: string, args: Record<string, unknown>): string {
|
|
32
|
+
const paths: unknown[] = [args.path, args.source, args.destination];
|
|
33
|
+
if (tool === 'apply_patch' && Array.isArray(args.edits)) {
|
|
34
|
+
for (const edit of args.edits) if (edit && typeof edit === 'object') paths.push(edit.path);
|
|
35
|
+
}
|
|
36
|
+
if (['ls', 'grep', 'find', 'glob'].includes(tool) && args.path === undefined) paths.push('.');
|
|
37
|
+
const backend = shellForTool(tool);
|
|
38
|
+
if (backend === 'bash' && typeof args.command === 'string') {
|
|
39
|
+
const shell = classifyShell(args.command, cwd);
|
|
40
|
+
if (shell.kind === 'read') paths.push(...shell.paths);
|
|
41
|
+
}
|
|
42
|
+
const resolved = paths.filter((target): target is string => typeof target === 'string').map(target => resolvePermissionPath(cwd, target));
|
|
43
|
+
return JSON.stringify(canonical([cwd, tool, backend && executionShells()[backend]?.shell, args, resolved]));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type PermissionReviewer = (summary: { tool: 'bash'; operation: 'pwd' }) => Promise<'allow' | 'deny' | 'ask'>;
|
|
47
|
+
export function createPermissionModes(pi: ExtensionAPI, options: { reviewer?: PermissionReviewer; reviewerTimeoutMs?: number } = {}) {
|
|
48
|
+
let mode: PermissionMode = 'default';
|
|
49
|
+
let launchMode: string | undefined;
|
|
50
|
+
let bypassConfirmed = false;
|
|
51
|
+
let priorTools: string[] | undefined;
|
|
52
|
+
let pendingPlan: string | undefined;
|
|
53
|
+
let epoch = 0;
|
|
54
|
+
let turnDeclines = 0, sessionDeclines = 0;
|
|
55
|
+
const listeners = new Set<() => void>();
|
|
56
|
+
const approvals = new Set<string>();
|
|
57
|
+
const bashApprovals = new Set<string>();
|
|
58
|
+
const commitApprovals = new Map<string, (ctx: ExtensionContext, args: Record<string, unknown>, tool: string, server?: string) => boolean>();
|
|
59
|
+
const denials: PermissionActivity[] = [];
|
|
60
|
+
const prompter = createPermissionPrompter();
|
|
61
|
+
const block = (tool: string, reason: string) => {
|
|
62
|
+
denials.unshift({ tool, reason });
|
|
63
|
+
if (denials.length > 20) denials.pop();
|
|
64
|
+
return { block: true as const, reason };
|
|
65
|
+
};
|
|
66
|
+
pi.registerFlag?.('permission-mode', { description: 'Permission mode (default, acceptEdits, plan, auto, dontAsk, bypassPermissions)', type: 'string' });
|
|
67
|
+
pi.registerFlag?.(MCP_RESOURCE_SERVER_FLAG, { type: 'string', description: 'Allow prompts for Pi MCP resource calls to one configured server by name' });
|
|
68
|
+
const allowed = (value: string): value is PermissionMode => cycle.includes(value as PermissionMode) ||
|
|
69
|
+
(value === 'dontAsk' && launchMode === value) || (value === 'bypassPermissions' && launchMode === value && bypassConfirmed);
|
|
70
|
+
const change = (next: PermissionMode, persist = true) => {
|
|
71
|
+
if (!allowed(next)) return false;
|
|
72
|
+
if (mode !== 'plan' && next === 'plan' && pi.getActiveTools && pi.setActiveTools) {
|
|
73
|
+
priorTools = pi.getActiveTools().filter(name => name !== 'plan_note' && availableShellTool(name));
|
|
74
|
+
pi.setActiveTools([...priorTools.filter(name => planTools.has(name)), 'plan_note']);
|
|
75
|
+
} else if (mode === 'plan' && next !== 'plan' && priorTools && pi.setActiveTools) {
|
|
76
|
+
pi.setActiveTools(priorTools); priorTools = undefined;
|
|
77
|
+
}
|
|
78
|
+
mode = next;
|
|
79
|
+
epoch++;
|
|
80
|
+
approvals.clear();
|
|
81
|
+
bashApprovals.clear();
|
|
82
|
+
commitApprovals.clear();
|
|
83
|
+
if (next !== 'plan') pendingPlan = undefined;
|
|
84
|
+
if (persist) pi.appendEntry?.(MODE_ENTRY, { mode: next });
|
|
85
|
+
for (const fn of listeners) fn();
|
|
86
|
+
return true;
|
|
87
|
+
};
|
|
88
|
+
const cycleMode = () => { change(cycle[(cycle.indexOf(mode) + 1) % cycle.length]!); };
|
|
89
|
+
registerPermissionRules(pi, () => ({ mode: labels[mode], approvals: approvals.size + bashApprovals.size, denials }));
|
|
90
|
+
pi.registerTool?.({
|
|
91
|
+
name: 'plan_note', label: 'Plan note', description: 'Write the current session plan note in Plan mode.',
|
|
92
|
+
defaultActive: false,
|
|
93
|
+
executionMode: 'sequential',
|
|
94
|
+
parameters: Type.Object({ content: Type.String({ maxLength: MAX_PLAN_BYTES }) }),
|
|
95
|
+
async execute(_id, args, signal, _update, ctx) {
|
|
96
|
+
if (mode !== 'plan') throw new Error('Plan note is available only in Plan mode');
|
|
97
|
+
const started = epoch;
|
|
98
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
99
|
+
const previous = await readPlanNote(ctx.cwd, sessionId);
|
|
100
|
+
if (started !== epoch || signal?.aborted) throw new Error('Plan note write was cancelled');
|
|
101
|
+
const file = await writePlanNote(ctx.cwd, sessionId, args.content);
|
|
102
|
+
if (started === epoch && previous !== args.content) pendingPlan = args.content;
|
|
103
|
+
return { content: [{ type: 'text', text: `Plan saved to ${file}` }], details: {} };
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
pi.on('session_start', async (event, ctx) => {
|
|
107
|
+
epoch++;
|
|
108
|
+
commitApprovals.clear();
|
|
109
|
+
approvals.clear(); bashApprovals.clear(); denials.length = 0; pendingPlan = undefined; priorTools = undefined; mode = 'default'; turnDeclines = 0; sessionDeclines = 0;
|
|
110
|
+
launchMode = pi.getFlag?.('permission-mode') as string | undefined;
|
|
111
|
+
bypassConfirmed = false;
|
|
112
|
+
if (launchMode && ![...cycle, 'dontAsk', 'bypassPermissions'].includes(launchMode as PermissionMode)) throw new Error(`Invalid permission mode: ${launchMode}`);
|
|
113
|
+
if (launchMode === 'bypassPermissions') {
|
|
114
|
+
if (!ctx.hasUI) throw new Error('Bypass mode requires interactive confirmation');
|
|
115
|
+
bypassConfirmed = await prompter.confirm(ctx, 'Enable Bypass mode?', 'Routine mode prompts will be skipped; existing safety checks still apply.');
|
|
116
|
+
if (!bypassConfirmed) {
|
|
117
|
+
launchMode = undefined;
|
|
118
|
+
ctx.ui.notify('Bypass was not enabled. Staying in Manual mode.', 'warning');
|
|
119
|
+
change('default');
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const restored = restorePermissionMode(ctx.sessionManager?.getBranch?.() ?? []);
|
|
124
|
+
const config = loadPermissionRules(ctx.cwd, message => { if (ctx.hasUI) ctx.ui.notify(message, 'warning'); else console.warn(message); });
|
|
125
|
+
const saved = restored && allowed(restored) ? restored : undefined;
|
|
126
|
+
const next = (event.reason === 'reload' ? saved ?? launchMode : launchMode ?? saved) ?? config.defaultMode ?? 'default';
|
|
127
|
+
change(allowed(next) ? next : 'default', next !== saved);
|
|
128
|
+
});
|
|
129
|
+
pi.on('session_shutdown', event => {
|
|
130
|
+
epoch++;
|
|
131
|
+
approvals.clear();
|
|
132
|
+
bashApprovals.clear();
|
|
133
|
+
commitApprovals.clear();
|
|
134
|
+
// Pi snapshots the active tools after shutdown when rebuilding on reload.
|
|
135
|
+
if (event.reason === 'reload' && mode === 'plan' && priorTools) pi.setActiveTools(priorTools);
|
|
136
|
+
});
|
|
137
|
+
pi.on('session_tree', (_event, ctx) => {
|
|
138
|
+
approvals.clear(); denials.length = 0; pendingPlan = undefined;
|
|
139
|
+
const restored = restorePermissionMode(ctx?.sessionManager?.getBranch?.() ?? []);
|
|
140
|
+
const config = ctx?.cwd ? loadPermissionRules(ctx.cwd, message => { if (ctx.hasUI) ctx.ui.notify(message, 'warning'); else console.warn(message); }) : undefined;
|
|
141
|
+
const next = restored && allowed(restored) ? restored : launchMode && allowed(launchMode) ? launchMode : config?.defaultMode;
|
|
142
|
+
change(next && allowed(next) ? next : 'default', false);
|
|
143
|
+
});
|
|
144
|
+
pi.registerShortcut('alt+m', { description: 'Cycle permission mode', handler: cycleMode });
|
|
145
|
+
pi.on('agent_start', () => { turnDeclines = 0; });
|
|
146
|
+
pi.on('turn_start', () => { turnDeclines = 0; });
|
|
147
|
+
pi.on('turn_end', () => { commitApprovals.clear(); });
|
|
148
|
+
const decline = () => {
|
|
149
|
+
if (mode !== 'auto') return;
|
|
150
|
+
turnDeclines++; sessionDeclines++;
|
|
151
|
+
if (turnDeclines >= 3 || sessionDeclines >= 20) change('default');
|
|
152
|
+
};
|
|
153
|
+
pi.on('agent_before_settle', async (event, ctx) => {
|
|
154
|
+
if (mode !== 'plan' || pendingPlan === undefined || event.outcome !== 'completed' || !ctx.hasUI) return;
|
|
155
|
+
const started = epoch;
|
|
156
|
+
const content = pendingPlan;
|
|
157
|
+
pendingPlan = undefined;
|
|
158
|
+
try {
|
|
159
|
+
const session = ctx.sessionManager.getSessionId();
|
|
160
|
+
const file = planNotePath(ctx.cwd, session);
|
|
161
|
+
if (await readPlanNote(ctx.cwd, session) !== content || started !== epoch) return;
|
|
162
|
+
const choice = await prompter.choose(ctx, {
|
|
163
|
+
title: 'Ready to implement?',
|
|
164
|
+
preview: [{ text: file, color: 'dim' }, { text: content }],
|
|
165
|
+
options: [
|
|
166
|
+
{ value: 'Start in Edits', label: 'Yes, start in Edits mode' },
|
|
167
|
+
{ value: 'Start in Manual', label: 'Yes, ask before edits' },
|
|
168
|
+
{ value: 'Keep planning', label: 'No, keep planning' },
|
|
169
|
+
{ value: 'Discard the note' },
|
|
170
|
+
],
|
|
171
|
+
initial: 'Keep planning',
|
|
172
|
+
});
|
|
173
|
+
if (!choice || started !== epoch || ctx.signal?.aborted) return;
|
|
174
|
+
if (await readPlanNote(ctx.cwd, session) !== content || started !== epoch || ctx.signal?.aborted) {
|
|
175
|
+
ctx.ui.notify('The plan changed during review. It was not approved.', 'warning');
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const next = choice === 'Start in Edits' ? 'acceptEdits' : choice === 'Start in Manual' ? 'default' : undefined;
|
|
179
|
+
if (next) {
|
|
180
|
+
change(next, false);
|
|
181
|
+
const entries = [...event.entries, { type: 'custom' as const, customType: MODE_ENTRY, data: { mode: next } }];
|
|
182
|
+
const goal = readGoalState([...ctx.sessionManager.getBranch(), ...entries]);
|
|
183
|
+
if (goal?.status === 'active' || event.continue || event.context?.pendingMessages?.length || ctx.hasPendingMessages?.()) return { entries };
|
|
184
|
+
return { entries: [...entries, { type: 'custom_message' as const, customType: 'bi.plan-approval', content: `The plan in ${file} was approved. Implement it now.`, display: false }], continue: true };
|
|
185
|
+
}
|
|
186
|
+
else if (choice === 'Discard the note') await discardPlanNote(ctx.cwd, session);
|
|
187
|
+
} catch { /* Dismissal and UI errors leave Plan active. */ }
|
|
188
|
+
});
|
|
189
|
+
pi.on('tool_call', async (event, ctx) => {
|
|
190
|
+
const { toolName, input, toolCallId } = event;
|
|
191
|
+
if (!availableShellTool(toolName)) return block(toolName, 'Shell unavailable on this host');
|
|
192
|
+
const isCommit = toolName === 'git_commit';
|
|
193
|
+
const combinedGit = isCommit || toolName === 'git_add' || toolName === 'git_checkout' || (toolName === 'git_branch' && typeof (input as Record<string, unknown>).name === 'string');
|
|
194
|
+
const webFetch = toolName === 'web_fetch';
|
|
195
|
+
const webSearch = toolName === 'web_search';
|
|
196
|
+
const image = toolName === 'read' && !!imageMime((input as Record<string, unknown>)?.path);
|
|
197
|
+
const combined = (combinedGit || webSearch || image || ['bash', 'powershell', 'background', 'terminal', 'run_code', 'delete', 'notebook_edit', 'lsp', 'web_fetch'].includes(toolName)) && typeof ctx.sessionManager?.getSessionId === 'function';
|
|
198
|
+
if (combined) commitApprovals.delete(toolCallId);
|
|
199
|
+
const started = epoch;
|
|
200
|
+
const args = input as Record<string, unknown>;
|
|
201
|
+
const deny = (reason: string) => block(toolName, reason);
|
|
202
|
+
const mcpResource = isMcpResourceTool(toolName);
|
|
203
|
+
const imageModel = image ? ctx.model : undefined;
|
|
204
|
+
const imageEnabled = () => ctx.hasUI && ctx.isProjectTrusted?.() && ctx.model === imageModel && imageModel?.input?.includes('image') === true;
|
|
205
|
+
if (image && (!combined || !imageEnabled())) return deny('Image attachments require an interactive trusted project and an image-capable model.');
|
|
206
|
+
const mcpResourceEnabled = () => {
|
|
207
|
+
const server = pi.getFlag?.(MCP_RESOURCE_SERVER_FLAG);
|
|
208
|
+
return ctx.hasUI && ctx.isProjectTrusted?.() && validMcpServerName(server) && args?.server === server;
|
|
209
|
+
};
|
|
210
|
+
if (mcpResource && !mcpResourceEnabled()) return deny('MCP resources require an interactive trusted project and an explicit server matching --bi-mcp-resource-server.');
|
|
211
|
+
const webFetchEnabled = () => ctx.hasUI && ctx.isProjectTrusted?.() && pi.getFlag?.(WEB_FETCH_FLAG) === true && pi.getActiveTools().includes('web_fetch');
|
|
212
|
+
if (webFetch && (!combined || !webFetchEnabled())) return deny('Web fetch requires launch opt-in and an interactive trusted project.');
|
|
213
|
+
if (webSearch && !getTavilyKey()) return deny(webSearchSetupTip);
|
|
214
|
+
const webSearchEnabled = () => ctx.hasUI && ctx.isProjectTrusted?.() && !!getTavilyKey() &&
|
|
215
|
+
pi.getFlag?.(WEB_SEARCH_FLAG) === true && pi.getActiveTools().includes('web_search');
|
|
216
|
+
if (webSearch && (!combined || !webSearchEnabled())) return deny('Web search requires launch opt-in and an interactive trusted project.');
|
|
217
|
+
const load = () => loadPermissionRules(ctx.cwd, message => { if (ctx.hasUI) ctx.ui.notify(message, 'warning'); else console.warn(message); });
|
|
218
|
+
const loaded = load();
|
|
219
|
+
if (loaded.invalid) return deny('Invalid permission configuration; correct it before running tools.');
|
|
220
|
+
const decision = decidePermission(mode, toolName, input, ctx.cwd, loaded.rules);
|
|
221
|
+
if (decision.action === 'deny') return deny(decision.reason);
|
|
222
|
+
if (decision.action === 'allow') return undefined;
|
|
223
|
+
// Only Bi's own undo handler performs a target-aware confirmation after preflight.
|
|
224
|
+
// Other extensions' tools must continue through the normal gate.
|
|
225
|
+
if (toolName === 'undo' && mode !== 'dontAsk' && ctx.hasUI && !ctx.signal?.aborted) {
|
|
226
|
+
const registered = pi.getAllTools?.().find(tool => tool.name === 'undo');
|
|
227
|
+
if (registered?.sourceInfo.path === fileURLToPath(new URL('../../index.ts', import.meta.url))) return undefined;
|
|
228
|
+
}
|
|
229
|
+
const stillCurrent = () => started === epoch && !ctx.signal?.aborted;
|
|
230
|
+
const recheck = (currentInput = input) => {
|
|
231
|
+
const current = load();
|
|
232
|
+
if (current.invalid) return false;
|
|
233
|
+
const updated = decidePermission(mode, toolName, currentInput, ctx.cwd, current.rules);
|
|
234
|
+
return updated.action !== 'deny' && updated.source === decision.source && updated.reason === decision.reason;
|
|
235
|
+
};
|
|
236
|
+
// Only summarize a call when no operands, secrets, file contents or output are sent.
|
|
237
|
+
if (mode === 'auto' && decision.source === 'default' && options.reviewer && toolName === 'bash' && typeof args.command === 'string') {
|
|
238
|
+
const command = args.command;
|
|
239
|
+
const shell = classifyShell(command, ctx.cwd);
|
|
240
|
+
if (shell.kind === 'read' && shell.paths.length === 0 && command.trim() === 'pwd') {
|
|
241
|
+
let timer: number | undefined;
|
|
242
|
+
try {
|
|
243
|
+
const reviewed = await Promise.race([
|
|
244
|
+
options.reviewer({ tool: 'bash', operation: 'pwd' }),
|
|
245
|
+
new Promise<undefined>(resolve => { timer = setTimeout(resolve, options.reviewerTimeoutMs ?? 15_000); }),
|
|
246
|
+
]);
|
|
247
|
+
if (!stillCurrent()) return deny('Permission context changed while reviewing.');
|
|
248
|
+
if (reviewed === 'allow') return recheck() && args.command === command ? undefined : deny('Permission context changed while reviewing.');
|
|
249
|
+
if (reviewed === 'deny') { decline(); return deny('Reviewer declined permission.'); }
|
|
250
|
+
} catch { /* Timeout and reviewer failures fall back to the user. */ }
|
|
251
|
+
finally { if (timer) clearTimeout(timer); }
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if (!stillCurrent()) return deny('Permission context changed before approval.');
|
|
255
|
+
if (mode === 'dontAsk' || !ctx.hasUI) return deny('Permission requires an interactive confirmation.');
|
|
256
|
+
const canSave = decision.source === 'default' && ['write', 'edit', 'mkdir', 'copy', 'move', 'apply_patch'].includes(toolName);
|
|
257
|
+
try {
|
|
258
|
+
const server = toolName === 'lsp' && ctx.isProjectTrusted?.() ? await selectedLspServer(pi, ctx.cwd) : undefined;
|
|
259
|
+
if (toolName === 'lsp' && (!server || !stillCurrent())) return deny('LSP requires a trusted project and an explicitly configured server.');
|
|
260
|
+
const key = approvalKey(ctx.cwd, toolName, args);
|
|
261
|
+
if (canSave && approvals.has(key)) return undefined;
|
|
262
|
+
const sessionId = combined ? ctx.sessionManager.getSessionId() : undefined;
|
|
263
|
+
const rememberableDecision = decision.source === 'default' ||
|
|
264
|
+
(decision.source === 'boundary' && decision.reason === 'Unclassified shell command requires approval');
|
|
265
|
+
const remembered = toolName === 'bash' && rememberableDecision && sessionId && ctx.isProjectTrusted?.() && typeof args.command === 'string'
|
|
266
|
+
? rememberedShellCommand(args.command, ctx.cwd) : undefined;
|
|
267
|
+
// Refuse aliases/symlinks for the cd form: the remembered cwd must be unambiguous.
|
|
268
|
+
const candidate = remembered && (remembered.command === args.command || resolvePermissionPath(ctx.cwd, remembered.cwd) === remembered.cwd) ? remembered : undefined;
|
|
269
|
+
const candidateRealCwd = candidate ? resolvePermissionPath(candidate.cwd, '.') : undefined;
|
|
270
|
+
const bashKey = candidate ? JSON.stringify([sessionId, candidateRealCwd, approvalKey(candidate.cwd, toolName, { ...args, command: candidate.command })]) : undefined;
|
|
271
|
+
const saved = !!bashKey && candidate?.command === args.command && bashApprovals.has(bashKey);
|
|
272
|
+
const { title, preview } = previewToolCall(toolName, args);
|
|
273
|
+
const allowOnce = isCommit ? 'Yes, commit once' : 'Allow once';
|
|
274
|
+
const rememberBash = 'Remember bash command for session';
|
|
275
|
+
const selected = saved ? allowOnce : await prompter.choose(ctx, {
|
|
276
|
+
title,
|
|
277
|
+
preview: [{ text: decision.reason, color: 'dim' }, ...(server ? [{ text: `Server: ${server} --stdio` }] : []),
|
|
278
|
+
...(imageModel ? [{ text: `Model: ${imageModel.provider}/${imageModel.id}` }] : []), ...preview,
|
|
279
|
+
...(candidate ? [{ text: `Remember for this session in ${candidate.cwd}: ${candidate.command}` }] : [])],
|
|
280
|
+
options: [
|
|
281
|
+
{ value: allowOnce, label: isCommit ? allowOnce : 'Yes, allow once' },
|
|
282
|
+
...(canSave ? [{ value: 'Allow exact call for session', label: 'Yes, exact call for this session' }] : []),
|
|
283
|
+
...(candidate ? [{ value: rememberBash, label: `Yes, don't ask again this session for: ${candidate.command}` }] : []),
|
|
284
|
+
{ value: 'Deny', label: 'No' },
|
|
285
|
+
],
|
|
286
|
+
initial: 'Deny',
|
|
287
|
+
});
|
|
288
|
+
if (selected === allowOnce || (selected === 'Allow exact call for session' && canSave) || (selected === rememberBash && candidate && bashKey)) {
|
|
289
|
+
if (!stillCurrent() || !recheck() || approvalKey(ctx.cwd, toolName, args) !== key ||
|
|
290
|
+
(server && !ctx.isProjectTrusted?.()) || (webFetch && !webFetchEnabled()) || (webSearch && !webSearchEnabled()) ||
|
|
291
|
+
(image && !imageEnabled()) || (mcpResource && !mcpResourceEnabled()) ||
|
|
292
|
+
((saved || selected === rememberBash) && (!ctx.isProjectTrusted?.() || ctx.sessionManager.getSessionId() !== sessionId ||
|
|
293
|
+
(candidate && resolvePermissionPath(candidate.cwd, '.') !== candidateRealCwd)))) return deny('Permission context changed while waiting for approval.');
|
|
294
|
+
if (combined) {
|
|
295
|
+
// The prompt authorizes only this exact tool call.
|
|
296
|
+
commitApprovals.set(toolCallId, (executionCtx, executionArgs, executionTool, executionServer) =>
|
|
297
|
+
executionTool === toolName && executionServer === server && executionCtx.sessionManager.getSessionId() === sessionId && stillCurrent() && recheck(executionArgs) &&
|
|
298
|
+
(!image || (executionCtx.model === imageModel && imageEnabled())) &&
|
|
299
|
+
(!(saved || selected === rememberBash) || (executionCtx.isProjectTrusted?.() === true &&
|
|
300
|
+
(!candidate || resolvePermissionPath(candidate.cwd, '.') === candidateRealCwd))) &&
|
|
301
|
+
approvalKey(executionCtx.cwd, toolName, executionArgs) === key);
|
|
302
|
+
}
|
|
303
|
+
if (selected === 'Allow exact call for session') approvals.add(key);
|
|
304
|
+
if (selected === rememberBash && bashKey) bashApprovals.add(bashKey);
|
|
305
|
+
return undefined;
|
|
306
|
+
}
|
|
307
|
+
} catch { return deny('Unable to identify tool call safely.'); }
|
|
308
|
+
if (stillCurrent()) decline();
|
|
309
|
+
return deny('Permission declined.');
|
|
310
|
+
});
|
|
311
|
+
return {
|
|
312
|
+
get mode() { return mode; },
|
|
313
|
+
get label() { return labels[mode]; },
|
|
314
|
+
cycle: cycleMode,
|
|
315
|
+
enterPlan(): boolean {
|
|
316
|
+
if (!['default', 'acceptEdits', 'auto', 'plan'].includes(mode)) return false;
|
|
317
|
+
if (mode === 'plan') return true;
|
|
318
|
+
if (!pi.getActiveTools || !pi.setActiveTools) return false;
|
|
319
|
+
return change('plan');
|
|
320
|
+
},
|
|
321
|
+
prompter,
|
|
322
|
+
consumeCommitApproval(id: string, ctx: ExtensionContext, args: Record<string, unknown>, tool = 'git_commit', server?: string): boolean | undefined {
|
|
323
|
+
const approval = commitApprovals.get(id);
|
|
324
|
+
commitApprovals.delete(id);
|
|
325
|
+
if (!ctx.hasUI || ctx.signal?.aborted) return false;
|
|
326
|
+
try {
|
|
327
|
+
if (approval) return approval(ctx, args, tool, server);
|
|
328
|
+
const loaded = loadPermissionRules(ctx.cwd, () => {});
|
|
329
|
+
// An allow decision can skip the gate, but not the Git tool's confirmation.
|
|
330
|
+
if (!loaded.invalid && decidePermission(mode, tool, args, ctx.cwd, loaded.rules).action === 'allow') return undefined;
|
|
331
|
+
} catch { /* An invalid or stale approval cannot authorize a commit. */ }
|
|
332
|
+
return false;
|
|
333
|
+
},
|
|
334
|
+
subscribe(fn: () => void) { listeners.add(fn); return () => { listeners.delete(fn); }; },
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
export type PermissionController = ReturnType<typeof createPermissionModes>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export const MCP_RESOURCE_SERVER_FLAG = 'bi-mcp-resource-server';
|
|
2
|
+
const resourceTools = new Set(['list_mcp_resources', 'list_mcp_resource_templates', 'read_mcp_resource']);
|
|
3
|
+
|
|
4
|
+
export function isMcpResourceTool(tool: string): boolean {
|
|
5
|
+
return resourceTools.has(tool);
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function validMcpServerName(value: unknown): value is string {
|
|
9
|
+
return typeof value === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(value);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function boundedString(value: unknown): value is string {
|
|
13
|
+
return typeof value === 'string' && value.length <= 2048 && !!value.trim() && !/[\p{Cc}\p{Cf}\u2028\u2029]/u.test(value);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function validMcpResourceArgs(tool: string, args: Record<string, unknown>): boolean {
|
|
17
|
+
if (!Object.hasOwn(args, 'server') || !validMcpServerName(args.server)) return false;
|
|
18
|
+
if (tool === 'read_mcp_resource') return Object.keys(args).length === 2 && Object.hasOwn(args, 'uri') && boundedString(args.uri);
|
|
19
|
+
return Object.keys(args).every(key => key === 'server' || key === 'cursor') &&
|
|
20
|
+
(args.cursor === undefined || boundedString(args.cursor));
|
|
21
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { isProtectedWrite, isWithin, resolvePermissionPath } from './paths.ts';
|
|
3
|
+
import { decidePermission, type PermissionRules } from './policy.ts';
|
|
4
|
+
|
|
5
|
+
/** Resolve a name for local display only, without obtaining broader access than an ordinary read. */
|
|
6
|
+
export function permittedMetadataPath(cwd: string, mode: string, name: string, rules: PermissionRules, tool: 'read' | 'ls' = 'read') {
|
|
7
|
+
try {
|
|
8
|
+
if (!name || name.includes('\0') || name.length > 4096) return;
|
|
9
|
+
const lexical = path.resolve(cwd, name), root = resolvePermissionPath(cwd, '.');
|
|
10
|
+
const resolved = resolvePermissionPath(cwd, name);
|
|
11
|
+
if (!isWithin(root, resolved) || !isWithin(path.resolve(cwd), lexical) ||
|
|
12
|
+
isProtectedWrite(lexical) || isProtectedWrite(resolved)) return;
|
|
13
|
+
const relative = path.relative(root, resolved);
|
|
14
|
+
if (path.join(root, path.relative(cwd, lexical)) !== resolved) return;
|
|
15
|
+
if (decidePermission(mode, tool, { path: name }, cwd, rules).action !== 'allow') return;
|
|
16
|
+
return { absolute: resolved, relative: relative.split(path.sep).join('/') };
|
|
17
|
+
} catch { /* Refuse names that cannot be classified safely. */ }
|
|
18
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { lstatSync, realpathSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
/** Resolve symlinks in the nearest existing ancestor, including for new files. */
|
|
5
|
+
export function resolvePermissionPath(cwd: string, target: string): string {
|
|
6
|
+
let current = path.resolve(cwd, target);
|
|
7
|
+
const suffix: string[] = [];
|
|
8
|
+
for (;;) {
|
|
9
|
+
try {
|
|
10
|
+
return path.resolve(realpathSync(current), ...suffix.reverse());
|
|
11
|
+
} catch (error) {
|
|
12
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
13
|
+
// A dangling symlink exists but realpath cannot resolve it: fail closed.
|
|
14
|
+
try {
|
|
15
|
+
lstatSync(current);
|
|
16
|
+
throw error;
|
|
17
|
+
} catch (statError) {
|
|
18
|
+
if ((statError as NodeJS.ErrnoException).code !== 'ENOENT' || statError === error) throw statError;
|
|
19
|
+
}
|
|
20
|
+
const parent = path.dirname(current);
|
|
21
|
+
if (parent === current) throw error;
|
|
22
|
+
suffix.push(path.basename(current));
|
|
23
|
+
current = parent;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function isWithin(root: string, target: string): boolean {
|
|
29
|
+
const relative = path.relative(root, target);
|
|
30
|
+
return relative === '' || (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith(`..${path.sep}`));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Conservative component-based protection; callers must check lexical and resolved paths. */
|
|
34
|
+
export function isProtectedWrite(target: string): boolean {
|
|
35
|
+
const parts = path.resolve(target).split(path.sep).filter(Boolean).map((part) => part.toLowerCase());
|
|
36
|
+
return parts.some((part, index) =>
|
|
37
|
+
part === '.git' || part === 'node_modules' || part === '.ssh' ||
|
|
38
|
+
part === '.gnupg' || part === '.aws' || part.startsWith('.env') ||
|
|
39
|
+
['.netrc', '.npmrc', '.pypirc', 'id_rsa', 'id_dsa', 'id_ecdsa', 'id_ed25519'].includes(part) ||
|
|
40
|
+
['.bashrc', '.bash_profile', '.bash_login', '.bash_logout', '.profile', '.zshrc', '.zshenv', '.zprofile', '.zlogin', '.zlogout'].includes(part) ||
|
|
41
|
+
/\.(?:pem|key|p12|pfx)$/.test(part) ||
|
|
42
|
+
(part === '.pi' && parts.slice(index + 1).some(child => ['settings.json', 'extensions', 'permission-modes.json'].includes(child))),
|
|
43
|
+
);
|
|
44
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { constants, promises as fs } from 'node:fs';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { isWithin, resolvePermissionPath } from './paths.ts';
|
|
5
|
+
|
|
6
|
+
/** Session IDs are opaque; do not permit them to become path components. */
|
|
7
|
+
export function planNotePath(cwd: string, sessionId: string): string {
|
|
8
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(sessionId)) throw new Error('Invalid session ID for plan note');
|
|
9
|
+
const root = resolvePermissionPath(cwd, '.');
|
|
10
|
+
const file = path.join(root, '.pi', 'plans', `${sessionId}.md`);
|
|
11
|
+
const resolved = resolvePermissionPath(root, file);
|
|
12
|
+
if (!isWithin(root, resolved) || resolved !== file) throw new Error('Plan note path contains a symlink or escapes the project');
|
|
13
|
+
return file;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const MAX_PLAN_BYTES = 64 * 1024;
|
|
17
|
+
|
|
18
|
+
export async function readPlanNote(cwd: string, sessionId: string): Promise<string | undefined> {
|
|
19
|
+
const file = planNotePath(cwd, sessionId);
|
|
20
|
+
let handle;
|
|
21
|
+
try { handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
|
|
22
|
+
catch (error) {
|
|
23
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
const stat = await handle.stat();
|
|
28
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_PLAN_BYTES || planNotePath(cwd, sessionId) !== file) return undefined;
|
|
29
|
+
const buffer = Buffer.alloc(MAX_PLAN_BYTES + 1);
|
|
30
|
+
let length = 0;
|
|
31
|
+
while (length < buffer.length) {
|
|
32
|
+
const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
|
|
33
|
+
if (!bytesRead) break;
|
|
34
|
+
length += bytesRead;
|
|
35
|
+
}
|
|
36
|
+
return length <= MAX_PLAN_BYTES ? buffer.toString('utf8', 0, length) : undefined;
|
|
37
|
+
} finally { await handle.close(); }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function writePlanNote(cwd: string, sessionId: string, content: string): Promise<string> {
|
|
41
|
+
if (Buffer.byteLength(content) > MAX_PLAN_BYTES) throw new Error('Plan note is limited to 64 KiB');
|
|
42
|
+
const file = planNotePath(cwd, sessionId);
|
|
43
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
44
|
+
const temporary = path.join(path.dirname(file), `.${sessionId}.${randomUUID()}.tmp`);
|
|
45
|
+
try {
|
|
46
|
+
await fs.writeFile(temporary, content, { flag: 'wx', mode: 0o600 });
|
|
47
|
+
if (planNotePath(cwd, sessionId) !== file) throw new Error('Plan note destination changed');
|
|
48
|
+
await fs.rename(temporary, file);
|
|
49
|
+
} finally {
|
|
50
|
+
await fs.unlink(temporary).catch((error: NodeJS.ErrnoException) => { if (error.code !== 'ENOENT') throw error; });
|
|
51
|
+
}
|
|
52
|
+
return file;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function discardPlanNote(cwd: string, sessionId: string): Promise<void> {
|
|
56
|
+
const file = planNotePath(cwd, sessionId);
|
|
57
|
+
await fs.unlink(file).catch((error: NodeJS.ErrnoException) => { if (error.code !== 'ENOENT') throw error; });
|
|
58
|
+
}
|