@justjoshn/pi-snoop-tui 0.0.0-stage → 0.1.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## [0.1.1]
4
+
5
+ - Refactor TUI components, row layout, and tests to adhere verbatim to `AGENTS.md` (immutable patterns, closure state cells, `zod` input validation, named constants, and small functions) with no behavior changes.
6
+ - Port pure data and CLI benchmark scripts (`medium-fixture`, `mixed-fixture`, `mockup-fixture`, `report`, `summary`, `profile-summary`, and `capture`) to TypeScript under `AGENTS.md`.
7
+
8
+ ## [0.1.0]
9
+
10
+ - Add paired `snoop-dark` and `snoop-light` themes.
11
+ - Add compact rows for read, edit, write, bash, grep, find, and ls.
12
+ - Keep native tool detail rendering on expansion.
13
+ - Add compact rows for tools without renderers, with their arguments and plain output on expansion.
14
+ - Start every tool row's target in one column. Tool names longer than eight characters push only their own target.
15
+ - Add a single-line footer, workspace header, and static working indicator.
16
+ - List theme files without a glob, so loading the package skips Node's first `fs.globSync` call at startup.
17
+ - Cache rendered lines and tool summaries without extension-owned timers or render-time I/O.
18
+ - Pad and color expanded tool panels without a nested `Box`, and find blank edge lines without stripping every line, so Ctrl+O and typing with expanded rows do less work per row.
package/README.md CHANGED
@@ -1,3 +1,65 @@
1
- # Temporary Holding Version
1
+ # pi-snoop-tui
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A compact look for Pi's interactive terminal UI. Paired light and dark themes use graphite neutrals and a soft blue accent. The header, transcript, editor, and footer share one gutter on both sides, set by Pi's `outputPad` setting.
4
+
5
+ ![pi-snoop-tui in a Pi session](https://raw.githubusercontent.com/just-joshn/pi-customizations/main/extensions/pi-snoop-tui/docs/demo.gif)
6
+
7
+ Tool rows show a status marker, tool name, target, and result summary. Successful calls collapse to one line. Running bash calls show up to three output lines. Errors show up to five lines. Expand tools with your configured shortcut, normally Ctrl+O, to see Pi's native detail rendering.
8
+
9
+ The footer shows the workspace, branch, extension statuses, model, thinking level, and context usage on one line. The header shows `pi / workspace`.
10
+
11
+ The editor sits between two thin rules. The top rule ends with `ready`, or `● working` while the agent runs. Pi's retry, compaction, and branch summary messages appear in the same place. A `›` prompt marks the first line, and the text starts in the same column as tool names. User messages in the transcript get the same `›`, unless they start with Markdown block syntax. In bash mode the rules take the theme's bash color.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ pi install npm:@justjoshn/pi-snoop-tui
17
+ ```
18
+
19
+ Built and tested against Pi 1.5.2.
20
+
21
+ Add these recommended native settings to `~/.pi/agent/settings.json`:
22
+
23
+ ```json
24
+ {
25
+ "theme": "snoop-light/snoop-dark",
26
+ "quietStartup": true,
27
+ "hideThinkingBlock": true,
28
+ "outputPad": 1,
29
+ "collapseChangelog": true,
30
+ "autocompleteMaxVisible": 5
31
+ }
32
+ ```
33
+
34
+ The theme pair follows your terminal's light or dark appearance. Use `snoop-dark` or `snoop-light` to choose one explicitly. The package never writes your settings.
35
+
36
+ The editor layout replaces the `editorPaddingX` setting. If another extension already set a custom editor, this package leaves it in place and keeps its own header and footer. Pi assigns its callbacks, key handlers, and border color directly onto the editor instance, so a wrapper around another extension's editor cannot keep them in sync.
37
+
38
+ Run `pi config` to toggle `tool-rows.ts`, `footer.ts`, and `chrome.ts` independently. Chrome includes the header, the editor, the user prompt marker, and the working state. Tool rows also work with stock themes.
39
+
40
+ ## Native limits
41
+
42
+ Pi owns the blank line between tool rows. This package cannot remove it through the native renderer API.
43
+
44
+ Your terminal owns the canvas background. For dark mode, set it near `#14151a`. For light mode, use `okhsl(250 12% 97%)`.
45
+
46
+ Expanded content stays native, including syntax highlighting, diffs, and truncation notices. Read detail does not add line numbers. Edit previews appear after execution, not before it. Successful writes have no expanded source preview because Pi puts that content in its call renderer, which this package does not invoke. Other tools keep their own renderers. A tool with no renderer of its own, such as `codemode`, `pi_spawn`, or an MCP tool before its server connects, gets the same one-line row: its name, its main string argument, and the size of its output. Expanded, it shows the arguments as compact JSON and the full plain-text output.
47
+
48
+ The footer replaces Pi's token and cost totals. It preserves other extensions' status messages, then shrinks or drops lower-priority segments when space is limited.
49
+
50
+ ## Rendering work
51
+
52
+ The package starts no timers and performs no file or process operations. Collapsed rows memoize output summaries and only style bounded previews. Header and footer lines and the editor rules cache their rendered output. Context usage refreshes on lifecycle events, not on terminal frames.
53
+
54
+ A theme change clears component caches.
55
+
56
+ ## Develop
57
+
58
+ ```sh
59
+ bun install
60
+ bun run --filter @justjoshn/pi-snoop-tui typecheck
61
+ cd extensions/pi-snoop-tui
62
+ bunx vitest run --coverage
63
+ ```
64
+
65
+ Tests cover the shared gutter, editor rules and status labels at every width, the user prompt marker, Pi's call-before-result ordering, isolated native renderer state, cache invalidation, theme role parity, and terminal widths with CJK text and emoji.
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@justjoshn/pi-snoop-tui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "A calm, compact, fast look for Pi's interactive TUI: graphite themes, one-line tool rows, a single-row footer.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/just-joshn/pi-customizations.git",
13
+ "directory": "extensions/pi-snoop-tui"
14
+ },
15
+ "keywords": [
16
+ "pi-package"
17
+ ],
18
+ "engines": {
19
+ "node": ">=22.19.0"
20
+ },
21
+ "exports": {
22
+ "./package.json": "./package.json"
23
+ },
24
+ "pi": {
25
+ "extensions": [
26
+ "./src/tool-rows.ts",
27
+ "./src/footer.ts",
28
+ "./src/chrome.ts"
29
+ ],
30
+ "themes": [
31
+ "./themes/snoop-dark.json",
32
+ "./themes/snoop-light.json"
33
+ ]
34
+ },
35
+ "files": [
36
+ "src",
37
+ "themes",
38
+ "README.md",
39
+ "CHANGELOG.md"
40
+ ],
41
+ "scripts": {
42
+ "test": "vitest run",
43
+ "test:coverage": "vitest run --coverage",
44
+ "typecheck": "tsc -p ."
45
+ },
46
+ "peerDependencies": {
47
+ "@earendil-works/pi-coding-agent": "*",
48
+ "@earendil-works/pi-tui": "*"
49
+ },
50
+ "devDependencies": {
51
+ "@earendil-works/pi-ai": "1.5.2",
52
+ "@earendil-works/pi-coding-agent": "1.5.2",
53
+ "@earendil-works/pi-tui": "1.5.2",
54
+ "@types/node": "^22.19.0",
55
+ "@vitest/coverage-v8": "^5.0.2",
56
+ "typescript": "^7.0.2",
57
+ "vitest": "^5.0.2"
58
+ },
59
+ "dependencies": {
60
+ "zod": "^4"
61
+ }
62
+ }
package/src/cell.ts ADDED
@@ -0,0 +1,15 @@
1
+ /** A single replaceable value. Holds mutable state in a closure, so owners never assign to their own fields. */
2
+ export interface Cell<T> {
3
+ readonly read: () => T;
4
+ readonly write: (next: T) => void;
5
+ }
6
+
7
+ export function cell<T>(initial: T): Cell<T> {
8
+ let value = initial;
9
+ return {
10
+ read: () => value,
11
+ write: (next) => {
12
+ value = next;
13
+ },
14
+ };
15
+ }
package/src/chrome.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { basename } from 'node:path';
2
+
3
+ import type { ExtensionAPI, ExtensionUIContext, Theme } from '@earendil-works/pi-coding-agent';
4
+ import type { Component } from '@earendil-works/pi-tui';
5
+ import { cell } from './cell.ts';
6
+ import { createRuleEditor } from './editor.ts';
7
+ import { fitPlain, gutterAt, gutterOf, sanitizeLine } from './text.ts';
8
+
9
+ type EditorFactory = NonNullable<ReturnType<ExtensionUIContext['getEditorComponent']>>;
10
+ const HEADER_MIN_INNER = 5;
11
+ const MARKDOWN_START = /^(?: {4}|\t|\s*(?:[#>`~|*+-]|\d+[.)]))/;
12
+
13
+ export function markUserPrompt(markdown: string): string {
14
+ return !markdown.trim() || MARKDOWN_START.test(markdown) ? markdown : `› ${markdown}`;
15
+ }
16
+
17
+ export default function chrome(pi: ExtensionAPI): void {
18
+ let ownEditor: EditorFactory | undefined;
19
+ pi.registerMarkdownTransformer(markUserPrompt, { messageTypes: ['user'] });
20
+ pi.on('session_start', (_event, ctx) => {
21
+ if (!ctx.hasUI) return;
22
+ const gutter = gutterOf(pi);
23
+ ctx.ui.setHeader((_tui, theme) => headerLine(theme, basename(ctx.cwd) || ctx.cwd, gutter));
24
+ ctx.ui.setWorkingIndicator({ frames: [] });
25
+ ctx.ui.setWorkingMessage('working');
26
+ ctx.ui.setHiddenThinkingLabel('thinking');
27
+ // An editor from another extension wins: Pi assigns callbacks, handlers, and border color onto the instance, so it cannot be wrapped safely.
28
+ const previous = ctx.ui.getEditorComponent();
29
+ if (previous && previous !== ownEditor) return;
30
+ ownEditor = (tui, editorTheme, keybindings) => createRuleEditor(tui, editorTheme, keybindings, () => ctx.ui.theme, gutter);
31
+ ctx.ui.setEditorComponent(ownEditor);
32
+ });
33
+ }
34
+ export function headerLine(theme: Theme, workspace: string, gutter: number): Component {
35
+ const cache = cell<{ width: number; lines: string[] } | undefined>(undefined);
36
+ return {
37
+ render(width: number): string[] {
38
+ const cached = cache.read();
39
+ if (cached?.width === width) return cached.lines;
40
+ const g = gutterAt(gutter, width);
41
+ const inner = width - 2 * g;
42
+ const text = inner < HEADER_MIN_INNER ? theme.fg('accent', fitPlain('pi', inner)) : theme.fg('accent', 'pi') + theme.fg('dim', ' / ') + theme.fg('muted', fitPlain(sanitizeLine(workspace), inner - HEADER_MIN_INNER));
43
+ const lines = ['', ' '.repeat(g) + text, ''];
44
+ cache.write({ width, lines });
45
+ return lines;
46
+ },
47
+ invalidate(): void {
48
+ cache.write(undefined);
49
+ },
50
+ };
51
+ }
package/src/editor.ts ADDED
@@ -0,0 +1,120 @@
1
+ import { CustomEditor, type KeybindingsManager, type Theme } from '@earendil-works/pi-coding-agent';
2
+ import { type EditorTheme, type TUI, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
3
+ import { cell } from './cell.ts';
4
+ import { gutterAt } from './text.ts';
5
+
6
+ type Indicator = NonNullable<Parameters<CustomEditor['setWorkingStatusIndicator']>[0]>;
7
+ export type EditorStatus = { readonly kind: 'ready' } | { readonly kind: 'working' } | { readonly kind: 'pi'; readonly indicator: Indicator };
8
+ const READY: EditorStatus = { kind: 'ready' };
9
+ const WORKING: EditorStatus = { kind: 'working' };
10
+ export const PROMPT_INSET = 3;
11
+ const BORDER_LABEL_RESERVE = 5;
12
+
13
+ export function editorStatus(indicator: Indicator | undefined): EditorStatus {
14
+ if (!indicator) return READY;
15
+ return indicator.kind === 'working' ? WORKING : { kind: 'pi', indicator };
16
+ }
17
+
18
+ interface RuleCache {
19
+ readonly width: number;
20
+ readonly hidden: number;
21
+ readonly border: (text: string) => string;
22
+ readonly theme: Theme;
23
+ readonly status: EditorStatus | undefined;
24
+ readonly piLabel: string;
25
+ readonly line: string;
26
+ }
27
+
28
+ interface EditorConfig {
29
+ readonly theme: () => Theme;
30
+ readonly gutter: number;
31
+ }
32
+
33
+ abstract class RuleEditor extends CustomEditor {
34
+ protected abstract readonly config: EditorConfig;
35
+ private readonly snoopStatus = cell<EditorStatus>(READY);
36
+ private readonly topRule = cell<RuleCache | undefined>(undefined);
37
+ private readonly bottomRule = cell<RuleCache | undefined>(undefined);
38
+ private readonly prompt = cell<{ theme: Theme; text: string } | undefined>(undefined);
39
+ override setPaddingX(_padding: number): void {
40
+ super.setPaddingX(this.config.gutter + PROMPT_INSET);
41
+ }
42
+ override setWorkingStatusIndicator(indicator: Indicator | undefined): void {
43
+ this.snoopStatus.write(editorStatus(indicator));
44
+ super.setWorkingStatusIndicator(indicator);
45
+ }
46
+ protected override renderTopBorder(width: number, hidden: number): string {
47
+ const theme = this.config.theme();
48
+ const status = this.snoopStatus.read();
49
+ const piLabel = status.kind === 'pi' ? status.indicator.renderInBorder(Math.max(1, width - BORDER_LABEL_RESERVE)) : '';
50
+ const cached = this.topRule.read();
51
+ if (cached && cached.width === width && cached.hidden === hidden && cached.border === this.borderColor && cached.theme === theme && cached.status === status && cached.piLabel === piLabel) return cached.line;
52
+ const left = hidden > 0 ? `${theme.fg('dim', `↑ ${hidden}`)} ` : '';
53
+ const line = this.rule(width, left, ` ${statusLabel(status, theme, piLabel)}`);
54
+ this.topRule.write({ width, hidden, border: this.borderColor, theme, status, piLabel, line });
55
+ return line;
56
+ }
57
+ protected override renderBottomBorder(width: number, hidden: number): string {
58
+ const theme = this.config.theme();
59
+ const cached = this.bottomRule.read();
60
+ if (cached && cached.width === width && cached.hidden === hidden && cached.border === this.borderColor && cached.theme === theme) return cached.line;
61
+ const line = this.rule(width, '', hidden > 0 ? ` ${theme.fg('dim', `↓ ${hidden}`)}` : '');
62
+ this.bottomRule.write({ width, hidden, border: this.borderColor, theme, status: undefined, piLabel: '', line });
63
+ return line;
64
+ }
65
+ private rule(width: number, left: string, right: string): string {
66
+ const g = gutterAt(this.config.gutter, width);
67
+ const inner = width - 2 * g;
68
+ const labels = visibleWidth(left) + visibleWidth(right);
69
+ const [start, end, fill] = labels < inner ? [left, right, inner - labels] : ['', '', inner];
70
+ const line = ' '.repeat(g) + start + this.borderColor('─'.repeat(Math.max(0, fill))) + end + ' '.repeat(g);
71
+ return visibleWidth(line) <= width ? line : truncateToWidth(line, width, '');
72
+ }
73
+ override render(width: number): string[] {
74
+ const lines = super.render(width);
75
+ const inset = this.config.gutter + PROMPT_INSET;
76
+ const first = lines[1];
77
+ if (first === undefined || gutterAt(inset, width) < inset) return lines;
78
+ return lines.with(1, this.promptText(this.config.theme()) + first.slice(inset));
79
+ }
80
+ private promptText(theme: Theme): string {
81
+ const cached = this.prompt.read();
82
+ if (cached?.theme === theme) return cached.text;
83
+ const text = `${' '.repeat(this.config.gutter)}${theme.fg('accent', '›')}${' '.repeat(PROMPT_INSET - 1)}`;
84
+ this.prompt.write({ theme, text });
85
+ return text;
86
+ }
87
+ override invalidate(): void {
88
+ super.invalidate();
89
+ this.topRule.write(undefined);
90
+ this.bottomRule.write(undefined);
91
+ this.prompt.write(undefined);
92
+ }
93
+ }
94
+
95
+ /** Builds a RuleEditor bound to `theme` and `gutter`. The config rides in a subclass field so no instance field is assigned. */
96
+ export function createRuleEditor(tui: TUI, editorTheme: EditorTheme, keybindings: KeybindingsManager, theme: () => Theme, gutter: number): CustomEditor {
97
+ const config: EditorConfig = { theme, gutter };
98
+ class ConfiguredEditor extends RuleEditor {
99
+ protected override readonly config = config;
100
+ constructor() {
101
+ super(tui, editorTheme, keybindings, { embedWorkingStatus: true, paddingX: gutter + PROMPT_INSET });
102
+ }
103
+ }
104
+ return new ConfiguredEditor();
105
+ }
106
+
107
+ function statusLabel(status: EditorStatus, theme: Theme, piLabel: string): string {
108
+ switch (status.kind) {
109
+ case 'ready':
110
+ return theme.fg('muted', 'ready');
111
+ case 'working':
112
+ return `${theme.fg('accent', '●')} ${theme.fg('muted', 'working')}`;
113
+ case 'pi':
114
+ return piLabel;
115
+ default: {
116
+ const unreachable: never = status;
117
+ return unreachable;
118
+ }
119
+ }
120
+ }
package/src/footer.ts ADDED
@@ -0,0 +1,153 @@
1
+ import { basename } from 'node:path';
2
+
3
+ import type { ExtensionAPI, ExtensionContext, ReadonlyFooterDataProvider, Theme } from '@earendil-works/pi-coding-agent';
4
+ import { type Component, type TUI, visibleWidth } from '@earendil-works/pi-tui';
5
+ import { cell } from './cell.ts';
6
+ import { fitPlain, gutterAt, gutterOf, sanitizeLine } from './text.ts';
7
+
8
+ type ThinkingLevel = ReturnType<ExtensionAPI['getThinkingLevel']>;
9
+ export interface FooterSnapshot {
10
+ readonly workspace: string;
11
+ readonly model: string | undefined;
12
+ readonly thinking: ThinkingLevel | undefined;
13
+ readonly ctxPercent: number | null;
14
+ }
15
+ const CTX_ERROR_PERCENT = 90;
16
+ const CTX_WARNING_PERCENT = 70;
17
+ export const SEGMENT_ORDER = [
18
+ { id: 'workspace', side: 'left', priority: 0, minWidth: 6 },
19
+ { id: 'branch', side: 'left', priority: 4 },
20
+ { id: 'statuses', side: 'right', priority: 3, minWidth: 8 },
21
+ { id: 'model', side: 'right', priority: 2, minWidth: 8 },
22
+ { id: 'thinking', side: 'right', priority: 5 },
23
+ { id: 'ctx', side: 'right', priority: 1 },
24
+ ] as const;
25
+ export type SegmentId = (typeof SEGMENT_ORDER)[number]['id'];
26
+ export interface Segment {
27
+ readonly id: SegmentId;
28
+ readonly side: 'left' | 'right';
29
+ readonly priority: number;
30
+ readonly text: string;
31
+ readonly minWidth?: number;
32
+ }
33
+ export default function footer(pi: ExtensionAPI): void {
34
+ let snapshot: FooterSnapshot | undefined;
35
+ let mounted: TUI | undefined;
36
+ const refresh = (ctx: ExtensionContext): void => {
37
+ const next = readSnapshot(ctx, pi.getThinkingLevel());
38
+ if (snapshot && sameSnapshot(snapshot, next)) return;
39
+ snapshot = Object.freeze(next);
40
+ mounted?.requestRender();
41
+ };
42
+ pi.on('session_start', (_event, ctx) => {
43
+ if (!ctx.hasUI) return;
44
+ refresh(ctx);
45
+ const gutter = gutterOf(pi);
46
+ ctx.ui.setFooter((tui, theme, data) => {
47
+ mounted = tui;
48
+ const release = (): void => {
49
+ if (mounted === tui) mounted = undefined;
50
+ };
51
+ return snoopFooter(theme, data, () => snapshot, release, gutter);
52
+ });
53
+ });
54
+ const onChange = (_event: unknown, ctx: ExtensionContext): void => {
55
+ if (ctx.hasUI) refresh(ctx);
56
+ };
57
+ pi.on('model_select', onChange);
58
+ pi.on('thinking_level_select', onChange);
59
+ pi.on('turn_end', onChange);
60
+ pi.on('agent_end', onChange);
61
+ pi.on('session_compact', onChange);
62
+ pi.on('session_tree', onChange);
63
+ }
64
+ export function readSnapshot(ctx: Pick<ExtensionContext, 'cwd' | 'model' | 'getContextUsage'>, thinking: ThinkingLevel): FooterSnapshot {
65
+ return { workspace: basename(ctx.cwd) || ctx.cwd, model: ctx.model?.id, thinking: ctx.model?.reasoning ? thinking : undefined, ctxPercent: ctx.getContextUsage()?.percent ?? null };
66
+ }
67
+ export function sameSnapshot(a: FooterSnapshot, b: FooterSnapshot): boolean {
68
+ return a.workspace === b.workspace && a.model === b.model && a.thinking === b.thinking && a.ctxPercent === b.ctxPercent;
69
+ }
70
+ function joinSide(segments: readonly Segment[], side: Segment['side'], render: (segment: Segment) => string, separator: (text: string) => string = (text) => text): string {
71
+ return segments
72
+ .filter((segment) => segment.side === side)
73
+ .map((segment, index) => (index ? separator(segment.id === 'ctx' ? ' ' : ' · ') : '') + render(segment))
74
+ .join('');
75
+ }
76
+ function rowWidth(segments: readonly Segment[]): number {
77
+ const left = joinSide(segments, 'left', (s) => s.text);
78
+ const right = joinSide(segments, 'right', (s) => s.text);
79
+ return visibleWidth(left) + visibleWidth(right) + (left && right ? 2 : 0);
80
+ }
81
+ function shrinkOnce(fitted: readonly Segment[], target: number): readonly Segment[] {
82
+ const lowest = fitted.reduce((a, b) => (a.priority > b.priority || (a.priority === b.priority && a.side === 'right') ? a : b));
83
+ const size = visibleWidth(lowest.text);
84
+ const min = lowest.priority === 0 ? 0 : lowest.minWidth;
85
+ if (min === undefined || size <= min) return fitted.filter((s) => s !== lowest);
86
+ const text = fitPlain(lowest.text, Math.max(min, size - (rowWidth(fitted) - target)));
87
+ return fitted.map((s) => (s === lowest ? { ...s, text } : s));
88
+ }
89
+ export function fitSegments(segments: readonly Segment[], width: number): readonly Segment[] {
90
+ const target = Math.max(0, width);
91
+ let fitted: readonly Segment[] = segments.filter((s) => s.text).map((s) => ({ ...s, text: sanitizeLine(s.text) }));
92
+ while (rowWidth(fitted) > target) fitted = shrinkOnce(fitted, target);
93
+ return fitted;
94
+ }
95
+ export function statusText(statuses: ReadonlyMap<string, string>): string {
96
+ return [...statuses.entries()]
97
+ .toSorted(([a], [b]) => a.localeCompare(b))
98
+ .map(([, text]) => sanitizeLine(text).trim())
99
+ .filter(Boolean)
100
+ .join(' · ');
101
+ }
102
+ function ctxColor(percent: number | null | undefined): 'dim' | 'error' | 'warning' | 'accent' {
103
+ if (percent == null) return 'dim';
104
+ if (percent > CTX_ERROR_PERCENT) return 'error';
105
+ return percent > CTX_WARNING_PERCENT ? 'warning' : 'accent';
106
+ }
107
+ function segmentTexts(snapshot: FooterSnapshot | undefined, branch: string | null, statuses: string): Record<SegmentId, string> {
108
+ return {
109
+ workspace: snapshot?.workspace ?? '',
110
+ branch: branch ?? '',
111
+ statuses,
112
+ model: snapshot?.model ?? '',
113
+ thinking: snapshot?.thinking ?? '',
114
+ ctx: snapshot?.ctxPercent == null ? 'ctx ?' : `ctx ${Math.round(snapshot.ctxPercent)}%`,
115
+ };
116
+ }
117
+ function footerLine(theme: Theme, snapshot: FooterSnapshot | undefined, branch: string | null, statuses: string, width: number, gutter: number): string {
118
+ const texts = segmentTexts(snapshot, branch, statuses);
119
+ const g = gutterAt(gutter, width);
120
+ const inner = width - 2 * g;
121
+ const fitted = fitSegments(
122
+ SEGMENT_ORDER.map((s) => ({ ...s, text: texts[s.id] })),
123
+ inner,
124
+ );
125
+ const style = (s: Segment): string => theme.fg(s.id === 'workspace' ? 'text' : s.id !== 'ctx' ? 'muted' : ctxColor(snapshot?.ctxPercent), s.text);
126
+ const separator = (text: string): string => theme.fg('dim', text);
127
+ const left = joinSide(fitted, 'left', style, separator);
128
+ const right = joinSide(fitted, 'right', style, separator);
129
+ const gap = left && right ? Math.max(2, inner - visibleWidth(left) - visibleWidth(right)) : 0;
130
+ return ' '.repeat(g) + left + ' '.repeat(gap) + right;
131
+ }
132
+ export function snoopFooter(theme: Theme, data: ReadonlyFooterDataProvider, read: () => FooterSnapshot | undefined, onDispose: () => void, gutter: number): Component & { dispose(): void } {
133
+ const cache = cell<{ width: number; snapshot: FooterSnapshot | undefined; branch: string | null; statuses: string; line: string } | undefined>(undefined);
134
+ return {
135
+ render(width: number): string[] {
136
+ const snapshot = read();
137
+ const branch = data.getGitBranch();
138
+ const statuses = statusText(data.getExtensionStatuses());
139
+ const cached = cache.read();
140
+ if (cached?.width === width && cached.snapshot === snapshot && cached.branch === branch && cached.statuses === statuses) return [cached.line];
141
+ const line = footerLine(theme, snapshot, branch, statuses, width, gutter);
142
+ cache.write({ width, snapshot, branch, statuses, line });
143
+ return [line];
144
+ },
145
+ invalidate(): void {
146
+ cache.write(undefined);
147
+ },
148
+ dispose(): void {
149
+ cache.write(undefined);
150
+ onDispose();
151
+ },
152
+ };
153
+ }
@@ -0,0 +1,84 @@
1
+ import type { Theme } from '@earendil-works/pi-coding-agent';
2
+ import { type Component, truncateToWidth } from '@earendil-works/pi-tui';
3
+ import { cell } from '../cell.ts';
4
+ import { fitPlain, sanitizeLine } from '../text.ts';
5
+ import type { Preview } from './specs.ts';
6
+ import { layoutHeader, ROW_INSET, type RowView } from './view.ts';
7
+
8
+ interface LinesCache {
9
+ readonly width: number;
10
+ readonly view: RowView;
11
+ readonly lines: string[];
12
+ }
13
+ const MARKERS = {
14
+ pending: ['dim', '·'],
15
+ running: ['accent', '•'],
16
+ done: ['success', '✓'],
17
+ failed: ['error', '✗'],
18
+ } as const;
19
+
20
+ export function createRowHeader(view: () => RowView, theme: Theme): Component {
21
+ const cache = cell<LinesCache | undefined>(undefined);
22
+ return {
23
+ render(width) {
24
+ const current = view();
25
+ const cached = cache.read();
26
+ if (cached?.width === width && cached.view === current) return cached.lines;
27
+ const pad = Math.min(current.pad, Math.max(0, width - 1));
28
+ const layout = layoutHeader(current, width - 2 * pad);
29
+ const [color, marker] = MARKERS[current.phase];
30
+ const line =
31
+ ' '.repeat(pad) +
32
+ theme.fg(color, marker) +
33
+ ' ' +
34
+ theme.fg(current.phase === 'pending' ? 'dim' : 'toolTitle', layout.verb) +
35
+ theme.fg(current.phase === 'pending' ? 'dim' : 'text', layout.target) +
36
+ ' '.repeat(layout.gap) +
37
+ theme.fg('dim', layout.meta);
38
+ const lines = [width < pad + ROW_INSET ? truncateToWidth(line, width, '') : line];
39
+ cache.write({ width, view: current, lines });
40
+ return lines;
41
+ },
42
+ invalidate() {
43
+ cache.write(undefined);
44
+ },
45
+ };
46
+ }
47
+
48
+ function previewLines(theme: Theme, preview: Preview, hint: string | undefined, indent: number, width: number): string[] {
49
+ const line = (text: string, tone: 'error' | 'toolOutput' | 'dim'): string => ' '.repeat(indent) + theme.fg(tone, fitPlain(sanitizeLine(text), width - indent));
50
+ const lines = preview.lines.map((text) => line(text, preview.tone === 'error' ? 'error' : 'toolOutput'));
51
+ if (!hint) return lines;
52
+ switch (preview.from) {
53
+ case 'head':
54
+ return [...lines, line(`… ${preview.hidden} more · ${hint}`, 'dim')];
55
+ case 'tail':
56
+ return [line(`… ${preview.hidden} earlier · ${hint}`, 'dim'), ...lines];
57
+ default: {
58
+ const unreachable: never = preview.from;
59
+ return unreachable;
60
+ }
61
+ }
62
+ }
63
+
64
+ export function createRowBody(view: () => RowView, theme: Theme, invalidatePanel: () => void): Component {
65
+ const cache = cell<LinesCache | undefined>(undefined);
66
+ return {
67
+ render(width) {
68
+ const current = view();
69
+ const body = current.body;
70
+ if (body.kind === 'none') return [];
71
+ if (body.kind === 'panel') return body.panel.render(width);
72
+ const cached = cache.read();
73
+ if (cached?.width === width && cached.view === current) return cached.lines;
74
+ const indent = Math.min(current.pad + ROW_INSET, Math.max(0, width - 1));
75
+ const lines = previewLines(theme, body.preview, body.hint, indent, width);
76
+ cache.write({ width, view: current, lines });
77
+ return lines;
78
+ },
79
+ invalidate() {
80
+ cache.write(undefined);
81
+ invalidatePanel();
82
+ },
83
+ };
84
+ }
@@ -0,0 +1,80 @@
1
+ import type { Theme } from '@earendil-works/pi-coding-agent';
2
+ import { type Component, stripTerminalSequences, Text, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
3
+ import { cell } from '../cell.ts';
4
+ import { ROW_INSET, type Tone } from './view.ts';
5
+
6
+ export interface Panel extends Component {
7
+ showChild(child: Component, tone: Tone): void;
8
+ showText(text: string, tone: Tone): void;
9
+ }
10
+ interface PanelContent {
11
+ readonly child: Component;
12
+ readonly frame: ((text: string) => string) | undefined;
13
+ }
14
+ interface PanelCache {
15
+ readonly width: number;
16
+ readonly source: readonly string[];
17
+ readonly lines: string[];
18
+ }
19
+ const SGR_PARAMS = /^[\d;]*$/;
20
+ const MIN_FRAMED_WIDTH = 3;
21
+
22
+ function sameLines(a: readonly string[], b: readonly string[]): boolean {
23
+ return a === b || (a.length === b.length && a.every((line, i) => line === b[i]));
24
+ }
25
+ // Skips color codes in place. `stripTerminalSequences` copies every line, so it only settles other escapes.
26
+ function isBlank(line: string | undefined): boolean {
27
+ const text = line ?? '';
28
+ for (let i = 0; i < text.length; i++) {
29
+ if (text[i] === '\x1b') {
30
+ const end = text.indexOf('m', i);
31
+ if (text[i + 1] !== '[' || end === -1 || !SGR_PARAMS.test(text.slice(i + 2, end))) return stripTerminalSequences(text).trim() === '';
32
+ i = end;
33
+ } else if (text[i]?.trim()) {
34
+ return false;
35
+ }
36
+ }
37
+ return true;
38
+ }
39
+ function trimBlankEdges(source: readonly string[]): readonly string[] {
40
+ let start = 0;
41
+ let end = source.length;
42
+ while (start < end && isBlank(source[start])) start++;
43
+ while (end > start && isBlank(source[end - 1])) end--;
44
+ return source.slice(start, end);
45
+ }
46
+
47
+ export function createPanel(theme: Theme, pad: () => number): Panel {
48
+ const backgrounds: Record<Tone, (text: string) => string> = { ok: (text) => theme.bg('toolPendingBg', text), error: (text) => theme.bg('toolErrorBg', text) };
49
+ const content = cell<PanelContent>({ child: new Text('', 0, 0), frame: undefined });
50
+ const cache = cell<PanelCache | undefined>(undefined);
51
+ return {
52
+ showChild(child, tone) {
53
+ if (content.read().frame !== backgrounds[tone]) cache.write(undefined);
54
+ content.write({ child, frame: backgrounds[tone] });
55
+ },
56
+ showText(text, tone) {
57
+ content.write({ child: new Text(text, 1, 0, backgrounds[tone]), frame: undefined });
58
+ cache.write(undefined);
59
+ },
60
+ render(width) {
61
+ const { child, frame } = content.read();
62
+ const indent = Math.min(pad() + ROW_INSET, Math.max(0, width - 1));
63
+ const boxWidth = Math.max(1, width - indent - pad());
64
+ const source = child.render(frame ? Math.max(1, boxWidth - 2) : boxWidth);
65
+ const cached = cache.read();
66
+ if (cached?.width === width && sameLines(cached.source, source)) return cached.lines;
67
+ const prefix = ' '.repeat(indent);
68
+ const lines = trimBlankEdges(source).map((line) => {
69
+ const framed = frame ? frame(` ${line}${' '.repeat(Math.max(0, boxWidth - 1 - visibleWidth(line)))}`) : line;
70
+ return boxWidth < MIN_FRAMED_WIDTH ? truncateToWidth(prefix + framed, width, '') : prefix + framed;
71
+ });
72
+ cache.write({ width, source, lines });
73
+ return lines;
74
+ },
75
+ invalidate() {
76
+ cache.write(undefined);
77
+ content.read().child.invalidate();
78
+ },
79
+ };
80
+ }
@@ -0,0 +1,123 @@
1
+ import type { AgentToolResult, Theme, ToolRenderers, ToolRenderResultOptions } from '@earendil-works/pi-coding-agent';
2
+ import type { Component } from '@earendil-works/pi-tui';
3
+ import { type Cell, cell } from '../cell.ts';
4
+ import { sanitizeLine } from '../text.ts';
5
+ import { createRowBody, createRowHeader } from './components.ts';
6
+ import { createPanel, type Panel } from './panel.ts';
7
+ import type { ResultSummary, ToolSpec } from './specs.ts';
8
+ import { type BodyView, derivePhase, type RowView, sameBody, type ToolRenderContext } from './view.ts';
9
+
10
+ const ROW_STATE = Symbol('snoop.rowState');
11
+ interface SummaryMemo {
12
+ readonly content: AgentToolResult<unknown>['content'];
13
+ readonly details: unknown;
14
+ readonly args: unknown;
15
+ readonly isPartial: boolean;
16
+ readonly isError: boolean;
17
+ readonly value: ResultSummary;
18
+ }
19
+ interface RowState {
20
+ readonly [ROW_STATE]: true;
21
+ readonly view: Cell<RowView>;
22
+ readonly summary: Cell<SummaryMemo | undefined>;
23
+ readonly native: Record<string, unknown>;
24
+ readonly nativeResult: Cell<Component | undefined>;
25
+ readonly panel: Cell<Panel | undefined>;
26
+ readonly header: Component;
27
+ readonly body: Component;
28
+ }
29
+
30
+ function parseArgs(args: unknown): Record<string, unknown> {
31
+ return args !== null && typeof args === 'object' ? (args as Record<string, unknown>) : {};
32
+ }
33
+ function createRowState(spec: ToolSpec, theme: Theme, ctx: ToolRenderContext): RowState {
34
+ const view = cell(Object.freeze<RowView>({ phase: derivePhase(ctx), verb: spec.verb, target: spec.target(parseArgs(ctx.args), ctx.cwd), meta: undefined, body: { kind: 'none' }, pad: ctx.outputPad }));
35
+ const panel = cell<Panel | undefined>(undefined);
36
+ return {
37
+ [ROW_STATE]: true,
38
+ view,
39
+ summary: cell<SummaryMemo | undefined>(undefined),
40
+ native: {},
41
+ nativeResult: cell<Component | undefined>(undefined),
42
+ panel,
43
+ header: createRowHeader(view.read, theme),
44
+ body: createRowBody(view.read, theme, () => panel.read()?.invalidate()),
45
+ };
46
+ }
47
+ function isRowState(value: unknown): value is RowState {
48
+ return typeof value === 'object' && value !== null && ROW_STATE in value;
49
+ }
50
+ function rowState(ctx: ToolRenderContext, spec: ToolSpec, theme: Theme): RowState {
51
+ const existing = ctx.state.snoop;
52
+ if (isRowState(existing)) return existing;
53
+ const created = createRowState(spec, theme, ctx);
54
+ ctx.state.snoop = created;
55
+ return created;
56
+ }
57
+
58
+ function expandedBody(state: RowState, native: ToolRenderers, result: AgentToolResult<unknown>, options: ToolRenderResultOptions, theme: Theme, ctx: ToolRenderContext): BodyView {
59
+ const tone = ctx.isError ? 'error' : 'ok';
60
+ const panel = state.panel.read() ?? createPanel(theme, () => state.view.read().pad);
61
+ state.panel.write(panel);
62
+ if (native.renderResult) {
63
+ // Native call renderers start timers and edit previews. Only delegate result detail.
64
+ const nativeResult = native.renderResult(result, options, theme, { ...ctx, state: state.native, lastComponent: state.nativeResult.read(), outputPad: 0 });
65
+ state.nativeResult.write(nativeResult);
66
+ panel.showChild(nativeResult, tone);
67
+ } else {
68
+ panel.showText(plainDetail(theme, ctx.args, result), tone);
69
+ }
70
+ return { kind: 'panel', panel, tone };
71
+ }
72
+ function resultBody(state: RowState, native: ToolRenderers, summary: ResultSummary, result: AgentToolResult<unknown>, options: ToolRenderResultOptions, theme: Theme, ctx: ToolRenderContext): BodyView {
73
+ if (options.expanded) return expandedBody(state, native, result, options, theme, ctx);
74
+ if (!summary.preview) return { kind: 'none' };
75
+ return { kind: 'preview', preview: summary.preview, hint: summary.preview.hidden > 0 ? ctx.keyText('app.tools.expand') : undefined };
76
+ }
77
+
78
+ export function compactRenderers(spec: ToolSpec, native: ToolRenderers): ToolRenderers {
79
+ return {
80
+ renderShell: 'self',
81
+ renderCall(args, theme, ctx) {
82
+ const state = rowState(ctx, spec, theme);
83
+ commit(state, { ...state.view.read(), phase: derivePhase(ctx), target: spec.target(parseArgs(args), ctx.cwd), pad: ctx.outputPad });
84
+ return state.header;
85
+ },
86
+ renderResult(result, options, theme, ctx) {
87
+ const state = rowState(ctx, spec, theme);
88
+ const summary = summarizeOnce(state, spec, result, options, ctx);
89
+ const body = resultBody(state, native, summary, result, options, theme, ctx);
90
+ commit(state, { ...state.view.read(), phase: derivePhase(ctx), meta: summary.meta, body });
91
+ return state.body;
92
+ },
93
+ };
94
+ }
95
+ function plainDetail(theme: Theme, args: unknown, result: AgentToolResult<unknown>): string {
96
+ const output = result.content
97
+ .filter((c) => c.type === 'text')
98
+ .map((c) => c.text)
99
+ .join('\n')
100
+ .split('\n')
101
+ .map(sanitizeLine)
102
+ .join('\n');
103
+ const json = sanitizeLine(JSON.stringify(args) ?? '');
104
+ return [json && theme.fg('dim', json), output && theme.fg('toolOutput', output)].filter(Boolean).join('\n\n');
105
+ }
106
+ function commit(state: RowState, next: RowView): void {
107
+ const prev = state.view.read();
108
+ if (prev.phase === next.phase && prev.verb === next.verb && prev.pad === next.pad && prev.target.text === next.target.text && prev.target.kind === next.target.kind && prev.meta === next.meta && sameBody(prev.body, next.body)) return;
109
+ if (prev.pad !== next.pad) state.panel.read()?.invalidate();
110
+ state.view.write(Object.freeze(next));
111
+ }
112
+ function summarizeOnce(state: RowState, spec: ToolSpec, result: AgentToolResult<unknown>, options: ToolRenderResultOptions, ctx: ToolRenderContext): ResultSummary {
113
+ const memo = state.summary.read();
114
+ if (memo && memo.content === result.content && memo.details === result.details && memo.args === ctx.args && memo.isPartial === options.isPartial && memo.isError === ctx.isError) return memo.value;
115
+ const text = result.content
116
+ .filter((c) => c.type === 'text')
117
+ .map((c) => c.text)
118
+ .join('\n');
119
+ const images = result.content.filter((c) => c.type === 'image').length;
120
+ const value = spec.summarize({ args: parseArgs(ctx.args), text, images, details: result.details, isError: ctx.isError, isPartial: options.isPartial });
121
+ state.summary.write({ content: result.content, details: result.details, args: ctx.args, isPartial: options.isPartial, isError: ctx.isError, value });
122
+ return value;
123
+ }
@@ -0,0 +1,188 @@
1
+ import { formatReadLineRange } from '@earendil-works/pi-coding-agent';
2
+ import { z } from 'zod';
3
+ import { countLines, headLines, type LineSlice, tailLines } from '../text.ts';
4
+
5
+ export interface Preview extends LineSlice {
6
+ readonly tone: 'output' | 'error';
7
+ readonly from: 'head' | 'tail';
8
+ }
9
+ export interface ResultSummary {
10
+ readonly meta: string | undefined;
11
+ readonly preview: Preview | undefined;
12
+ }
13
+ export interface ToolArgs {
14
+ [key: string]: unknown;
15
+ path?: unknown;
16
+ offset?: unknown;
17
+ limit?: unknown;
18
+ pattern?: unknown;
19
+ command?: unknown;
20
+ content?: unknown;
21
+ }
22
+ export interface ResultInput {
23
+ readonly args: ToolArgs;
24
+ readonly text: string;
25
+ readonly images: number;
26
+ readonly details: unknown;
27
+ readonly isError: boolean;
28
+ readonly isPartial: boolean;
29
+ }
30
+ export interface TargetText {
31
+ readonly text: string;
32
+ readonly kind: 'path' | 'plain';
33
+ }
34
+ export interface ToolSpec {
35
+ readonly verb: string;
36
+ target(args: ToolArgs | undefined, cwd: string): TargetText;
37
+ summarize(input: ResultInput): ResultSummary;
38
+ }
39
+ export const RUNNING_TAIL_LINES = 3;
40
+ export const ERROR_PREVIEW_LINES = 5;
41
+ const HomeEnv = z.object({ HOME: z.string().optional(), USERPROFILE: z.string().optional() });
42
+ const homeEnv = HomeEnv.parse(process.env);
43
+ const HOME = homeEnv.HOME ?? homeEnv.USERPROFILE;
44
+ const STATUS_TAIL_CHARS = 200;
45
+
46
+ function str(value: unknown): string {
47
+ return typeof value === 'string' ? value : '';
48
+ }
49
+ function field(value: unknown, key: string): unknown {
50
+ return value && typeof value === 'object' && key in value ? Reflect.get(value, key) : undefined;
51
+ }
52
+ function relPath(value: unknown, cwd: string): string {
53
+ const path = str(value);
54
+ if (path.startsWith(`${cwd}/`)) return path.slice(cwd.length + 1);
55
+ if (HOME && (path === HOME || path.startsWith(`${HOME}/`))) return `~${path.slice(HOME.length)}`;
56
+ return path;
57
+ }
58
+ function pathTarget(args: ToolArgs | undefined, cwd: string): TargetText {
59
+ return { kind: 'path', text: relPath(args?.path, cwd) };
60
+ }
61
+ function firstLine(text: string): string {
62
+ const end = text.indexOf('\n');
63
+ return (end === -1 ? text : text.slice(0, end)).replace(/\s+/g, ' ') + (end === -1 ? '' : '…');
64
+ }
65
+ function summary(meta: string): ResultSummary {
66
+ return { meta, preview: undefined };
67
+ }
68
+ function failed(input: ResultInput, meta = 'failed'): ResultSummary {
69
+ return { meta, preview: { ...headLines(input.text, ERROR_PREVIEW_LINES), tone: 'error', from: 'head' } };
70
+ }
71
+ function checked(input: ResultInput, ok: () => ResultSummary): ResultSummary {
72
+ return input.isError ? failed(input) : ok();
73
+ }
74
+ function withoutNotice(text: string): string {
75
+ const start = text.lastIndexOf('\n\n[');
76
+ return start === -1 ? text : text.slice(0, start);
77
+ }
78
+ function units(count: number, unit: 'line' | 'match' | 'file' | 'entry', limited = false): string {
79
+ const plurals = { line: 'lines', match: 'matches', file: 'files', entry: 'entries' };
80
+ return `${count}${limited ? '+' : ''} ${count === 1 ? unit : plurals[unit]}`;
81
+ }
82
+ function countPatchLines(patch: string): { added: number; removed: number } {
83
+ let added = 0;
84
+ let removed = 0;
85
+ for (let start = 0; start < patch.length; ) {
86
+ if (patch[start] === '+' && !patch.startsWith('+++', start)) added++;
87
+ if (patch[start] === '-' && !patch.startsWith('---', start)) removed++;
88
+ const end = patch.indexOf('\n', start);
89
+ start = end === -1 ? patch.length : end + 1;
90
+ }
91
+ return { added, removed };
92
+ }
93
+ function listing(input: ResultInput, unit: 'match' | 'file' | 'entry', limit: string, empty: string): ResultSummary {
94
+ return checked(input, () => {
95
+ const total = field(field(input.details, 'truncation'), 'totalLines');
96
+ const count = input.text.startsWith(empty) ? 0 : typeof total === 'number' ? total : countLines(withoutNotice(input.text));
97
+ return summary(units(count, unit, Boolean(field(input.details, limit))));
98
+ });
99
+ }
100
+
101
+ export const TOOL_SPECS = {
102
+ read: {
103
+ verb: 'read',
104
+ target: (args, cwd) => ({
105
+ kind: 'path',
106
+ text: relPath(args?.path, cwd) + formatReadLineRange(typeof args?.offset === 'number' ? args.offset : undefined, typeof args?.limit === 'number' ? args.limit : undefined),
107
+ }),
108
+ summarize: (input) =>
109
+ checked(input, () => {
110
+ if (input.images > 0) return summary('image');
111
+ const total = field(field(input.details, 'truncation'), 'totalLines');
112
+ return summary(units(typeof total === 'number' ? total : countLines(withoutNotice(input.text)), 'line'));
113
+ }),
114
+ },
115
+ edit: {
116
+ verb: 'edit',
117
+ target: pathTarget,
118
+ summarize: (input) =>
119
+ checked(input, () => {
120
+ const patch = str(field(input.details, 'patch'));
121
+ const { added, removed } = countPatchLines(patch);
122
+ return patch ? summary(`+${added} −${removed}`) : summary('edited');
123
+ }),
124
+ },
125
+ write: {
126
+ verb: 'write',
127
+ target: pathTarget,
128
+ summarize: (input) => checked(input, () => summary(units(countLines(str(input.args.content)), 'line'))),
129
+ },
130
+ bash: {
131
+ verb: 'bash',
132
+ target: (args) => ({ kind: 'plain', text: firstLine(str(args?.command)) }),
133
+ summarize: (input) => {
134
+ if (input.isPartial) return { meta: undefined, preview: { ...tailLines(input.text, RUNNING_TAIL_LINES), tone: 'output', from: 'tail' } };
135
+ if (!input.isError) return summary('exit 0');
136
+ const rawTail = input.text.slice(-STATUS_TAIL_CHARS);
137
+ const tail = rawTail.trimEnd();
138
+ const exit = /Command exited with code (\d+)$/.exec(tail);
139
+ const meta = exit ? `exit ${exit[1]}` : /Command timed out/.test(tail) ? 'timeout' : /Command aborted$/.test(tail) ? 'aborted' : 'failed';
140
+ const status = /Command (?:exited with code \d+|timed out[^\n]*|aborted)$/.exec(tail);
141
+ const text = status ? input.text.slice(0, input.text.length - rawTail.length + status.index).trimEnd() : input.text;
142
+ return { meta, preview: { ...tailLines(text, ERROR_PREVIEW_LINES), tone: 'error', from: 'tail' } };
143
+ },
144
+ },
145
+ grep: {
146
+ verb: 'grep',
147
+ target: (args) => ({ kind: 'plain', text: str(args?.pattern) + (typeof args?.path === 'string' ? ` ${args.path}` : '') }),
148
+ summarize: (input) => (input.text === 'No matches found' && !input.isError ? summary('no matches') : listing(input, 'match', 'matchLimitReached', 'No matches found')),
149
+ },
150
+ find: {
151
+ verb: 'find',
152
+ target: (args) => ({ kind: 'plain', text: str(args?.pattern) }),
153
+ summarize: (input) => listing(input, 'file', 'resultLimitReached', 'No files found'),
154
+ },
155
+ ls: {
156
+ verb: 'ls',
157
+ target: (args, cwd) => pathTarget({ path: args?.path ?? '.' }, cwd),
158
+ summarize: (input) => listing(input, 'entry', 'entryLimitReached', '(empty directory)'),
159
+ },
160
+ } satisfies Record<string, ToolSpec>;
161
+
162
+ export type CompactToolName = keyof typeof TOOL_SPECS;
163
+ export const VERB_COLUMN = 8;
164
+ export function isCompactTool(name: string): name is CompactToolName {
165
+ return Object.hasOwn(TOOL_SPECS, name);
166
+ }
167
+
168
+ const TARGET_KEYS = ['command', 'path', 'code', 'brief', 'name', 'query', 'url'];
169
+
170
+ export function genericSpec(toolName: string): ToolSpec {
171
+ return {
172
+ verb: toolName,
173
+ target: (args, cwd) => {
174
+ const fields = args ?? {};
175
+ const key = TARGET_KEYS.find((name) => typeof fields[name] === 'string') ?? Object.keys(fields).find((name) => typeof fields[name] === 'string');
176
+ const value = key === undefined ? '' : str(fields[key]);
177
+ return key === 'path' ? { kind: 'path', text: relPath(value, cwd) } : { kind: 'plain', text: firstLine(value) };
178
+ },
179
+ summarize: (input) => {
180
+ if (input.isPartial) return { meta: undefined, preview: undefined };
181
+ if (input.isError) {
182
+ const exit = /exit(?:ed with)? code (\d+)\s*$/i.exec(input.text.slice(-STATUS_TAIL_CHARS));
183
+ return failed(input, exit ? `exit ${exit[1]}` : 'failed');
184
+ }
185
+ return summary(input.images > 0 ? 'image' : units(countLines(input.text), 'line'));
186
+ },
187
+ };
188
+ }
@@ -0,0 +1,47 @@
1
+ import type { ToolRenderers } from '@earendil-works/pi-coding-agent';
2
+ import type { Component } from '@earendil-works/pi-tui';
3
+ import { visibleWidth } from '@earendil-works/pi-tui';
4
+ import { fitPath, fitPlain, sanitizeLine } from '../text.ts';
5
+ import { type Preview, type TargetText, VERB_COLUMN } from './specs.ts';
6
+
7
+ export type ToolRenderContext = Parameters<NonNullable<ToolRenderers['renderCall']>>[2];
8
+ export type RowPhase = 'pending' | 'running' | 'done' | 'failed';
9
+ export type Tone = 'ok' | 'error';
10
+ export type BodyView = { readonly kind: 'none' } | { readonly kind: 'preview'; readonly preview: Preview; readonly hint: string | undefined } | { readonly kind: 'panel'; readonly panel: Component; readonly tone: Tone };
11
+ export interface RowView {
12
+ readonly phase: RowPhase;
13
+ readonly verb: string;
14
+ readonly target: TargetText;
15
+ readonly meta: string | undefined;
16
+ readonly body: BodyView;
17
+ readonly pad: number;
18
+ }
19
+ /** Columns taken by the marker and its gap, and the indent of body lines under the header. */
20
+ export const ROW_INSET = 3;
21
+ const META_MIN_ROOM = 10;
22
+
23
+ export function derivePhase(ctx: Pick<ToolRenderContext, 'executionStarted' | 'isPartial' | 'isError'>): RowPhase {
24
+ if (!ctx.isPartial) return ctx.isError ? 'failed' : 'done';
25
+ return ctx.executionStarted ? 'running' : 'pending';
26
+ }
27
+ export interface HeaderLayout {
28
+ readonly verb: string;
29
+ readonly target: string;
30
+ readonly gap: number;
31
+ readonly meta: string;
32
+ }
33
+ export function layoutHeader(view: Pick<RowView, 'verb' | 'target' | 'meta'>, width: number): HeaderLayout {
34
+ const available = Math.max(0, width - ROW_INSET);
35
+ const verb = fitPlain(`${view.verb.padEnd(VERB_COLUMN)} `, available);
36
+ const rest = available - visibleWidth(verb);
37
+ const metaText = sanitizeLine(view.meta ?? '');
38
+ const meta = visibleWidth(metaText) + META_MIN_ROOM <= rest ? metaText : '';
39
+ const target = (view.target.kind === 'path' ? fitPath : fitPlain)(sanitizeLine(view.target.text), rest - (meta ? visibleWidth(meta) + 2 : 0));
40
+ return { verb, target, meta, gap: meta ? rest - visibleWidth(target) - visibleWidth(meta) : 0 };
41
+ }
42
+ export function sameBody(a: BodyView, b: BodyView): boolean {
43
+ if (a.kind !== b.kind) return false;
44
+ if (a.kind === 'none' && b.kind === 'none') return true;
45
+ if (a.kind === 'preview' && b.kind === 'preview') return a.preview === b.preview && a.hint === b.hint;
46
+ return a.kind === 'panel' && b.kind === 'panel' && a.panel === b.panel && a.tone === b.tone;
47
+ }
package/src/text.ts ADDED
@@ -0,0 +1,70 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import { replaceControlCharacters, stripTerminalSequences, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
3
+
4
+ const PATH_SEPARATOR = '/';
5
+
6
+ export interface LineSlice {
7
+ readonly lines: readonly string[];
8
+ readonly hidden: number;
9
+ }
10
+
11
+ export function countLines(text: string): number {
12
+ let count = 0;
13
+ for (let i = text.indexOf('\n'); i !== -1; i = text.indexOf('\n', i + 1)) count++;
14
+ return count + Number(text.length > 0 && !text.endsWith('\n'));
15
+ }
16
+
17
+ export function headLines(text: string, max: number): LineSlice {
18
+ let lines: readonly string[] = [];
19
+ let start = 0;
20
+ while (start < text.length && lines.length < max) {
21
+ const end = text.indexOf('\n', start);
22
+ lines = [...lines, text.slice(start, end === -1 ? text.length : end).replace(/\r$/, '')];
23
+ start = end === -1 ? text.length : end + 1;
24
+ }
25
+ return { lines, hidden: countLines(text) - lines.length };
26
+ }
27
+
28
+ export function tailLines(text: string, max: number): LineSlice {
29
+ let lines: readonly string[] = [];
30
+ let end = text.endsWith('\n') ? text.length - 1 : text.length;
31
+ while (end > 0 && lines.length < max) {
32
+ const start = text.lastIndexOf('\n', end - 1);
33
+ lines = [...lines, text.slice(start + 1, end).replace(/\r$/, '')];
34
+ end = start;
35
+ }
36
+ if (end === 0 && lines.length < max && text.startsWith('\n')) lines = [...lines, ''];
37
+ return { lines: lines.toReversed(), hidden: countLines(text) - lines.length };
38
+ }
39
+
40
+ export function sanitizeLine(line: string): string {
41
+ return replaceControlCharacters(stripTerminalSequences(line.replace(/\t/g, ' ').replace(/[\r\n]/g, ' ')));
42
+ }
43
+
44
+ export function gutterOf(pi: Pick<ExtensionAPI, 'getSettings'>): number {
45
+ return pi.getSettings().outputPad ?? 1;
46
+ }
47
+
48
+ export function gutterAt(gutter: number, width: number): number {
49
+ return Math.min(gutter, Math.max(0, Math.floor((width - 1) / 2)));
50
+ }
51
+
52
+ export function fitPlain(text: string, width: number): string {
53
+ if (width <= 0) return '';
54
+ return visibleWidth(text) <= width ? text : truncateToWidth(text, width, '…');
55
+ }
56
+
57
+ export function fitPath(path: string, width: number): string {
58
+ if (visibleWidth(path) <= width) return path;
59
+ const parts = path.split(PATH_SEPARATOR);
60
+ const base = parts.at(-1) ?? '';
61
+ const fallback = `…/${base}`;
62
+ if (visibleWidth(fallback) > width) return fitPlain(base, width);
63
+ let prefix = '';
64
+ for (const part of parts.slice(0, -1)) {
65
+ const next = `${prefix}${part}/`;
66
+ if (visibleWidth(next + fallback) > width) break;
67
+ prefix = next;
68
+ }
69
+ return prefix + fallback;
70
+ }
@@ -0,0 +1,11 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import { compactRenderers } from './rows/row.ts';
3
+ import { genericSpec, isCompactTool, TOOL_SPECS } from './rows/specs.ts';
4
+
5
+ export default function toolRows(pi: ExtensionAPI): void {
6
+ pi.registerToolRenderer((toolName, next) => {
7
+ const native = next();
8
+ if (isCompactTool(toolName)) return native ? compactRenderers(TOOL_SPECS[toolName], native) : native;
9
+ return native?.renderCall || native?.renderResult ? native : compactRenderers(genericSpec(toolName), {});
10
+ });
11
+ }
@@ -0,0 +1,86 @@
1
+ {
2
+ "$schema": "https://pi.dev/schemas/theme.schema.json",
3
+ "name": "snoop-dark",
4
+ "appearance": "dark",
5
+ "vars": {
6
+ "canvas": "#14151a",
7
+ "surface": "#1f222a",
8
+ "panel": "#1f222a",
9
+ "panelErr": "#2a2025",
10
+ "line": "#474753",
11
+ "dim": "#6f7383",
12
+ "muted": "#a6aabb",
13
+ "text": "#e9ecf4",
14
+ "accent": "#b4cde8",
15
+ "accentSoft": "#93a9c2",
16
+ "accentBg": "#2a3344",
17
+ "sage": "#b3c2b3",
18
+ "rose": "#cea8a7",
19
+ "amber": "#d6c79c",
20
+ "teal": "#a9c6cf",
21
+ "match": "#3a3a2c"
22
+ },
23
+ "colors": {
24
+ "accent": "accent",
25
+ "border": "line",
26
+ "borderAccent": "accentSoft",
27
+ "borderMuted": "line",
28
+ "success": "sage",
29
+ "error": "rose",
30
+ "warning": "amber",
31
+ "muted": "muted",
32
+ "dim": "dim",
33
+ "text": "text",
34
+ "thinkingText": "dim",
35
+ "selectedBg": "accentBg",
36
+ "scrollbarTrack": "surface",
37
+ "scrollbarThumb": "line",
38
+ "searchMatchBg": "match",
39
+ "searchMatchText": "text",
40
+ "userMessageBg": "surface",
41
+ "userMessageText": "text",
42
+ "customMessageBg": "surface",
43
+ "customMessageText": "muted",
44
+ "customMessageLabel": "accent",
45
+ "toolPendingBg": "panel",
46
+ "toolSuccessBg": "panel",
47
+ "toolErrorBg": "panelErr",
48
+ "toolTitle": "accent",
49
+ "toolOutput": "muted",
50
+ "mdHeading": "text",
51
+ "mdLink": "accent",
52
+ "mdLinkUrl": "dim",
53
+ "mdCode": "teal",
54
+ "mdCodeBlock": "text",
55
+ "mdCodeBlockBorder": "line",
56
+ "mdQuote": "muted",
57
+ "mdQuoteBorder": "line",
58
+ "mdHr": "line",
59
+ "mdListBullet": "dim",
60
+ "toolDiffAdded": "sage",
61
+ "toolDiffRemoved": "rose",
62
+ "toolDiffContext": "dim",
63
+ "syntaxComment": "dim",
64
+ "syntaxKeyword": "accent",
65
+ "syntaxFunction": "text",
66
+ "syntaxVariable": "text",
67
+ "syntaxString": "sage",
68
+ "syntaxNumber": "amber",
69
+ "syntaxType": "teal",
70
+ "syntaxOperator": "muted",
71
+ "syntaxPunctuation": "muted",
72
+ "thinkingOff": "line",
73
+ "thinkingMinimal": "line",
74
+ "thinkingLow": "line",
75
+ "thinkingMedium": "line",
76
+ "thinkingHigh": "line",
77
+ "thinkingXhigh": "line",
78
+ "thinkingMax": "line",
79
+ "bashMode": "amber"
80
+ },
81
+ "export": {
82
+ "pageBg": "canvas",
83
+ "cardBg": "surface",
84
+ "infoBg": "match"
85
+ }
86
+ }
@@ -0,0 +1,85 @@
1
+ {
2
+ "$schema": "https://pi.dev/schemas/theme.schema.json",
3
+ "name": "snoop-light",
4
+ "appearance": "light",
5
+ "vars": {
6
+ "canvas": "okhsl(250 12% 97%)",
7
+ "surface": "okhsl(250 14% 93%)",
8
+ "panel": "okhsl(250 14% 93%)",
9
+ "panelErr": "okhsl(15 30% 94%)",
10
+ "line": "okhsl(250 8% 80%)",
11
+ "dim": "okhsl(250 6% 58%)",
12
+ "muted": "okhsl(250 7% 45%)",
13
+ "text": "okhsl(250 10% 20%)",
14
+ "accent": "okhsl(245 55% 45%)",
15
+ "accentSoft": "okhsl(245 35% 60%)",
16
+ "accentBg": "okhsl(245 35% 89%)",
17
+ "sage": "okhsl(150 45% 38%)",
18
+ "rose": "okhsl(15 60% 46%)",
19
+ "amber": "okhsl(70 70% 40%)",
20
+ "teal": "okhsl(205 50% 40%)"
21
+ },
22
+ "colors": {
23
+ "accent": "accent",
24
+ "border": "line",
25
+ "borderAccent": "accentSoft",
26
+ "borderMuted": "line",
27
+ "success": "sage",
28
+ "error": "rose",
29
+ "warning": "amber",
30
+ "muted": "muted",
31
+ "dim": "dim",
32
+ "text": "text",
33
+ "thinkingText": "dim",
34
+ "selectedBg": "accentBg",
35
+ "scrollbarTrack": "surface",
36
+ "scrollbarThumb": "line",
37
+ "searchMatchBg": "okhsl(75 40% 88%)",
38
+ "searchMatchText": "text",
39
+ "userMessageBg": "surface",
40
+ "userMessageText": "text",
41
+ "customMessageBg": "surface",
42
+ "customMessageText": "muted",
43
+ "customMessageLabel": "accent",
44
+ "toolPendingBg": "panel",
45
+ "toolSuccessBg": "panel",
46
+ "toolErrorBg": "panelErr",
47
+ "toolTitle": "accent",
48
+ "toolOutput": "muted",
49
+ "mdHeading": "text",
50
+ "mdLink": "accent",
51
+ "mdLinkUrl": "dim",
52
+ "mdCode": "teal",
53
+ "mdCodeBlock": "text",
54
+ "mdCodeBlockBorder": "line",
55
+ "mdQuote": "muted",
56
+ "mdQuoteBorder": "line",
57
+ "mdHr": "line",
58
+ "mdListBullet": "dim",
59
+ "toolDiffAdded": "sage",
60
+ "toolDiffRemoved": "rose",
61
+ "toolDiffContext": "dim",
62
+ "syntaxComment": "dim",
63
+ "syntaxKeyword": "accent",
64
+ "syntaxFunction": "text",
65
+ "syntaxVariable": "text",
66
+ "syntaxString": "sage",
67
+ "syntaxNumber": "amber",
68
+ "syntaxType": "teal",
69
+ "syntaxOperator": "muted",
70
+ "syntaxPunctuation": "muted",
71
+ "thinkingOff": "line",
72
+ "thinkingMinimal": "line",
73
+ "thinkingLow": "line",
74
+ "thinkingMedium": "line",
75
+ "thinkingHigh": "line",
76
+ "thinkingXhigh": "line",
77
+ "thinkingMax": "line",
78
+ "bashMode": "amber"
79
+ },
80
+ "export": {
81
+ "pageBg": "canvas",
82
+ "cardBg": "surface",
83
+ "infoBg": "okhsl(75 40% 88%)"
84
+ }
85
+ }