@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.
- package/README.md +327 -327
- package/package.json +1 -1
- package/src/format.ts +165 -165
- package/src/gutter.ts +236 -236
- package/src/index.ts +660 -660
- package/src/segment.ts +311 -311
- package/src/shell-description.ts +75 -75
- package/src/thinking.ts +524 -524
- package/src/timeline.ts +881 -881
- package/src/tool-lines.ts +173 -173
- package/src/tool-row.ts +387 -387
- package/src/tool-summary.ts +237 -237
- package/src/types.ts +13 -13
package/src/segment.ts
CHANGED
|
@@ -1,311 +1,311 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pure pieces of the fold model (fold-more.md §5): how a content block of an assistant message
|
|
3
|
-
* takes part in a segment, which shell commands count as changes, and the summary line text.
|
|
4
|
-
* Streaming and seed both go through these functions, so a resumed session folds the same way.
|
|
5
|
-
*/
|
|
6
|
-
import { argsOf, formatDuration, plural, str, thoughtLabel } from "./format.js";
|
|
7
|
-
import { isMergeableTool, isShellTool, skillReadName } from "./tool-summary.js";
|
|
8
|
-
|
|
9
|
-
export interface FoldPolicy {
|
|
10
|
-
/** Fold on at all; off leaves rows and read-only groups exactly as before. */
|
|
11
|
-
enabled: boolean;
|
|
12
|
-
/** Fewest items a segment needs before it folds into one summary line. */
|
|
13
|
-
minItems: number;
|
|
14
|
-
/** Thinking runs join segments; false (`thinking.lines = 0`) makes them text boundaries. */
|
|
15
|
-
thinking: boolean;
|
|
16
|
-
/** Whether this plugin draws the tool's row; any other tool is an opaque boundary. */
|
|
17
|
-
manage: (name: string) => boolean;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export const FOLD_OFF: FoldPolicy = {
|
|
21
|
-
enabled: false,
|
|
22
|
-
minItems: 2,
|
|
23
|
-
thinking: true,
|
|
24
|
-
manage: () => false,
|
|
25
|
-
};
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* - `fold`: joins the current segment;
|
|
29
|
-
* - `text`: visible text (or a thinking run when thinking does not fold) ends the segment;
|
|
30
|
-
* - `mutation`: edit/write or a changing command ends the segment and stands alone;
|
|
31
|
-
* - `opaque`: an unmanaged tool or a SKILL.md read ends the segment and draws itself as before;
|
|
32
|
-
* - `skip`: nothing on screen (empty text or thinking, unknown block types).
|
|
33
|
-
*/
|
|
34
|
-
export type BlockClass = "fold" | "text" | "mutation" | "opaque" | "skip";
|
|
35
|
-
|
|
36
|
-
interface BlockLike {
|
|
37
|
-
type?: unknown;
|
|
38
|
-
text?: unknown;
|
|
39
|
-
thinking?: unknown;
|
|
40
|
-
name?: unknown;
|
|
41
|
-
arguments?: unknown;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Classify one content block. `final` says whether a tool call's arguments are complete: until
|
|
46
|
-
* then a shell command or a read joins provisionally, because its arguments may still turn it
|
|
47
|
-
* into a change or a skill load (§5.2).
|
|
48
|
-
*/
|
|
49
|
-
export function classifyBlock(block: unknown, policy: FoldPolicy, final = true): BlockClass {
|
|
50
|
-
if (!block || typeof block !== "object") return "skip";
|
|
51
|
-
const value = block as BlockLike;
|
|
52
|
-
if (value.type === "text") {
|
|
53
|
-
return typeof value.text === "string" && value.text.trim() ? "text" : "skip";
|
|
54
|
-
}
|
|
55
|
-
if (value.type === "thinking") {
|
|
56
|
-
if (!thinkingText(value).trim()) return "skip";
|
|
57
|
-
return policy.thinking ? "fold" : "text";
|
|
58
|
-
}
|
|
59
|
-
if (value.type === "toolCall") {
|
|
60
|
-
const name = typeof value.name === "string" ? value.name : "";
|
|
61
|
-
if (!name || !policy.manage(name)) return "opaque";
|
|
62
|
-
const args = argsOf(value.arguments);
|
|
63
|
-
if (isShellTool(name)) {
|
|
64
|
-
if (!final) return "fold";
|
|
65
|
-
return isMutatingShell(str(args.command)) ? "mutation" : "fold";
|
|
66
|
-
}
|
|
67
|
-
if (isMergeableTool(name)) {
|
|
68
|
-
if (final && skillReadName(name, args) !== undefined) return "opaque";
|
|
69
|
-
return "fold";
|
|
70
|
-
}
|
|
71
|
-
// edit, write, and any other managed tool that changes things.
|
|
72
|
-
return "mutation";
|
|
73
|
-
}
|
|
74
|
-
return "skip";
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function thinkingText(block: BlockLike): string {
|
|
78
|
-
return typeof block.thinking === "string" ? block.thinking : typeof block.text === "string" ? block.text : "";
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/** A thinking run as pi draws it: consecutive thinking blocks with at least one non-empty block. */
|
|
82
|
-
export interface ThinkingRun {
|
|
83
|
-
/** pi's run index: counts only runs with text, the same way pi numbers its click overrides. */
|
|
84
|
-
runIndex: number;
|
|
85
|
-
text: string;
|
|
86
|
-
firstBlock: number;
|
|
87
|
-
lastBlock: number;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** pi's grouping of thinking blocks into runs, including which runs get no index (all empty). */
|
|
91
|
-
export function thinkingRuns(content: unknown): ThinkingRun[] {
|
|
92
|
-
if (!Array.isArray(content)) return [];
|
|
93
|
-
const runs: ThinkingRun[] = [];
|
|
94
|
-
let runIndex = 0;
|
|
95
|
-
for (let index = 0; index < content.length; index++) {
|
|
96
|
-
if (!isThinkingBlock(content[index])) continue;
|
|
97
|
-
const first = index;
|
|
98
|
-
const parts: string[] = [];
|
|
99
|
-
for (; index < content.length && isThinkingBlock(content[index]); index++) {
|
|
100
|
-
const text = thinkingText(content[index] as BlockLike).trim();
|
|
101
|
-
if (text) parts.push(text);
|
|
102
|
-
}
|
|
103
|
-
index--;
|
|
104
|
-
if (parts.length === 0) continue;
|
|
105
|
-
runs.push({ runIndex: runIndex++, text: parts.join("\n\n"), firstBlock: first, lastBlock: index });
|
|
106
|
-
}
|
|
107
|
-
return runs;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
function isThinkingBlock(value: unknown): boolean {
|
|
111
|
-
return Boolean(value && typeof value === "object" && (value as BlockLike).type === "thinking");
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/** Anchor key of a thinking run: persisted data has the message timestamp but no message id. */
|
|
115
|
-
export function thinkingAnchor(timestamp: number, runIndex: number): string {
|
|
116
|
-
return `msg:${timestamp}#${runIndex}`;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// ---------------------------------------------------------------------------
|
|
120
|
-
// isMutatingShell
|
|
121
|
-
// ---------------------------------------------------------------------------
|
|
122
|
-
|
|
123
|
-
const GIT_CHANGES = new Set([
|
|
124
|
-
"commit", "push", "reset", "checkout", "merge", "rebase", "stash", "apply",
|
|
125
|
-
"switch", "restore", "clean", "rm", "mv", "cherry-pick", "revert", "pull", "am",
|
|
126
|
-
]);
|
|
127
|
-
|
|
128
|
-
const FILE_CHANGES = new Set([
|
|
129
|
-
"rm", "rmdir", "mv", "cp", "mkdir", "touch", "chmod", "chown", "ln", "unlink", "truncate", "tee",
|
|
130
|
-
// PowerShell cmdlets and the aliases cmd.exe users type.
|
|
131
|
-
"remove-item", "move-item", "copy-item", "new-item", "rename-item", "set-content", "add-content",
|
|
132
|
-
"clear-content", "out-file", "set-itemproperty", "ri", "mi", "cpi", "ni", "del", "erase", "rd",
|
|
133
|
-
"ren", "move", "copy", "md",
|
|
134
|
-
]);
|
|
135
|
-
|
|
136
|
-
const INSTALLERS: Record<string, Set<string>> = {
|
|
137
|
-
npm: new Set(["install", "i", "add", "remove", "rm", "uninstall", "un", "ci", "update", "up", "upgrade", "link"]),
|
|
138
|
-
pnpm: new Set(["install", "i", "add", "remove", "rm", "uninstall", "un", "update", "up", "upgrade", "link"]),
|
|
139
|
-
yarn: new Set(["install", "add", "remove", "upgrade", "up", "link"]),
|
|
140
|
-
bun: new Set(["install", "i", "add", "remove", "rm", "update", "upgrade", "link"]),
|
|
141
|
-
pip: new Set(["install", "uninstall"]),
|
|
142
|
-
pip3: new Set(["install", "uninstall"]),
|
|
143
|
-
uv: new Set(["add", "remove", "sync", "pip"]),
|
|
144
|
-
cargo: new Set(["install", "uninstall", "add", "remove"]),
|
|
145
|
-
go: new Set(["get", "install"]),
|
|
146
|
-
apt: new Set(["install", "remove", "purge", "upgrade"]),
|
|
147
|
-
"apt-get": new Set(["install", "remove", "purge", "upgrade"]),
|
|
148
|
-
brew: new Set(["install", "uninstall", "upgrade"]),
|
|
149
|
-
winget: new Set(["install", "uninstall", "upgrade"]),
|
|
150
|
-
choco: new Set(["install", "uninstall", "upgrade"]),
|
|
151
|
-
scoop: new Set(["install", "uninstall", "update"]),
|
|
152
|
-
};
|
|
153
|
-
|
|
154
|
-
/** Words in front of the real command that do not change what it is. */
|
|
155
|
-
const PREFIXES = new Set(["sudo", "command", "builtin", "exec", "time", "nice", "nohup", "env", "xargs", "doas"]);
|
|
156
|
-
|
|
157
|
-
/** Output targets that are not files. */
|
|
158
|
-
const NULL_TARGETS = /^(?:\/dev\/(?:null|stdout|stderr|tty)|\$null|nul)$/i;
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* Conservative test for a shell command that changes files, git state, or installed packages
|
|
162
|
-
* (fold-more.md §5.2). A false positive only shows one more row, a false negative hides a change
|
|
163
|
-
* inside a summary, so anything that looks like a change counts.
|
|
164
|
-
*/
|
|
165
|
-
export function isMutatingShell(command: string): boolean {
|
|
166
|
-
// `bash -c "…"` / `powershell -Command '…'`: the quoted script is the real command.
|
|
167
|
-
for (const match of command.matchAll(NESTED_SCRIPT)) {
|
|
168
|
-
const script = match[2];
|
|
169
|
-
if (script && isMutatingShell(script)) return true;
|
|
170
|
-
}
|
|
171
|
-
const source = stripQuoted(command);
|
|
172
|
-
if (hasFileRedirect(source)) return true;
|
|
173
|
-
for (const segment of source.split(/\|\||&&|[;|&\n()`]|\$\(/)) {
|
|
174
|
-
const words = segment.trim().split(/\s+/).filter(Boolean);
|
|
175
|
-
let index = 0;
|
|
176
|
-
while (index < words.length) {
|
|
177
|
-
const word = words[index]!;
|
|
178
|
-
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word) || word.startsWith("-") || PREFIXES.has(commandName(word))) {
|
|
179
|
-
index++;
|
|
180
|
-
continue;
|
|
181
|
-
}
|
|
182
|
-
break;
|
|
183
|
-
}
|
|
184
|
-
const name = commandName(words[index] ?? "");
|
|
185
|
-
if (!name) continue;
|
|
186
|
-
const rest = words.slice(index + 1);
|
|
187
|
-
if (FILE_CHANGES.has(name)) return true;
|
|
188
|
-
if (name === "find") {
|
|
189
|
-
if (rest.includes("-delete")) return true;
|
|
190
|
-
const exec = rest.findIndex((word) => word === "-exec" || word === "-execdir");
|
|
191
|
-
if (exec >= 0 && FILE_CHANGES.has(commandName(rest[exec + 1] ?? ""))) return true;
|
|
192
|
-
}
|
|
193
|
-
if ((name === "sed" || name === "perl") && rest.some((word) => /^-[A-Za-z]*i/.test(word) || word.startsWith("--in-place"))) {
|
|
194
|
-
return true;
|
|
195
|
-
}
|
|
196
|
-
if (name === "git") {
|
|
197
|
-
const sub = rest.find((word, position) => !word.startsWith("-") && !isGitOptionValue(rest, position));
|
|
198
|
-
if (sub && GIT_CHANGES.has(sub.toLowerCase())) return true;
|
|
199
|
-
}
|
|
200
|
-
const installer = INSTALLERS[name];
|
|
201
|
-
if (installer) {
|
|
202
|
-
const sub = rest.find((word) => !word.startsWith("-"));
|
|
203
|
-
if (sub ? installer.has(sub.toLowerCase()) : name === "yarn" || name === "bun") return true;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
return false;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/** `git -C dir status`: the word after -C / -c is the option's value, not the subcommand. */
|
|
210
|
-
function isGitOptionValue(words: string[], position: number): boolean {
|
|
211
|
-
const previous = words[position - 1];
|
|
212
|
-
return previous === "-C" || previous === "-c" || previous === "--git-dir" || previous === "--work-tree";
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
function commandName(word: string): string {
|
|
216
|
-
const base = word.replace(/\\/g, "/").split("/").pop() ?? "";
|
|
217
|
-
return base.replace(/\.(?:exe|cmd|bat)$/i, "").toLowerCase();
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
const NESTED_SCRIPT = /\b(?:sh|bash|zsh|dash|pwsh|powershell|cmd)(?:\.exe)?\s+(?:-{1,2}\w+\s+)*?(?:-c|-Command|\/c)\s+(['"])([\s\S]*?)\1/gi;
|
|
221
|
-
|
|
222
|
-
/**
|
|
223
|
-
* Replace quoted strings and heredoc bodies with a placeholder so operators inside them do not
|
|
224
|
-
* count. The rest of a heredoc's first line (`cat <<EOF > out`) stays.
|
|
225
|
-
*/
|
|
226
|
-
function stripQuoted(command: string): string {
|
|
227
|
-
return command
|
|
228
|
-
.replace(/<<-?\s*['"]?(\w+)['"]?([^\n]*)\n(?:[\s\S]*?\n)?[ \t]*\1[ \t]*(?=\n|$)/g, (_match, _tag, rest: string) => ` Q ${rest}`)
|
|
229
|
-
.replace(/'[^']*'/g, "Q")
|
|
230
|
-
.replace(/"(?:\\.|[^"\\])*"/g, "Q");
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
function hasFileRedirect(source: string): boolean {
|
|
234
|
-
const pattern = /(?:^|[^<>=-])(?:\d|&)?>>?\|?\s*([^\s;|&()<>]+)?/g;
|
|
235
|
-
for (const match of source.matchAll(pattern)) {
|
|
236
|
-
const target = match[1];
|
|
237
|
-
if (!target) continue;
|
|
238
|
-
// 2>&1, >&2: duplicating a descriptor writes no file.
|
|
239
|
-
if (target.startsWith("&")) continue;
|
|
240
|
-
if (NULL_TARGETS.test(target)) continue;
|
|
241
|
-
return true;
|
|
242
|
-
}
|
|
243
|
-
return false;
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
// ---------------------------------------------------------------------------
|
|
247
|
-
// Summary line
|
|
248
|
-
// ---------------------------------------------------------------------------
|
|
249
|
-
|
|
250
|
-
export interface FoldStats {
|
|
251
|
-
thinking: {
|
|
252
|
-
count: number;
|
|
253
|
-
/** Summed `durationMs` of the messages with thinking; undefined when none is known. */
|
|
254
|
-
ms?: number;
|
|
255
|
-
active: boolean;
|
|
256
|
-
};
|
|
257
|
-
commands: { count: number; active: boolean };
|
|
258
|
-
reads: number;
|
|
259
|
-
searches: number;
|
|
260
|
-
lists: number;
|
|
261
|
-
/** A read, search, or listing is still running. */
|
|
262
|
-
exploreActive: boolean;
|
|
263
|
-
tools: number;
|
|
264
|
-
/** Tools that failed; interrupted ones are counted apart and are not failures (DESIGN.md §9). */
|
|
265
|
-
failed: number;
|
|
266
|
-
interrupted: number;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
/**
|
|
270
|
-
* The parts of a segment's summary line, without the failure count. Each kind takes its own
|
|
271
|
-
* tense: `Thinking 12s · Ran 2 commands · Read 5 files` (fold-more.md §5.4).
|
|
272
|
-
*/
|
|
273
|
-
export function summaryParts(stats: FoldStats): string[] {
|
|
274
|
-
const parts: string[] = [];
|
|
275
|
-
const { thinking, commands } = stats;
|
|
276
|
-
if (thinking.count > 0) {
|
|
277
|
-
if (thinking.active) {
|
|
278
|
-
parts.push(thinking.ms !== undefined && thinking.ms >= 1_000 ? `Thinking ${formatDuration(thinking.ms)}` : "Thinking");
|
|
279
|
-
} else if (thinking.ms !== undefined) {
|
|
280
|
-
// Same wording as the list items under it (`Thought for 1.5s`).
|
|
281
|
-
parts.push(thoughtLabel(thinking.ms));
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
if (commands.count > 0) {
|
|
285
|
-
parts.push(`${commands.active ? "Running" : "Ran"} ${plural(commands.count, "command")}`);
|
|
286
|
-
}
|
|
287
|
-
const explore = stats.exploreActive;
|
|
288
|
-
if (stats.reads > 0) {
|
|
289
|
-
parts.push(`${explore ? "Reading" : "Read"} ${plural(stats.reads, "file")}`);
|
|
290
|
-
if (stats.searches > 0) parts.push(plural(stats.searches, "search", "searches"));
|
|
291
|
-
if (stats.lists > 0) parts.push(plural(stats.lists, "dir"));
|
|
292
|
-
} else if (stats.searches > 0) {
|
|
293
|
-
parts.push(`${explore ? "Searching" : "Searched"} ${plural(stats.searches, "pattern")}`);
|
|
294
|
-
if (stats.lists > 0) parts.push(plural(stats.lists, "dir"));
|
|
295
|
-
} else if (stats.lists > 0) {
|
|
296
|
-
parts.push(`${explore ? "Listing" : "Listed"} ${plural(stats.lists, "dir")}`);
|
|
297
|
-
}
|
|
298
|
-
// Only thinking with no known duration (an old session): still say what the line stands for.
|
|
299
|
-
if (parts.length === 0) parts.push(thinking.active ? "Thinking" : "Thought");
|
|
300
|
-
return parts;
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
export function summaryText(stats: FoldStats): string {
|
|
304
|
-
return summaryParts(stats).join(" · ");
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
/** Column-0 marker of a summary line: none, `!` when some tools failed, `×` when all did. */
|
|
308
|
-
export function summaryMarker(stats: FoldStats): " " | "!" | "×" {
|
|
309
|
-
if (stats.failed === 0) return " ";
|
|
310
|
-
return stats.failed >= stats.tools ? "×" : "!";
|
|
311
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Pure pieces of the fold model (fold-more.md §5): how a content block of an assistant message
|
|
3
|
+
* takes part in a segment, which shell commands count as changes, and the summary line text.
|
|
4
|
+
* Streaming and seed both go through these functions, so a resumed session folds the same way.
|
|
5
|
+
*/
|
|
6
|
+
import { argsOf, formatDuration, plural, str, thoughtLabel } from "./format.js";
|
|
7
|
+
import { isMergeableTool, isShellTool, skillReadName } from "./tool-summary.js";
|
|
8
|
+
|
|
9
|
+
export interface FoldPolicy {
|
|
10
|
+
/** Fold on at all; off leaves rows and read-only groups exactly as before. */
|
|
11
|
+
enabled: boolean;
|
|
12
|
+
/** Fewest items a segment needs before it folds into one summary line. */
|
|
13
|
+
minItems: number;
|
|
14
|
+
/** Thinking runs join segments; false (`thinking.lines = 0`) makes them text boundaries. */
|
|
15
|
+
thinking: boolean;
|
|
16
|
+
/** Whether this plugin draws the tool's row; any other tool is an opaque boundary. */
|
|
17
|
+
manage: (name: string) => boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const FOLD_OFF: FoldPolicy = {
|
|
21
|
+
enabled: false,
|
|
22
|
+
minItems: 2,
|
|
23
|
+
thinking: true,
|
|
24
|
+
manage: () => false,
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* - `fold`: joins the current segment;
|
|
29
|
+
* - `text`: visible text (or a thinking run when thinking does not fold) ends the segment;
|
|
30
|
+
* - `mutation`: edit/write or a changing command ends the segment and stands alone;
|
|
31
|
+
* - `opaque`: an unmanaged tool or a SKILL.md read ends the segment and draws itself as before;
|
|
32
|
+
* - `skip`: nothing on screen (empty text or thinking, unknown block types).
|
|
33
|
+
*/
|
|
34
|
+
export type BlockClass = "fold" | "text" | "mutation" | "opaque" | "skip";
|
|
35
|
+
|
|
36
|
+
interface BlockLike {
|
|
37
|
+
type?: unknown;
|
|
38
|
+
text?: unknown;
|
|
39
|
+
thinking?: unknown;
|
|
40
|
+
name?: unknown;
|
|
41
|
+
arguments?: unknown;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Classify one content block. `final` says whether a tool call's arguments are complete: until
|
|
46
|
+
* then a shell command or a read joins provisionally, because its arguments may still turn it
|
|
47
|
+
* into a change or a skill load (§5.2).
|
|
48
|
+
*/
|
|
49
|
+
export function classifyBlock(block: unknown, policy: FoldPolicy, final = true): BlockClass {
|
|
50
|
+
if (!block || typeof block !== "object") return "skip";
|
|
51
|
+
const value = block as BlockLike;
|
|
52
|
+
if (value.type === "text") {
|
|
53
|
+
return typeof value.text === "string" && value.text.trim() ? "text" : "skip";
|
|
54
|
+
}
|
|
55
|
+
if (value.type === "thinking") {
|
|
56
|
+
if (!thinkingText(value).trim()) return "skip";
|
|
57
|
+
return policy.thinking ? "fold" : "text";
|
|
58
|
+
}
|
|
59
|
+
if (value.type === "toolCall") {
|
|
60
|
+
const name = typeof value.name === "string" ? value.name : "";
|
|
61
|
+
if (!name || !policy.manage(name)) return "opaque";
|
|
62
|
+
const args = argsOf(value.arguments);
|
|
63
|
+
if (isShellTool(name)) {
|
|
64
|
+
if (!final) return "fold";
|
|
65
|
+
return isMutatingShell(str(args.command)) ? "mutation" : "fold";
|
|
66
|
+
}
|
|
67
|
+
if (isMergeableTool(name)) {
|
|
68
|
+
if (final && skillReadName(name, args) !== undefined) return "opaque";
|
|
69
|
+
return "fold";
|
|
70
|
+
}
|
|
71
|
+
// edit, write, and any other managed tool that changes things.
|
|
72
|
+
return "mutation";
|
|
73
|
+
}
|
|
74
|
+
return "skip";
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function thinkingText(block: BlockLike): string {
|
|
78
|
+
return typeof block.thinking === "string" ? block.thinking : typeof block.text === "string" ? block.text : "";
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A thinking run as pi draws it: consecutive thinking blocks with at least one non-empty block. */
|
|
82
|
+
export interface ThinkingRun {
|
|
83
|
+
/** pi's run index: counts only runs with text, the same way pi numbers its click overrides. */
|
|
84
|
+
runIndex: number;
|
|
85
|
+
text: string;
|
|
86
|
+
firstBlock: number;
|
|
87
|
+
lastBlock: number;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** pi's grouping of thinking blocks into runs, including which runs get no index (all empty). */
|
|
91
|
+
export function thinkingRuns(content: unknown): ThinkingRun[] {
|
|
92
|
+
if (!Array.isArray(content)) return [];
|
|
93
|
+
const runs: ThinkingRun[] = [];
|
|
94
|
+
let runIndex = 0;
|
|
95
|
+
for (let index = 0; index < content.length; index++) {
|
|
96
|
+
if (!isThinkingBlock(content[index])) continue;
|
|
97
|
+
const first = index;
|
|
98
|
+
const parts: string[] = [];
|
|
99
|
+
for (; index < content.length && isThinkingBlock(content[index]); index++) {
|
|
100
|
+
const text = thinkingText(content[index] as BlockLike).trim();
|
|
101
|
+
if (text) parts.push(text);
|
|
102
|
+
}
|
|
103
|
+
index--;
|
|
104
|
+
if (parts.length === 0) continue;
|
|
105
|
+
runs.push({ runIndex: runIndex++, text: parts.join("\n\n"), firstBlock: first, lastBlock: index });
|
|
106
|
+
}
|
|
107
|
+
return runs;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function isThinkingBlock(value: unknown): boolean {
|
|
111
|
+
return Boolean(value && typeof value === "object" && (value as BlockLike).type === "thinking");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Anchor key of a thinking run: persisted data has the message timestamp but no message id. */
|
|
115
|
+
export function thinkingAnchor(timestamp: number, runIndex: number): string {
|
|
116
|
+
return `msg:${timestamp}#${runIndex}`;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
// isMutatingShell
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
const GIT_CHANGES = new Set([
|
|
124
|
+
"commit", "push", "reset", "checkout", "merge", "rebase", "stash", "apply",
|
|
125
|
+
"switch", "restore", "clean", "rm", "mv", "cherry-pick", "revert", "pull", "am",
|
|
126
|
+
]);
|
|
127
|
+
|
|
128
|
+
const FILE_CHANGES = new Set([
|
|
129
|
+
"rm", "rmdir", "mv", "cp", "mkdir", "touch", "chmod", "chown", "ln", "unlink", "truncate", "tee",
|
|
130
|
+
// PowerShell cmdlets and the aliases cmd.exe users type.
|
|
131
|
+
"remove-item", "move-item", "copy-item", "new-item", "rename-item", "set-content", "add-content",
|
|
132
|
+
"clear-content", "out-file", "set-itemproperty", "ri", "mi", "cpi", "ni", "del", "erase", "rd",
|
|
133
|
+
"ren", "move", "copy", "md",
|
|
134
|
+
]);
|
|
135
|
+
|
|
136
|
+
const INSTALLERS: Record<string, Set<string>> = {
|
|
137
|
+
npm: new Set(["install", "i", "add", "remove", "rm", "uninstall", "un", "ci", "update", "up", "upgrade", "link"]),
|
|
138
|
+
pnpm: new Set(["install", "i", "add", "remove", "rm", "uninstall", "un", "update", "up", "upgrade", "link"]),
|
|
139
|
+
yarn: new Set(["install", "add", "remove", "upgrade", "up", "link"]),
|
|
140
|
+
bun: new Set(["install", "i", "add", "remove", "rm", "update", "upgrade", "link"]),
|
|
141
|
+
pip: new Set(["install", "uninstall"]),
|
|
142
|
+
pip3: new Set(["install", "uninstall"]),
|
|
143
|
+
uv: new Set(["add", "remove", "sync", "pip"]),
|
|
144
|
+
cargo: new Set(["install", "uninstall", "add", "remove"]),
|
|
145
|
+
go: new Set(["get", "install"]),
|
|
146
|
+
apt: new Set(["install", "remove", "purge", "upgrade"]),
|
|
147
|
+
"apt-get": new Set(["install", "remove", "purge", "upgrade"]),
|
|
148
|
+
brew: new Set(["install", "uninstall", "upgrade"]),
|
|
149
|
+
winget: new Set(["install", "uninstall", "upgrade"]),
|
|
150
|
+
choco: new Set(["install", "uninstall", "upgrade"]),
|
|
151
|
+
scoop: new Set(["install", "uninstall", "update"]),
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
/** Words in front of the real command that do not change what it is. */
|
|
155
|
+
const PREFIXES = new Set(["sudo", "command", "builtin", "exec", "time", "nice", "nohup", "env", "xargs", "doas"]);
|
|
156
|
+
|
|
157
|
+
/** Output targets that are not files. */
|
|
158
|
+
const NULL_TARGETS = /^(?:\/dev\/(?:null|stdout|stderr|tty)|\$null|nul)$/i;
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Conservative test for a shell command that changes files, git state, or installed packages
|
|
162
|
+
* (fold-more.md §5.2). A false positive only shows one more row, a false negative hides a change
|
|
163
|
+
* inside a summary, so anything that looks like a change counts.
|
|
164
|
+
*/
|
|
165
|
+
export function isMutatingShell(command: string): boolean {
|
|
166
|
+
// `bash -c "…"` / `powershell -Command '…'`: the quoted script is the real command.
|
|
167
|
+
for (const match of command.matchAll(NESTED_SCRIPT)) {
|
|
168
|
+
const script = match[2];
|
|
169
|
+
if (script && isMutatingShell(script)) return true;
|
|
170
|
+
}
|
|
171
|
+
const source = stripQuoted(command);
|
|
172
|
+
if (hasFileRedirect(source)) return true;
|
|
173
|
+
for (const segment of source.split(/\|\||&&|[;|&\n()`]|\$\(/)) {
|
|
174
|
+
const words = segment.trim().split(/\s+/).filter(Boolean);
|
|
175
|
+
let index = 0;
|
|
176
|
+
while (index < words.length) {
|
|
177
|
+
const word = words[index]!;
|
|
178
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word) || word.startsWith("-") || PREFIXES.has(commandName(word))) {
|
|
179
|
+
index++;
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
const name = commandName(words[index] ?? "");
|
|
185
|
+
if (!name) continue;
|
|
186
|
+
const rest = words.slice(index + 1);
|
|
187
|
+
if (FILE_CHANGES.has(name)) return true;
|
|
188
|
+
if (name === "find") {
|
|
189
|
+
if (rest.includes("-delete")) return true;
|
|
190
|
+
const exec = rest.findIndex((word) => word === "-exec" || word === "-execdir");
|
|
191
|
+
if (exec >= 0 && FILE_CHANGES.has(commandName(rest[exec + 1] ?? ""))) return true;
|
|
192
|
+
}
|
|
193
|
+
if ((name === "sed" || name === "perl") && rest.some((word) => /^-[A-Za-z]*i/.test(word) || word.startsWith("--in-place"))) {
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
if (name === "git") {
|
|
197
|
+
const sub = rest.find((word, position) => !word.startsWith("-") && !isGitOptionValue(rest, position));
|
|
198
|
+
if (sub && GIT_CHANGES.has(sub.toLowerCase())) return true;
|
|
199
|
+
}
|
|
200
|
+
const installer = INSTALLERS[name];
|
|
201
|
+
if (installer) {
|
|
202
|
+
const sub = rest.find((word) => !word.startsWith("-"));
|
|
203
|
+
if (sub ? installer.has(sub.toLowerCase()) : name === "yarn" || name === "bun") return true;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** `git -C dir status`: the word after -C / -c is the option's value, not the subcommand. */
|
|
210
|
+
function isGitOptionValue(words: string[], position: number): boolean {
|
|
211
|
+
const previous = words[position - 1];
|
|
212
|
+
return previous === "-C" || previous === "-c" || previous === "--git-dir" || previous === "--work-tree";
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function commandName(word: string): string {
|
|
216
|
+
const base = word.replace(/\\/g, "/").split("/").pop() ?? "";
|
|
217
|
+
return base.replace(/\.(?:exe|cmd|bat)$/i, "").toLowerCase();
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const NESTED_SCRIPT = /\b(?:sh|bash|zsh|dash|pwsh|powershell|cmd)(?:\.exe)?\s+(?:-{1,2}\w+\s+)*?(?:-c|-Command|\/c)\s+(['"])([\s\S]*?)\1/gi;
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Replace quoted strings and heredoc bodies with a placeholder so operators inside them do not
|
|
224
|
+
* count. The rest of a heredoc's first line (`cat <<EOF > out`) stays.
|
|
225
|
+
*/
|
|
226
|
+
function stripQuoted(command: string): string {
|
|
227
|
+
return command
|
|
228
|
+
.replace(/<<-?\s*['"]?(\w+)['"]?([^\n]*)\n(?:[\s\S]*?\n)?[ \t]*\1[ \t]*(?=\n|$)/g, (_match, _tag, rest: string) => ` Q ${rest}`)
|
|
229
|
+
.replace(/'[^']*'/g, "Q")
|
|
230
|
+
.replace(/"(?:\\.|[^"\\])*"/g, "Q");
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function hasFileRedirect(source: string): boolean {
|
|
234
|
+
const pattern = /(?:^|[^<>=-])(?:\d|&)?>>?\|?\s*([^\s;|&()<>]+)?/g;
|
|
235
|
+
for (const match of source.matchAll(pattern)) {
|
|
236
|
+
const target = match[1];
|
|
237
|
+
if (!target) continue;
|
|
238
|
+
// 2>&1, >&2: duplicating a descriptor writes no file.
|
|
239
|
+
if (target.startsWith("&")) continue;
|
|
240
|
+
if (NULL_TARGETS.test(target)) continue;
|
|
241
|
+
return true;
|
|
242
|
+
}
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// ---------------------------------------------------------------------------
|
|
247
|
+
// Summary line
|
|
248
|
+
// ---------------------------------------------------------------------------
|
|
249
|
+
|
|
250
|
+
export interface FoldStats {
|
|
251
|
+
thinking: {
|
|
252
|
+
count: number;
|
|
253
|
+
/** Summed `durationMs` of the messages with thinking; undefined when none is known. */
|
|
254
|
+
ms?: number;
|
|
255
|
+
active: boolean;
|
|
256
|
+
};
|
|
257
|
+
commands: { count: number; active: boolean };
|
|
258
|
+
reads: number;
|
|
259
|
+
searches: number;
|
|
260
|
+
lists: number;
|
|
261
|
+
/** A read, search, or listing is still running. */
|
|
262
|
+
exploreActive: boolean;
|
|
263
|
+
tools: number;
|
|
264
|
+
/** Tools that failed; interrupted ones are counted apart and are not failures (DESIGN.md §9). */
|
|
265
|
+
failed: number;
|
|
266
|
+
interrupted: number;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The parts of a segment's summary line, without the failure count. Each kind takes its own
|
|
271
|
+
* tense: `Thinking 12s · Ran 2 commands · Read 5 files` (fold-more.md §5.4).
|
|
272
|
+
*/
|
|
273
|
+
export function summaryParts(stats: FoldStats): string[] {
|
|
274
|
+
const parts: string[] = [];
|
|
275
|
+
const { thinking, commands } = stats;
|
|
276
|
+
if (thinking.count > 0) {
|
|
277
|
+
if (thinking.active) {
|
|
278
|
+
parts.push(thinking.ms !== undefined && thinking.ms >= 1_000 ? `Thinking ${formatDuration(thinking.ms)}` : "Thinking");
|
|
279
|
+
} else if (thinking.ms !== undefined) {
|
|
280
|
+
// Same wording as the list items under it (`Thought for 1.5s`).
|
|
281
|
+
parts.push(thoughtLabel(thinking.ms));
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (commands.count > 0) {
|
|
285
|
+
parts.push(`${commands.active ? "Running" : "Ran"} ${plural(commands.count, "command")}`);
|
|
286
|
+
}
|
|
287
|
+
const explore = stats.exploreActive;
|
|
288
|
+
if (stats.reads > 0) {
|
|
289
|
+
parts.push(`${explore ? "Reading" : "Read"} ${plural(stats.reads, "file")}`);
|
|
290
|
+
if (stats.searches > 0) parts.push(plural(stats.searches, "search", "searches"));
|
|
291
|
+
if (stats.lists > 0) parts.push(plural(stats.lists, "dir"));
|
|
292
|
+
} else if (stats.searches > 0) {
|
|
293
|
+
parts.push(`${explore ? "Searching" : "Searched"} ${plural(stats.searches, "pattern")}`);
|
|
294
|
+
if (stats.lists > 0) parts.push(plural(stats.lists, "dir"));
|
|
295
|
+
} else if (stats.lists > 0) {
|
|
296
|
+
parts.push(`${explore ? "Listing" : "Listed"} ${plural(stats.lists, "dir")}`);
|
|
297
|
+
}
|
|
298
|
+
// Only thinking with no known duration (an old session): still say what the line stands for.
|
|
299
|
+
if (parts.length === 0) parts.push(thinking.active ? "Thinking" : "Thought");
|
|
300
|
+
return parts;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export function summaryText(stats: FoldStats): string {
|
|
304
|
+
return summaryParts(stats).join(" · ");
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Column-0 marker of a summary line: none, `!` when some tools failed, `×` when all did. */
|
|
308
|
+
export function summaryMarker(stats: FoldStats): " " | "!" | "×" {
|
|
309
|
+
if (stats.failed === 0) return " ";
|
|
310
|
+
return stats.failed >= stats.tools ? "×" : "!";
|
|
311
|
+
}
|