@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,312 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { Type } from 'typebox';
|
|
3
|
+
import { readTodos, TODO_ENTRY } from '../tools/todo.ts';
|
|
4
|
+
import { askQuestion } from './ask-user.ts';
|
|
5
|
+
import { createToolSystem } from '../tools/index.ts';
|
|
6
|
+
import { nodeCommandPreview } from '../tools/execution.ts';
|
|
7
|
+
import { availableShellTool, shellForTool } from '../tools/shells.ts';
|
|
8
|
+
import type { AskResult, DispatchResult, ToolContext } from '../types/index.ts';
|
|
9
|
+
import type { PermissionController } from './permission-modes/index.ts';
|
|
10
|
+
import { decidePermission } from './permission-modes/policy.ts';
|
|
11
|
+
import { loadPermissionRules } from './permission-modes/rules.ts';
|
|
12
|
+
import { createPermissionPrompter } from '../tui/permission-dialog.ts';
|
|
13
|
+
import { literal } from '../tui/text.ts';
|
|
14
|
+
import { resolvePermissionPath } from './permission-modes/paths.ts';
|
|
15
|
+
import { toolPresentation } from '../tui/tool-renderer.ts';
|
|
16
|
+
import { LSP_FLAG, resolveLspServer } from '../tools/lsp.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 { clearLspSelection, registerLspMenu, selectedLspServer } from './lsp-menu.ts';
|
|
20
|
+
import { imageMime } from '../tools/image-read.ts';
|
|
21
|
+
import { showRewindHistory } from '../commands/rewind-history.ts';
|
|
22
|
+
|
|
23
|
+
const readOutputSchema = Type.Union([Type.String(), Type.Object({
|
|
24
|
+
type: Type.Literal('image'), data: Type.String(), mimeType: Type.String(), note: Type.String(),
|
|
25
|
+
})]);
|
|
26
|
+
|
|
27
|
+
export function registerTools(pi: ExtensionAPI, permissionModes?: PermissionController) {
|
|
28
|
+
// Pi supplies the UI context only while executing a tool. Keep the callback
|
|
29
|
+
// injected at registration and bind the current context immediately before dispatch.
|
|
30
|
+
let activeContext: ExtensionContext | undefined;
|
|
31
|
+
const interactive = Boolean(process.stdin.isTTY);
|
|
32
|
+
const prompter = permissionModes?.prompter ?? createPermissionPrompter();
|
|
33
|
+
const { registry, dispatcher, processManager, journal } = createToolSystem(interactive ? {
|
|
34
|
+
askUser: async (questions): Promise<AskResult> => {
|
|
35
|
+
const ctx = activeContext;
|
|
36
|
+
if (!ctx?.hasUI || permissionModes?.mode === 'dontAsk') return { status: 'declined' };
|
|
37
|
+
const answers = [];
|
|
38
|
+
for (const question of questions) {
|
|
39
|
+
const answer = await askQuestion(ctx, question);
|
|
40
|
+
if (!answer) return { status: 'declined' };
|
|
41
|
+
answers.push(answer);
|
|
42
|
+
}
|
|
43
|
+
return { status: 'answered', answers };
|
|
44
|
+
},
|
|
45
|
+
} : {});
|
|
46
|
+
|
|
47
|
+
let sessionLifetime = new AbortController();
|
|
48
|
+
const retireProcesses = (renew: boolean) => {
|
|
49
|
+
sessionLifetime.abort();
|
|
50
|
+
processManager.clear();
|
|
51
|
+
if (renew) sessionLifetime = new AbortController();
|
|
52
|
+
};
|
|
53
|
+
if (registry.has('lsp')) {
|
|
54
|
+
pi.registerFlag?.(LSP_FLAG, { type: 'string', description: 'Opt into LSP with an absolute path to a trusted local stdio server' });
|
|
55
|
+
if (permissionModes) registerLspMenu(pi, permissionModes, () => sessionLifetime.signal);
|
|
56
|
+
}
|
|
57
|
+
if (registry.has('web_fetch')) {
|
|
58
|
+
pi.registerFlag?.(WEB_FETCH_FLAG, { type: 'boolean', description: 'Opt into model-initiated public HTTPS fetches with per-request approval' });
|
|
59
|
+
}
|
|
60
|
+
if (registry.has('web_search')) pi.registerFlag?.(WEB_SEARCH_FLAG, {
|
|
61
|
+
type: 'boolean', description: 'Opt into Tavily web search with per-query approval',
|
|
62
|
+
});
|
|
63
|
+
pi.on?.('session_start', async (_event, ctx) => {
|
|
64
|
+
retireProcesses(true);
|
|
65
|
+
const active = pi.getActiveTools?.();
|
|
66
|
+
if (active?.some(name => !availableShellTool(name))) pi.setActiveTools(active.filter(name => availableShellTool(name)));
|
|
67
|
+
clearLspSelection(pi);
|
|
68
|
+
if (registry.has('web_fetch') && permissionModes && ctx.hasUI && ctx.isProjectTrusted?.() &&
|
|
69
|
+
!['plan', 'dontAsk'].includes(permissionModes.mode) && pi.getFlag?.(WEB_FETCH_FLAG) === true) {
|
|
70
|
+
const tools = pi.getActiveTools();
|
|
71
|
+
if (!tools.includes('web_fetch')) pi.setActiveTools([...tools, 'web_fetch']);
|
|
72
|
+
}
|
|
73
|
+
if (registry.has('web_search') && pi.getFlag?.(WEB_SEARCH_FLAG) === true && ctx.hasUI) {
|
|
74
|
+
if (!getTavilyKey()) ctx.ui.notify(webSearchSetupTip, 'warning');
|
|
75
|
+
else if (permissionModes && ctx.isProjectTrusted?.() && !['plan', 'dontAsk'].includes(permissionModes.mode)) {
|
|
76
|
+
const tools = pi.getActiveTools();
|
|
77
|
+
if (!tools.includes('web_search')) pi.setActiveTools([...tools, 'web_search']);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const flag = pi.getFlag?.(LSP_FLAG);
|
|
81
|
+
if (!flag || !registry.has('lsp') || !permissionModes || permissionModes.mode === 'plan' || !ctx.isProjectTrusted?.()) return;
|
|
82
|
+
const lifetime = sessionLifetime.signal;
|
|
83
|
+
if (!await resolveLspServer(flag, ctx.cwd)) {
|
|
84
|
+
ctx.ui.notify('Honeycomb LSP requires an existing executable outside the workspace.', 'warning');
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (lifetime.aborted || (permissionModes.mode as string) === 'plan') return;
|
|
88
|
+
const tools = pi.getActiveTools();
|
|
89
|
+
if (!tools.includes('lsp')) pi.setActiveTools([...tools, 'lsp']);
|
|
90
|
+
});
|
|
91
|
+
pi.on?.('session_tree', () => retireProcesses(true));
|
|
92
|
+
pi.on?.('session_shutdown', () => { clearLspSelection(pi); retireProcesses(false); });
|
|
93
|
+
|
|
94
|
+
let undoEpoch = 0, turnCount = 0;
|
|
95
|
+
let undoTurn: number | undefined;
|
|
96
|
+
if (permissionModes && journal) {
|
|
97
|
+
const retireHistory = () => { journal.reset(++undoEpoch); turnCount = 0; undoTurn = undefined; };
|
|
98
|
+
pi.on?.('session_start', retireHistory);
|
|
99
|
+
pi.on?.('session_tree', retireHistory);
|
|
100
|
+
pi.on?.('session_shutdown', retireHistory);
|
|
101
|
+
pi.on?.('turn_start', () => { undoTurn = ++turnCount; });
|
|
102
|
+
pi.on?.('turn_end', () => { undoTurn = undefined; });
|
|
103
|
+
}
|
|
104
|
+
const undoContext = (ctx: ExtensionContext, signal?: AbortSignal): Pick<ToolContext, 'undoEpoch' | 'undoTurn' | 'checkUndo' | 'confirmDestructive'> => {
|
|
105
|
+
const epoch = undoEpoch;
|
|
106
|
+
const mode = permissionModes?.mode ?? 'default';
|
|
107
|
+
const checkUndo: NonNullable<ToolContext['checkUndo']> = entries => {
|
|
108
|
+
if (epoch !== undoEpoch || signal?.aborted || !ctx.hasUI || ['plan', 'dontAsk'].includes(mode) || (permissionModes?.mode ?? 'default') !== mode) return false;
|
|
109
|
+
const config = loadPermissionRules(ctx.cwd, () => {});
|
|
110
|
+
if (config.invalid || decidePermission(mode, 'undo', {}, ctx.cwd, config.rules).action === 'deny') return false;
|
|
111
|
+
return entries.every(({ file: path, before }) => before === null ? decidePermission(mode, 'delete', { path }, ctx.cwd, config.rules).action !== 'deny' : ['write', 'edit'].every(tool => decidePermission(mode, tool, tool === 'write' ? { path, content: '' } : { path, old_str: '', new_str: '' }, ctx.cwd, config.rules).action !== 'deny'));
|
|
112
|
+
};
|
|
113
|
+
return { undoEpoch: epoch, undoTurn, checkUndo, confirmDestructive: (operation, targets) => prompter.confirm(ctx, `Confirm ${operation}`, literal(targets, true), signal) };
|
|
114
|
+
};
|
|
115
|
+
const rewindCommand: Parameters<ExtensionAPI['registerCommand']>[1] = {
|
|
116
|
+
description: 'Restore the last tracked file operation, or inspect /rewind history [turn]',
|
|
117
|
+
async handler(args, ctx) {
|
|
118
|
+
if (!ctx.hasUI) return;
|
|
119
|
+
if (ctx.mode !== 'tui' || !ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
120
|
+
return ctx.ui.notify('Use /rewind in an idle terminal session.', 'warning');
|
|
121
|
+
}
|
|
122
|
+
if (!registry.has('undo') || !journal || !permissionModes) return ctx.ui.notify('The Honeycomb agent tool group is disabled.', 'warning');
|
|
123
|
+
const input = args.trim();
|
|
124
|
+
if (input) {
|
|
125
|
+
const history = /^history(?:\s+(0|[1-9][0-9]{0,8}))?$/.exec(input);
|
|
126
|
+
if (!history) return ctx.ui.notify('Usage: /rewind [history [turn]]', 'warning');
|
|
127
|
+
return showRewindHistory(ctx, permissionModes, journal, undoEpoch, history[1] === undefined ? undefined : Number(history[1]));
|
|
128
|
+
}
|
|
129
|
+
const guard = undoContext(ctx);
|
|
130
|
+
const result = await dispatcher.dispatch({ name: 'undo', arguments: {} }, {
|
|
131
|
+
...guard, workingDirectory: ctx.cwd, sessionId: actualSessionId(ctx), signal: ctx.signal,
|
|
132
|
+
checkUndo: paths => ctx.isIdle() && !ctx.hasPendingMessages() && !!guard.checkUndo?.(paths),
|
|
133
|
+
});
|
|
134
|
+
ctx.ui.notify(result.success ? result.output ?? 'Restored patch.' : result.error ?? 'Restore failed.', result.success ? 'info' : 'warning');
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
if (permissionModes) {
|
|
138
|
+
pi.registerCommand?.('rewind', rewindCommand);
|
|
139
|
+
pi.registerCommand?.('checkpoint', { ...rewindCommand, description: 'Alias for /rewind (latest Honeycomb file operation only)' });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
for (const tool of registry.list()) {
|
|
143
|
+
pi.registerTool({
|
|
144
|
+
name: tool.name,
|
|
145
|
+
label: `🔧 ${tool.name}`,
|
|
146
|
+
description: tool.description,
|
|
147
|
+
...(['lsp', 'web_fetch', 'web_search'].includes(tool.name) ? { defaultActive: false, executionMode: 'sequential' as const } : {}),
|
|
148
|
+
...(tool.name === 'subagent' ? { defaultActive: false } : {}),
|
|
149
|
+
...(tool.promptSnippet ? { promptSnippet: tool.promptSnippet } : {}),
|
|
150
|
+
...(tool.promptGuidelines ? { promptGuidelines: tool.promptGuidelines } : {}),
|
|
151
|
+
parameters: Type.Unsafe(tool.parameters as never),
|
|
152
|
+
...(tool.name === 'read' ? { outputSchema: readOutputSchema } : {}),
|
|
153
|
+
...(['ask_user', 'todo', 'memory', 'edit', 'write', 'apply_patch', 'undo', 'notebook_edit'].includes(tool.name) ? { executionMode: 'sequential' as const } : {}),
|
|
154
|
+
...toolPresentation(tool.name),
|
|
155
|
+
async execute(toolCallId, params, callSignal, _onUpdate, ctx) {
|
|
156
|
+
const attachImage = tool.name === 'read' && !!imageMime((params as Record<string, unknown>)?.path);
|
|
157
|
+
const lifetime = attachImage || ['bash', 'powershell', 'background', 'terminal', 'run_code', 'process', 'kill', 'grep',
|
|
158
|
+
'todo', 'memory', 'write', 'edit', 'apply_patch', 'undo', 'notebook_edit', 'lsp', 'web_fetch', 'web_search'].includes(tool.name)
|
|
159
|
+
? sessionLifetime.signal : undefined;
|
|
160
|
+
const signal = lifetime && callSignal ? AbortSignal.any([callSignal, lifetime]) : lifetime ?? callSignal;
|
|
161
|
+
activeContext = ctx;
|
|
162
|
+
let sessionId: string;
|
|
163
|
+
try {
|
|
164
|
+
sessionId = actualSessionId(ctx);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
167
|
+
return {
|
|
168
|
+
content: [{ type: 'text' as const, text: message }],
|
|
169
|
+
details: { success: false, errorCode: 'INTERNAL_ERROR' },
|
|
170
|
+
isError: true,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
const confirm = async (title: string, text: string) => {
|
|
174
|
+
const mode = permissionModes?.mode;
|
|
175
|
+
if (!ctx.hasUI || mode === 'dontAsk') return false;
|
|
176
|
+
return await prompter.confirm(ctx, title, text, signal) && permissionModes?.mode === mode;
|
|
177
|
+
};
|
|
178
|
+
const notebookEpoch = undoEpoch;
|
|
179
|
+
const callMode = permissionModes?.mode;
|
|
180
|
+
const imageModel = attachImage ? ctx.model : undefined;
|
|
181
|
+
const imageApprovalCurrent = () => {
|
|
182
|
+
if (!callMode || callMode !== permissionModes?.mode || signal?.aborted || !ctx.hasUI ||
|
|
183
|
+
!ctx.isProjectTrusted?.() || ctx.model !== imageModel || !imageModel?.input?.includes('image')) return false;
|
|
184
|
+
const config = loadPermissionRules(ctx.cwd, () => {});
|
|
185
|
+
return !config.invalid && decidePermission(callMode, 'read', params, ctx.cwd, config.rules).action === 'ask';
|
|
186
|
+
};
|
|
187
|
+
const context: ToolContext = {
|
|
188
|
+
sessionId,
|
|
189
|
+
workingDirectory: ctx.cwd,
|
|
190
|
+
...(attachImage ? {
|
|
191
|
+
authorizeImage: () => imageApprovalCurrent() && permissionModes?.consumeCommitApproval(toolCallId, ctx, params as Record<string, unknown>, tool.name) === true,
|
|
192
|
+
imageApprovalCurrent,
|
|
193
|
+
} : {}),
|
|
194
|
+
...(tool.name === 'lsp' ? { authorizeLsp: async (file: string) => {
|
|
195
|
+
if (!permissionModes || !ctx.isProjectTrusted?.() || signal?.aborted) return;
|
|
196
|
+
const server = await selectedLspServer(pi, ctx.cwd);
|
|
197
|
+
const args = params as Record<string, unknown>;
|
|
198
|
+
if (!server || signal?.aborted || !ctx.isProjectTrusted?.() || typeof args.path !== 'string' || resolvePermissionPath(ctx.cwd, args.path) !== file) return;
|
|
199
|
+
if (permissionModes.consumeCommitApproval(toolCallId, ctx, args, tool.name, server) === true) return server;
|
|
200
|
+
}, canReadLspLocation: (file: string) => {
|
|
201
|
+
if (!permissionModes || !ctx.isProjectTrusted?.() || signal?.aborted) return false;
|
|
202
|
+
const config = loadPermissionRules(ctx.cwd, () => {});
|
|
203
|
+
return !config.invalid && decidePermission(permissionModes.mode, 'read', { path: file }, ctx.cwd, config.rules).action === 'allow';
|
|
204
|
+
} } : {}),
|
|
205
|
+
...(tool.name === 'web_fetch' ? { authorizeWebFetch: () =>
|
|
206
|
+
!!permissionModes && ctx.hasUI && !!ctx.isProjectTrusted?.() && !signal?.aborted &&
|
|
207
|
+
pi.getFlag?.(WEB_FETCH_FLAG) === true && pi.getActiveTools().includes('web_fetch') &&
|
|
208
|
+
permissionModes.consumeCommitApproval(toolCallId, ctx, params as Record<string, unknown>, tool.name) === true,
|
|
209
|
+
} : {}),
|
|
210
|
+
...(tool.name === 'web_search' ? { authorizeWebSearch: () => {
|
|
211
|
+
if (!permissionModes || !ctx.hasUI || !ctx.isProjectTrusted?.() || signal?.aborted ||
|
|
212
|
+
pi.getFlag?.(WEB_SEARCH_FLAG) !== true || !pi.getActiveTools().includes('web_search')) return;
|
|
213
|
+
const key = getTavilyKey();
|
|
214
|
+
if (key && permissionModes.consumeCommitApproval(toolCallId, ctx, params as Record<string, unknown>, tool.name)) return key;
|
|
215
|
+
} } : {}),
|
|
216
|
+
...(tool.name === 'todo' ? { todoStore: {
|
|
217
|
+
read: () => readTodos(ctx.sessionManager.getBranch()),
|
|
218
|
+
write: items => { signal?.throwIfAborted(); pi.appendEntry(TODO_ENTRY, items); },
|
|
219
|
+
} } : {}),
|
|
220
|
+
...(tool.name === 'memory' && permissionModes ? { canAccessMemory: (file: string, write: boolean) => {
|
|
221
|
+
if (!callMode || callMode !== permissionModes.mode || signal?.aborted) return false;
|
|
222
|
+
const config = loadPermissionRules(ctx.cwd, () => {});
|
|
223
|
+
return !config.invalid && decidePermission(callMode, 'memory', params, ctx.cwd, config.rules).action !== 'deny' &&
|
|
224
|
+
decidePermission(callMode, 'read', { path: file }, ctx.cwd, config.rules).action === 'allow' &&
|
|
225
|
+
(!write || decidePermission(callMode, 'write', { path: file, content: '' }, ctx.cwd, config.rules).action !== 'deny');
|
|
226
|
+
} } : {}),
|
|
227
|
+
signal,
|
|
228
|
+
confirmDestructive: async (operation, target) => {
|
|
229
|
+
if (tool.name === 'notebook_edit' && operation === 'edit notebook cell') {
|
|
230
|
+
try {
|
|
231
|
+
const args = params as Record<string, unknown>;
|
|
232
|
+
if (signal?.aborted || typeof args.path !== 'string' || resolvePermissionPath(ctx.cwd, args.path) !== target) return false;
|
|
233
|
+
return permissionModes?.consumeCommitApproval(toolCallId, ctx, args, tool.name) === true;
|
|
234
|
+
} catch { return false; }
|
|
235
|
+
}
|
|
236
|
+
if (tool.name === 'delete' && operation === 'delete') {
|
|
237
|
+
try {
|
|
238
|
+
const args = params as Record<string, unknown>;
|
|
239
|
+
if (signal?.aborted || typeof args.path !== 'string' || resolvePermissionPath(ctx.cwd, args.path) !== target) return false;
|
|
240
|
+
return permissionModes?.consumeCommitApproval?.(toolCallId, ctx, args, tool.name) ?? confirm('Confirm delete', target);
|
|
241
|
+
} catch { return false; }
|
|
242
|
+
}
|
|
243
|
+
const gitOperations: Record<string, string> = { git_commit: 'git commit', git_add: 'git add', git_checkout: 'git checkout', git_branch: 'create git branch' };
|
|
244
|
+
if (gitOperations[tool.name] === operation) {
|
|
245
|
+
if (signal?.aborted) return false;
|
|
246
|
+
return permissionModes?.consumeCommitApproval?.(toolCallId, ctx, params as Record<string, unknown>, tool.name)
|
|
247
|
+
?? confirm(tool.name === 'git_commit' ? 'Commit staged changes?' : `Confirm ${operation}`, target);
|
|
248
|
+
}
|
|
249
|
+
return confirm(`Confirm ${operation}`, target);
|
|
250
|
+
},
|
|
251
|
+
confirmSensitiveRead: description => confirm('Allow sensitive Git diff?', description),
|
|
252
|
+
confirmCommand: (command, shell) => {
|
|
253
|
+
const args = params as Record<string, unknown>;
|
|
254
|
+
const expected = tool.name === 'terminal' && typeof args.input === 'string'
|
|
255
|
+
? `Send terminal input to ${args.processId}:\n${args.input}`
|
|
256
|
+
: tool.name === 'run_code' && typeof args.code === 'string'
|
|
257
|
+
? nodeCommandPreview(args.code)
|
|
258
|
+
: args.command;
|
|
259
|
+
const expectedShell = tool.name === 'run_code' ? 'node' : shellForTool(tool.name);
|
|
260
|
+
if (command !== expected || shell !== expectedShell || signal?.aborted) return Promise.resolve(false);
|
|
261
|
+
const approved = permissionModes?.consumeCommitApproval?.(toolCallId, ctx, args, tool.name);
|
|
262
|
+
return approved === undefined ? confirm(shell === 'powershell' ? 'Run PowerShell command?' : 'Run shell command?', command) : Promise.resolve(approved);
|
|
263
|
+
},
|
|
264
|
+
...(['edit', 'write', 'apply_patch', 'undo'].includes(tool.name) ? undoContext(ctx, signal) : {}),
|
|
265
|
+
...(tool.name === 'notebook_edit' ? {
|
|
266
|
+
undoEpoch: notebookEpoch,
|
|
267
|
+
undoTurn,
|
|
268
|
+
checkNotebookEdit: () => {
|
|
269
|
+
if (!callMode || notebookEpoch !== undoEpoch || permissionModes?.mode !== callMode) return false;
|
|
270
|
+
const config = loadPermissionRules(ctx.cwd, () => {});
|
|
271
|
+
return !config.invalid && decidePermission(callMode, tool.name, params, ctx.cwd, config.rules).action === 'ask';
|
|
272
|
+
},
|
|
273
|
+
} : {}),
|
|
274
|
+
};
|
|
275
|
+
const dispatched = await dispatcher.dispatch(
|
|
276
|
+
{ name: tool.name, arguments: params as Record<string, unknown> },
|
|
277
|
+
context,
|
|
278
|
+
);
|
|
279
|
+
const result: DispatchResult = lifetime?.aborted
|
|
280
|
+
? { success: false, error: 'Tool session ended', errorCode: 'OPERATION_CANCELLED' }
|
|
281
|
+
: dispatched;
|
|
282
|
+
const text = result.output ?? result.error ?? '';
|
|
283
|
+
return {
|
|
284
|
+
content: [{ type: 'text' as const, text }, ...(result.image ? [result.image] : [])],
|
|
285
|
+
...(tool.name === 'read' && result.success ? { structuredContent: result.image ? { ...result.image, note: text } : text } : {}),
|
|
286
|
+
details: { success: result.success, errorCode: result.errorCode, metadata: result.metadata },
|
|
287
|
+
...(result.success ? {} : { isError: true }),
|
|
288
|
+
};
|
|
289
|
+
},
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
return { processManager: registry.has('process') ? processManager : undefined, hasMemory: registry.has('memory') };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function actualSessionId(ctx: ExtensionContext): string {
|
|
296
|
+
const sessionManager = (ctx as ExtensionContext | undefined)?.sessionManager as
|
|
297
|
+
| { getSessionId?: () => unknown }
|
|
298
|
+
| undefined;
|
|
299
|
+
if (typeof sessionManager?.getSessionId !== 'function') {
|
|
300
|
+
throw new Error('File tracking unavailable: Pi session manager does not expose getSessionId()');
|
|
301
|
+
}
|
|
302
|
+
let sessionId: unknown;
|
|
303
|
+
try {
|
|
304
|
+
sessionId = sessionManager.getSessionId();
|
|
305
|
+
} catch {
|
|
306
|
+
throw new Error('File tracking unavailable: Pi session ID could not be obtained');
|
|
307
|
+
}
|
|
308
|
+
if (typeof sessionId !== 'string' || !sessionId) {
|
|
309
|
+
throw new Error('File tracking unavailable: Pi session ID is unavailable');
|
|
310
|
+
}
|
|
311
|
+
return sessionId;
|
|
312
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { lstatSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
4
|
+
import type { PathRule } from '../config/path-rules.ts';
|
|
5
|
+
import { loadProjectConfig } from '../config/project.ts';
|
|
6
|
+
import { literal } from '../tui/text.ts';
|
|
7
|
+
import type { PermissionController } from './permission-modes/index.ts';
|
|
8
|
+
import { isProtectedWrite, isWithin, resolvePermissionPath } from './permission-modes/paths.ts';
|
|
9
|
+
import { decidePermission } from './permission-modes/policy.ts';
|
|
10
|
+
import { loadPermissionRules } from './permission-modes/rules.ts';
|
|
11
|
+
|
|
12
|
+
const SCOPE_ENTRY = 'bi.path-scope';
|
|
13
|
+
|
|
14
|
+
function pathScope(ctx: ExtensionContext): string | undefined {
|
|
15
|
+
const entry = ctx.sessionManager.getBranch().findLast(item => item.type === 'custom' && item.customType === SCOPE_ENTRY);
|
|
16
|
+
return entry?.type === 'custom' && typeof entry.data === 'string' ? entry.data : undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function mayReadConfig(ctx: ExtensionContext, mode: string): boolean {
|
|
20
|
+
if (!ctx.isProjectTrusted() || ctx.signal?.aborted) return false;
|
|
21
|
+
try {
|
|
22
|
+
const root = resolvePermissionPath(ctx.cwd, '.');
|
|
23
|
+
const config = path.join(root, '.pi', 'config.json');
|
|
24
|
+
if (resolvePermissionPath(root, config) !== config) return false;
|
|
25
|
+
const stat = lstatSync(config);
|
|
26
|
+
if (!stat.isFile() || stat.nlink !== 1) return false;
|
|
27
|
+
const { invalid, rules } = loadPermissionRules(ctx.cwd, () => {});
|
|
28
|
+
return !invalid && decidePermission(mode, 'read', { path: config }, ctx.cwd, rules).action === 'allow';
|
|
29
|
+
} catch { return false; }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function scopedPath(ctx: ExtensionContext, target: string, mode: string): string | undefined {
|
|
33
|
+
const name = target.replace(/\\/g, '/');
|
|
34
|
+
if (!name || name.length > 4096 || name.startsWith('/') || /[:*?\p{Cc}]/u.test(name) || name.split('/').includes('..')) return;
|
|
35
|
+
try {
|
|
36
|
+
const root = resolvePermissionPath(ctx.cwd, '.');
|
|
37
|
+
const file = path.resolve(root, name);
|
|
38
|
+
const relative = path.relative(root, file).split(path.sep).join('/');
|
|
39
|
+
if (!relative || !isWithin(root, file) || isProtectedWrite(file) || relative.split('/').some(part => ['.pi', '.bi'].includes(part.toLowerCase())) ||
|
|
40
|
+
resolvePermissionPath(root, file) !== file) return;
|
|
41
|
+
const { invalid, rules } = loadPermissionRules(ctx.cwd, () => {});
|
|
42
|
+
if (!invalid && decidePermission(mode, 'read', { path: file }, ctx.cwd, rules).action === 'allow') return relative;
|
|
43
|
+
} catch { /* Invalid or changed targets do not grant a scope. */ }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function matchingRules(pathScope: string, rules: PathRule[]): PathRule[] {
|
|
47
|
+
return rules.filter(rule => path.posix.matchesGlob(pathScope, rule.pattern));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function activePathRules(ctx: ExtensionContext, mode: string, rules?: PathRule[]) {
|
|
51
|
+
if (!rules?.length || !mayReadConfig(ctx, mode)) return;
|
|
52
|
+
const target = pathScope(ctx);
|
|
53
|
+
const scope = target && scopedPath(ctx, target, mode);
|
|
54
|
+
if (scope) {
|
|
55
|
+
const selected = matchingRules(scope, rules);
|
|
56
|
+
if (selected.length) return { scope, rules: selected };
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function registerScopedRulesCommand(pi: ExtensionAPI, permissions: PermissionController): void {
|
|
61
|
+
pi.registerCommand('rules', {
|
|
62
|
+
description: 'Show, select or clear the trusted path-rule scope on this session branch',
|
|
63
|
+
async handler(args, ctx) {
|
|
64
|
+
if (!ctx.hasUI || ctx.mode !== 'tui') return;
|
|
65
|
+
if (!ctx.isIdle() || ctx.hasPendingMessages() || !ctx.isProjectTrusted()) {
|
|
66
|
+
return ctx.ui.notify('Path rules require an idle, trusted terminal.', 'warning');
|
|
67
|
+
}
|
|
68
|
+
const input = args.trim();
|
|
69
|
+
if (input === 'clear') {
|
|
70
|
+
pi.appendEntry(SCOPE_ENTRY, null);
|
|
71
|
+
return ctx.ui.notify('Path rule scope cleared on this branch.', 'info');
|
|
72
|
+
}
|
|
73
|
+
const mode = permissions.mode, session = ctx.sessionManager.getSessionId(), leaf = ctx.sessionManager.getLeafId();
|
|
74
|
+
const current = () => ctx.isIdle() && !ctx.hasPendingMessages() && permissions.mode === mode &&
|
|
75
|
+
ctx.sessionManager.getSessionId() === session && ctx.sessionManager.getLeafId() === leaf && mayReadConfig(ctx, mode);
|
|
76
|
+
if (!current()) return ctx.ui.notify('No readable project config for path rules.', 'warning');
|
|
77
|
+
const config = await loadProjectConfig(ctx.cwd);
|
|
78
|
+
if (!current()) return;
|
|
79
|
+
const rules = config.systemPrompt?.pathRules;
|
|
80
|
+
if (!rules?.length) return ctx.ui.notify('No path rules configured in systemPrompt.pathRules.', 'info');
|
|
81
|
+
const target = input || pathScope(ctx);
|
|
82
|
+
if (!target) return ctx.ui.notify('No scope selected. Use /rules <relative-path> to opt in on this branch.', 'info');
|
|
83
|
+
const scope = scopedPath(ctx, target, mode);
|
|
84
|
+
if (!scope) return ctx.ui.notify('Path rule selection requires a permitted workspace-relative path.', 'warning');
|
|
85
|
+
const selected = matchingRules(scope, rules);
|
|
86
|
+
if (!selected.length) return ctx.ui.notify('No rules match this path; existing selection was not changed.', 'info');
|
|
87
|
+
if (input) pi.appendEntry(SCOPE_ENTRY, scope);
|
|
88
|
+
ctx.ui.notify(`Path scope: ${literal(scope)}. Matching rules: ${selected.map(rule => literal(rule.pattern)).join(', ')}.`, 'info');
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ExtensionAPI,
|
|
3
|
+
NormalizedBuildSystemPromptOptions,
|
|
4
|
+
} from '@earendil-works/pi-coding-agent';
|
|
5
|
+
import { BI_CONFIG } from '../config/index.ts';
|
|
6
|
+
import { loadProjectConfig } from '../config/project.ts';
|
|
7
|
+
import type { PermissionController } from './permission-modes/index.ts';
|
|
8
|
+
import { activePathRules } from './scoped-rules.ts';
|
|
9
|
+
|
|
10
|
+
function buildBiSystemPrompt(
|
|
11
|
+
options: NormalizedBuildSystemPromptOptions,
|
|
12
|
+
projectInstructions?: string,
|
|
13
|
+
scoped?: ReturnType<typeof activePathRules>,
|
|
14
|
+
): string {
|
|
15
|
+
const parts: string[] = [];
|
|
16
|
+
|
|
17
|
+
if (options.customPrompt?.trim()) {
|
|
18
|
+
parts.push(options.customPrompt.trim());
|
|
19
|
+
}
|
|
20
|
+
parts.push(BI_CONFIG.systemPrompt.core.join('\n'));
|
|
21
|
+
if (projectInstructions?.trim()) {
|
|
22
|
+
parts.push(`<project_specific_instructions>\n${projectInstructions.trim()}\n</project_specific_instructions>`);
|
|
23
|
+
}
|
|
24
|
+
if (scoped) {
|
|
25
|
+
parts.push(`<path_scoped_instructions>\nApply these project instructions only when working on ${JSON.stringify(scoped.scope)}:\n\n${scoped.rules.map(rule => rule.instructions).join('\n\n')}\n</path_scoped_instructions>`);
|
|
26
|
+
}
|
|
27
|
+
parts.push(`Working directory: ${options.cwd}`);
|
|
28
|
+
|
|
29
|
+
const tools = options.selectedTools.filter((tool) => !options.hiddenTools.includes(tool));
|
|
30
|
+
if (tools.length > 0) {
|
|
31
|
+
const lines = tools.map((name) => {
|
|
32
|
+
const snippet = options.toolSnippets[name];
|
|
33
|
+
const header = ` - ${name}${snippet ? `: ${snippet}` : ''}`;
|
|
34
|
+
const guidelines = (options.toolGuidelines[name] ?? []).map((rule) => ` - ${rule}`);
|
|
35
|
+
return [header, ...guidelines].join('\n');
|
|
36
|
+
});
|
|
37
|
+
parts.push(`<available_tools>\n${lines.join('\n')}\n</available_tools>`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (options.contextFiles.length > 0) {
|
|
41
|
+
const blocks = options.contextFiles
|
|
42
|
+
.map((file) => `<context_file path="${file.path}">\n${file.content}\n</context_file>`)
|
|
43
|
+
.join('\n');
|
|
44
|
+
parts.push(`<project_context>\n${blocks}\n</project_context>`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (options.skills.length > 0) {
|
|
48
|
+
const lines = options.skills.map((skill) => ` - ${skill.name}: ${skill.description}`);
|
|
49
|
+
parts.push(`<skills>\n${lines.join('\n')}\n</skills>`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
for (const [tag, content] of Object.entries(options.sections)) {
|
|
53
|
+
if (content.trim()) {
|
|
54
|
+
parts.push(`<${tag}>\n${content.trim()}\n</${tag}>`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (options.appendSystemPrompt.trim()) {
|
|
59
|
+
parts.push(options.appendSystemPrompt.trim());
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return parts.join('\n\n');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function registerSystemInstruction(pi: ExtensionAPI, permissionModes?: PermissionController) {
|
|
66
|
+
pi.on('before_agent_start', async (event, ctx) => {
|
|
67
|
+
// Project config is repository content. Only inject its prompt when Pi marks
|
|
68
|
+
// the current project as trusted; the core bi prompt always stays in place.
|
|
69
|
+
const configured = ctx.isProjectTrusted() ? (await loadProjectConfig(event.systemPromptOptions.cwd)).systemPrompt : undefined;
|
|
70
|
+
const scoped = activePathRules(ctx, permissionModes?.mode ?? 'default', configured?.pathRules);
|
|
71
|
+
const instruction = permissionModes ? `\n\nCurrent permission mode: ${permissionModes.label}. ${permissionModes.mode === 'plan' ? 'Investigate without changing project files. Use plan_note for the current session plan; implementation requires explicit approval.' : 'Tool calls are subject to the current permission gate and existing tool safety checks.'}` : '';
|
|
72
|
+
return { systemPrompt: buildBiSystemPrompt(event.systemPromptOptions, configured?.additional, scoped) + instruction };
|
|
73
|
+
});
|
|
74
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { BI_CONFIG } from './config/index.ts';
|
|
3
|
+
import { ensureProjectConfig, loadProjectConfig } from './config/project.ts';
|
|
4
|
+
import { ensureQuietStartup, registerSystemInstruction, registerTools } from './extension/index.ts';
|
|
5
|
+
import {
|
|
6
|
+
registerBtwCommand,
|
|
7
|
+
registerDiffCommand,
|
|
8
|
+
registerDiscoveryCommands,
|
|
9
|
+
registerDoctorCommand,
|
|
10
|
+
registerGoalCommand,
|
|
11
|
+
registerInitCommand,
|
|
12
|
+
registerPlanCommand,
|
|
13
|
+
registerReviewCommand,
|
|
14
|
+
registerSecurityReviewCommand,
|
|
15
|
+
registerSimplifyCommand,
|
|
16
|
+
registerTasksCommand,
|
|
17
|
+
registerVerifyCommand,
|
|
18
|
+
registerWorktreeCommand,
|
|
19
|
+
} from './commands/index.ts';
|
|
20
|
+
import { installTui } from './tui/index.ts';
|
|
21
|
+
import { registerWorkingFeedback } from './tui/working-feedback.ts';
|
|
22
|
+
import { createPermissionModes } from './extension/permission-modes/index.ts';
|
|
23
|
+
import { registerScopedRulesCommand } from './extension/scoped-rules.ts';
|
|
24
|
+
import { registerMemoryCommands } from './commands/memory.ts';
|
|
25
|
+
import { registerClaudeMigrationPreview } from './commands/claude-migrate.ts';
|
|
26
|
+
import { registerHooksCommand } from './commands/hooks.ts';
|
|
27
|
+
import { registerStatsCommand } from './commands/stats.ts';
|
|
28
|
+
|
|
29
|
+
// Pi extension entry point.
|
|
30
|
+
// Loaded via the "pi.extensions" manifest in package.json.
|
|
31
|
+
// Test with: pi -e ./
|
|
32
|
+
export default function (pi: ExtensionAPI) {
|
|
33
|
+
const permissionModes = createPermissionModes(pi);
|
|
34
|
+
const { processManager, hasMemory } = registerTools(pi, permissionModes);
|
|
35
|
+
if (hasMemory) registerMemoryCommands(pi, permissionModes);
|
|
36
|
+
registerSystemInstruction(pi, permissionModes);
|
|
37
|
+
registerScopedRulesCommand(pi, permissionModes);
|
|
38
|
+
registerBtwCommand(pi, permissionModes);
|
|
39
|
+
registerDiffCommand(pi, permissionModes);
|
|
40
|
+
registerDiscoveryCommands(pi, permissionModes);
|
|
41
|
+
registerClaudeMigrationPreview(pi, permissionModes);
|
|
42
|
+
registerHooksCommand(pi, permissionModes, processManager);
|
|
43
|
+
registerStatsCommand(pi, permissionModes);
|
|
44
|
+
registerDoctorCommand(pi, permissionModes);
|
|
45
|
+
registerInitCommand(pi);
|
|
46
|
+
registerPlanCommand(pi, permissionModes);
|
|
47
|
+
registerGoalCommand(pi);
|
|
48
|
+
registerReviewCommand(pi);
|
|
49
|
+
registerSecurityReviewCommand(pi, permissionModes, { specialists: true });
|
|
50
|
+
registerSimplifyCommand(pi);
|
|
51
|
+
registerTasksCommand(pi, processManager && { processManager, permissions: permissionModes });
|
|
52
|
+
registerVerifyCommand(pi, permissionModes);
|
|
53
|
+
registerWorktreeCommand(pi, permissionModes);
|
|
54
|
+
registerWorkingFeedback(pi);
|
|
55
|
+
|
|
56
|
+
pi.on('session_start', async (event, ctx) => {
|
|
57
|
+
if (ctx.mode === 'tui') {
|
|
58
|
+
const config = await loadProjectConfig(ctx.cwd);
|
|
59
|
+
installTui(ctx, permissionModes, config.ui?.footerStyle ?? BI_CONFIG.ui.footerStyle, event.reason === 'startup');
|
|
60
|
+
}
|
|
61
|
+
if (permissionModes.mode !== 'plan') {
|
|
62
|
+
await ensureProjectConfig(ctx.cwd);
|
|
63
|
+
const projectConfig = await loadProjectConfig(ctx.cwd);
|
|
64
|
+
await ensureQuietStartup(
|
|
65
|
+
ctx.cwd,
|
|
66
|
+
projectConfig.startup?.autoEnableQuietStartup ?? BI_CONFIG.startup.autoEnableQuietStartup,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
if (ctx.mode !== 'tui') ctx.ui.notify(BI_CONFIG.ui.startupMessage, 'info');
|
|
70
|
+
});
|
|
71
|
+
}
|