@justjoshn/pi-snoop-tui 0.1.0 → 0.1.2

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.
@@ -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
+ }
package/src/rows/row.ts CHANGED
@@ -1,47 +1,78 @@
1
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';
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';
5
9
 
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
- }
10
+ const ROW_STATE = Symbol('snoop.rowState');
17
11
  interface SummaryMemo {
18
- content: AgentToolResult<unknown>['content'];
19
- details: unknown;
20
- args: unknown;
21
- isPartial: boolean;
22
- isError: boolean;
23
- value: ResultSummary;
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;
24
18
  }
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
- }
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;
38
28
  }
29
+
39
30
  function parseArgs(args: unknown): Record<string, unknown> {
40
31
  return args !== null && typeof args === 'object' ? (args as Record<string, unknown>) : {};
41
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
+ }
42
50
  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;
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 };
45
76
  }
46
77
 
47
78
  export function compactRenderers(spec: ToolSpec, native: ToolRenderers): ToolRenderers {
@@ -49,69 +80,37 @@ export function compactRenderers(spec: ToolSpec, native: ToolRenderers): ToolRen
49
80
  renderShell: 'self',
50
81
  renderCall(args, theme, ctx) {
51
82
  const state = rowState(ctx, spec, theme);
52
- commit(state, { ...state.view, phase: derivePhase(ctx), target: spec.target(parseArgs(args), ctx.cwd), pad: ctx.outputPad });
83
+ commit(state, { ...state.view.read(), phase: derivePhase(ctx), target: spec.target(parseArgs(args), ctx.cwd), pad: ctx.outputPad });
53
84
  return state.header;
54
85
  },
55
86
  renderResult(result, options, theme, ctx) {
56
87
  const state = rowState(ctx, spec, theme);
57
88
  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 });
89
+ const body = resultBody(state, native, summary, result, options, theme, ctx);
90
+ commit(state, { ...state.view.read(), phase: derivePhase(ctx), meta: summary.meta, body });
79
91
  return state.body;
80
92
  },
81
93
  };
82
94
  }
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;
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');
107
105
  }
108
106
  function commit(state: RowState, next: RowView): void {
109
- const prev = state.view;
107
+ const prev = state.view.read();
110
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;
111
- state.view = Object.freeze(next);
109
+ if (prev.pad !== next.pad) state.panel.read()?.invalidate();
110
+ state.view.write(Object.freeze(next));
112
111
  }
113
112
  function summarizeOnce(state: RowState, spec: ToolSpec, result: AgentToolResult<unknown>, options: ToolRenderResultOptions, ctx: ToolRenderContext): ResultSummary {
114
- const memo = state.summary;
113
+ const memo = state.summary.read();
115
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;
116
115
  const text = result.content
117
116
  .filter((c) => c.type === 'text')
@@ -119,113 +118,6 @@ function summarizeOnce(state: RowState, spec: ToolSpec, result: AgentToolResult<
119
118
  .join('\n');
120
119
  const images = result.content.filter((c) => c.type === 'image').length;
121
120
  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 };
121
+ state.summary.write({ content: result.content, details: result.details, args: ctx.args, isPartial: options.isPartial, isError: ctx.isError, value });
123
122
  return value;
124
123
  }
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
- }
package/src/rows/specs.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { formatReadLineRange } from '@earendil-works/pi-coding-agent';
2
+ import { z } from 'zod';
2
3
  import { countLines, headLines, type LineSlice, tailLines } from '../text.ts';
3
4
 
4
5
  export interface Preview extends LineSlice {
@@ -10,6 +11,7 @@ export interface ResultSummary {
10
11
  readonly preview: Preview | undefined;
11
12
  }
12
13
  export interface ToolArgs {
14
+ [key: string]: unknown;
13
15
  path?: unknown;
14
16
  offset?: unknown;
15
17
  limit?: unknown;
@@ -36,7 +38,10 @@ export interface ToolSpec {
36
38
  }
37
39
  export const RUNNING_TAIL_LINES = 3;
38
40
  export const ERROR_PREVIEW_LINES = 5;
39
- const HOME = process.env['HOME'] ?? process.env['USERPROFILE'];
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;
40
45
 
41
46
  function str(value: unknown): string {
42
47
  return typeof value === 'string' ? value : '';
@@ -53,11 +58,18 @@ function relPath(value: unknown, cwd: string): string {
53
58
  function pathTarget(args: ToolArgs | undefined, cwd: string): TargetText {
54
59
  return { kind: 'path', text: relPath(args?.path, cwd) };
55
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
+ }
56
65
  function summary(meta: string): ResultSummary {
57
66
  return { meta, preview: undefined };
58
67
  }
68
+ function failed(input: ResultInput, meta = 'failed'): ResultSummary {
69
+ return { meta, preview: { ...headLines(input.text, ERROR_PREVIEW_LINES), tone: 'error', from: 'head' } };
70
+ }
59
71
  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();
72
+ return input.isError ? failed(input) : ok();
61
73
  }
62
74
  function withoutNotice(text: string): string {
63
75
  const start = text.lastIndexOf('\n\n[');
@@ -67,6 +79,17 @@ function units(count: number, unit: 'line' | 'match' | 'file' | 'entry', limited
67
79
  const plurals = { line: 'lines', match: 'matches', file: 'files', entry: 'entries' };
68
80
  return `${count}${limited ? '+' : ''} ${count === 1 ? unit : plurals[unit]}`;
69
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
+ }
70
93
  function listing(input: ResultInput, unit: 'match' | 'file' | 'entry', limit: string, empty: string): ResultSummary {
71
94
  return checked(input, () => {
72
95
  const total = field(field(input.details, 'truncation'), 'totalLines');
@@ -95,14 +118,7 @@ export const TOOL_SPECS = {
95
118
  summarize: (input) =>
96
119
  checked(input, () => {
97
120
  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
- }
121
+ const { added, removed } = countPatchLines(patch);
106
122
  return patch ? summary(`+${added} −${removed}`) : summary('edited');
107
123
  }),
108
124
  },
@@ -113,15 +129,11 @@ export const TOOL_SPECS = {
113
129
  },
114
130
  bash: {
115
131
  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
- },
132
+ target: (args) => ({ kind: 'plain', text: firstLine(str(args?.command)) }),
121
133
  summarize: (input) => {
122
134
  if (input.isPartial) return { meta: undefined, preview: { ...tailLines(input.text, RUNNING_TAIL_LINES), tone: 'output', from: 'tail' } };
123
135
  if (!input.isError) return summary('exit 0');
124
- const rawTail = input.text.slice(-200);
136
+ const rawTail = input.text.slice(-STATUS_TAIL_CHARS);
125
137
  const tail = rawTail.trimEnd();
126
138
  const exit = /Command exited with code (\d+)$/.exec(tail);
127
139
  const meta = exit ? `exit ${exit[1]}` : /Command timed out/.test(tail) ? 'timeout' : /Command aborted$/.test(tail) ? 'aborted' : 'failed';
@@ -148,7 +160,29 @@ export const TOOL_SPECS = {
148
160
  } satisfies Record<string, ToolSpec>;
149
161
 
150
162
  export type CompactToolName = keyof typeof TOOL_SPECS;
151
- export const VERB_COLUMN = Math.max(...Object.values(TOOL_SPECS).map((spec) => spec.verb.length));
163
+ export const VERB_COLUMN = 8;
152
164
  export function isCompactTool(name: string): name is CompactToolName {
153
165
  return Object.hasOwn(TOOL_SPECS, name);
154
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 CHANGED
@@ -1,5 +1,8 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
1
2
  import { replaceControlCharacters, stripTerminalSequences, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
2
3
 
4
+ const PATH_SEPARATOR = '/';
5
+
3
6
  export interface LineSlice {
4
7
  readonly lines: readonly string[];
5
8
  readonly hidden: number;
@@ -12,32 +15,40 @@ export function countLines(text: string): number {
12
15
  }
13
16
 
14
17
  export function headLines(text: string, max: number): LineSlice {
15
- const lines: string[] = [];
18
+ let lines: readonly string[] = [];
16
19
  let start = 0;
17
20
  while (start < text.length && lines.length < max) {
18
21
  const end = text.indexOf('\n', start);
19
- lines.push(text.slice(start, end === -1 ? text.length : end).replace(/\r$/, ''));
22
+ lines = [...lines, text.slice(start, end === -1 ? text.length : end).replace(/\r$/, '')];
20
23
  start = end === -1 ? text.length : end + 1;
21
24
  }
22
25
  return { lines, hidden: countLines(text) - lines.length };
23
26
  }
24
27
 
25
28
  export function tailLines(text: string, max: number): LineSlice {
26
- const lines: string[] = [];
29
+ let lines: readonly string[] = [];
27
30
  let end = text.endsWith('\n') ? text.length - 1 : text.length;
28
31
  while (end > 0 && lines.length < max) {
29
32
  const start = text.lastIndexOf('\n', end - 1);
30
- lines.push(text.slice(start + 1, end).replace(/\r$/, ''));
33
+ lines = [...lines, text.slice(start + 1, end).replace(/\r$/, '')];
31
34
  end = start;
32
35
  }
33
- if (end === 0 && lines.length < max && text.startsWith('\n')) lines.push('');
34
- return { lines: lines.reverse(), hidden: countLines(text) - lines.length };
36
+ if (end === 0 && lines.length < max && text.startsWith('\n')) lines = [...lines, ''];
37
+ return { lines: lines.toReversed(), hidden: countLines(text) - lines.length };
35
38
  }
36
39
 
37
40
  export function sanitizeLine(line: string): string {
38
41
  return replaceControlCharacters(stripTerminalSequences(line.replace(/\t/g, ' ').replace(/[\r\n]/g, ' ')));
39
42
  }
40
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
+
41
52
  export function fitPlain(text: string, width: number): string {
42
53
  if (width <= 0) return '';
43
54
  return visibleWidth(text) <= width ? text : truncateToWidth(text, width, '…');
@@ -45,16 +56,15 @@ export function fitPlain(text: string, width: number): string {
45
56
 
46
57
  export function fitPath(path: string, width: number): string {
47
58
  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);
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);
52
63
  let prefix = '';
53
- for (const part of parts) {
64
+ for (const part of parts.slice(0, -1)) {
54
65
  const next = `${prefix}${part}/`;
55
- if (visibleWidth(next + fitted) > width) break;
66
+ if (visibleWidth(next + fallback) > width) break;
56
67
  prefix = next;
57
68
  }
58
- fitted = prefix + fitted;
59
- return fitted;
69
+ return prefix + fallback;
60
70
  }
package/src/tool-rows.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
2
  import { compactRenderers } from './rows/row.ts';
3
- import { isCompactTool, TOOL_SPECS } from './rows/specs.ts';
3
+ import { genericSpec, isCompactTool, TOOL_SPECS } from './rows/specs.ts';
4
4
 
5
5
  export default function toolRows(pi: ExtensionAPI): void {
6
6
  pi.registerToolRenderer((toolName, next) => {
7
- if (!isCompactTool(toolName)) return next();
8
7
  const native = next();
9
- return native ? compactRenderers(TOOL_SPECS[toolName], native) : native;
8
+ if (isCompactTool(toolName)) return native ? compactRenderers(TOOL_SPECS[toolName], native) : native;
9
+ return native?.renderCall || native?.renderResult ? native : compactRenderers(genericSpec(toolName), {});
10
10
  });
11
11
  }