@aoshizuku/pi-bettertui 0.1.1 → 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.
@@ -1,237 +1,237 @@
1
- import { clipMiddle, countLines, displayPath, lineRange, plural, sanitizeText, str } from "./format.js";
2
- import type { ToolResultSnapshot } from "./types.js";
3
-
4
- export const TOOL_LABELS: Record<string, string> = {
5
- read: "Read",
6
- bash: "Bash",
7
- powershell: "PowerShell",
8
- edit: "Edit",
9
- write: "Write",
10
- grep: "Grep",
11
- find: "Find",
12
- ls: "LS",
13
- };
14
-
15
- export const MANAGED_TOOL_NAMES = new Set(Object.keys(TOOL_LABELS));
16
- export const MERGEABLE_TOOL_NAMES = new Set(["read", "grep", "find", "ls"]);
17
-
18
- export function isManagedTool(name: string): boolean {
19
- return MANAGED_TOOL_NAMES.has(name);
20
- }
21
-
22
- export function isMergeableTool(name: string): boolean {
23
- return MERGEABLE_TOOL_NAMES.has(name);
24
- }
25
-
26
- export function isShellTool(name: string): boolean {
27
- return name === "bash" || name === "powershell";
28
- }
29
-
30
- /**
31
- * The skill name when a read loads a skill (`…/<name>/SKILL.md`), else undefined.
32
- * Such reads get their own `● [Skill] (name)` row instead of joining a read group.
33
- */
34
- export function skillReadName(name: string, args: Record<string, unknown>): string | undefined {
35
- if (name !== "read") return undefined;
36
- const parts = str(args.file_path ?? args.path).replace(/\\/g, "/").split("/").filter(Boolean);
37
- if (parts.at(-1) !== "SKILL.md") return undefined;
38
- return parts.at(-2) ?? "SKILL.md";
39
- }
40
-
41
- export function resultText(result: ToolResultSnapshot | undefined): string {
42
- if (!result) return "";
43
- return sanitizeText(
44
- result.content
45
- .map((block) => (block.type === "text" ? (block.text ?? "") : ""))
46
- .join("\n"),
47
- ).trim();
48
- }
49
-
50
- /**
51
- * pi's texts for a call cut short by an interrupt: `Operation aborted` (the agent loop, the built-in
52
- * tools, and the interactive mode for calls whose arguments were still streaming), `Command aborted`
53
- * (appended under a command's output), a bare `aborted`, and `Aborted after N retry attempts`.
54
- */
55
- const INTERRUPT_LINE = /^(?:(?:operation|command|request)(?: was)? )?aborted(?: after \d+ retry attempts?)?\.?$/i;
56
-
57
- /**
58
- * Whether an error result only says the call was interrupted (DESIGN.md §9): the user stopped the
59
- * run, the tool did not fail. Only the last line counts, so a command's own output above
60
- * pi's `Command aborted` does not matter.
61
- */
62
- export function isInterrupted(result: ToolResultSnapshot | undefined): boolean {
63
- if (!result?.isError) return false;
64
- const lines = resultText(result).split("\n");
65
- const last = lines[lines.length - 1]?.trim() ?? "";
66
- return INTERRUPT_LINE.test(last);
67
- }
68
-
69
- /** An error result that is a real failure, not an interrupt. */
70
- export function isFailed(result: ToolResultSnapshot | undefined): boolean {
71
- return result?.isError === true && !isInterrupted(result);
72
- }
73
-
74
- export function resultImageCount(result: ToolResultSnapshot | undefined): number {
75
- return result?.content.filter((block) => block.type === "image").length ?? 0;
76
- }
77
-
78
- function details(result: ToolResultSnapshot | undefined): Record<string, unknown> {
79
- const value = result?.details;
80
- return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : {};
81
- }
82
-
83
- function truncationTotal(result: ToolResultSnapshot | undefined): number | undefined {
84
- const value = details(result).truncation;
85
- if (typeof value !== "object" || value === null) return undefined;
86
- const totalLines = (value as { totalLines?: unknown }).totalLines;
87
- return typeof totalLines === "number" && Number.isSafeInteger(totalLines) ? totalLines : undefined;
88
- }
89
-
90
- function truncated(result: ToolResultSnapshot | undefined): boolean {
91
- const value = details(result).truncation;
92
- return typeof value === "object" && value !== null && (value as { truncated?: unknown }).truncated === true;
93
- }
94
-
95
- export function diffStats(diff: string): { added: number; removed: number } {
96
- let added = 0;
97
- let removed = 0;
98
- for (const line of diff.split("\n")) {
99
- if (line.startsWith("+++") || line.startsWith("---")) continue;
100
- if (line.startsWith("+")) added++;
101
- else if (line.startsWith("-")) removed++;
102
- }
103
- return { added, removed };
104
- }
105
-
106
- export function callDetail(name: string, args: Record<string, unknown>, cwd: string): string {
107
- const path = displayPath(str(args.file_path ?? args.path), cwd);
108
- switch (name) {
109
- case "read":
110
- return path + lineRange(args);
111
- case "edit":
112
- case "write":
113
- return path;
114
- case "bash":
115
- case "powershell":
116
- return shellDetail(args);
117
- case "grep": {
118
- const pattern = str(args.pattern);
119
- return pattern ? `/${pattern}/${path ? ` in ${path}` : ""}` : path;
120
- }
121
- case "find": {
122
- const pattern = str(args.pattern);
123
- return pattern && path ? `${pattern} in ${path}` : pattern || path;
124
- }
125
- case "ls":
126
- return path || ".";
127
- default:
128
- return "";
129
- }
130
- }
131
-
132
- /** Widest a raw command may get in a row header; the rest is cut from the middle. */
133
- export const SHELL_COMMAND_MAX_WIDTH = 72;
134
-
135
- /** The model's description when it gave one, otherwise a width-capped command. */
136
- export function shellDetail(args: Record<string, unknown>): string {
137
- const description = sanitizeText(str(args.description)).replace(/\s+/g, " ").trim();
138
- if (description) return description;
139
- return shellCommandSummary(str(args.command));
140
- }
141
-
142
- export function shellCommandSummary(command: string, maxWidth = SHELL_COMMAND_MAX_WIDTH): string {
143
- const lines = sanitizeText(command).replace(/\r\n?/g, "\n").trim().split("\n");
144
- const head = clipMiddle((lines[0] ?? "").trim(), maxWidth);
145
- return lines.length > 1 ? `${head} … (+${lines.length - 1} lines)` : head;
146
- }
147
-
148
- /** Full command split into display lines, for the expanded view. */
149
- export function shellCommandLines(args: Record<string, unknown>): string[] {
150
- const command = sanitizeText(str(args.command)).replace(/\r\n?/g, "\n").replace(/^\n+|\s+$/g, "");
151
- return command ? command.split("\n").map((line) => line.trimEnd()) : [];
152
- }
153
-
154
- /** Stable identity for "how many distinct files did this group touch?". */
155
- export function targetKey(name: string, args: Record<string, unknown>, fallback: string): string {
156
- if (name === "read" || name === "edit" || name === "write" || name === "ls") {
157
- const path = str(args.file_path ?? args.path);
158
- return path || fallback;
159
- }
160
- if (name === "grep" || name === "find") {
161
- const pattern = str(args.pattern);
162
- const path = str(args.path);
163
- return `${pattern}\u0000${path}` || fallback;
164
- }
165
- return fallback;
166
- }
167
-
168
- export function summarizeResult(name: string, result: ToolResultSnapshot, args: Record<string, unknown>): string {
169
- const text = resultText(result);
170
- switch (name) {
171
- case "read": {
172
- if (resultImageCount(result) > 0) {
173
- // pi (1.6.0 on) names the model here when it has no image input and only saw a placeholder.
174
- return details(result).imageUnsupportedByModel ? "image · model has no image input" : "image";
175
- }
176
- const lines = truncationTotal(result) ?? countLines(text);
177
- return plural(lines, "line") + (truncated(result) ? " · truncated" : "");
178
- }
179
- case "bash":
180
- case "powershell": {
181
- const lines = truncationTotal(result) ?? countLines(text);
182
- const exit = result.isError ? /Command exited with code (\d+)/.exec(text)?.[1] : undefined;
183
- const head = result.isError ? (exit ? `Failed (exit ${exit})` : "Failed") : "Done";
184
- return `${head} · ${lines === 0 ? "no output" : plural(lines, "line")}`;
185
- }
186
- case "edit": {
187
- const diff = details(result).diff;
188
- if (typeof diff !== "string") return result.isError ? "Failed" : "Edited";
189
- const { added, removed } = diffStats(diff);
190
- return `+${added} −${removed}`;
191
- }
192
- case "write": {
193
- const content = str(args.content);
194
- return `${plural(countLines(content), "line")} written`;
195
- }
196
- case "grep": {
197
- if (text === "No matches found") return "No matches";
198
- const files = new Set<string>();
199
- let matches = 0;
200
- for (const line of text.split("\n")) {
201
- const match = /^(.+?):\d+: /.exec(line);
202
- if (!match) continue;
203
- matches++;
204
- files.add(match[1]!);
205
- }
206
- return `${plural(matches, "match", "matches")} in ${plural(files.size, "file")}`;
207
- }
208
- case "find":
209
- return text === "No files found matching pattern" ? "No files" : plural(countLines(text), "file");
210
- case "ls":
211
- return text === "(empty directory)" ? "Empty" : plural(countLines(text), "entry", "entries");
212
- default:
213
- return text ? plural(countLines(text), "line") : "Done";
214
- }
215
- }
216
-
217
- export function summarizeGeneric(result: ToolResultSnapshot | undefined): string {
218
- const text = resultText(result);
219
- const lines = text.split("\n").filter((line) => line.trim());
220
- const head = sanitizeText((lines[0] ?? "").replace(/^#+\s+/, ""));
221
- const counts = lines.length ? plural(lines.length, "line") : "Done";
222
- return counts + (head ? ` · ${head}` : "");
223
- }
224
-
225
- /** Last meaningful lines of a result, used for error tails and expanded previews. */
226
- export function resultLines(result: ToolResultSnapshot | undefined, max: number, keep: "head" | "tail" = "tail"): string[] {
227
- const lines = resultText(result)
228
- .split("\n")
229
- .map((line) => line.trimEnd())
230
- .filter((line) => line.trim() !== "");
231
- if (lines.length <= max) return lines;
232
- return keep === "head" ? lines.slice(0, max) : lines.slice(-max);
233
- }
234
-
235
- export function resultLineTotal(result: ToolResultSnapshot | undefined): number {
236
- return resultText(result).split("\n").filter((line) => line.trim() !== "").length;
237
- }
1
+ import { clipMiddle, countLines, displayPath, lineRange, plural, sanitizeText, str } from "./format.js";
2
+ import type { ToolResultSnapshot } from "./types.js";
3
+
4
+ export const TOOL_LABELS: Record<string, string> = {
5
+ read: "Read",
6
+ bash: "Bash",
7
+ powershell: "PowerShell",
8
+ edit: "Edit",
9
+ write: "Write",
10
+ grep: "Grep",
11
+ find: "Find",
12
+ ls: "LS",
13
+ };
14
+
15
+ export const MANAGED_TOOL_NAMES = new Set(Object.keys(TOOL_LABELS));
16
+ export const MERGEABLE_TOOL_NAMES = new Set(["read", "grep", "find", "ls"]);
17
+
18
+ export function isManagedTool(name: string): boolean {
19
+ return MANAGED_TOOL_NAMES.has(name);
20
+ }
21
+
22
+ export function isMergeableTool(name: string): boolean {
23
+ return MERGEABLE_TOOL_NAMES.has(name);
24
+ }
25
+
26
+ export function isShellTool(name: string): boolean {
27
+ return name === "bash" || name === "powershell";
28
+ }
29
+
30
+ /**
31
+ * The skill name when a read loads a skill (`…/<name>/SKILL.md`), else undefined.
32
+ * Such reads get their own `● [Skill] (name)` row instead of joining a read group.
33
+ */
34
+ export function skillReadName(name: string, args: Record<string, unknown>): string | undefined {
35
+ if (name !== "read") return undefined;
36
+ const parts = str(args.file_path ?? args.path).replace(/\\/g, "/").split("/").filter(Boolean);
37
+ if (parts.at(-1) !== "SKILL.md") return undefined;
38
+ return parts.at(-2) ?? "SKILL.md";
39
+ }
40
+
41
+ export function resultText(result: ToolResultSnapshot | undefined): string {
42
+ if (!result) return "";
43
+ return sanitizeText(
44
+ result.content
45
+ .map((block) => (block.type === "text" ? (block.text ?? "") : ""))
46
+ .join("\n"),
47
+ ).trim();
48
+ }
49
+
50
+ /**
51
+ * pi's texts for a call cut short by an interrupt: `Operation aborted` (the agent loop, the built-in
52
+ * tools, and the interactive mode for calls whose arguments were still streaming), `Command aborted`
53
+ * (appended under a command's output), a bare `aborted`, and `Aborted after N retry attempts`.
54
+ */
55
+ const INTERRUPT_LINE = /^(?:(?:operation|command|request)(?: was)? )?aborted(?: after \d+ retry attempts?)?\.?$/i;
56
+
57
+ /**
58
+ * Whether an error result only says the call was interrupted (DESIGN.md §9): the user stopped the
59
+ * run, the tool did not fail. Only the last line counts, so a command's own output above
60
+ * pi's `Command aborted` does not matter.
61
+ */
62
+ export function isInterrupted(result: ToolResultSnapshot | undefined): boolean {
63
+ if (!result?.isError) return false;
64
+ const lines = resultText(result).split("\n");
65
+ const last = lines[lines.length - 1]?.trim() ?? "";
66
+ return INTERRUPT_LINE.test(last);
67
+ }
68
+
69
+ /** An error result that is a real failure, not an interrupt. */
70
+ export function isFailed(result: ToolResultSnapshot | undefined): boolean {
71
+ return result?.isError === true && !isInterrupted(result);
72
+ }
73
+
74
+ export function resultImageCount(result: ToolResultSnapshot | undefined): number {
75
+ return result?.content.filter((block) => block.type === "image").length ?? 0;
76
+ }
77
+
78
+ function details(result: ToolResultSnapshot | undefined): Record<string, unknown> {
79
+ const value = result?.details;
80
+ return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : {};
81
+ }
82
+
83
+ function truncationTotal(result: ToolResultSnapshot | undefined): number | undefined {
84
+ const value = details(result).truncation;
85
+ if (typeof value !== "object" || value === null) return undefined;
86
+ const totalLines = (value as { totalLines?: unknown }).totalLines;
87
+ return typeof totalLines === "number" && Number.isSafeInteger(totalLines) ? totalLines : undefined;
88
+ }
89
+
90
+ function truncated(result: ToolResultSnapshot | undefined): boolean {
91
+ const value = details(result).truncation;
92
+ return typeof value === "object" && value !== null && (value as { truncated?: unknown }).truncated === true;
93
+ }
94
+
95
+ export function diffStats(diff: string): { added: number; removed: number } {
96
+ let added = 0;
97
+ let removed = 0;
98
+ for (const line of diff.split("\n")) {
99
+ if (line.startsWith("+++") || line.startsWith("---")) continue;
100
+ if (line.startsWith("+")) added++;
101
+ else if (line.startsWith("-")) removed++;
102
+ }
103
+ return { added, removed };
104
+ }
105
+
106
+ export function callDetail(name: string, args: Record<string, unknown>, cwd: string): string {
107
+ const path = displayPath(str(args.file_path ?? args.path), cwd);
108
+ switch (name) {
109
+ case "read":
110
+ return path + lineRange(args);
111
+ case "edit":
112
+ case "write":
113
+ return path;
114
+ case "bash":
115
+ case "powershell":
116
+ return shellDetail(args);
117
+ case "grep": {
118
+ const pattern = str(args.pattern);
119
+ return pattern ? `/${pattern}/${path ? ` in ${path}` : ""}` : path;
120
+ }
121
+ case "find": {
122
+ const pattern = str(args.pattern);
123
+ return pattern && path ? `${pattern} in ${path}` : pattern || path;
124
+ }
125
+ case "ls":
126
+ return path || ".";
127
+ default:
128
+ return "";
129
+ }
130
+ }
131
+
132
+ /** Widest a raw command may get in a row header; the rest is cut from the middle. */
133
+ export const SHELL_COMMAND_MAX_WIDTH = 72;
134
+
135
+ /** The model's description when it gave one, otherwise a width-capped command. */
136
+ export function shellDetail(args: Record<string, unknown>): string {
137
+ const description = sanitizeText(str(args.description)).replace(/\s+/g, " ").trim();
138
+ if (description) return description;
139
+ return shellCommandSummary(str(args.command));
140
+ }
141
+
142
+ export function shellCommandSummary(command: string, maxWidth = SHELL_COMMAND_MAX_WIDTH): string {
143
+ const lines = sanitizeText(command).replace(/\r\n?/g, "\n").trim().split("\n");
144
+ const head = clipMiddle((lines[0] ?? "").trim(), maxWidth);
145
+ return lines.length > 1 ? `${head} … (+${lines.length - 1} lines)` : head;
146
+ }
147
+
148
+ /** Full command split into display lines, for the expanded view. */
149
+ export function shellCommandLines(args: Record<string, unknown>): string[] {
150
+ const command = sanitizeText(str(args.command)).replace(/\r\n?/g, "\n").replace(/^\n+|\s+$/g, "");
151
+ return command ? command.split("\n").map((line) => line.trimEnd()) : [];
152
+ }
153
+
154
+ /** Stable identity for "how many distinct files did this group touch?". */
155
+ export function targetKey(name: string, args: Record<string, unknown>, fallback: string): string {
156
+ if (name === "read" || name === "edit" || name === "write" || name === "ls") {
157
+ const path = str(args.file_path ?? args.path);
158
+ return path || fallback;
159
+ }
160
+ if (name === "grep" || name === "find") {
161
+ const pattern = str(args.pattern);
162
+ const path = str(args.path);
163
+ return `${pattern}\u0000${path}` || fallback;
164
+ }
165
+ return fallback;
166
+ }
167
+
168
+ export function summarizeResult(name: string, result: ToolResultSnapshot, args: Record<string, unknown>): string {
169
+ const text = resultText(result);
170
+ switch (name) {
171
+ case "read": {
172
+ if (resultImageCount(result) > 0) {
173
+ // pi (1.6.0 on) names the model here when it has no image input and only saw a placeholder.
174
+ return details(result).imageUnsupportedByModel ? "image · model has no image input" : "image";
175
+ }
176
+ const lines = truncationTotal(result) ?? countLines(text);
177
+ return plural(lines, "line") + (truncated(result) ? " · truncated" : "");
178
+ }
179
+ case "bash":
180
+ case "powershell": {
181
+ const lines = truncationTotal(result) ?? countLines(text);
182
+ const exit = result.isError ? /Command exited with code (\d+)/.exec(text)?.[1] : undefined;
183
+ const head = result.isError ? (exit ? `Failed (exit ${exit})` : "Failed") : "Done";
184
+ return `${head} · ${lines === 0 ? "no output" : plural(lines, "line")}`;
185
+ }
186
+ case "edit": {
187
+ const diff = details(result).diff;
188
+ if (typeof diff !== "string") return result.isError ? "Failed" : "Edited";
189
+ const { added, removed } = diffStats(diff);
190
+ return `+${added} −${removed}`;
191
+ }
192
+ case "write": {
193
+ const content = str(args.content);
194
+ return `${plural(countLines(content), "line")} written`;
195
+ }
196
+ case "grep": {
197
+ if (text === "No matches found") return "No matches";
198
+ const files = new Set<string>();
199
+ let matches = 0;
200
+ for (const line of text.split("\n")) {
201
+ const match = /^(.+?):\d+: /.exec(line);
202
+ if (!match) continue;
203
+ matches++;
204
+ files.add(match[1]!);
205
+ }
206
+ return `${plural(matches, "match", "matches")} in ${plural(files.size, "file")}`;
207
+ }
208
+ case "find":
209
+ return text === "No files found matching pattern" ? "No files" : plural(countLines(text), "file");
210
+ case "ls":
211
+ return text === "(empty directory)" ? "Empty" : plural(countLines(text), "entry", "entries");
212
+ default:
213
+ return text ? plural(countLines(text), "line") : "Done";
214
+ }
215
+ }
216
+
217
+ export function summarizeGeneric(result: ToolResultSnapshot | undefined): string {
218
+ const text = resultText(result);
219
+ const lines = text.split("\n").filter((line) => line.trim());
220
+ const head = sanitizeText((lines[0] ?? "").replace(/^#+\s+/, ""));
221
+ const counts = lines.length ? plural(lines.length, "line") : "Done";
222
+ return counts + (head ? ` · ${head}` : "");
223
+ }
224
+
225
+ /** Last meaningful lines of a result, used for error tails and expanded previews. */
226
+ export function resultLines(result: ToolResultSnapshot | undefined, max: number, keep: "head" | "tail" = "tail"): string[] {
227
+ const lines = resultText(result)
228
+ .split("\n")
229
+ .map((line) => line.trimEnd())
230
+ .filter((line) => line.trim() !== "");
231
+ if (lines.length <= max) return lines;
232
+ return keep === "head" ? lines.slice(0, max) : lines.slice(-max);
233
+ }
234
+
235
+ export function resultLineTotal(result: ToolResultSnapshot | undefined): number {
236
+ return resultText(result).split("\n").filter((line) => line.trim() !== "").length;
237
+ }
package/src/types.ts CHANGED
@@ -1,13 +1,13 @@
1
- export interface ToolContentBlock {
2
- type: string;
3
- text?: string;
4
- data?: string;
5
- mimeType?: string;
6
- }
7
-
8
- export interface ToolResultSnapshot {
9
- content: ToolContentBlock[];
10
- details?: unknown;
11
- isError: boolean;
12
- durationMs?: number;
13
- }
1
+ export interface ToolContentBlock {
2
+ type: string;
3
+ text?: string;
4
+ data?: string;
5
+ mimeType?: string;
6
+ }
7
+
8
+ export interface ToolResultSnapshot {
9
+ content: ToolContentBlock[];
10
+ details?: unknown;
11
+ isError: boolean;
12
+ durationMs?: number;
13
+ }