@casualjim/pi-pretty 0.7.0 → 0.7.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.
package/src/types.ts CHANGED
@@ -23,30 +23,30 @@ export type { ImageContent, TextContent };
23
23
  // ---------------------------------------------------------------------------
24
24
 
25
25
  export interface ThemeLike {
26
- fg: (key: string, text: string) => string;
27
- bold: (text: string) => string;
28
- getBgAnsi?: (key: string) => string;
26
+ fg: (key: string, text: string) => string;
27
+ bold: (text: string) => string;
28
+ getBgAnsi?: (key: string) => string;
29
29
  }
30
30
 
31
31
  export interface RenderCtxLike {
32
- lastComponent?: ComponentLike;
33
- toolCallId?: string;
34
- isError?: boolean;
35
- state: Record<string, unknown>;
36
- expanded?: boolean;
37
- invalidate?: () => void;
32
+ lastComponent?: ComponentLike;
33
+ toolCallId?: string;
34
+ isError?: boolean;
35
+ state: Record<string, unknown>;
36
+ expanded?: boolean;
37
+ invalidate?: () => void;
38
38
  }
39
39
 
40
40
  export interface TextLike {
41
- setText(v: string): void;
42
- getText?(): string;
41
+ setText(v: string): void;
42
+ getText?(): string;
43
43
  }
44
44
 
45
45
  /** Minimal Component interface matching pi-tui's Component. */
46
46
  export interface ComponentLike {
47
- setText(v: string): void;
48
- render(width: number): string[];
49
- invalidate?(): void;
47
+ setText(v: string): void;
48
+ render(width: number): string[];
49
+ invalidate?(): void;
50
50
  }
51
51
 
52
52
  // ---------------------------------------------------------------------------
@@ -54,73 +54,61 @@ export interface ComponentLike {
54
54
  // ---------------------------------------------------------------------------
55
55
 
56
56
  export type ReadDetails =
57
- | { _type: "readImage"; filePath: string }
58
- | { _type: "readFile"; filePath: string; content: string; offset: number; lineCount: number };
59
-
60
- export interface BashDetails extends Record<string, unknown> {
61
- _type: "bashResult";
62
- text: string;
63
- exitCode: number | null;
64
- command: string;
65
- }
57
+ | { _type: "readImage"; filePath: string }
58
+ | { _type: "readFile"; filePath: string; content: string; offset: number; lineCount: number };
66
59
 
67
60
  export interface LsDetails extends Record<string, unknown> {
68
- _type: "lsResult";
69
- text: string;
70
- path: string;
71
- entryCount: number;
61
+ _type: "lsResult";
62
+ text: string;
63
+ path: string;
64
+ entryCount: number;
72
65
  }
73
66
 
74
67
  export interface FindDetails extends Record<string, unknown> {
75
- _type: "findResult";
76
- text: string;
77
- pattern: string;
78
- matchCount: number;
79
- notices?: string[];
68
+ _type: "findResult";
69
+ text: string;
70
+ pattern: string;
71
+ matchCount: number;
72
+ notices?: string[];
80
73
  }
81
74
 
82
75
  export interface GrepDetails extends Record<string, unknown> {
83
- _type: "grepResult";
84
- text: string;
85
- pattern: string;
86
- matchCount: number;
76
+ _type: "grepResult";
77
+ text: string;
78
+ pattern: string;
79
+ matchCount: number;
87
80
  }
88
81
 
89
- export type AnyDetails = ReadDetails | BashDetails | LsDetails | FindDetails | GrepDetails;
82
+ export type AnyDetails = ReadDetails | LsDetails | FindDetails | GrepDetails;
90
83
 
91
84
  // ---------------------------------------------------------------------------
92
85
  // Tool input types
93
86
  // ---------------------------------------------------------------------------
94
87
 
95
88
  export interface ReadInput {
96
- path: string;
97
- offset?: number;
98
- limit?: number;
99
- }
100
-
101
- export interface BashInput {
102
- command: string;
103
- timeout?: number;
89
+ path: string;
90
+ offset?: number;
91
+ limit?: number;
104
92
  }
105
93
 
106
94
  export interface LsInput {
107
- path?: string;
95
+ path?: string;
108
96
  }
109
97
 
110
98
  export interface FindInput {
111
- pattern: string;
112
- path?: string;
113
- limit?: number;
99
+ pattern: string;
100
+ path?: string;
101
+ limit?: number;
114
102
  }
115
103
 
116
104
  export interface GrepInput {
117
- pattern: string;
118
- path?: string;
119
- glob?: string;
120
- context?: number;
121
- limit?: number;
122
- literal?: boolean;
123
- ignoreCase?: boolean;
105
+ pattern: string;
106
+ path?: string;
107
+ glob?: string;
108
+ context?: number;
109
+ limit?: number;
110
+ literal?: boolean;
111
+ ignoreCase?: boolean;
124
112
  }
125
113
 
126
114
  // ---------------------------------------------------------------------------
@@ -132,26 +120,26 @@ export interface GrepInput {
132
120
  * Accepts both the real SDK's ToolDefinition<> return type and test mocks.
133
121
  */
134
122
  export interface SdkToolDef {
135
- name?: string;
136
- description?: string;
137
- label?: string;
138
- parameters?: unknown;
139
- promptSnippet?: string;
140
- promptGuidelines?: string[];
141
- constrainedSampling?: false | ConstrainedSamplingConfig;
142
- execute: (...args: any[]) => Promise<AgentToolResult<any>>;
123
+ name?: string;
124
+ description?: string;
125
+ label?: string;
126
+ parameters?: unknown;
127
+ promptSnippet?: string;
128
+ promptGuidelines?: string[];
129
+ constrainedSampling?: false | ConstrainedSamplingConfig;
130
+ execute: (...args: any[]) => Promise<AgentToolResult<any>>;
143
131
  }
144
132
 
145
133
  export interface SdkTools {
146
- createReadTool?: (cwd: string) => SdkToolDef;
147
- createReadToolDefinition?: (cwd: string) => SdkToolDef;
148
- createLsTool?: (cwd: string) => SdkToolDef;
149
- createLsToolDefinition?: (cwd: string) => SdkToolDef;
150
- createFindTool?: (cwd: string) => SdkToolDef;
151
- createFindToolDefinition?: (cwd: string) => SdkToolDef;
152
- createGrepTool?: (cwd: string) => SdkToolDef;
153
- createGrepToolDefinition?: (cwd: string) => SdkToolDef;
154
- getAgentDir?: () => string;
134
+ createReadTool?: (cwd: string) => SdkToolDef;
135
+ createReadToolDefinition?: (cwd: string) => SdkToolDef;
136
+ createLsTool?: (cwd: string) => SdkToolDef;
137
+ createLsToolDefinition?: (cwd: string) => SdkToolDef;
138
+ createFindTool?: (cwd: string) => SdkToolDef;
139
+ createFindToolDefinition?: (cwd: string) => SdkToolDef;
140
+ createGrepTool?: (cwd: string) => SdkToolDef;
141
+ createGrepToolDefinition?: (cwd: string) => SdkToolDef;
142
+ getAgentDir?: () => string;
155
143
  }
156
144
 
157
145
  // ---------------------------------------------------------------------------
@@ -160,27 +148,27 @@ export interface SdkTools {
160
148
 
161
149
  /** Minimal FFF service shape for tools that only need fileSearch. */
162
150
  export interface FffServiceLike {
163
- readonly isAvailable: boolean;
164
- readonly partialIndex: boolean;
165
- getFinder(): import("@ff-labs/fff-node").FileFinder | null;
151
+ readonly isAvailable: boolean;
152
+ readonly partialIndex: boolean;
153
+ getFinder(): import("@ff-labs/fff-node").FileFinder | null;
166
154
  }
167
155
 
168
156
  /** Full FFF service for grep tools that also need cursor store. */
169
157
  export interface FffServiceWithCursor extends FffServiceLike {
170
- getCursorStore(): CursorStore;
158
+ getCursorStore(): CursorStore;
171
159
  }
172
160
 
173
161
  /** FFF lifecycle interface (used by session lifecycle code). */
174
162
  export interface FffService extends FffServiceWithCursor {
175
- ensureFinder(cwd: string, options?: FffInitOptions): Promise<void>;
176
- destroy(): void;
177
- isModuleLoaded(): boolean;
178
- tryLoadModule(): Promise<boolean>;
163
+ ensureFinder(cwd: string, options?: FffInitOptions): Promise<void>;
164
+ destroy(): void;
165
+ isModuleLoaded(): boolean;
166
+ tryLoadModule(): Promise<boolean>;
179
167
  }
180
168
 
181
169
  export interface CursorStore {
182
- store(cursor: unknown): string;
183
- get(id: string): unknown | undefined;
170
+ store(cursor: unknown): string;
171
+ get(id: string): unknown | undefined;
184
172
  }
185
173
 
186
174
  // ---------------------------------------------------------------------------
@@ -190,13 +178,13 @@ export interface CursorStore {
190
178
  export type CustomEditorConstructor = new (...args: ConstructorParameters<typeof CustomEditor>) => CustomEditor;
191
179
 
192
180
  export interface PiPrettyDeps {
193
- sdk?: SdkTools;
194
- TextComponent?: new (text?: string, x?: number, y?: number) => ComponentLike;
195
- fffModule?: typeof import("@ff-labs/fff-node");
196
- /** Host AssistantMessageComponent class for the per-row label patch; defaults
197
- * to the package export. Injectable so tests can verify against the exact
198
- * class instance they construct rows from. */
199
- assistantMessageComponent?: unknown;
200
- /** Host CustomEditor class for the live prompt icon; defaults to the package export. */
201
- customEditorClass?: CustomEditorConstructor;
181
+ sdk?: SdkTools;
182
+ TextComponent?: new (text?: string, x?: number, y?: number) => ComponentLike;
183
+ fffModule?: typeof import("@ff-labs/fff-node");
184
+ /** Host AssistantMessageComponent class for the per-row label patch; defaults
185
+ * to the package export. Injectable so tests can verify against the exact
186
+ * class instance they construct rows from. */
187
+ assistantMessageComponent?: unknown;
188
+ /** Host CustomEditor class for the live prompt icon; defaults to the package export. */
189
+ customEditorClass?: CustomEditorConstructor;
202
190
  }
@@ -400,6 +400,7 @@ export class WorkingWidget {
400
400
  #tui: WidgetTuiLike | undefined;
401
401
  #started = false;
402
402
  #disposed = false;
403
+ #suffix = "";
403
404
 
404
405
  setFrames(frames: string[], intervalMs: number): void {
405
406
  this.#frames = frames;
@@ -407,6 +408,13 @@ export class WorkingWidget {
407
408
  this.#index = 0;
408
409
  }
409
410
 
411
+ /** Trailing label (the elapsed turn clock); plain text, dimmed at render. */
412
+ setSuffix(text: string): void {
413
+ if (text === this.#suffix) return;
414
+ this.#suffix = text;
415
+ this.#tui?.requestRender();
416
+ }
417
+
410
418
  attach(tui: WidgetTuiLike): void {
411
419
  this.#tui = tui;
412
420
  }
@@ -445,7 +453,9 @@ export class WorkingWidget {
445
453
  render(width: number): string[] {
446
454
  if (!this.#started || this.#frames.length === 0) return [];
447
455
  const frame = this.#frames[this.#index % this.#frames.length] ?? "";
448
- return [truncateToWidth(frame, Math.max(1, width))];
456
+ // The native host appends its own space after the frame; this row does not.
457
+ const suffix = this.#suffix === "" ? "" : ` ${FG_DIM}${this.#suffix}${RESET_FG}`;
458
+ return [truncateToWidth(`${frame}${suffix}`, Math.max(1, width))];
449
459
  }
450
460
 
451
461
  invalidate(): void {
@@ -773,6 +783,8 @@ export interface WorkingIndicatorController {
773
783
  stop(): void;
774
784
  /** Remove the indicator and stop the animation. */
775
785
  dispose(): void;
786
+ /** Update the trailing label (the elapsed turn clock); "" clears it. */
787
+ setSuffix(text: string): void;
776
788
  /** @deprecated Token stats are owned by Pi and are no longer rendered here. */
777
789
  setStats(text: string | undefined): void;
778
790
  /** Request a host render for consumers that drive another animated label. */
@@ -802,6 +814,7 @@ export async function installWorkingIndicator(
802
814
  start() {},
803
815
  stop() {},
804
816
  dispose() {},
817
+ setSuffix() {},
805
818
  setStats() {},
806
819
  requestRender() {},
807
820
  frames: [],
@@ -835,10 +848,12 @@ export async function installWorkingIndicator(
835
848
  if (typeof setWorkingIndicator === "function" && typeof setWorkingMessage === "function") {
836
849
  let started = false;
837
850
  let disposed = false;
851
+ let suffix = "";
838
852
  const updateNativeMessage = (): void => {
839
- // Keep Pi's built-in message hidden because the custom frame already
840
- // supplies the working label; no hint or token suffix is added here.
841
- setWorkingMessage.call(ui, "");
853
+ // The host renders `frame + " " + message`, so the elapsed clock rides
854
+ // the message slot: appending there leaves the sweep untouched, unlike
855
+ // re-calling setWorkingIndicator, which would reset the frame index.
856
+ setWorkingMessage.call(ui, suffix);
842
857
  };
843
858
 
844
859
  try {
@@ -878,6 +893,11 @@ export async function installWorkingIndicator(
878
893
  setWorkingIndicator.call(ui);
879
894
  setWorkingMessage.call(ui);
880
895
  },
896
+ setSuffix: (text: string) => {
897
+ if (disposed || text === suffix) return;
898
+ suffix = text;
899
+ updateNativeMessage();
900
+ },
881
901
  setStats: (_text: string | undefined) => {},
882
902
  requestRender: () => updateNativeMessage(),
883
903
  frames,
@@ -905,6 +925,7 @@ export async function installWorkingIndicator(
905
925
  widget.dispose();
906
926
  ui.setWidget(WIDGET_KEY, undefined);
907
927
  },
928
+ setSuffix: (text: string) => widget.setSuffix(text),
908
929
  setStats: (_text: string | undefined) => {},
909
930
  requestRender: () => widget.requestRender(),
910
931
  frames,
@@ -1,21 +0,0 @@
1
- /* Declaration boundary for @casualjim/pi-pretty/bash-renderers.
2
- *
3
- * Consumers (pi-heimdall) type-check against this file — their strict tsconfig
4
- * flags do not apply to it (skipLibCheck). The runtime entry stays bash.ts. */
5
-
6
- import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
7
-
8
- type Result = AgentToolResult<Record<string, unknown>>;
9
-
10
- export interface BashRenderers {
11
- renderShell: "self";
12
- /** Renders the `$ command` call header; returns the host Text component. */
13
- renderCall: (args: any, theme: any, ctx: any) => unknown;
14
- /** Renders bash output with pi-pretty styling; returns the host Text component. */
15
- renderResult: (result: Result, options: unknown, theme: any, ctx: any) => unknown;
16
- }
17
-
18
- /** Build pi-pretty's bash renderers. TextComp is the host TUI Text class; when omitted, pi-tui's Text is used. */
19
- export declare function createBashRenderers(
20
- TextComp?: new (t?: string, x?: number, y?: number) => { setText(v: string): void },
21
- ): BashRenderers;
package/src/tools/bash.ts DELETED
@@ -1,163 +0,0 @@
1
- /* pi-pretty: bash renderers — display-only.
2
- *
3
- * pi-heimdall owns the `bash` tool (sandboxed execute) and attaches these
4
- * renderers, so output keeps pi-pretty styling. pi-pretty itself never
5
- * registers, substitutes, or executes the bash tool. */
6
-
7
- import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
8
- import { resolveBaseBackground, TOOL_RESULT_INDENT, termWidth } from "../config.js";
9
- import { compactErrorLines, inferBashExitCode, stripBashExitStatusLine } from "../helpers.js";
10
- import {
11
- fillToolBackground,
12
- fillToolBody,
13
- rememberToolTitle,
14
- renderToolDuration,
15
- renderToolError,
16
- setCollapsedToolTitle,
17
- } from "../render.js";
18
- import { resolveTextCtor } from "../tui-text.js";
19
- import type { BashDetails, ComponentLike, RenderCtxLike, ThemeLike, TextContent } from "../types.js";
20
-
21
- type Result = AgentToolResult<Record<string, unknown>>;
22
- const BASH_RESULT_RENDER_KEY = "__piPrettyBashResultRender";
23
- export interface BashRenderers {
24
- renderShell: "self";
25
- /** Returns the host Text component; loosely typed so the tool owner can attach it to its ToolDefinition. */
26
- renderCall: (args: any, theme: ThemeLike, ctx: RenderCtxLike) => unknown;
27
- renderResult: (result: Result, opt: unknown, theme: ThemeLike, ctx: RenderCtxLike) => unknown;
28
- }
29
-
30
- export function createBashRenderers(
31
- TextComp?: new (t?: string, x?: number, y?: number) => { setText(v: string): void },
32
- ): BashRenderers {
33
- const TC = resolveTextCtor(TextComp);
34
-
35
- return {
36
- renderShell: "self",
37
-
38
- renderCall(args: any, theme: ThemeLike, ctx: RenderCtxLike) {
39
- resolveBaseBackground(theme);
40
- const text = (ctx.lastComponent ?? new TC("", 0, 0)) as ComponentLike;
41
- const t = typeof args.timeout === "number" ? ` ${theme.fg("muted", `(timeout ${args.timeout}s)`)}` : "";
42
- const tw = termWidth() || 80;
43
- const rawCmd = String(args.command ?? "");
44
- const headerBudget = ctx.expanded ? tw : Math.max(8, tw - 20);
45
- const cmd =
46
- rawCmd.length === 0
47
- ? theme.fg("toolOutput", "...")
48
- : !ctx.expanded && rawCmd.length > headerBudget
49
- ? `${rawCmd.slice(0, Math.max(1, headerBudget))}…`
50
- : rawCmd;
51
- const commandLabel = theme.fg(ctx.isError ? "error" : "toolTitle", theme.bold(`$ ${cmd}`));
52
- const renderTitle = (suffix = ""): string =>
53
- fillToolBackground(
54
- `\n${TOOL_RESULT_INDENT}${commandLabel}${t}${suffix}\n`,
55
- undefined,
56
- ctx.expanded ? undefined : tw,
57
- );
58
- rememberToolTitle(ctx, text, renderTitle);
59
- text.setText(renderTitle());
60
- return text;
61
- },
62
-
63
- renderResult(result: Result, _opt: unknown, theme: ThemeLike, ctx: RenderCtxLike) {
64
- resolveBaseBackground(theme);
65
-
66
- const text = (ctx.lastComponent ?? new TC("", 0, 0)) as ComponentLike;
67
- restoreBashResultRender(ctx, text);
68
- const displayResult = result;
69
-
70
- const details = displayResult.details;
71
- const tc = getText(displayResult);
72
- const d: BashDetails | undefined =
73
- (details as BashDetails)?._type === "bashResult"
74
- ? (details as BashDetails)
75
- : tc || ctx.isError
76
- ? {
77
- _type: "bashResult",
78
- text: tc || "Error",
79
- exitCode: inferBashExitCode(tc, ctx.isError ? 1 : 0),
80
- command: "",
81
- }
82
- : undefined;
83
-
84
- if (d?._type === "bashResult") {
85
- const isErr = ctx.isError || (d.exitCode !== null && d.exitCode !== 0);
86
- const cleaned = stripBashExitStatusLine(d.text);
87
- const output = isErr ? compactErrorLines(cleaned).join("\n") : cleaned;
88
- const lineCount = output.split("\n").length;
89
- const info = [
90
- `${lineCount} lines`,
91
- renderToolDuration(displayResult),
92
- !ctx.expanded ? "ctrl+o to expand" : "",
93
- ]
94
- .filter(Boolean)
95
- .map((part) => theme.fg("dim", part))
96
- .join(theme.fg("dim", " · "));
97
- const header = `${TOOL_RESULT_INDENT}${info}`;
98
- const rw = termWidth();
99
-
100
- if (setCollapsedToolTitle(ctx, text, ` ${info}`)) return text;
101
-
102
- const renderFn = (w: number) => {
103
- if (!ctx.expanded) return fillToolBody(header, undefined, w);
104
- if (!output.trim()) return fillToolBody(header, undefined, w);
105
- const show = output.split("\n");
106
- const out = [header, "", ...show.map((line: string) => `${TOOL_RESULT_INDENT}${line}`)];
107
- return fillToolBody(out.join("\n"), undefined, w);
108
- };
109
-
110
- text.setText(renderFn(rw));
111
- const baseRender =
112
- typeof (text as ComponentLike).render === "function" ? (text as ComponentLike).render.bind(text) : null;
113
- if (baseRender) {
114
- ctx.state[BASH_RESULT_RENDER_KEY] = baseRender;
115
- let key: string | undefined;
116
- // SAFETY: same host Text component contract as restoreBashResultRender;
117
- // we memoize renders behind the component's own render(width) hook.
118
- (text as unknown as Record<string, unknown>).render = (w: number) => {
119
- const width = Math.max(1, Math.floor(w || termWidth()));
120
- const k = `bash:${ctx.expanded ? "1" : "0"}:${width}:${d.exitCode ?? "killed"}:${output.length}:${renderToolDuration(displayResult)}`;
121
- if (key !== k) {
122
- text.setText(renderFn(width));
123
- key = k;
124
- }
125
- return baseRender(width);
126
- };
127
- }
128
- return text;
129
- }
130
-
131
- if (ctx.isError) {
132
- text.setText(renderToolError(tc || "Error", theme));
133
- return text;
134
- }
135
- const fc = displayResult.content?.[0];
136
- text.setText(
137
- fillToolBody(
138
- `${TOOL_RESULT_INDENT}${theme.fg("dim", fc && "text" in fc ? String(fc.text).slice(0, 120) : "done")}`,
139
- ),
140
- );
141
- return text;
142
- },
143
- };
144
- }
145
-
146
- function restoreBashResultRender(ctx: RenderCtxLike, text: ComponentLike): void {
147
- const state = ctx.state;
148
- const original = state[BASH_RESULT_RENDER_KEY] as ((width: number) => string[]) | undefined;
149
- if (!original) return;
150
- // SAFETY: text is the host Text component created in renderResult; the host TUI
151
- // contract guarantees render(width): string[] even though ComponentLike omits it.
152
- (text as unknown as { render: (width: number) => string[] }).render = original;
153
- delete state[BASH_RESULT_RENDER_KEY];
154
- }
155
-
156
- function getText(result: Result): string {
157
- return (
158
- ((result.content ?? []) as TextContent[])
159
- .filter((c) => c.type === "text")
160
- .map((c) => c.text)
161
- .join("\n") ?? ""
162
- );
163
- }