@preapexis/honeycomb 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +15 -0
- package/README.md +443 -2
- package/bin/bee.js +18 -0
- package/package.json +66 -4
- package/plan/tools/tool-parity.md +61 -0
- package/src/commands/btw.ts +95 -0
- package/src/commands/claude-migrate.ts +63 -0
- package/src/commands/diff.ts +119 -0
- package/src/commands/discovery.ts +112 -0
- package/src/commands/doctor.ts +80 -0
- package/src/commands/goal/index.ts +254 -0
- package/src/commands/goal/report.ts +66 -0
- package/src/commands/goal/state.ts +74 -0
- package/src/commands/hooks.ts +38 -0
- package/src/commands/index.ts +13 -0
- package/src/commands/init.ts +66 -0
- package/src/commands/memory.ts +70 -0
- package/src/commands/plan.ts +36 -0
- package/src/commands/review-report.ts +23 -0
- package/src/commands/review.ts +21 -0
- package/src/commands/rewind-history.ts +40 -0
- package/src/commands/security-review.ts +138 -0
- package/src/commands/simplify.ts +21 -0
- package/src/commands/stats.ts +125 -0
- package/src/commands/tasks.ts +87 -0
- package/src/commands/verify.ts +21 -0
- package/src/commands/worktree.ts +138 -0
- package/src/config/bi.config.json +77 -0
- package/src/config/index.ts +47 -0
- package/src/config/limits.ts +12 -0
- package/src/config/path-rules.ts +19 -0
- package/src/config/project.ts +133 -0
- package/src/extension/ask-user.ts +52 -0
- package/src/extension/index.ts +4 -0
- package/src/extension/lsp-install.ts +95 -0
- package/src/extension/lsp-menu.ts +90 -0
- package/src/extension/permission-modes/index.ts +337 -0
- package/src/extension/permission-modes/mcp-resources.ts +21 -0
- package/src/extension/permission-modes/metadata.ts +18 -0
- package/src/extension/permission-modes/paths.ts +44 -0
- package/src/extension/permission-modes/plan-note.ts +58 -0
- package/src/extension/permission-modes/policy.ts +236 -0
- package/src/extension/permission-modes/preview.ts +104 -0
- package/src/extension/permission-modes/rules.ts +67 -0
- package/src/extension/permission-modes/shell.ts +183 -0
- package/src/extension/permission-modes/state.ts +6 -0
- package/src/extension/quiet-startup.ts +25 -0
- package/src/extension/register-tools.ts +312 -0
- package/src/extension/scoped-rules.ts +91 -0
- package/src/extension/system-instruction.ts +74 -0
- package/src/index.ts +71 -0
- package/src/tools/advanced.ts +133 -0
- package/src/tools/agent.ts +379 -0
- package/src/tools/dispatcher.ts +80 -0
- package/src/tools/executable.ts +15 -0
- package/src/tools/execution.ts +289 -0
- package/src/tools/filesystem.ts +662 -0
- package/src/tools/git.ts +196 -0
- package/src/tools/glob.ts +81 -0
- package/src/tools/grep.ts +203 -0
- package/src/tools/image-read.ts +71 -0
- package/src/tools/index.ts +52 -0
- package/src/tools/lsp-client.ts +104 -0
- package/src/tools/lsp.ts +172 -0
- package/src/tools/memory-store.ts +77 -0
- package/src/tools/notebook.ts +169 -0
- package/src/tools/registry.ts +31 -0
- package/src/tools/shells.ts +63 -0
- package/src/tools/todo.ts +119 -0
- package/src/tools/undo-journal.ts +46 -0
- package/src/tools/web-fetch.ts +119 -0
- package/src/tools/web-search.ts +76 -0
- package/src/tools/write-file.ts +14 -0
- package/src/tui/editor.ts +65 -0
- package/src/tui/footer-stats.ts +35 -0
- package/src/tui/header.ts +81 -0
- package/src/tui/index.ts +124 -0
- package/src/tui/mascot.ts +59 -0
- package/src/tui/permission-dialog.ts +94 -0
- package/src/tui/permission-rules.ts +64 -0
- package/src/tui/tasks-panel.ts +84 -0
- package/src/tui/text.ts +55 -0
- package/src/tui/tool-renderer.ts +42 -0
- package/src/tui/working-feedback.ts +220 -0
- package/src/types/agent.ts +54 -0
- package/src/types/common.ts +1 -0
- package/src/types/execution.ts +24 -0
- package/src/types/index.ts +4 -0
- package/src/types/tools.ts +61 -0
- package/themes/catppuccin-mocha.json +80 -0
- package/themes/github-dark.json +80 -0
- package/themes/honeycomb-dark.json +81 -0
- package/themes/honeycomb-light.json +81 -0
- package/themes/tokyo-day.json +80 -0
- package/themes/tokyo-night.json +80 -0
- package/themes/vercel-black.json +80 -0
- package/themes/vercel-light.json +80 -0
package/src/tui/index.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { visibleWidth } from '@earendil-works/pi-tui';
|
|
3
|
+
import { basename } from 'node:path';
|
|
4
|
+
import { readGitStatus } from '../tools/git.ts';
|
|
5
|
+
import type { PermissionController, PermissionMode } from '../extension/permission-modes/index.ts';
|
|
6
|
+
import { hasBiPromptEditor, installPromptEditor } from './editor.ts';
|
|
7
|
+
import { createWelcomeHeader, displayModel } from './header.ts';
|
|
8
|
+
import { compactNumber, durationText, footerStats } from './footer-stats.ts';
|
|
9
|
+
import { ASCII, fit, glyphs, literal } from './text.ts';
|
|
10
|
+
|
|
11
|
+
const badges = {
|
|
12
|
+
default: ['manual mode on', 'muted', '⏸'],
|
|
13
|
+
acceptEdits: ['accept edits on', 'success', '⏵⏵'],
|
|
14
|
+
plan: ['plan mode on', 'accent', '⏸'],
|
|
15
|
+
auto: ['auto mode on', 'warning', '⏵⏵'],
|
|
16
|
+
dontAsk: ['no prompts', 'warning', '⏵⏵'],
|
|
17
|
+
bypassPermissions: ['bypass permissions on', 'error', '⏵⏵'],
|
|
18
|
+
} as const satisfies Record<PermissionMode, readonly [string, string, string]>;
|
|
19
|
+
|
|
20
|
+
type ModeSource = Pick<PermissionController, 'mode' | 'label' | 'cycle' | 'subscribe'>;
|
|
21
|
+
|
|
22
|
+
export function installTui(ctx: ExtensionContext, permissions?: ModeSource, footerStyle: 'compact' | 'detailed' = 'detailed', animateHeader = false): void {
|
|
23
|
+
const cycleKey = installPromptEditor(ctx, permissions?.cycle);
|
|
24
|
+
ctx.ui.setHeader((tui, theme) => createWelcomeHeader(tui, theme, ctx, cycleKey, animateHeader));
|
|
25
|
+
|
|
26
|
+
ctx.ui.setFooter((tui, theme, footerData) => {
|
|
27
|
+
const unsubscribeMode = permissions?.subscribe(() => tui.requestRender());
|
|
28
|
+
const abort = new AbortController();
|
|
29
|
+
let dirty = false;
|
|
30
|
+
let polling = false;
|
|
31
|
+
let cachedStats: ReturnType<typeof footerStats> | undefined;
|
|
32
|
+
let cacheKey = '';
|
|
33
|
+
const pollGit = async () => {
|
|
34
|
+
if (polling || abort.signal.aborted || !footerData.getGitBranch()) return;
|
|
35
|
+
polling = true;
|
|
36
|
+
try {
|
|
37
|
+
const result = await readGitStatus({ workingDirectory: ctx.cwd, sessionId: 'footer', signal: abort.signal }, ['--porcelain'], 1500);
|
|
38
|
+
const next = !!result.success && !!result.output?.trim();
|
|
39
|
+
if (!abort.signal.aborted && next !== dirty) {
|
|
40
|
+
dirty = next;
|
|
41
|
+
tui.requestRender();
|
|
42
|
+
}
|
|
43
|
+
} catch { /* A status check must not interrupt the editor. */ }
|
|
44
|
+
finally { polling = false; }
|
|
45
|
+
};
|
|
46
|
+
void pollGit();
|
|
47
|
+
const tick = setInterval(() => { void pollGit(); tui.requestRender(); }, 5000);
|
|
48
|
+
tick.unref?.();
|
|
49
|
+
const unsubscribe = footerData.onBranchChange(() => {
|
|
50
|
+
dirty = false;
|
|
51
|
+
void pollGit();
|
|
52
|
+
tui.requestRender();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
dispose() {
|
|
57
|
+
abort.abort();
|
|
58
|
+
clearInterval(tick);
|
|
59
|
+
unsubscribe();
|
|
60
|
+
unsubscribeMode?.();
|
|
61
|
+
},
|
|
62
|
+
invalidate() {},
|
|
63
|
+
render(width: number): string[] {
|
|
64
|
+
if (width <= 0) return [];
|
|
65
|
+
const mode = permissions?.mode ?? 'default';
|
|
66
|
+
const [label, color, symbol] = badges[mode];
|
|
67
|
+
const marker = `${ASCII ? (symbol === '⏸' ? '||' : '>>') : symbol} `;
|
|
68
|
+
const full = theme.fg(color, marker + label);
|
|
69
|
+
const badge = permissions ? (visibleWidth(full) <= width ? full : theme.fg(color, permissions.label)) : '';
|
|
70
|
+
const branch = footerData.getGitBranch();
|
|
71
|
+
const cwd = literal(basename(ctx.cwd) || ctx.cwd);
|
|
72
|
+
const name = !hasBiPromptEditor(ctx) ? ctx.sessionManager.getSessionName?.() : undefined;
|
|
73
|
+
const nameLine = name ? fit(literal(name), width) : '';
|
|
74
|
+
const sessionLine = nameLine ? [theme.fg('dim', ' '.repeat(Math.max(0, width - visibleWidth(nameLine))) + nameLine)] : [];
|
|
75
|
+
const entries = ctx.sessionManager.getEntries();
|
|
76
|
+
const key = `${ctx.sessionManager.getSessionId()}:${ctx.sessionManager.getLeafId()}:${entries.length}`;
|
|
77
|
+
if (!cachedStats || cacheKey !== key) { cachedStats = footerStats(entries); cacheKey = key; }
|
|
78
|
+
const stats = cachedStats;
|
|
79
|
+
if (footerStyle === 'compact') {
|
|
80
|
+
const level = ctx.thinkingLevel;
|
|
81
|
+
const thinking = level && level !== 'off' ? (ASCII ? ` (thinking: ${literal(level)})` : ` 💭 ${literal(level)}`) : '';
|
|
82
|
+
const location = cwd + (branch ? ` ${literal(branch)}${dirty ? (ASCII ? ' *' : ' ●') : ''}` : '');
|
|
83
|
+
const average = stats.prompts ? stats.cost / stats.prompts : 0;
|
|
84
|
+
const parts = [displayModel(ctx.model) + thinking, location, `$${stats.cost.toFixed(2)} (~$${average.toFixed(2)}/prompt)`];
|
|
85
|
+
const status = () => parts.join(` ${glyphs.side} `);
|
|
86
|
+
while (parts.length > 1 && visibleWidth(status()) > width) parts.pop();
|
|
87
|
+
const runHint = ctx.isIdle() ? '' : theme.fg('dim', `${badge ? ` ${glyphs.sep} ` : ''}esc to interrupt`);
|
|
88
|
+
const modeLine = visibleWidth(badge + runHint) <= width ? badge + runHint : badge || runHint;
|
|
89
|
+
return [...sessionLine, theme.fg('dim', fit(status(), width)), ...(modeLine ? [fit(modeLine, width)] : [])];
|
|
90
|
+
}
|
|
91
|
+
const hint = theme.fg('dim', ` (${cycleKey} to cycle)`);
|
|
92
|
+
const left = badge + (permissions && visibleWidth(badge + hint) <= width ? hint : '');
|
|
93
|
+
const context = ctx.getContextUsage?.();
|
|
94
|
+
const percent = context?.percent == null ? null : Math.max(0, Math.min(100, Math.floor(context.percent)));
|
|
95
|
+
const bar = percent === null ? '? context' : `${(ASCII ? '#' : '▰').repeat(Math.round(percent / 10))}${(ASCII ? '-' : '▱').repeat(10 - Math.round(percent / 10))} ${percent}%`;
|
|
96
|
+
const model = displayModel(ctx.model) + (ctx.thinkingLevel && ctx.thinkingLevel !== 'off' ? ` · ${literal(ctx.thinkingLevel)}` : '');
|
|
97
|
+
const last = [...ctx.sessionManager.getBranch()].reverse().find(entry => entry.type === 'message' && entry.message.role === 'assistant');
|
|
98
|
+
const lastMessage = last?.type === 'message' && last.message.role === 'assistant' ? last.message : undefined;
|
|
99
|
+
const lastModel = lastMessage && ctx.model && (lastMessage.model !== ctx.model.id || lastMessage.provider !== ctx.model.provider)
|
|
100
|
+
? ` (last: ${literal(lastMessage.provider)}/${literal(lastMessage.model)})` : '';
|
|
101
|
+
const contextColor = percent === null ? 'dim' : percent >= 80 ? 'error' : percent >= 50 ? 'warning' : 'success';
|
|
102
|
+
const first = [theme.fg('accent', model + lastModel), theme.fg(contextColor, bar + (context?.contextWindow ? ` of ${compactNumber(context.contextWindow)}` : '')), `${ASCII ? 'prompts' : '💬'} ${stats.prompts}`, cwd + (branch ? ` (${literal(branch)}${dirty ? '*' : ''})` : '')];
|
|
103
|
+
const hit = stats.input ? ` (${Math.round(stats.read / stats.input * 100)}% hit)` : '';
|
|
104
|
+
const start = Date.parse(ctx.sessionManager.getHeader()?.timestamp ?? '');
|
|
105
|
+
const second = [`↓ ${compactNumber(stats.input)} in ↑ ${compactNumber(stats.output)} out`, `cache R ${compactNumber(stats.read)} W ${compactNumber(stats.write)}${hit}`,
|
|
106
|
+
...(stats.timed ? [`${durationText(stats.duration)} API${stats.timed < stats.assistants ? ' partial' : ''}`] : []),
|
|
107
|
+
...(Number.isFinite(start) ? [`${durationText(Date.now() - start)} elapsed`] : []),
|
|
108
|
+
...(stats.models.length > 1 ? [stats.models.map(model => literal(model)).join(' + ')] : [])];
|
|
109
|
+
const cost = `est. $${stats.cost.toFixed(3)}`;
|
|
110
|
+
const line = (parts: string[], right?: string) => {
|
|
111
|
+
const shown = [...parts];
|
|
112
|
+
const joined = () => shown.join(` ${glyphs.sep} `);
|
|
113
|
+
if (right && visibleWidth(joined()) + visibleWidth(right) + 3 <= width) {
|
|
114
|
+
return joined() + ' '.repeat(width - visibleWidth(joined()) - visibleWidth(right)) + right;
|
|
115
|
+
}
|
|
116
|
+
if (right) shown.push(right);
|
|
117
|
+
while (shown.length > 1 && visibleWidth(joined()) > width) shown.pop();
|
|
118
|
+
return fit(joined(), width);
|
|
119
|
+
};
|
|
120
|
+
return [...sessionLine, line(first.slice(0, -1), first.at(-1)), theme.fg('dim', line(second, cost)), ...(left ? [fit(left, width)] : [])];
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
});
|
|
124
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { ASCII } from './text.ts';
|
|
2
|
+
|
|
3
|
+
// Pixel grid from the 22px rectangles in assets/pixel_honeybee_mascot.svg (shadow omitted).
|
|
4
|
+
const pixels = [
|
|
5
|
+
' D D ',
|
|
6
|
+
' D D ',
|
|
7
|
+
' BBB DDDDDD BBB ',
|
|
8
|
+
'BLLLDYYYYYYDLLLB',
|
|
9
|
+
'BLLDYWDYYWDYDLLB',
|
|
10
|
+
'BLLDYDDYYDDYDLLB',
|
|
11
|
+
' BBDYYYDDYYYDBB ',
|
|
12
|
+
' DYYYYYYYYYYD ',
|
|
13
|
+
' DDDDDDDDDDDD ',
|
|
14
|
+
' DYYYYYYYYYYD ',
|
|
15
|
+
' DDDDDDDDDDDD ',
|
|
16
|
+
' DDYYYYYYDD ',
|
|
17
|
+
' DDDDDDDD ',
|
|
18
|
+
' DD ',
|
|
19
|
+
];
|
|
20
|
+
const colors: Record<string, number> = { B: 111, L: 255, D: 58, Y: 220, W: 231 };
|
|
21
|
+
|
|
22
|
+
function renderPixels(grid: string[]): string[] {
|
|
23
|
+
return grid.filter((_, row) => row % 2 === 0).map((top, row) =>
|
|
24
|
+
Array.from(top, (pixel, col) => {
|
|
25
|
+
const fg = colors[pixel];
|
|
26
|
+
const bg = colors[grid[row * 2 + 1]?.[col] ?? ' '];
|
|
27
|
+
if (fg === undefined && bg === undefined) return ' ';
|
|
28
|
+
if (fg === undefined) return `\x1b[38;5;${bg}m▄\x1b[39m`;
|
|
29
|
+
return `\x1b[38;5;${fg}${bg === undefined ? '' : `;48;5;${bg}`}m▀\x1b[39;49m`;
|
|
30
|
+
}).join(''),
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Approximate the animated SVG's wing flap by raising only the wing pixels.
|
|
35
|
+
const wingsUp = pixels.map((line, row) => Array.from(line, (pixel, col) => {
|
|
36
|
+
if (pixel !== ' ' && pixel !== 'B' && pixel !== 'L') return pixel;
|
|
37
|
+
const below = pixels[row + 1]?.[col];
|
|
38
|
+
return below === 'B' || below === 'L' ? below : ' ';
|
|
39
|
+
}).join(''));
|
|
40
|
+
const blank = ' '.repeat(pixels[0]!.length);
|
|
41
|
+
const resting = ASCII ? [
|
|
42
|
+
'',
|
|
43
|
+
' \\ / ',
|
|
44
|
+
' .-(o o)-. ',
|
|
45
|
+
" '<| -- |>' ",
|
|
46
|
+
' |====| ',
|
|
47
|
+
' \\==/ ',
|
|
48
|
+
' v ',
|
|
49
|
+
] : renderPixels([blank, blank, ...pixels]);
|
|
50
|
+
|
|
51
|
+
export const MASCOT_FACE = '<(o.o)>';
|
|
52
|
+
export const mascotFrames = ASCII ? [resting] : [
|
|
53
|
+
resting,
|
|
54
|
+
renderPixels([blank, blank, ...wingsUp]),
|
|
55
|
+
renderPixels([blank, ...pixels, blank]),
|
|
56
|
+
renderPixels([blank, ...wingsUp, blank]),
|
|
57
|
+
renderPixels([...pixels, blank, blank]),
|
|
58
|
+
renderPixels([...wingsUp, blank, blank]),
|
|
59
|
+
];
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { matchesKey, wrapTextWithAnsi } from '@earendil-works/pi-tui';
|
|
3
|
+
import { fit, glyphs as g, literal } from './text.ts';
|
|
4
|
+
|
|
5
|
+
export type PreviewLine = { text: string; color?: 'dim' | 'warning' | 'toolDiffAdded' | 'toolDiffRemoved' };
|
|
6
|
+
const numberKeys = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] as const;
|
|
7
|
+
|
|
8
|
+
type Choice<T extends string> = { value: T; label?: string };
|
|
9
|
+
type Dialog<T extends string> = {
|
|
10
|
+
title: string;
|
|
11
|
+
preview: readonly PreviewLine[];
|
|
12
|
+
options: readonly Choice<T>[];
|
|
13
|
+
initial: T;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
async function show<T extends string>(ctx: ExtensionContext, dialog: Dialog<T>, signal: AbortSignal | undefined,
|
|
17
|
+
fallback: () => Promise<T | undefined>): Promise<T | undefined> {
|
|
18
|
+
if (!ctx.hasUI || signal?.aborted) return;
|
|
19
|
+
let result: T | undefined;
|
|
20
|
+
try {
|
|
21
|
+
result = ctx.mode === 'tui' ? await ctx.ui.custom<T | undefined>((tui, theme, keys, done) => {
|
|
22
|
+
let selected = Math.max(0, dialog.options.findIndex(o => o.value === dialog.initial));
|
|
23
|
+
let first = 0;
|
|
24
|
+
let viewport = 1;
|
|
25
|
+
let lines: string[] = [];
|
|
26
|
+
let cachedWidth: number | undefined;
|
|
27
|
+
const cancel = () => done(undefined);
|
|
28
|
+
signal?.addEventListener('abort', cancel, { once: true });
|
|
29
|
+
return {
|
|
30
|
+
render(width) {
|
|
31
|
+
if (width <= 0) return [];
|
|
32
|
+
if (cachedWidth !== width) {
|
|
33
|
+
cachedWidth = width;
|
|
34
|
+
lines = dialog.preview.flatMap(({ text, color }) => wrapTextWithAnsi(literal(text, true), Math.max(1, width - 2))
|
|
35
|
+
.map(line => color ? theme.fg(color, line) : line));
|
|
36
|
+
}
|
|
37
|
+
viewport = Math.max(1, Math.min(12, tui.terminal.rows - dialog.options.length - 6, Math.floor(tui.terminal.rows / 2)));
|
|
38
|
+
first = Math.max(0, Math.min(first, lines.length - viewport));
|
|
39
|
+
const preview = lines.slice(first, first + viewport).map(line => ' ' + line);
|
|
40
|
+
if (lines.length > viewport) {
|
|
41
|
+
preview.push(theme.fg('dim', ` ${first + 1}-${Math.min(first + viewport, lines.length)}/${lines.length} PageUp/PageDown`));
|
|
42
|
+
}
|
|
43
|
+
return [theme.fg('warning', g.rule.repeat(width)), theme.fg('warning', dialog.title), ...preview, '',
|
|
44
|
+
...dialog.options.map(({ value, label }, i) => {
|
|
45
|
+
const text = `${i === selected ? g.pointer : ' '} ${i + 1}. ${label ?? value}`;
|
|
46
|
+
return i === selected ? theme.fg('accent', text) : text;
|
|
47
|
+
}), theme.fg('dim', 'Enter to select · Esc to cancel')].map(line => fit(line, width));
|
|
48
|
+
},
|
|
49
|
+
handleInput(data) {
|
|
50
|
+
if (signal?.aborted || keys.matches(data, 'tui.select.cancel')) return cancel();
|
|
51
|
+
const number = numberKeys.findIndex(key => matchesKey(data, key));
|
|
52
|
+
if (number >= 0 && dialog.options[number]) return done(dialog.options[number]!.value);
|
|
53
|
+
if (keys.matches(data, 'tui.select.confirm')) return done(dialog.options[selected]?.value);
|
|
54
|
+
if (keys.matches(data, 'tui.select.up')) selected = (selected + dialog.options.length - 1) % dialog.options.length;
|
|
55
|
+
else if (keys.matches(data, 'tui.select.down')) selected = (selected + 1) % dialog.options.length;
|
|
56
|
+
else if (keys.matches(data, 'tui.select.pageUp')) first -= viewport;
|
|
57
|
+
else if (keys.matches(data, 'tui.select.pageDown')) first += viewport;
|
|
58
|
+
else return;
|
|
59
|
+
tui.requestRender();
|
|
60
|
+
},
|
|
61
|
+
invalidate() { cachedWidth = undefined; },
|
|
62
|
+
dispose() { signal?.removeEventListener('abort', cancel); },
|
|
63
|
+
};
|
|
64
|
+
}, { blocked: { kind: 'permission', message: dialog.title } }) : await fallback();
|
|
65
|
+
} catch { /* Dismissal, a failed UI, or an unsupported client never grants permission. */ }
|
|
66
|
+
return !signal?.aborted && dialog.options.some(option => option.value === result) ? result : undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Tool batches can execute in parallel. Do not stack two approval prompts over one editor. */
|
|
70
|
+
export function createPermissionPrompter() {
|
|
71
|
+
let queue = Promise.resolve();
|
|
72
|
+
function enqueue<T>(run: () => Promise<T>): Promise<T> {
|
|
73
|
+
const result = queue.then(run);
|
|
74
|
+
queue = result.then(() => undefined, () => undefined);
|
|
75
|
+
return result;
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
choose<T extends string>(ctx: ExtensionContext, dialog: Dialog<T>): Promise<T | undefined> {
|
|
79
|
+
const signal = ctx.signal;
|
|
80
|
+
return enqueue(() => show(ctx, dialog, signal, async () => {
|
|
81
|
+
const details = dialog.preview.map(({ text }) => literal(text, true)).join('\n');
|
|
82
|
+
const choice = await ctx.ui.select(details ? `${dialog.title}\n${details}` : dialog.title, dialog.options.map(o => o.value), { signal });
|
|
83
|
+
return dialog.options.find(o => o.value === choice)?.value;
|
|
84
|
+
}));
|
|
85
|
+
},
|
|
86
|
+
async confirm(ctx: ExtensionContext, title: string, message: string, signal = ctx.signal): Promise<boolean> {
|
|
87
|
+
const dialog: Dialog<'Yes' | 'No'> = { title, preview: [{ text: message }], options: [{ value: 'Yes' }, { value: 'No' }], initial: 'No' };
|
|
88
|
+
const result = await enqueue(() => show(ctx, dialog, signal, async () => await ctx.ui.confirm(title, literal(message, true), { signal }) ? 'Yes' : 'No'));
|
|
89
|
+
return result === 'Yes';
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export type PermissionPrompter = ReturnType<typeof createPermissionPrompter>;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { matchesKey } from '@earendil-works/pi-tui';
|
|
3
|
+
import { loadPermissionRules } from '../extension/permission-modes/rules.ts';
|
|
4
|
+
import { fit, glyphs, literal } from './text.ts';
|
|
5
|
+
|
|
6
|
+
export type PermissionActivity = { tool: string; reason: string };
|
|
7
|
+
|
|
8
|
+
/** Read-only so a cloned project cannot acquire new tool permissions through the viewer. */
|
|
9
|
+
export function registerPermissionRules(pi: ExtensionAPI, snapshot: () => { mode: string; approvals: number; denials: readonly PermissionActivity[] }): void {
|
|
10
|
+
const command: Parameters<ExtensionAPI['registerCommand']>[1] = {
|
|
11
|
+
description: 'Inspect effective permission rules and recent denials',
|
|
12
|
+
async handler(_args, ctx) {
|
|
13
|
+
if (!ctx.hasUI) return;
|
|
14
|
+
if (!ctx.isIdle()) { ctx.ui.notify('Wait for the current run before viewing permissions.', 'warning'); return; }
|
|
15
|
+
const issues: string[] = [];
|
|
16
|
+
const { groups, invalid } = loadPermissionRules(ctx.cwd, message => issues.push(message));
|
|
17
|
+
const { mode, approvals, denials } = snapshot();
|
|
18
|
+
const tabs = ['Allow', 'Ask', 'Deny', 'Recently denied'] as const;
|
|
19
|
+
const rows = [
|
|
20
|
+
...(['allow', 'ask', 'deny'] as const).map(action => groups.flatMap(group =>
|
|
21
|
+
(group.rules[action] ?? []).map(rule => `[${group.label}] ${literal(rule)}`))),
|
|
22
|
+
denials.map(({ tool, reason }) => `${literal(tool)}: ${literal(reason)}`),
|
|
23
|
+
];
|
|
24
|
+
const summary = `Mode: ${mode} · ${approvals} saved for this session`;
|
|
25
|
+
if (ctx.mode !== 'tui') {
|
|
26
|
+
ctx.ui.notify([summary, ...issues.map(issue => literal(issue)), ...tabs.flatMap((tab, i) => [tab, ...rows[i]!])].join('\n'), invalid ? 'warning' : 'info');
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
await ctx.ui.custom<void>((tui, theme, keys, done) => {
|
|
30
|
+
let tab = 0, first = 0, page = 1;
|
|
31
|
+
return {
|
|
32
|
+
render(width) {
|
|
33
|
+
if (width <= 0) return [];
|
|
34
|
+
page = Math.max(1, Math.min(14, tui.terminal.rows - 8));
|
|
35
|
+
const current = rows[tab]!;
|
|
36
|
+
first = Math.max(0, Math.min(first, current.length - page));
|
|
37
|
+
const headings = tabs.map((name, index) => theme.fg(index === tab ? 'accent' : 'dim', name)).join(' ');
|
|
38
|
+
const lines = [theme.fg('accent', 'Permissions'), summary,
|
|
39
|
+
...(invalid ? [theme.fg('error', 'Invalid configuration. Tool calls are blocked.'), ...issues.map(issue => literal(issue))] : []),
|
|
40
|
+
'', width >= 37 ? headings : `${tab + 1}/${tabs.length} ${tabs[tab]}`, glyphs.rule.repeat(width),
|
|
41
|
+
...(current.length ? current.slice(first, first + page) : ['No entries']),
|
|
42
|
+
...(current.length > page ? [theme.fg('dim', `${first + 1}-${Math.min(first + page, current.length)}/${current.length}`)] : []),
|
|
43
|
+
'', theme.fg('dim', 'Left/Right or Tab: switch · Up/Down: scroll · Esc: close')];
|
|
44
|
+
return lines.map(line => fit(line, width));
|
|
45
|
+
},
|
|
46
|
+
handleInput(data) {
|
|
47
|
+
if (keys.matches(data, 'tui.select.cancel')) return done(undefined);
|
|
48
|
+
if (matchesKey(data, 'left') || matchesKey(data, 'shift+tab')) { tab = (tab + tabs.length - 1) % tabs.length; first = 0; }
|
|
49
|
+
else if (matchesKey(data, 'right') || keys.matches(data, 'tui.input.tab')) { tab = (tab + 1) % tabs.length; first = 0; }
|
|
50
|
+
else if (keys.matches(data, 'tui.select.up')) first--;
|
|
51
|
+
else if (keys.matches(data, 'tui.select.down')) first++;
|
|
52
|
+
else if (keys.matches(data, 'tui.select.pageUp')) first -= page;
|
|
53
|
+
else if (keys.matches(data, 'tui.select.pageDown')) first += page;
|
|
54
|
+
else return;
|
|
55
|
+
tui.requestRender();
|
|
56
|
+
},
|
|
57
|
+
invalidate() {},
|
|
58
|
+
};
|
|
59
|
+
});
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
pi.registerCommand?.('permissions', command);
|
|
63
|
+
pi.registerCommand?.('allowed-tools', { ...command, description: 'Alias for /permissions (read-only)' });
|
|
64
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { ExtensionCommandContext } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { matchesKey } from '@earendil-works/pi-tui';
|
|
3
|
+
import type { ManagedJob } from '../types/execution.ts';
|
|
4
|
+
import { fit, literal } from './text.ts';
|
|
5
|
+
|
|
6
|
+
export interface JobsView {
|
|
7
|
+
current: () => boolean;
|
|
8
|
+
list: () => ManagedJob[] | undefined;
|
|
9
|
+
output: (id: string) => string | undefined;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const MAX_JOB_PREVIEW = 8000;
|
|
13
|
+
|
|
14
|
+
export function jobLabel(job: ManagedJob): string {
|
|
15
|
+
const { id, exited } = job;
|
|
16
|
+
const status = !exited ? 'Running' : exited.signal ? `Stopped (${exited.signal})` :
|
|
17
|
+
exited.code === null ? 'Finished' : `Exited (${exited.code})`;
|
|
18
|
+
return `${status} — ${id}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function showTasksPanel(ctx: ExtensionCommandContext, tasks: string[], jobs?: JobsView, openJobs = false) {
|
|
22
|
+
return ctx.ui.custom<void>((tui, theme, keys, done) => {
|
|
23
|
+
let tab = openJobs ? 'jobs' : 'tasks';
|
|
24
|
+
let entries = openJobs ? jobs?.list() : undefined;
|
|
25
|
+
let selected = 0, offset = 0, page = 1;
|
|
26
|
+
let detail: { id: string; rows: string[] } | undefined;
|
|
27
|
+
const refreshOutput = (id: string) => {
|
|
28
|
+
const output = jobs?.output(id);
|
|
29
|
+
const rows = output === undefined ? ['Job output is no longer available.'] : output ?
|
|
30
|
+
literal(output.slice(0, MAX_JOB_PREVIEW).replace(/\r\n/g, '\n'), true).split('\n') : ['No captured output.'];
|
|
31
|
+
if (output && output.length > MAX_JOB_PREVIEW) rows.push(`… Preview limited to ${MAX_JOB_PREVIEW} characters.`);
|
|
32
|
+
detail = { id, rows };
|
|
33
|
+
};
|
|
34
|
+
return {
|
|
35
|
+
render(width) {
|
|
36
|
+
page = Math.max(1, tui.terminal.rows - 5);
|
|
37
|
+
const title = theme.fg('accent', `Session tasks${jobs ? ` — ${tab === 'tasks' ? 'Goals & todos' : 'Jobs'}` : ''}`);
|
|
38
|
+
const render = (rows: string[], hint: string) => [title, ...rows, hint].map(line => fit(line, width));
|
|
39
|
+
if (tab === 'jobs' && !jobs?.current()) return render(['Session or permission mode changed.'], 'Esc: close');
|
|
40
|
+
if (tab === 'jobs' && !detail && entries?.length) {
|
|
41
|
+
offset = Math.max(0, Math.min(offset, selected));
|
|
42
|
+
if (selected >= offset + page) offset = selected - page + 1;
|
|
43
|
+
return render(entries.slice(offset, offset + page).map((job, i) =>
|
|
44
|
+
`${offset + i === selected ? '> ' : ' '}${literal(jobLabel(job))}`), 'Tab: todos · ↑/↓: select · Enter: output · r: refresh · Esc: close');
|
|
45
|
+
}
|
|
46
|
+
const rows = tab === 'tasks' ? tasks : detail?.rows ?? [entries ? 'No jobs with permitted status in this session.' : 'Jobs unavailable in the current mode or rules.'];
|
|
47
|
+
offset = Math.max(0, Math.min(offset, rows.length - page));
|
|
48
|
+
const hint = detail ? '↑/↓/PgUp/PgDn: scroll · r: refresh · Esc: back' :
|
|
49
|
+
`${jobs ? (tab === 'tasks' ? 'Tab: jobs · ' : 'Tab: todos · r: refresh · ') : ''}↑/↓/PgUp/PgDn: scroll · Esc: close`;
|
|
50
|
+
return render([...(detail ? [`Output — ${literal(detail.id)}`] : []), ...rows.slice(offset, offset + page)], hint);
|
|
51
|
+
},
|
|
52
|
+
handleInput(data) {
|
|
53
|
+
if (keys.matches(data, 'tui.select.cancel')) {
|
|
54
|
+
if (!detail || !jobs?.current()) return done(undefined);
|
|
55
|
+
detail = undefined;
|
|
56
|
+
offset = selected;
|
|
57
|
+
} else if (jobs && keys.matches(data, 'tui.input.tab')) {
|
|
58
|
+
tab = tab === 'tasks' ? 'jobs' : 'tasks';
|
|
59
|
+
if (tab === 'jobs') entries = jobs.list();
|
|
60
|
+
detail = undefined;
|
|
61
|
+
selected = offset = 0;
|
|
62
|
+
} else if (tab === 'jobs' && jobs?.current() && matchesKey(data, 'r')) {
|
|
63
|
+
if (detail) refreshOutput(detail.id);
|
|
64
|
+
else {
|
|
65
|
+
const id = entries?.[selected]?.id;
|
|
66
|
+
entries = jobs.list();
|
|
67
|
+
selected = Math.max(0, entries?.findIndex(job => job.id === id) ?? -1);
|
|
68
|
+
}
|
|
69
|
+
} else if (tab === 'jobs' && !detail && entries?.[selected] && keys.matches(data, 'tui.select.confirm')) {
|
|
70
|
+
refreshOutput(entries[selected].id);
|
|
71
|
+
offset = 0;
|
|
72
|
+
} else {
|
|
73
|
+
const delta = keys.matches(data, 'tui.select.up') ? -1 : keys.matches(data, 'tui.select.down') ? 1 :
|
|
74
|
+
keys.matches(data, 'tui.select.pageUp') ? -page : keys.matches(data, 'tui.select.pageDown') ? page : 0;
|
|
75
|
+
if (!delta) return;
|
|
76
|
+
if (tab === 'jobs' && !detail && entries?.length) selected = Math.max(0, Math.min(selected + delta, entries.length - 1));
|
|
77
|
+
else offset += delta;
|
|
78
|
+
}
|
|
79
|
+
tui.requestRender();
|
|
80
|
+
},
|
|
81
|
+
invalidate() {},
|
|
82
|
+
};
|
|
83
|
+
});
|
|
84
|
+
}
|
package/src/tui/text.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
|
|
2
|
+
|
|
3
|
+
export const ASCII =
|
|
4
|
+
process.env.BI_ASCII === '1' ||
|
|
5
|
+
process.env.TERM === 'linux' ||
|
|
6
|
+
(process.platform === 'win32' && !process.env.WT_SESSION && !process.env.TERM_PROGRAM);
|
|
7
|
+
|
|
8
|
+
export const glyphs = ASCII
|
|
9
|
+
? {
|
|
10
|
+
pointer: '> ',
|
|
11
|
+
rule: '-',
|
|
12
|
+
side: '|',
|
|
13
|
+
tl: '+',
|
|
14
|
+
tr: '+',
|
|
15
|
+
bl: '+',
|
|
16
|
+
br: '+',
|
|
17
|
+
top: '+',
|
|
18
|
+
bottom: '+',
|
|
19
|
+
mark: '*',
|
|
20
|
+
sep: '|',
|
|
21
|
+
}
|
|
22
|
+
: {
|
|
23
|
+
pointer: '❯',
|
|
24
|
+
rule: '─',
|
|
25
|
+
side: '│',
|
|
26
|
+
tl: '╭',
|
|
27
|
+
tr: '╮',
|
|
28
|
+
bl: '╰',
|
|
29
|
+
br: '╯',
|
|
30
|
+
top: '┬',
|
|
31
|
+
bottom: '┴',
|
|
32
|
+
mark: '✦',
|
|
33
|
+
sep: '·',
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** Render untrusted metadata literally, including ANSI and direction-changing controls. */
|
|
37
|
+
export function literal(text: string, multiline = false): string {
|
|
38
|
+
return text.replace(/[\p{Cc}\u061c\u200e\u200f\u2028-\u202e\u2066-\u206f]/gu, (char) => {
|
|
39
|
+
if (char === '\n') return multiline ? char : '\\n';
|
|
40
|
+
if (char === '\r') return '\\r';
|
|
41
|
+
if (char === '\t') return '\\t';
|
|
42
|
+
return `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`;
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function pad(text: string, width: number, centered = false): string {
|
|
47
|
+
const clipped = truncateToWidth(text, width, ASCII ? '...' : '…');
|
|
48
|
+
const gap = Math.max(0, width - visibleWidth(clipped));
|
|
49
|
+
const left = centered ? Math.floor(gap / 2) : 0;
|
|
50
|
+
return ' '.repeat(left) + clipped + ' '.repeat(gap - left);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function fit(text: string, width: number): string {
|
|
54
|
+
return truncateToWidth(text, Math.max(0, width), ASCII ? '...' : '…');
|
|
55
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { ToolRenderers } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { Text } from '@earendil-works/pi-tui';
|
|
3
|
+
import { ASCII, literal } from './text.ts';
|
|
4
|
+
|
|
5
|
+
const labels = new Map([
|
|
6
|
+
['read', 'Read'], ['write', 'Write'], ['edit', 'Edit'], ['bash', 'Bash'], ['powershell', 'PowerShell'],
|
|
7
|
+
['grep', 'Search'], ['find', 'Find'], ['ls', 'List'], ['apply_patch', 'Patch'],
|
|
8
|
+
]);
|
|
9
|
+
|
|
10
|
+
export function toolPresentation(name: string): ToolRenderers {
|
|
11
|
+
const label = labels.get(name);
|
|
12
|
+
if (!label) return {};
|
|
13
|
+
const marker = ASCII ? '*' : '●';
|
|
14
|
+
const resultMarker = ASCII ? ' -> ' : ' ⎿ ';
|
|
15
|
+
return {
|
|
16
|
+
renderShell: 'self',
|
|
17
|
+
renderCall(args, theme, ctx) {
|
|
18
|
+
const { command, path, pattern, query, name } = (args ?? {}) as Record<string, unknown>;
|
|
19
|
+
const operand = command ?? pattern ?? query ?? path ?? name;
|
|
20
|
+
const location = typeof operand === 'string' && operand ? `(${literal(operand.slice(0, 150))}${operand.length > 150 ? '...' : ''})` : '';
|
|
21
|
+
return new Text(theme.fg(ctx.isError ? 'error' : 'accent', marker) + ' ' + theme.bold(label) + theme.fg('muted', location), 0, 0);
|
|
22
|
+
},
|
|
23
|
+
renderResult(result, { expanded, isPartial }, theme, ctx) {
|
|
24
|
+
if (isPartial) return new Text(theme.fg('dim', `${resultMarker}Running...`), 0, 0);
|
|
25
|
+
const output = result.content.flatMap(part => part.type === 'text' ? [part.text] : []).join('\n').trimEnd();
|
|
26
|
+
const lines = output ? output.split(/\r\n|\n|\r/) : [];
|
|
27
|
+
const hideRead = name === 'read' && !ctx.isError && !expanded && !result.content.some(part => part.type === 'image');
|
|
28
|
+
const limit = expanded ? lines.length : name === 'edit' || name === 'apply_patch' ? 7 : 3;
|
|
29
|
+
const first = output ? [] : [ctx.isError ? 'Failed' : 'Done'];
|
|
30
|
+
const shown = hideRead ? [`Read ${lines.length} line${lines.length === 1 ? '' : 's'} of output`] : [...first, ...lines.slice(0, limit)];
|
|
31
|
+
const remaining = hideRead ? lines.length : Math.max(0, lines.length - limit);
|
|
32
|
+
const hint = !expanded && remaining ? ctx.keyHint?.('app.tools.expand', 'to expand') : undefined;
|
|
33
|
+
if (remaining) shown.push(hideRead ? (hint ?? 'Output collapsed') : `${remaining} more lines${hint ? ` (${hint})` : ''}`);
|
|
34
|
+
const text = shown.map((line, i) => {
|
|
35
|
+
const diff = name === 'edit' || name === 'apply_patch';
|
|
36
|
+
const color = ctx.isError ? 'error' : diff && line.startsWith('+') ? 'toolDiffAdded' : diff && line.startsWith('-') ? 'toolDiffRemoved' : 'muted';
|
|
37
|
+
return theme.fg(color, (i === 0 ? resultMarker : ' ') + literal(line));
|
|
38
|
+
}).join('\n');
|
|
39
|
+
return new Text(text, 0, 0);
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|