@casualjim/pi-pretty 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +48 -0
- package/package.json +71 -0
- package/src/autocomplete.ts +91 -0
- package/src/config.ts +468 -0
- package/src/fff-helpers.ts +86 -0
- package/src/fff.ts +340 -0
- package/src/find-glob.ts +21 -0
- package/src/helpers.ts +75 -0
- package/src/index.ts +556 -0
- package/src/notices.ts +3 -0
- package/src/prompt-editor.ts +104 -0
- package/src/render.ts +488 -0
- package/src/session-color.ts +172 -0
- package/src/tools/bash.d.ts +21 -0
- package/src/tools/bash.ts +163 -0
- package/src/tools/find.ts +231 -0
- package/src/tools/grep.ts +187 -0
- package/src/tools/labels.ts +3 -0
- package/src/tools/ls.ts +119 -0
- package/src/tools/metrics.ts +60 -0
- package/src/tools/read.ts +319 -0
- package/src/tui-text.ts +17 -0
- package/src/types.ts +202 -0
- package/src/working-indicator.ts +912 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,556 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-pretty — Pretty terminal output for pi built-in tools.
|
|
3
|
+
*
|
|
4
|
+
* Enhances read, ls, find, and grep with:
|
|
5
|
+
* • Syntax-highlighted file content (Shiki)
|
|
6
|
+
* • Tree-view directory listings with file-type icons
|
|
7
|
+
* • FFF-accelerated find/grep with SDK fallback
|
|
8
|
+
* • Custom ANSI rendering for all tools
|
|
9
|
+
*
|
|
10
|
+
* The bash tool is owned by pi-heimdall (sandboxed execute); it attaches
|
|
11
|
+
* pi-pretty's bash renderers from ./tools/bash.js so output stays styled.
|
|
12
|
+
* pi-pretty never registers or substitutes bash itself.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { readFileSync } from "node:fs";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import type {
|
|
18
|
+
ExtensionAPI,
|
|
19
|
+
ExtensionCommandContext,
|
|
20
|
+
ExtensionContext,
|
|
21
|
+
MessageEndEvent,
|
|
22
|
+
MessageUpdateEvent,
|
|
23
|
+
SessionInfoChangedEvent,
|
|
24
|
+
} from "@earendil-works/pi-coding-agent";
|
|
25
|
+
import * as hostSdk from "@earendil-works/pi-coding-agent";
|
|
26
|
+
import { createFffAutocompleteProvider } from "./autocomplete.js";
|
|
27
|
+
import {
|
|
28
|
+
applyConfig,
|
|
29
|
+
getDefaultAgentDir,
|
|
30
|
+
loadConfig,
|
|
31
|
+
normalizeToolList,
|
|
32
|
+
resolveFffScanSettings,
|
|
33
|
+
resolveToolSets,
|
|
34
|
+
} from "./config.js";
|
|
35
|
+
import { type FffInitOptions, type FffService, getSharedFffService, isFffRestrictedBasePathError } from "./fff.js";
|
|
36
|
+
import { createPromptEditorClass } from "./prompt-editor.js";
|
|
37
|
+
import { registerFindTool } from "./tools/find.js";
|
|
38
|
+
import { registerGrepTool } from "./tools/grep.js";
|
|
39
|
+
import { registerLsTool } from "./tools/ls.js";
|
|
40
|
+
import { registerReadTool } from "./tools/read.js";
|
|
41
|
+
import type { PiPrettyDeps, SdkTools } from "./types.js";
|
|
42
|
+
import {
|
|
43
|
+
createThinkingLabelAnimator,
|
|
44
|
+
createThinkingTimer,
|
|
45
|
+
installPerRowThinkingLabels,
|
|
46
|
+
installWorkingIndicator,
|
|
47
|
+
type PerRowThinkingLabels,
|
|
48
|
+
resolveThinkingIndicatorSettings,
|
|
49
|
+
resolveWorkingIndicatorSettings,
|
|
50
|
+
type ThinkingTimer,
|
|
51
|
+
thinkingBlockActive,
|
|
52
|
+
WORKING_INTERVAL_MS,
|
|
53
|
+
type WorkingIndicatorController,
|
|
54
|
+
} from "./working-indicator.js";
|
|
55
|
+
|
|
56
|
+
// ---------------------------------------------------------------------------
|
|
57
|
+
// Config
|
|
58
|
+
// ---------------------------------------------------------------------------
|
|
59
|
+
|
|
60
|
+
const DEFAULT_DISABLED_TOOLS = new Set(["ls"]);
|
|
61
|
+
const USER_MESSAGE_ICON = "❯";
|
|
62
|
+
type EditorFactory = Parameters<ExtensionContext["ui"]["setEditorComponent"]>[0];
|
|
63
|
+
type EditorUiCompatibility = {
|
|
64
|
+
setEditorComponent?: (factory: EditorFactory) => void;
|
|
65
|
+
getEditorComponent?: () => EditorFactory;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
function envTools(name: "PRETTY_DISABLE_TOOLS" | "PRETTY_ENABLE_TOOLS"): Set<string> {
|
|
69
|
+
return new Set(normalizeToolList((process.env[name] ?? "").split(",")));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
// Entry
|
|
74
|
+
// ---------------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
export type { PiPrettyDeps };
|
|
77
|
+
|
|
78
|
+
export default async function piPrettyExtension(pi: ExtensionAPI, deps?: PiPrettyDeps): Promise<void> {
|
|
79
|
+
const config = loadConfig();
|
|
80
|
+
applyConfig(config);
|
|
81
|
+
pi.registerMarkdownTransformer?.((markdown, context) => {
|
|
82
|
+
if (context.messageType !== "user" || markdown.trim() === "") return markdown;
|
|
83
|
+
return ` ${USER_MESSAGE_ICON} ${markdown}`;
|
|
84
|
+
});
|
|
85
|
+
pi.registerFlag?.("pretty-fff-home-scan", {
|
|
86
|
+
description: "Allow FFF to index the home directory when Pi starts there",
|
|
87
|
+
type: "boolean",
|
|
88
|
+
});
|
|
89
|
+
pi.registerFlag?.("pretty-fff-root-scan", {
|
|
90
|
+
description: "Allow FFF to index the filesystem root when Pi starts there",
|
|
91
|
+
type: "boolean",
|
|
92
|
+
});
|
|
93
|
+
const fffScanSettings = resolveFffScanSettings(config, {
|
|
94
|
+
enableHomeScanning: pi.getFlag?.("pretty-fff-home-scan"),
|
|
95
|
+
enableRootScanning: pi.getFlag?.("pretty-fff-root-scan"),
|
|
96
|
+
});
|
|
97
|
+
const fffInitOptions: FffInitOptions = {
|
|
98
|
+
enableHomeDirScanning: fffScanSettings.enableHomeScanning,
|
|
99
|
+
enableFsRootScanning: fffScanSettings.enableRootScanning,
|
|
100
|
+
};
|
|
101
|
+
const { disabledTools, enabledTools } = resolveToolSets(
|
|
102
|
+
envTools("PRETTY_DISABLE_TOOLS"),
|
|
103
|
+
envTools("PRETTY_ENABLE_TOOLS"),
|
|
104
|
+
config,
|
|
105
|
+
);
|
|
106
|
+
const isToolEnabled = (name: string) => {
|
|
107
|
+
const normalizedName = name.toLowerCase();
|
|
108
|
+
return (
|
|
109
|
+
!disabledTools.has(normalizedName) &&
|
|
110
|
+
(!DEFAULT_DISABLED_TOOLS.has(normalizedName) || enabledTools.has(normalizedName))
|
|
111
|
+
);
|
|
112
|
+
};
|
|
113
|
+
const cwd = process.cwd();
|
|
114
|
+
|
|
115
|
+
// ------------------------------------------------------------------
|
|
116
|
+
// FFF service init
|
|
117
|
+
// ------------------------------------------------------------------
|
|
118
|
+
// Keep FFF independent from the Pi SDK import. Published extension installs
|
|
119
|
+
// run in Pi's isolated npm root; importing a nested Pi SDK at activation time
|
|
120
|
+
// has proven crash-prone across host Pi versions. FFF commands and indexing
|
|
121
|
+
// should still work even when SDK tool factories are unavailable.
|
|
122
|
+
|
|
123
|
+
const maybeGetAgentDir = deps?.sdk?.getAgentDir;
|
|
124
|
+
const agentDir = typeof maybeGetAgentDir === "function" ? maybeGetAgentDir() : getDefaultAgentDir();
|
|
125
|
+
const fffService: FffService | null = getSharedFffService(deps?.fffModule, agentDir);
|
|
126
|
+
|
|
127
|
+
// Text component for custom rendering (DI-friendly)
|
|
128
|
+
const TextComp = deps?.TextComponent;
|
|
129
|
+
|
|
130
|
+
// ------------------------------------------------------------------
|
|
131
|
+
// FFF commands
|
|
132
|
+
// ------------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
if (fffService) {
|
|
135
|
+
pi.registerCommand("fff-health", {
|
|
136
|
+
description: "Show FFF file finder health and indexer status",
|
|
137
|
+
handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
138
|
+
const fff = fffService;
|
|
139
|
+
if (!fff || !fff.isAvailable) {
|
|
140
|
+
ctx.ui.notify("FFF not initialized", "warning");
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const finder = fff.getFinder();
|
|
144
|
+
if (!finder) {
|
|
145
|
+
ctx.ui.notify("FFF not initialized", "warning");
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const health = finder.healthCheck();
|
|
149
|
+
if (!health.ok) {
|
|
150
|
+
ctx.ui.notify(`Health check failed: ${health.error}`, "error");
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const h = health.value;
|
|
154
|
+
const lines = [
|
|
155
|
+
`FFF v${h.version}`,
|
|
156
|
+
`Git: ${h.git.repositoryFound ? `yes (${h.git.workdir ?? "unknown"})` : "no"}`,
|
|
157
|
+
`Picker: ${h.filePicker.initialized ? `${h.filePicker.indexedFiles ?? 0} files` : "not initialized"}`,
|
|
158
|
+
`Frecency: ${h.frecency.initialized ? "active" : "disabled"}`,
|
|
159
|
+
`Query tracker: ${h.queryTracker.initialized ? "active" : "disabled"}`,
|
|
160
|
+
`Partial index: ${fff.partialIndex ? "yes (scan timed out)" : "no"}`,
|
|
161
|
+
];
|
|
162
|
+
const progress = finder.getScanProgress();
|
|
163
|
+
if (progress.ok) {
|
|
164
|
+
lines.push(
|
|
165
|
+
`Scanning: ${progress.value.isScanning ? "yes" : "no"} (${progress.value.scannedFilesCount} files)`,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
pi.registerCommand("fff-rescan", {
|
|
173
|
+
description: "Trigger FFF to rescan files",
|
|
174
|
+
handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
175
|
+
const fff = fffService!;
|
|
176
|
+
if (!fff.isAvailable) {
|
|
177
|
+
ctx.ui.notify("FFF not initialized", "warning");
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const finder = fff.getFinder();
|
|
181
|
+
if (!finder) {
|
|
182
|
+
ctx.ui.notify("FFF not initialized", "warning");
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
const result = finder.scanFiles();
|
|
186
|
+
if (!result.ok) {
|
|
187
|
+
ctx.ui.notify(`Rescan failed: ${result.error}`, "error");
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
fff.partialIndex = false;
|
|
191
|
+
ctx.ui.notify("FFF rescan triggered", "info");
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ------------------------------------------------------------------
|
|
197
|
+
// Session lifecycle
|
|
198
|
+
// ------------------------------------------------------------------
|
|
199
|
+
|
|
200
|
+
const workingSettings = resolveWorkingIndicatorSettings(config.workingIndicator);
|
|
201
|
+
const thinkingSettings = resolveThinkingIndicatorSettings(config.thinkingIndicator);
|
|
202
|
+
let workingController: WorkingIndicatorController | undefined;
|
|
203
|
+
let thinkingTimer: ThinkingTimer | undefined;
|
|
204
|
+
let thinkingInterval: ReturnType<typeof setInterval> | undefined;
|
|
205
|
+
let thinkingLastMessage: unknown;
|
|
206
|
+
let thinkingHiddenCheckedAt = 0;
|
|
207
|
+
let workingSessionName: string | undefined;
|
|
208
|
+
let workingStreaming = false;
|
|
209
|
+
let promptEditorInstalled = false;
|
|
210
|
+
let previousEditorFactory: EditorFactory;
|
|
211
|
+
// SAFETY: the host SDK re-exports CustomEditor only in TUI-capable builds;
|
|
212
|
+
// presence is feature-detected (typeof check) before any use.
|
|
213
|
+
const hostCustomEditor =
|
|
214
|
+
deps?.customEditorClass ??
|
|
215
|
+
(hostSdk as unknown as { CustomEditor?: PiPrettyDeps["customEditorClass"] }).CustomEditor;
|
|
216
|
+
const installPromptEditor = (ctx: ExtensionContext): void => {
|
|
217
|
+
if (ctx.mode !== "tui" || promptEditorInstalled || typeof hostCustomEditor !== "function") return;
|
|
218
|
+
// SAFETY: EditorUiCompatibility members are optional and each use is guarded
|
|
219
|
+
// by a typeof check; older hosts simply omit them.
|
|
220
|
+
const editorUi = ctx.ui as unknown as EditorUiCompatibility;
|
|
221
|
+
if (typeof editorUi.setEditorComponent !== "function") return;
|
|
222
|
+
previousEditorFactory = editorUi.getEditorComponent?.();
|
|
223
|
+
const PromptEditor = createPromptEditorClass(hostCustomEditor, (icon) => {
|
|
224
|
+
const theme = ctx.ui.theme;
|
|
225
|
+
return typeof theme.getThinkingBorderColor === "function"
|
|
226
|
+
? theme.getThinkingBorderColor(ctx.thinkingLevel ?? "off")(icon)
|
|
227
|
+
: theme.fg("thinkingText", icon);
|
|
228
|
+
});
|
|
229
|
+
editorUi.setEditorComponent((tui, theme, keybindings) => new PromptEditor(tui, theme, keybindings));
|
|
230
|
+
promptEditorInstalled = true;
|
|
231
|
+
};
|
|
232
|
+
let perRowLabels: PerRowThinkingLabels | undefined;
|
|
233
|
+
/** Accumulated thinking time per message timestamp — later runs in the same
|
|
234
|
+
* message resume from this total instead of rewinding to zero. */
|
|
235
|
+
const thinkingElapsedMs = new Map<number, number>();
|
|
236
|
+
|
|
237
|
+
/** Message timestamps are the per-row identity the label patch keys on. */
|
|
238
|
+
const messageTimestamp = (message: unknown): number | undefined => {
|
|
239
|
+
const ts = (message as { timestamp?: unknown } | undefined)?.timestamp;
|
|
240
|
+
return typeof ts === "number" ? ts : undefined;
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
/** pi persists the thinking-visibility toggle as a top-level settings key. */
|
|
244
|
+
const thinkingHidden = (): boolean => {
|
|
245
|
+
try {
|
|
246
|
+
const dir = getDefaultAgentDir();
|
|
247
|
+
if (!dir) return false;
|
|
248
|
+
const parsed = JSON.parse(readFileSync(join(dir, "settings.json"), "utf8")) as {
|
|
249
|
+
hideThinkingBlock?: unknown;
|
|
250
|
+
};
|
|
251
|
+
return parsed.hideThinkingBlock === true;
|
|
252
|
+
} catch {
|
|
253
|
+
return false;
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* True when the 500ms-cached hidden check is stale and settings now show
|
|
259
|
+
* thinking revealed — the single re-check shared by the ticker and the
|
|
260
|
+
* completed-phase message_update path (timestamp guard runs before the read).
|
|
261
|
+
*/
|
|
262
|
+
const thinkingRevealed = (): boolean => {
|
|
263
|
+
if (Date.now() - thinkingHiddenCheckedAt <= 500) return false;
|
|
264
|
+
thinkingHiddenCheckedAt = Date.now();
|
|
265
|
+
return !thinkingHidden();
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
const safeSessionName = (ctx: ExtensionContext): string | undefined => {
|
|
269
|
+
try {
|
|
270
|
+
return ctx.sessionManager?.getSessionName?.() ?? undefined;
|
|
271
|
+
} catch {
|
|
272
|
+
return undefined;
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
// (Re-)install the working indicator: new session, reload, or session rename
|
|
277
|
+
// (the accent tint tracks the name, omp-style). Preserves streaming state so a
|
|
278
|
+
// mid-stream rename does not drop the row.
|
|
279
|
+
const installIndicator = async (ctx: ExtensionContext): Promise<void> => {
|
|
280
|
+
workingController?.dispose();
|
|
281
|
+
workingController = undefined;
|
|
282
|
+
try {
|
|
283
|
+
const controller = await installWorkingIndicator(ctx.ui, workingSettings, undefined, workingSessionName);
|
|
284
|
+
workingController = controller;
|
|
285
|
+
if (workingStreaming) controller.start();
|
|
286
|
+
// Noop install (disabled/blank) after a previous install → restore pi's loader.
|
|
287
|
+
if (controller.frames.length === 0) ctx.ui.setWorkingVisible?.(true);
|
|
288
|
+
} catch (error: unknown) {
|
|
289
|
+
try {
|
|
290
|
+
ctx.ui.setWorkingVisible?.(true);
|
|
291
|
+
} catch {
|
|
292
|
+
// Host without the API — nothing to restore.
|
|
293
|
+
}
|
|
294
|
+
ctx.ui?.notify?.(
|
|
295
|
+
`pi-pretty working indicator failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
296
|
+
"warning",
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
pi.on("session_start", async (_event: unknown, ctx: ExtensionContext) => {
|
|
302
|
+
if (ctx.mode === "tui") {
|
|
303
|
+
installPromptEditor(ctx);
|
|
304
|
+
ctx.ui.setToolsExpanded(false);
|
|
305
|
+
// Per-row hidden-thinking labels: intercept the host's label fan-out so
|
|
306
|
+
// each row keeps its own duration. Falls back to the global-label
|
|
307
|
+
// behavior whenever the host class is missing or reshaped.
|
|
308
|
+
perRowLabels = thinkingSettings.enabled
|
|
309
|
+
? installPerRowThinkingLabels(
|
|
310
|
+
deps?.assistantMessageComponent ??
|
|
311
|
+
(hostSdk as { AssistantMessageComponent?: unknown }).AssistantMessageComponent,
|
|
312
|
+
)
|
|
313
|
+
: undefined;
|
|
314
|
+
workingSessionName = safeSessionName(ctx);
|
|
315
|
+
await installIndicator(ctx);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
if (!fffService) return;
|
|
319
|
+
|
|
320
|
+
try {
|
|
321
|
+
// Try dynamic import if sync require failed
|
|
322
|
+
if (!fffService.isModuleLoaded()) {
|
|
323
|
+
const loaded = await fffService.tryLoadModule();
|
|
324
|
+
if (!loaded) return;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
await fffService.ensureFinder(ctx.cwd, fffInitOptions);
|
|
328
|
+
if (fffService.partialIndex) {
|
|
329
|
+
ctx.ui?.notify?.("FFF: scan timed out — using partial index. Run /fff-rescan when ready.", "warning");
|
|
330
|
+
} else {
|
|
331
|
+
const ui = ctx.ui;
|
|
332
|
+
ui?.setStatus?.("fff", "FFF indexed");
|
|
333
|
+
setTimeout(() => ui?.setStatus?.("fff", undefined), 3000);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// Register FFF-backed @-mention autocomplete only after a finder exists.
|
|
337
|
+
ctx.ui?.addAutocompleteProvider?.((current) =>
|
|
338
|
+
createFffAutocompleteProvider(current, () => fffService?.getFinder() ?? null),
|
|
339
|
+
);
|
|
340
|
+
} catch (error: unknown) {
|
|
341
|
+
// Root/home refusal is an intentional FFF safety boundary. FFF is an
|
|
342
|
+
// accelerator, so fall back to the SDK without interrupting startup.
|
|
343
|
+
if (isFffRestrictedBasePathError(error, fffInitOptions)) return;
|
|
344
|
+
ctx.ui?.notify?.(`FFF init failed: ${error instanceof Error ? error.message : String(error)}`, "warning");
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
// Re-apply the indicator when the session is (re)named so the accent tint
|
|
349
|
+
// tracks the name; omp derives the accent the same way.
|
|
350
|
+
pi.on("session_info_changed", async (event: SessionInfoChangedEvent, ctx: ExtensionContext) => {
|
|
351
|
+
if (ctx.mode !== "tui") return;
|
|
352
|
+
if (event.name === workingSessionName) return;
|
|
353
|
+
workingSessionName = event.name;
|
|
354
|
+
if (workingSettings.enabled) await installIndicator(ctx);
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
// Drive the working indicator with the streaming lifecycle (the host row is hidden until agent_start).
|
|
358
|
+
pi.on("agent_start", async (_event: unknown, ctx: ExtensionContext) => {
|
|
359
|
+
if (ctx.mode !== "tui") return;
|
|
360
|
+
workingStreaming = true;
|
|
361
|
+
workingController?.start();
|
|
362
|
+
});
|
|
363
|
+
const stopStreaming = async (_event: unknown, ctx: ExtensionContext): Promise<void> => {
|
|
364
|
+
if (ctx.mode !== "tui") return;
|
|
365
|
+
workingStreaming = false;
|
|
366
|
+
workingController?.stop();
|
|
367
|
+
stopThinkingShimmer();
|
|
368
|
+
};
|
|
369
|
+
pi.on("agent_end", stopStreaming);
|
|
370
|
+
pi.on("agent_settled", stopStreaming);
|
|
371
|
+
|
|
372
|
+
const clearThinkingInterval = (): void => {
|
|
373
|
+
if (!thinkingInterval) return;
|
|
374
|
+
clearInterval(thinkingInterval);
|
|
375
|
+
thinkingInterval = undefined;
|
|
376
|
+
};
|
|
377
|
+
|
|
378
|
+
const stopThinkingShimmer = (): void => {
|
|
379
|
+
clearThinkingInterval();
|
|
380
|
+
perRowLabels?.clearActive();
|
|
381
|
+
try {
|
|
382
|
+
thinkingTimer?.restore();
|
|
383
|
+
} catch {
|
|
384
|
+
// Teardown must never throw — a host that explodes on restore is left
|
|
385
|
+
// with whatever label it has; the interval is already gone.
|
|
386
|
+
}
|
|
387
|
+
thinkingTimer = undefined;
|
|
388
|
+
thinkingLastMessage = undefined;
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
const completeThinkingShimmer = (): void => {
|
|
392
|
+
clearThinkingInterval();
|
|
393
|
+
const ts = messageTimestamp(thinkingLastMessage);
|
|
394
|
+
const frozenMs = thinkingTimer?.complete();
|
|
395
|
+
if (ts !== undefined && frozenMs !== undefined) {
|
|
396
|
+
thinkingElapsedMs.set(ts, frozenMs);
|
|
397
|
+
perRowLabels?.complete(ts, frozenMs);
|
|
398
|
+
}
|
|
399
|
+
// The completed row is no longer the animating one — drop the active mark
|
|
400
|
+
// so subsequent global writes freeze it at its own duration.
|
|
401
|
+
perRowLabels?.clearActive();
|
|
402
|
+
thinkingLastMessage = undefined;
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
/** Surface one warning without letting a throwing host escape the crash guard. */
|
|
406
|
+
const notifyThinkingFailure = (ctx: ExtensionContext, error: unknown): void => {
|
|
407
|
+
try {
|
|
408
|
+
ctx.ui?.notify?.(
|
|
409
|
+
`pi-pretty thinking indicator failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
410
|
+
"warning",
|
|
411
|
+
);
|
|
412
|
+
} catch {
|
|
413
|
+
// A host that throws on notify too must not crash the timer path.
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
// Same 30fps cadence as the working row — but the interval lives ONLY while
|
|
418
|
+
// the streaming message is actively emitting a thinking block (each label
|
|
419
|
+
// change rebuilds chat children, so the moment text or tool calls stream the
|
|
420
|
+
// label freezes as `Thought for {duration}` until the run ends).
|
|
421
|
+
const startThinkingShimmer = (ctx: ExtensionContext): void => {
|
|
422
|
+
if (thinkingInterval || !thinkingSettings.enabled) return;
|
|
423
|
+
try {
|
|
424
|
+
thinkingHiddenCheckedAt = Date.now();
|
|
425
|
+
if (!thinkingHidden()) return; // thinking visible: no label writes at all
|
|
426
|
+
const animator = createThinkingLabelAnimator(ctx.ui, workingSettings, workingSessionName, thinkingSettings);
|
|
427
|
+
const activeTs = messageTimestamp(thinkingLastMessage);
|
|
428
|
+
// Same message thinking again (interleaved runs): resume its total.
|
|
429
|
+
const resumeMs = activeTs === undefined ? 0 : (thinkingElapsedMs.get(activeTs) ?? 0);
|
|
430
|
+
thinkingTimer = createThinkingTimer(animator, Date.now, resumeMs);
|
|
431
|
+
if (activeTs !== undefined) perRowLabels?.setActive(activeTs);
|
|
432
|
+
thinkingTimer.tick();
|
|
433
|
+
thinkingInterval = setInterval(() => {
|
|
434
|
+
try {
|
|
435
|
+
if (!workingStreaming) {
|
|
436
|
+
stopThinkingShimmer();
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
if (thinkingRevealed()) {
|
|
440
|
+
stopThinkingShimmer();
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
if (!thinkingBlockActive(thinkingLastMessage)) {
|
|
444
|
+
// Thinking phase over: freeze its duration until the run ends.
|
|
445
|
+
completeThinkingShimmer();
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
thinkingTimer?.tick();
|
|
449
|
+
// The label has no widget of its own — ask the working indicator to
|
|
450
|
+
// request a host render even when deltas pause mid-thinking.
|
|
451
|
+
workingController?.requestRender();
|
|
452
|
+
} catch (error: unknown) {
|
|
453
|
+
// A throwing host call inside our timer would crash pi (uncaught in
|
|
454
|
+
// setInterval) — tear the label down and surface one warning instead.
|
|
455
|
+
stopThinkingShimmer();
|
|
456
|
+
notifyThinkingFailure(ctx, error);
|
|
457
|
+
}
|
|
458
|
+
}, WORKING_INTERVAL_MS);
|
|
459
|
+
} catch (error: unknown) {
|
|
460
|
+
stopThinkingShimmer();
|
|
461
|
+
notifyThinkingFailure(ctx, error);
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
// Remember the streaming message; lazily start the shimmer on the first
|
|
466
|
+
// thinking delta (thinkingHidden() is re-checked at most every 500ms). After
|
|
467
|
+
// the phase completes, deltas keep refreshing the visibility cache so a
|
|
468
|
+
// mid-run `hideThinkingBlock` toggle-off restores the default label.
|
|
469
|
+
pi.on("message_update", async (event: MessageUpdateEvent, ctx: ExtensionContext) => {
|
|
470
|
+
if (ctx.mode !== "tui" || !workingStreaming) return;
|
|
471
|
+
thinkingLastMessage = event.message;
|
|
472
|
+
if (thinkingInterval) {
|
|
473
|
+
// Complete immediately on the first text/tool delta instead of waiting
|
|
474
|
+
// for the next animation frame.
|
|
475
|
+
if (!thinkingBlockActive(event.message)) completeThinkingShimmer();
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
if (thinkingBlockActive(event.message)) {
|
|
479
|
+
// First thinking delta — or a later phase after tool calls — starts a
|
|
480
|
+
// fresh timer (the completed one is replaced wholesale).
|
|
481
|
+
startThinkingShimmer(ctx);
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
if (thinkingTimer && thinkingRevealed()) stopThinkingShimmer();
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
// The completed wording belongs to the message that produced it. The label
|
|
488
|
+
// is global, so once that assistant message ends, restore pi's default —
|
|
489
|
+
// otherwise every later phase stamps its frozen duration onto every hidden
|
|
490
|
+
// thinking row in the transcript (the image-read " Thought for 5s" stack).
|
|
491
|
+
pi.on("message_end", async (event: MessageEndEvent, ctx: ExtensionContext) => {
|
|
492
|
+
if (ctx.mode !== "tui" || event.message.role !== "assistant") return;
|
|
493
|
+
if (thinkingInterval || thinkingTimer) stopThinkingShimmer();
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
pi.on("session_shutdown", async (_event: unknown, ctx?: ExtensionContext) => {
|
|
497
|
+
if (promptEditorInstalled) {
|
|
498
|
+
if (ctx) {
|
|
499
|
+
// SAFETY: optional host hooks; typeof-guarded before the call below.
|
|
500
|
+
const editorUi = ctx.ui as unknown as EditorUiCompatibility;
|
|
501
|
+
if (typeof editorUi.setEditorComponent === "function") editorUi.setEditorComponent(previousEditorFactory);
|
|
502
|
+
}
|
|
503
|
+
promptEditorInstalled = false;
|
|
504
|
+
previousEditorFactory = undefined;
|
|
505
|
+
}
|
|
506
|
+
// Tear down the indicator animation; pi re-runs session_start (and our
|
|
507
|
+
// install) after resume or session switching.
|
|
508
|
+
workingController?.dispose();
|
|
509
|
+
workingController = undefined;
|
|
510
|
+
stopThinkingShimmer();
|
|
511
|
+
perRowLabels?.uninstall();
|
|
512
|
+
perRowLabels = undefined;
|
|
513
|
+
thinkingElapsedMs.clear();
|
|
514
|
+
workingStreaming = false;
|
|
515
|
+
// Intentionally keep the native FFF finder on session shutdown.
|
|
516
|
+
// Pi can emit shutdown/start during resume or session switching while the
|
|
517
|
+
// process keeps running. Native teardown, or dropping the JS handle while the
|
|
518
|
+
// native LMDB frecency env stays open, can make the next init fail with
|
|
519
|
+
// "environment already open in this program". Let process exit reclaim it.
|
|
520
|
+
});
|
|
521
|
+
|
|
522
|
+
// ------------------------------------------------------------------
|
|
523
|
+
// Resolve SDK tools
|
|
524
|
+
// ------------------------------------------------------------------
|
|
525
|
+
// Pi aliases static SDK imports to its host package for managed extensions.
|
|
526
|
+
// Native dynamic imports bypass that alias because the managed npm root omits
|
|
527
|
+
// Pi peer dependencies.
|
|
528
|
+
|
|
529
|
+
const sdk: SdkTools = deps?.sdk ?? {
|
|
530
|
+
createReadToolDefinition: hostSdk.createReadToolDefinition,
|
|
531
|
+
createLsToolDefinition: hostSdk.createLsToolDefinition,
|
|
532
|
+
createFindToolDefinition: hostSdk.createFindToolDefinition,
|
|
533
|
+
createGrepToolDefinition: hostSdk.createGrepToolDefinition,
|
|
534
|
+
};
|
|
535
|
+
const createReadTool = sdk.createReadToolDefinition ?? sdk.createReadTool;
|
|
536
|
+
const createLsTool = sdk.createLsToolDefinition ?? sdk.createLsTool;
|
|
537
|
+
const createFindTool = sdk.createFindToolDefinition ?? sdk.createFindTool;
|
|
538
|
+
const createGrepTool = sdk.createGrepToolDefinition ?? sdk.createGrepTool;
|
|
539
|
+
|
|
540
|
+
// ------------------------------------------------------------------
|
|
541
|
+
// Tool registration
|
|
542
|
+
// ------------------------------------------------------------------
|
|
543
|
+
|
|
544
|
+
if (isToolEnabled("read") && createReadTool) {
|
|
545
|
+
registerReadTool(pi, cwd, null, createReadTool(cwd), TextComp);
|
|
546
|
+
}
|
|
547
|
+
if (isToolEnabled("ls") && createLsTool) {
|
|
548
|
+
registerLsTool(pi, cwd, null, createLsTool(cwd), TextComp);
|
|
549
|
+
}
|
|
550
|
+
if (isToolEnabled("find") && createFindTool) {
|
|
551
|
+
registerFindTool(pi, cwd, fffService, createFindTool(cwd), TextComp);
|
|
552
|
+
}
|
|
553
|
+
if (isToolEnabled("grep") && createGrepTool) {
|
|
554
|
+
registerGrepTool(pi, cwd, fffService, createGrepTool(cwd), TextComp);
|
|
555
|
+
}
|
|
556
|
+
}
|
package/src/notices.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { CustomEditor } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { sliceByColumn, visibleWidth } from "@earendil-works/pi-tui";
|
|
3
|
+
|
|
4
|
+
/** Constructor shape used to preserve compatibility with older Pi hosts. */
|
|
5
|
+
export type CustomEditorConstructor = new (...args: ConstructorParameters<typeof CustomEditor>) => CustomEditor;
|
|
6
|
+
|
|
7
|
+
type PromptColor = (text: string) => string;
|
|
8
|
+
|
|
9
|
+
const PROMPT_ICON = "❯";
|
|
10
|
+
const PROMPT_WIDTH = 3; // one space on either side of the icon
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Build a CustomEditor subclass that reserves room for, and renders, the
|
|
14
|
+
* user-message prompt. The host still owns all editing and app keybindings.
|
|
15
|
+
*/
|
|
16
|
+
export function createPromptEditorClass(
|
|
17
|
+
Base: CustomEditorConstructor,
|
|
18
|
+
colorPrompt: PromptColor,
|
|
19
|
+
): CustomEditorConstructor {
|
|
20
|
+
// SAFETY: border hook support is feature-detected from the prototype; the
|
|
21
|
+
// declared-optional shape only widens what we probe, never what we call.
|
|
22
|
+
const basePrototype = Base.prototype as unknown as {
|
|
23
|
+
renderTopBorder?: unknown;
|
|
24
|
+
renderBottomBorder?: unknown;
|
|
25
|
+
};
|
|
26
|
+
const supportsBorderHooks =
|
|
27
|
+
typeof basePrototype.renderTopBorder === "function" && typeof basePrototype.renderBottomBorder === "function";
|
|
28
|
+
|
|
29
|
+
class PromptEditor extends Base {
|
|
30
|
+
private userPaddingX = 0;
|
|
31
|
+
private isScrolled = false;
|
|
32
|
+
private bottomBorderLine = "";
|
|
33
|
+
|
|
34
|
+
constructor(...args: ConstructorParameters<CustomEditorConstructor>) {
|
|
35
|
+
const [tui, theme, keybindings, options] = args;
|
|
36
|
+
super(tui, theme, keybindings, { ...(options ?? {}), embedWorkingStatus: true });
|
|
37
|
+
this.userPaddingX = super.getPaddingX();
|
|
38
|
+
super.setPaddingX(this.userPaddingX + this.promptWidth());
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
private promptWidth(): number {
|
|
42
|
+
// At zero user padding, reserve one extra column so the border leaves
|
|
43
|
+
// the same visible gap before the icon as padded editors.
|
|
44
|
+
return PROMPT_WIDTH + (supportsBorderHooks && this.userPaddingX === 0 ? 1 : 0);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
override getPaddingX(): number {
|
|
48
|
+
return this.userPaddingX;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
override setPaddingX(padding: number): void {
|
|
52
|
+
this.userPaddingX = Math.max(0, padding);
|
|
53
|
+
super.setPaddingX(this.userPaddingX + this.promptWidth());
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
protected override renderTopBorder(width: number, hiddenLineCount: number): string {
|
|
57
|
+
this.isScrolled = hiddenLineCount > 0;
|
|
58
|
+
return this.roundBorder(super.renderTopBorder(width, hiddenLineCount), width, "╭", "╮");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
protected override renderBottomBorder(width: number, hiddenLineCount: number): string {
|
|
62
|
+
this.bottomBorderLine = this.roundBorder(super.renderBottomBorder(width, hiddenLineCount), width, "╰", "╯");
|
|
63
|
+
return this.bottomBorderLine;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
private roundBorder(line: string, width: number, left: string, right: string): string {
|
|
67
|
+
if (width < 2 || visibleWidth(line) !== width) return line;
|
|
68
|
+
return `${this.borderColor(left)}${sliceByColumn(line, 1, width - 2, true)}${this.borderColor(right)}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
override render(width: number): string[] {
|
|
72
|
+
this.bottomBorderLine = "";
|
|
73
|
+
const lines = super.render(width);
|
|
74
|
+
if (lines.length < 2) return lines;
|
|
75
|
+
|
|
76
|
+
if (!this.isScrolled) {
|
|
77
|
+
const firstContentLine = lines[1];
|
|
78
|
+
if (firstContentLine) {
|
|
79
|
+
const maxPadding = Math.max(0, Math.floor((width - 1) / 2));
|
|
80
|
+
const promptPadding = Math.min(this.userPaddingX + this.promptWidth(), maxPadding);
|
|
81
|
+
if (promptPadding >= PROMPT_WIDTH && firstContentLine.startsWith(" ".repeat(promptPadding))) {
|
|
82
|
+
const promptStart = promptPadding - PROMPT_WIDTH;
|
|
83
|
+
const prompt = ` ${colorPrompt(PROMPT_ICON)} `;
|
|
84
|
+
lines[1] = `${firstContentLine.slice(0, promptStart)}${prompt}${firstContentLine.slice(promptPadding)}`;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (!supportsBorderHooks || !this.bottomBorderLine) return lines;
|
|
90
|
+
|
|
91
|
+
const bottomBorderIndex = lines.lastIndexOf(this.bottomBorderLine);
|
|
92
|
+
const contentEnd = bottomBorderIndex > 0 ? bottomBorderIndex : lines.length - 1;
|
|
93
|
+
for (let i = 1; i < contentEnd; i++) {
|
|
94
|
+
const line = lines[i];
|
|
95
|
+
if (!line || visibleWidth(line) !== width || !line.startsWith(" ") || !line.endsWith(" ")) continue;
|
|
96
|
+
lines[i] = `${this.borderColor("│")}${line.slice(1, -1)}${this.borderColor("│")}`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return lines;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return PromptEditor;
|
|
104
|
+
}
|