@justjoshn/pi-snoop-tui 0.0.0-stage → 0.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/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0]
4
+
5
+ - Add paired `snoop-dark` and `snoop-light` themes.
6
+ - Add compact rows for read, edit, write, bash, grep, find, and ls.
7
+ - Keep native tool detail rendering on expansion.
8
+ - Add a single-line footer, workspace header, and static working indicator.
9
+ - Cache rendered lines and tool summaries without extension-owned timers or render-time I/O.
package/README.md CHANGED
@@ -1,3 +1,60 @@
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.
4
+
5
+ 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.
6
+
7
+ The footer shows the workspace, branch, extension statuses, model, thinking level, and context usage on one line. The header shows `pi / workspace`. A static dot replaces the animated working indicator.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ pi install npm:@justjoshn/pi-snoop-tui
13
+ ```
14
+
15
+ Built and tested against Pi 1.5.2.
16
+
17
+ Add these recommended native settings to `~/.pi/agent/settings.json`:
18
+
19
+ ```json
20
+ {
21
+ "theme": "snoop-light/snoop-dark",
22
+ "quietStartup": true,
23
+ "hideThinkingBlock": true,
24
+ "outputPad": 1,
25
+ "editorPaddingX": 1,
26
+ "collapseChangelog": true,
27
+ "autocompleteMaxVisible": 5
28
+ }
29
+ ```
30
+
31
+ 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.
32
+
33
+ Run `pi config` to toggle `tool-rows.ts`, `footer.ts`, and `chrome.ts` independently. Chrome includes the header and working indicator. Tool rows also work with stock themes.
34
+
35
+ ## Native limits
36
+
37
+ Pi owns the blank line between tool rows. This package cannot remove it through the native renderer API.
38
+
39
+ Your terminal owns the canvas background. For dark mode, set it near `okhsl(250 10% 9%)`. For light mode, use `okhsl(250 12% 97%)`.
40
+
41
+ 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. Unknown tools keep their existing renderers.
42
+
43
+ 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.
44
+
45
+ ## Rendering work
46
+
47
+ 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 cache their rendered output. Context usage refreshes on lifecycle events, not on terminal frames.
48
+
49
+ A theme change clears component caches. The working dot takes the new theme color at the next agent start.
50
+
51
+ ## Develop
52
+
53
+ ```sh
54
+ bun install
55
+ bun run --filter @justjoshn/pi-snoop-tui typecheck
56
+ cd extensions/pi-snoop-tui
57
+ bunx vitest run --coverage
58
+ ```
59
+
60
+ Tests cover 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,57 @@
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.0",
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/*.json"
32
+ ]
33
+ },
34
+ "files": [
35
+ "src",
36
+ "themes",
37
+ "README.md",
38
+ "CHANGELOG.md"
39
+ ],
40
+ "scripts": {
41
+ "test": "vitest run",
42
+ "test:coverage": "vitest run --coverage",
43
+ "typecheck": "tsc -p ."
44
+ },
45
+ "peerDependencies": {
46
+ "@earendil-works/pi-coding-agent": "*",
47
+ "@earendil-works/pi-tui": "*"
48
+ },
49
+ "devDependencies": {
50
+ "@earendil-works/pi-coding-agent": "1.5.2",
51
+ "@earendil-works/pi-tui": "1.5.2",
52
+ "@types/node": "^22.19.0",
53
+ "@vitest/coverage-v8": "^5.0.2",
54
+ "typescript": "^7.0.2",
55
+ "vitest": "^5.0.2"
56
+ }
57
+ }
package/src/chrome.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { basename } from 'node:path';
2
+
3
+ import type { ExtensionAPI, ExtensionContext, Theme } from '@earendil-works/pi-coding-agent';
4
+ import type { Component } from '@earendil-works/pi-tui';
5
+ import { fitPlain, sanitizeLine } from './text.ts';
6
+
7
+ export default function chrome(pi: ExtensionAPI): void {
8
+ pi.on('session_start', (_event, ctx) => {
9
+ if (!ctx.hasUI) return;
10
+ ctx.ui.setHeader((_tui, theme) => new HeaderLine(theme, basename(ctx.cwd) || ctx.cwd));
11
+ setIndicator(ctx);
12
+ });
13
+ pi.on('agent_start', (_event, ctx) => {
14
+ if (ctx.hasUI) setIndicator(ctx);
15
+ });
16
+ }
17
+ function setIndicator(ctx: ExtensionContext): void {
18
+ ctx.ui.setWorkingIndicator({ frames: [ctx.ui.theme.fg('accent', '●')] });
19
+ }
20
+ export class HeaderLine implements Component {
21
+ private cache: { width: number; line: string } | undefined;
22
+ private readonly theme: Theme;
23
+ private readonly workspace: string;
24
+ constructor(theme: Theme, workspace: string) {
25
+ this.theme = theme;
26
+ this.workspace = workspace;
27
+ }
28
+ render(width: number): string[] {
29
+ if (this.cache?.width === width) return [this.cache.line];
30
+ const line = width < 5 ? this.theme.fg('accent', fitPlain('pi', width)) : this.theme.fg('accent', 'pi') + this.theme.fg('dim', ' / ') + this.theme.fg('muted', fitPlain(sanitizeLine(this.workspace), width - 5));
31
+ this.cache = { width, line };
32
+ return [line];
33
+ }
34
+ invalidate(): void {
35
+ this.cache = undefined;
36
+ }
37
+ }
package/src/footer.ts ADDED
@@ -0,0 +1,151 @@
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 { fitPlain, sanitizeLine } from './text.ts';
6
+
7
+ type ThinkingLevel = ReturnType<ExtensionAPI['getThinkingLevel']>;
8
+ export interface FooterSnapshot {
9
+ readonly workspace: string;
10
+ readonly model: string | undefined;
11
+ readonly thinking: ThinkingLevel | undefined;
12
+ readonly ctxPercent: number | null;
13
+ }
14
+ export const SEGMENT_ORDER = [
15
+ { id: 'workspace', side: 'left', priority: 0, minWidth: 6 },
16
+ { id: 'branch', side: 'left', priority: 4 },
17
+ { id: 'statuses', side: 'right', priority: 3, minWidth: 8 },
18
+ { id: 'model', side: 'right', priority: 2, minWidth: 8 },
19
+ { id: 'thinking', side: 'right', priority: 5 },
20
+ { id: 'ctx', side: 'right', priority: 1 },
21
+ ] as const;
22
+ export type SegmentId = (typeof SEGMENT_ORDER)[number]['id'];
23
+ export interface Segment {
24
+ readonly id: SegmentId;
25
+ readonly side: 'left' | 'right';
26
+ readonly priority: number;
27
+ readonly text: string;
28
+ readonly minWidth?: number;
29
+ }
30
+ export default function footer(pi: ExtensionAPI): void {
31
+ let snapshot: FooterSnapshot | undefined;
32
+ let mounted: TUI | undefined;
33
+ const refresh = (ctx: ExtensionContext): void => {
34
+ const next = readSnapshot(ctx, pi.getThinkingLevel());
35
+ if (snapshot && sameSnapshot(snapshot, next)) return;
36
+ snapshot = Object.freeze(next);
37
+ mounted?.requestRender();
38
+ };
39
+ pi.on('session_start', (_event, ctx) => {
40
+ if (!ctx.hasUI) return;
41
+ refresh(ctx);
42
+ ctx.ui.setFooter((tui, theme, data) => {
43
+ mounted = tui;
44
+ return new SnoopFooter(
45
+ theme,
46
+ data,
47
+ () => snapshot,
48
+ () => {
49
+ if (mounted === tui) mounted = undefined;
50
+ },
51
+ );
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
+ export function fitSegments(segments: readonly Segment[], width: number): readonly Segment[] {
82
+ const fitted = segments.filter((s) => s.text).map((s) => ({ ...s, text: sanitizeLine(s.text) }));
83
+ while (rowWidth(fitted) > Math.max(0, width)) {
84
+ const lowest = fitted.reduce((a, b) => (a.priority > b.priority || (a.priority === b.priority && a.side === 'right') ? a : b));
85
+ const size = visibleWidth(lowest.text);
86
+ const min = lowest.priority === 0 ? 0 : lowest.minWidth;
87
+ if (min !== undefined && size > min) {
88
+ lowest.text = fitPlain(lowest.text, Math.max(min, size - (rowWidth(fitted) - Math.max(0, width))));
89
+ } else {
90
+ fitted.splice(fitted.indexOf(lowest), 1);
91
+ }
92
+ }
93
+ return fitted;
94
+ }
95
+ export function statusText(statuses: ReadonlyMap<string, string>): string {
96
+ return [...statuses.entries()]
97
+ .sort(([a], [b]) => a.localeCompare(b))
98
+ .map(([, text]) => sanitizeLine(text).trim())
99
+ .filter(Boolean)
100
+ .join(' · ');
101
+ }
102
+ export class SnoopFooter implements Component {
103
+ private cache: { width: number; snapshot: FooterSnapshot | undefined; branch: string | null; statuses: string; line: string } | undefined;
104
+ private readonly theme: Theme;
105
+ private readonly data: ReadonlyFooterDataProvider;
106
+ private readonly read: () => FooterSnapshot | undefined;
107
+ private readonly onDispose: () => void;
108
+ constructor(theme: Theme, data: ReadonlyFooterDataProvider, read: () => FooterSnapshot | undefined, onDispose: () => void) {
109
+ this.theme = theme;
110
+ this.data = data;
111
+ this.read = read;
112
+ this.onDispose = onDispose;
113
+ }
114
+ render(width: number): string[] {
115
+ const snapshot = this.read();
116
+ const branch = this.data.getGitBranch();
117
+ const statuses = statusText(this.data.getExtensionStatuses());
118
+ if (this.cache?.width === width && this.cache.snapshot === snapshot && this.cache.branch === branch && this.cache.statuses === statuses) return [this.cache.line];
119
+ const texts: Record<SegmentId, string> = {
120
+ workspace: snapshot?.workspace ?? '',
121
+ branch: branch ?? '',
122
+ statuses,
123
+ model: snapshot?.model ?? '',
124
+ thinking: snapshot?.thinking ?? '',
125
+ ctx: snapshot?.ctxPercent == null ? 'ctx ?' : `ctx ${Math.round(snapshot.ctxPercent)}%`,
126
+ };
127
+ const fitted = fitSegments(
128
+ SEGMENT_ORDER.map((s) => ({ ...s, text: texts[s.id] })),
129
+ width,
130
+ );
131
+ const style = (s: Segment): string => {
132
+ const percent = snapshot?.ctxPercent;
133
+ const color = s.id === 'workspace' ? 'text' : s.id !== 'ctx' ? 'muted' : percent == null ? 'dim' : percent > 90 ? 'error' : percent > 70 ? 'warning' : 'accent';
134
+ return this.theme.fg(color, s.text);
135
+ };
136
+ const separator = (text: string): string => this.theme.fg('dim', text);
137
+ const left = joinSide(fitted, 'left', style, separator);
138
+ const right = joinSide(fitted, 'right', style, separator);
139
+ const gap = left && right ? Math.max(2, width - visibleWidth(left) - visibleWidth(right)) : 0;
140
+ const line = left + ' '.repeat(gap) + right;
141
+ this.cache = { width, snapshot, branch, statuses, line };
142
+ return [line];
143
+ }
144
+ invalidate(): void {
145
+ this.cache = undefined;
146
+ }
147
+ dispose(): void {
148
+ this.cache = undefined;
149
+ this.onDispose();
150
+ }
151
+ }
@@ -0,0 +1,231 @@
1
+ import type { AgentToolResult, Theme, ToolRenderers, ToolRenderResultOptions } from '@earendil-works/pi-coding-agent';
2
+ import { Box, type Component, Text, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
3
+ import { fitPath, fitPlain, sanitizeLine } from '../text.ts';
4
+ import { type Preview, type ResultSummary, type TargetText, type ToolSpec, VERB_COLUMN } from './specs.ts';
5
+
6
+ type ToolRenderContext = Parameters<NonNullable<ToolRenderers['renderCall']>>[2];
7
+ export type RowPhase = 'pending' | 'running' | 'done' | 'failed';
8
+ export type BodyView = { readonly kind: 'none' } | { readonly kind: 'preview'; readonly preview: Preview; readonly hint: string | undefined } | { readonly kind: 'native'; readonly panel: Component; readonly tone: 'ok' | 'error' };
9
+ export interface RowView {
10
+ readonly phase: RowPhase;
11
+ readonly verb: string;
12
+ readonly target: TargetText;
13
+ readonly meta: string | undefined;
14
+ readonly body: BodyView;
15
+ readonly pad: number;
16
+ }
17
+ interface SummaryMemo {
18
+ content: AgentToolResult<unknown>['content'];
19
+ details: unknown;
20
+ args: unknown;
21
+ isPartial: boolean;
22
+ isError: boolean;
23
+ value: ResultSummary;
24
+ }
25
+ class RowState {
26
+ view: RowView;
27
+ summary: SummaryMemo | undefined;
28
+ readonly native: Record<string, unknown> = {};
29
+ nativeResult: Component | undefined;
30
+ panel: Panel | undefined;
31
+ readonly header: RowHeader;
32
+ readonly body: RowBody;
33
+ constructor(spec: ToolSpec, theme: Theme, ctx: ToolRenderContext) {
34
+ this.view = 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
+ this.header = new RowHeader(this, theme);
36
+ this.body = new RowBody(this, theme);
37
+ }
38
+ }
39
+ function parseArgs(args: unknown): Record<string, unknown> {
40
+ return args !== null && typeof args === 'object' ? (args as Record<string, unknown>) : {};
41
+ }
42
+ function rowState(ctx: ToolRenderContext, spec: ToolSpec, theme: Theme): RowState {
43
+ if (!(ctx.state.snoop instanceof RowState)) ctx.state.snoop = new RowState(spec, theme, ctx);
44
+ return ctx.state.snoop;
45
+ }
46
+
47
+ export function compactRenderers(spec: ToolSpec, native: ToolRenderers): ToolRenderers {
48
+ return {
49
+ renderShell: 'self',
50
+ renderCall(args, theme, ctx) {
51
+ const state = rowState(ctx, spec, theme);
52
+ commit(state, { ...state.view, phase: derivePhase(ctx), target: spec.target(parseArgs(args), ctx.cwd), pad: ctx.outputPad });
53
+ return state.header;
54
+ },
55
+ renderResult(result, options, theme, ctx) {
56
+ const state = rowState(ctx, spec, theme);
57
+ const summary = summarizeOnce(state, spec, result, options, ctx);
58
+ let body: BodyView = { kind: 'none' };
59
+ if (options.expanded) {
60
+ // Native call renderers start timers and edit previews. Only delegate result detail.
61
+ state.nativeResult =
62
+ native.renderResult?.(result, options, theme, { ...ctx, state: state.native, lastComponent: state.nativeResult, outputPad: 0 }) ??
63
+ new Text(
64
+ result.content
65
+ .filter((c) => c.type === 'text')
66
+ .map((c) => c.text)
67
+ .join('\n'),
68
+ 0,
69
+ 0,
70
+ );
71
+ const tone = ctx.isError ? 'error' : 'ok';
72
+ state.panel ??= new Panel(theme, () => state.view.pad);
73
+ state.panel.set(state.nativeResult, tone);
74
+ body = { kind: 'native', panel: state.panel, tone };
75
+ } else if (summary.preview) {
76
+ body = { kind: 'preview', preview: summary.preview, hint: summary.preview.hidden > 0 ? ctx.keyText('app.tools.expand') : undefined };
77
+ }
78
+ commit(state, { ...state.view, phase: derivePhase(ctx), meta: summary.meta, body });
79
+ return state.body;
80
+ },
81
+ };
82
+ }
83
+ export function derivePhase(ctx: Pick<ToolRenderContext, 'executionStarted' | 'isPartial' | 'isError'>): RowPhase {
84
+ if (!ctx.isPartial) return ctx.isError ? 'failed' : 'done';
85
+ return ctx.executionStarted ? 'running' : 'pending';
86
+ }
87
+ export interface HeaderLayout {
88
+ readonly verb: string;
89
+ readonly target: string;
90
+ readonly gap: number;
91
+ readonly meta: string;
92
+ }
93
+ export function layoutHeader(view: Pick<RowView, 'verb' | 'target' | 'meta'>, width: number): HeaderLayout {
94
+ const available = Math.max(0, width - 3);
95
+ const verb = fitPlain(view.verb.padEnd(VERB_COLUMN + 2), available);
96
+ const rest = available - visibleWidth(verb);
97
+ const metaText = sanitizeLine(view.meta ?? '');
98
+ const meta = visibleWidth(metaText) + 10 <= rest ? metaText : '';
99
+ const target = (view.target.kind === 'path' ? fitPath : fitPlain)(sanitizeLine(view.target.text), rest - (meta ? visibleWidth(meta) + 2 : 0));
100
+ return { verb, target, meta, gap: meta ? rest - visibleWidth(target) - visibleWidth(meta) : 0 };
101
+ }
102
+ function sameBody(a: BodyView, b: BodyView): boolean {
103
+ if (a.kind !== b.kind) return false;
104
+ if (a.kind === 'none' && b.kind === 'none') return true;
105
+ if (a.kind === 'preview' && b.kind === 'preview') return a.preview === b.preview && a.hint === b.hint;
106
+ return a.kind === 'native' && b.kind === 'native' && a.panel === b.panel && a.tone === b.tone;
107
+ }
108
+ function commit(state: RowState, next: RowView): void {
109
+ const prev = state.view;
110
+ 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;
111
+ state.view = Object.freeze(next);
112
+ }
113
+ function summarizeOnce(state: RowState, spec: ToolSpec, result: AgentToolResult<unknown>, options: ToolRenderResultOptions, ctx: ToolRenderContext): ResultSummary {
114
+ const memo = state.summary;
115
+ 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;
116
+ const text = result.content
117
+ .filter((c) => c.type === 'text')
118
+ .map((c) => c.text)
119
+ .join('\n');
120
+ const images = result.content.filter((c) => c.type === 'image').length;
121
+ const value = spec.summarize({ args: parseArgs(ctx.args), text, images, details: result.details, isError: ctx.isError, isPartial: options.isPartial });
122
+ state.summary = { content: result.content, details: result.details, args: ctx.args, isPartial: options.isPartial, isError: ctx.isError, value };
123
+ return value;
124
+ }
125
+ const MARKERS = {
126
+ pending: ['dim', '·'],
127
+ running: ['accent', '•'],
128
+ done: ['success', '✓'],
129
+ failed: ['error', '✗'],
130
+ } as const;
131
+ class RowHeader implements Component {
132
+ private cache: { width: number; view: RowView; lines: string[] } | undefined;
133
+ private readonly state: RowState;
134
+ private readonly theme: Theme;
135
+ constructor(state: RowState, theme: Theme) {
136
+ this.state = state;
137
+ this.theme = theme;
138
+ }
139
+ render(width: number): string[] {
140
+ const view = this.state.view;
141
+ if (this.cache?.width === width && this.cache.view === view) return this.cache.lines;
142
+ const pad = Math.min(view.pad, Math.max(0, width - 1));
143
+ const layout = layoutHeader(view, width - pad);
144
+ const [color, marker] = MARKERS[view.phase];
145
+ const line =
146
+ ' '.repeat(pad) +
147
+ this.theme.fg(color, marker) +
148
+ ' ' +
149
+ this.theme.fg(view.phase === 'pending' ? 'dim' : 'toolTitle', layout.verb) +
150
+ this.theme.fg(view.phase === 'pending' ? 'dim' : 'text', layout.target) +
151
+ ' '.repeat(layout.gap) +
152
+ this.theme.fg('dim', layout.meta);
153
+ const lines = [truncateToWidth(line, width, '')];
154
+ this.cache = { width, view, lines };
155
+ return lines;
156
+ }
157
+ invalidate(): void {
158
+ this.cache = undefined;
159
+ }
160
+ }
161
+ class RowBody implements Component {
162
+ private cache: { width: number; view: RowView; lines: string[] } | undefined;
163
+ private readonly state: RowState;
164
+ private readonly theme: Theme;
165
+ constructor(state: RowState, theme: Theme) {
166
+ this.state = state;
167
+ this.theme = theme;
168
+ }
169
+ render(width: number): string[] {
170
+ const view = this.state.view;
171
+ const body = view.body;
172
+ switch (body.kind) {
173
+ case 'none':
174
+ return [];
175
+ case 'native':
176
+ return body.panel.render(width);
177
+ case 'preview': {
178
+ if (this.cache?.width === width && this.cache.view === view) return this.cache.lines;
179
+ const indent = Math.min(view.pad + 3, Math.max(0, width - 1));
180
+ const line = (text: string, tone: 'error' | 'toolOutput' | 'dim') => ' '.repeat(indent) + this.theme.fg(tone, fitPlain(sanitizeLine(text), width - indent));
181
+ const lines = body.preview.lines.map((text) => line(text, body.preview.tone === 'error' ? 'error' : 'toolOutput'));
182
+ if (body.hint) {
183
+ const from = body.preview.from;
184
+ switch (from) {
185
+ case 'head':
186
+ lines.push(line(`… ${body.preview.hidden} more · ${body.hint}`, 'dim'));
187
+ break;
188
+ case 'tail':
189
+ lines.unshift(line(`… ${body.preview.hidden} earlier · ${body.hint}`, 'dim'));
190
+ break;
191
+ default: {
192
+ const unreachable: never = from;
193
+ return unreachable;
194
+ }
195
+ }
196
+ }
197
+ this.cache = { width, view, lines };
198
+ return lines;
199
+ }
200
+ default: {
201
+ const unreachable: never = body;
202
+ return unreachable;
203
+ }
204
+ }
205
+ }
206
+ invalidate(): void {
207
+ this.cache = undefined;
208
+ this.state.panel?.invalidate();
209
+ }
210
+ }
211
+ class Panel implements Component {
212
+ private readonly box = new Box(1, 0);
213
+ private readonly theme: Theme;
214
+ private readonly pad: () => number;
215
+ constructor(theme: Theme, pad: () => number) {
216
+ this.theme = theme;
217
+ this.pad = pad;
218
+ }
219
+ set(child: Component, tone: 'ok' | 'error'): void {
220
+ this.box.clear();
221
+ this.box.addChild(child);
222
+ this.box.setBgFn((text) => this.theme.bg(tone === 'error' ? 'toolErrorBg' : 'toolPendingBg', text));
223
+ }
224
+ render(width: number): string[] {
225
+ const indent = Math.min(this.pad() + 3, Math.max(0, width - 1));
226
+ return this.box.render(Math.max(1, width - indent - this.pad())).map((line) => truncateToWidth(' '.repeat(indent) + line, width, ''));
227
+ }
228
+ invalidate(): void {
229
+ this.box.invalidate();
230
+ }
231
+ }
@@ -0,0 +1,154 @@
1
+ import { formatReadLineRange } from '@earendil-works/pi-coding-agent';
2
+ import { countLines, headLines, type LineSlice, tailLines } from '../text.ts';
3
+
4
+ export interface Preview extends LineSlice {
5
+ readonly tone: 'output' | 'error';
6
+ readonly from: 'head' | 'tail';
7
+ }
8
+ export interface ResultSummary {
9
+ readonly meta: string | undefined;
10
+ readonly preview: Preview | undefined;
11
+ }
12
+ export interface ToolArgs {
13
+ path?: unknown;
14
+ offset?: unknown;
15
+ limit?: unknown;
16
+ pattern?: unknown;
17
+ command?: unknown;
18
+ content?: unknown;
19
+ }
20
+ export interface ResultInput {
21
+ readonly args: ToolArgs;
22
+ readonly text: string;
23
+ readonly images: number;
24
+ readonly details: unknown;
25
+ readonly isError: boolean;
26
+ readonly isPartial: boolean;
27
+ }
28
+ export interface TargetText {
29
+ readonly text: string;
30
+ readonly kind: 'path' | 'plain';
31
+ }
32
+ export interface ToolSpec {
33
+ readonly verb: string;
34
+ target(args: ToolArgs | undefined, cwd: string): TargetText;
35
+ summarize(input: ResultInput): ResultSummary;
36
+ }
37
+ export const RUNNING_TAIL_LINES = 3;
38
+ export const ERROR_PREVIEW_LINES = 5;
39
+ const HOME = process.env['HOME'] ?? process.env['USERPROFILE'];
40
+
41
+ function str(value: unknown): string {
42
+ return typeof value === 'string' ? value : '';
43
+ }
44
+ function field(value: unknown, key: string): unknown {
45
+ return value && typeof value === 'object' && key in value ? Reflect.get(value, key) : undefined;
46
+ }
47
+ function relPath(value: unknown, cwd: string): string {
48
+ const path = str(value);
49
+ if (path.startsWith(`${cwd}/`)) return path.slice(cwd.length + 1);
50
+ if (HOME && (path === HOME || path.startsWith(`${HOME}/`))) return `~${path.slice(HOME.length)}`;
51
+ return path;
52
+ }
53
+ function pathTarget(args: ToolArgs | undefined, cwd: string): TargetText {
54
+ return { kind: 'path', text: relPath(args?.path, cwd) };
55
+ }
56
+ function summary(meta: string): ResultSummary {
57
+ return { meta, preview: undefined };
58
+ }
59
+ function checked(input: ResultInput, ok: () => ResultSummary): ResultSummary {
60
+ return input.isError ? { meta: 'failed', preview: { ...headLines(input.text, ERROR_PREVIEW_LINES), tone: 'error', from: 'head' } } : ok();
61
+ }
62
+ function withoutNotice(text: string): string {
63
+ const start = text.lastIndexOf('\n\n[');
64
+ return start === -1 ? text : text.slice(0, start);
65
+ }
66
+ function units(count: number, unit: 'line' | 'match' | 'file' | 'entry', limited = false): string {
67
+ const plurals = { line: 'lines', match: 'matches', file: 'files', entry: 'entries' };
68
+ return `${count}${limited ? '+' : ''} ${count === 1 ? unit : plurals[unit]}`;
69
+ }
70
+ function listing(input: ResultInput, unit: 'match' | 'file' | 'entry', limit: string, empty: string): ResultSummary {
71
+ return checked(input, () => {
72
+ const total = field(field(input.details, 'truncation'), 'totalLines');
73
+ const count = input.text.startsWith(empty) ? 0 : typeof total === 'number' ? total : countLines(withoutNotice(input.text));
74
+ return summary(units(count, unit, Boolean(field(input.details, limit))));
75
+ });
76
+ }
77
+
78
+ export const TOOL_SPECS = {
79
+ read: {
80
+ verb: 'read',
81
+ target: (args, cwd) => ({
82
+ kind: 'path',
83
+ text: relPath(args?.path, cwd) + formatReadLineRange(typeof args?.offset === 'number' ? args.offset : undefined, typeof args?.limit === 'number' ? args.limit : undefined),
84
+ }),
85
+ summarize: (input) =>
86
+ checked(input, () => {
87
+ if (input.images > 0) return summary('image');
88
+ const total = field(field(input.details, 'truncation'), 'totalLines');
89
+ return summary(units(typeof total === 'number' ? total : countLines(withoutNotice(input.text)), 'line'));
90
+ }),
91
+ },
92
+ edit: {
93
+ verb: 'edit',
94
+ target: pathTarget,
95
+ summarize: (input) =>
96
+ checked(input, () => {
97
+ const patch = str(field(input.details, 'patch'));
98
+ let added = 0;
99
+ let removed = 0;
100
+ for (let start = 0; start < patch.length; ) {
101
+ if (patch[start] === '+' && !patch.startsWith('+++', start)) added++;
102
+ if (patch[start] === '-' && !patch.startsWith('---', start)) removed++;
103
+ const end = patch.indexOf('\n', start);
104
+ start = end === -1 ? patch.length : end + 1;
105
+ }
106
+ return patch ? summary(`+${added} −${removed}`) : summary('edited');
107
+ }),
108
+ },
109
+ write: {
110
+ verb: 'write',
111
+ target: pathTarget,
112
+ summarize: (input) => checked(input, () => summary(units(countLines(str(input.args.content)), 'line'))),
113
+ },
114
+ bash: {
115
+ verb: 'bash',
116
+ target: (args) => {
117
+ const command = str(args?.command);
118
+ const end = command.indexOf('\n');
119
+ return { kind: 'plain', text: (end === -1 ? command : command.slice(0, end)).replace(/\s+/g, ' ') + (end === -1 ? '' : '…') };
120
+ },
121
+ summarize: (input) => {
122
+ if (input.isPartial) return { meta: undefined, preview: { ...tailLines(input.text, RUNNING_TAIL_LINES), tone: 'output', from: 'tail' } };
123
+ if (!input.isError) return summary('exit 0');
124
+ const rawTail = input.text.slice(-200);
125
+ const tail = rawTail.trimEnd();
126
+ const exit = /Command exited with code (\d+)$/.exec(tail);
127
+ const meta = exit ? `exit ${exit[1]}` : /Command timed out/.test(tail) ? 'timeout' : /Command aborted$/.test(tail) ? 'aborted' : 'failed';
128
+ const status = /Command (?:exited with code \d+|timed out[^\n]*|aborted)$/.exec(tail);
129
+ const text = status ? input.text.slice(0, input.text.length - rawTail.length + status.index).trimEnd() : input.text;
130
+ return { meta, preview: { ...tailLines(text, ERROR_PREVIEW_LINES), tone: 'error', from: 'tail' } };
131
+ },
132
+ },
133
+ grep: {
134
+ verb: 'grep',
135
+ target: (args) => ({ kind: 'plain', text: str(args?.pattern) + (typeof args?.path === 'string' ? ` ${args.path}` : '') }),
136
+ summarize: (input) => (input.text === 'No matches found' && !input.isError ? summary('no matches') : listing(input, 'match', 'matchLimitReached', 'No matches found')),
137
+ },
138
+ find: {
139
+ verb: 'find',
140
+ target: (args) => ({ kind: 'plain', text: str(args?.pattern) }),
141
+ summarize: (input) => listing(input, 'file', 'resultLimitReached', 'No files found'),
142
+ },
143
+ ls: {
144
+ verb: 'ls',
145
+ target: (args, cwd) => pathTarget({ path: args?.path ?? '.' }, cwd),
146
+ summarize: (input) => listing(input, 'entry', 'entryLimitReached', '(empty directory)'),
147
+ },
148
+ } satisfies Record<string, ToolSpec>;
149
+
150
+ export type CompactToolName = keyof typeof TOOL_SPECS;
151
+ export const VERB_COLUMN = Math.max(...Object.values(TOOL_SPECS).map((spec) => spec.verb.length));
152
+ export function isCompactTool(name: string): name is CompactToolName {
153
+ return Object.hasOwn(TOOL_SPECS, name);
154
+ }
package/src/text.ts ADDED
@@ -0,0 +1,60 @@
1
+ import { replaceControlCharacters, stripTerminalSequences, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
2
+
3
+ export interface LineSlice {
4
+ readonly lines: readonly string[];
5
+ readonly hidden: number;
6
+ }
7
+
8
+ export function countLines(text: string): number {
9
+ let count = 0;
10
+ for (let i = text.indexOf('\n'); i !== -1; i = text.indexOf('\n', i + 1)) count++;
11
+ return count + Number(text.length > 0 && !text.endsWith('\n'));
12
+ }
13
+
14
+ export function headLines(text: string, max: number): LineSlice {
15
+ const lines: string[] = [];
16
+ let start = 0;
17
+ while (start < text.length && lines.length < max) {
18
+ const end = text.indexOf('\n', start);
19
+ lines.push(text.slice(start, end === -1 ? text.length : end).replace(/\r$/, ''));
20
+ start = end === -1 ? text.length : end + 1;
21
+ }
22
+ return { lines, hidden: countLines(text) - lines.length };
23
+ }
24
+
25
+ export function tailLines(text: string, max: number): LineSlice {
26
+ const lines: string[] = [];
27
+ let end = text.endsWith('\n') ? text.length - 1 : text.length;
28
+ while (end > 0 && lines.length < max) {
29
+ const start = text.lastIndexOf('\n', end - 1);
30
+ lines.push(text.slice(start + 1, end).replace(/\r$/, ''));
31
+ end = start;
32
+ }
33
+ if (end === 0 && lines.length < max && text.startsWith('\n')) lines.push('');
34
+ return { lines: lines.reverse(), hidden: countLines(text) - lines.length };
35
+ }
36
+
37
+ export function sanitizeLine(line: string): string {
38
+ return replaceControlCharacters(stripTerminalSequences(line.replace(/\t/g, ' ').replace(/[\r\n]/g, ' ')));
39
+ }
40
+
41
+ export function fitPlain(text: string, width: number): string {
42
+ if (width <= 0) return '';
43
+ return visibleWidth(text) <= width ? text : truncateToWidth(text, width, '…');
44
+ }
45
+
46
+ export function fitPath(path: string, width: number): string {
47
+ if (visibleWidth(path) <= width) return path;
48
+ const parts = path.split('/');
49
+ const base = parts.pop() ?? '';
50
+ let fitted = `…/${base}`;
51
+ if (visibleWidth(fitted) > width) return fitPlain(base, width);
52
+ let prefix = '';
53
+ for (const part of parts) {
54
+ const next = `${prefix}${part}/`;
55
+ if (visibleWidth(next + fitted) > width) break;
56
+ prefix = next;
57
+ }
58
+ fitted = prefix + fitted;
59
+ return fitted;
60
+ }
@@ -0,0 +1,11 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import { compactRenderers } from './rows/row.ts';
3
+ import { isCompactTool, TOOL_SPECS } from './rows/specs.ts';
4
+
5
+ export default function toolRows(pi: ExtensionAPI): void {
6
+ pi.registerToolRenderer((toolName, next) => {
7
+ if (!isCompactTool(toolName)) return next();
8
+ const native = next();
9
+ return native ? compactRenderers(TOOL_SPECS[toolName], native) : native;
10
+ });
11
+ }
@@ -0,0 +1,85 @@
1
+ {
2
+ "$schema": "https://pi.dev/schemas/theme.schema.json",
3
+ "name": "snoop-dark",
4
+ "appearance": "dark",
5
+ "vars": {
6
+ "canvas": "okhsl(250 10% 9%)",
7
+ "surface": "okhsl(250 11% 14%)",
8
+ "panel": "okhsl(250 9% 12.5%)",
9
+ "panelErr": "okhsl(15 22% 13%)",
10
+ "line": "okhsl(250 7% 28%)",
11
+ "dim": "okhsl(250 6% 46%)",
12
+ "muted": "okhsl(250 7% 62%)",
13
+ "text": "okhsl(250 6% 87%)",
14
+ "accent": "okhsl(242 45% 74%)",
15
+ "accentSoft": "okhsl(242 28% 60%)",
16
+ "accentBg": "okhsl(245 25% 20%)",
17
+ "sage": "okhsl(150 28% 68%)",
18
+ "rose": "okhsl(15 45% 68%)",
19
+ "amber": "okhsl(75 45% 74%)",
20
+ "teal": "okhsl(205 30% 72%)"
21
+ },
22
+ "colors": {
23
+ "accent": "accent",
24
+ "border": "accentSoft",
25
+ "borderAccent": "accent",
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 25% 20%)",
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": "okhsl(250 8% 36%)",
73
+ "thinkingLow": "okhsl(246 14% 44%)",
74
+ "thinkingMedium": "okhsl(244 20% 50%)",
75
+ "thinkingHigh": "okhsl(243 28% 57%)",
76
+ "thinkingXhigh": "okhsl(242 36% 64%)",
77
+ "thinkingMax": "accent",
78
+ "bashMode": "amber"
79
+ },
80
+ "export": {
81
+ "pageBg": "canvas",
82
+ "cardBg": "surface",
83
+ "infoBg": "okhsl(75 25% 20%)"
84
+ }
85
+ }
@@ -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 12% 94.5%)",
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": "accentSoft",
25
+ "borderAccent": "accent",
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": "okhsl(250 8% 74%)",
73
+ "thinkingLow": "okhsl(246 16% 68%)",
74
+ "thinkingMedium": "okhsl(244 24% 62%)",
75
+ "thinkingHigh": "okhsl(243 34% 56%)",
76
+ "thinkingXhigh": "okhsl(244 44% 50%)",
77
+ "thinkingMax": "accent",
78
+ "bashMode": "amber"
79
+ },
80
+ "export": {
81
+ "pageBg": "canvas",
82
+ "cardBg": "surface",
83
+ "infoBg": "okhsl(75 40% 88%)"
84
+ }
85
+ }