@xzzpig/pi-tidy 0.0.0-stage → 0.1.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/CHANGELOG.md +1104 -0
- package/FORK-CHANGELOG.md +31 -0
- package/LICENSE +21 -0
- package/README.md +416 -2
- package/fork/defaults.ts +77 -0
- package/fork/index.ts +2 -0
- package/fork/install.ts +58 -0
- package/fork/thinking-row.ts +221 -0
- package/package.json +68 -3
- package/src/clean-copy.ts +313 -0
- package/src/clipboard.ts +29 -0
- package/src/config.ts +292 -0
- package/src/draw/frame-draw.ts +307 -0
- package/src/draw/icons.ts +2014 -0
- package/src/draw/paint.ts +57 -0
- package/src/frame.ts +20 -0
- package/src/hover.ts +185 -0
- package/src/index.ts +322 -0
- package/src/live.ts +91 -0
- package/src/messages/bash-mode-frame.ts +112 -0
- package/src/messages/error-lines.ts +331 -0
- package/src/messages/extension-notice.ts +204 -0
- package/src/messages/hex-swatches.ts +245 -0
- package/src/messages/message-frame.ts +515 -0
- package/src/messages/user-message.ts +207 -0
- package/src/theme-access.ts +26 -0
- package/src/tools/background-jobs.ts +617 -0
- package/src/tools/bash-highlight.ts +330 -0
- package/src/tools/codemode-body.ts +602 -0
- package/src/tools/result-preview.ts +56 -0
- package/src/tools/split-diff.ts +606 -0
- package/src/tools/tool-frame.ts +1019 -0
- package/src/tools/tool-group-view.ts +1160 -0
- package/src/tools/tool-groups.ts +706 -0
- package/src/tools/tool-lines.ts +621 -0
- package/src/tools/write-preview.ts +81 -0
- package/src/turns/code-blocks.ts +273 -0
- package/src/turns/turn-lifecycle.ts +43 -0
- package/src/turns/turn-state.ts +257 -0
- package/src/turns/turn-view.ts +504 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paint text in a configured color: a pi theme color name or a `#rrggbb` hex.
|
|
3
|
+
*
|
|
4
|
+
* `theme.fg` only knows its own tokens and throws on anything else, so a hex
|
|
5
|
+
* goes straight to an SGR sequence — truecolor, or the nearest xterm-256 entry
|
|
6
|
+
* when the theme runs in 256-color mode. An unknown name leaves the text
|
|
7
|
+
* unpainted rather than breaking the render.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { ThemeLike } from "../theme-access.ts";
|
|
11
|
+
|
|
12
|
+
const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
|
|
13
|
+
|
|
14
|
+
export function isHexColor(value: string): boolean {
|
|
15
|
+
return HEX_RE.test(value);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function hexToRgb(hex: string): [number, number, number] {
|
|
19
|
+
let body = hex.slice(1);
|
|
20
|
+
if (body.length === 3) body = [...body].map((ch) => ch + ch).join("");
|
|
21
|
+
return [0, 2, 4].map((i) => Number.parseInt(body.slice(i, i + 2), 16)) as [number, number, number];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The xterm-256 cube steps; grey ramp entries are 8, 18, …, 238. */
|
|
25
|
+
const CUBE = [0, 95, 135, 175, 215, 255];
|
|
26
|
+
|
|
27
|
+
function nearestCubeIndex(value: number): number {
|
|
28
|
+
let best = 0;
|
|
29
|
+
for (let i = 1; i < CUBE.length; i++) {
|
|
30
|
+
if (Math.abs(CUBE[i] - value) < Math.abs(CUBE[best] - value)) best = i;
|
|
31
|
+
}
|
|
32
|
+
return best;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function rgbTo256([r, g, b]: [number, number, number]): number {
|
|
36
|
+
const [ri, gi, bi] = [r, g, b].map(nearestCubeIndex);
|
|
37
|
+
const cube = 16 + 36 * ri + 6 * gi + bi;
|
|
38
|
+
const cubeDistance = (CUBE[ri] - r) ** 2 + (CUBE[gi] - g) ** 2 + (CUBE[bi] - b) ** 2;
|
|
39
|
+
const grey = Math.max(0, Math.min(23, Math.round(((r + g + b) / 3 - 8) / 10)));
|
|
40
|
+
const level = 8 + grey * 10;
|
|
41
|
+
const greyDistance = (level - r) ** 2 + (level - g) ** 2 + (level - b) ** 2;
|
|
42
|
+
return greyDistance < cubeDistance ? 232 + grey : cube;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function hexSgr(hex: string, theme: ThemeLike): string {
|
|
46
|
+
const rgb = hexToRgb(hex);
|
|
47
|
+
return theme.getColorMode?.() === "256color" ? `\x1b[38;5;${rgbTo256(rgb)}m` : `\x1b[38;2;${rgb.join(";")}m`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function paint(theme: ThemeLike, color: string, text: string): string {
|
|
51
|
+
if (isHexColor(color)) return `${hexSgr(color, theme)}${text}\x1b[39m`;
|
|
52
|
+
try {
|
|
53
|
+
return theme.fg(color, text);
|
|
54
|
+
} catch {
|
|
55
|
+
return text;
|
|
56
|
+
}
|
|
57
|
+
}
|
package/src/frame.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public entry for the frame patches. The work lives in:
|
|
3
|
+
*
|
|
4
|
+
* frame-draw.ts border drawing and escape-aware string helpers
|
|
5
|
+
* tool-frame.ts ToolExecutionComponent: the box, its clicks
|
|
6
|
+
* tool-group-view.ts how a box looks and reacts inside a group
|
|
7
|
+
* tool-groups.ts the grouping state machine
|
|
8
|
+
* hover.ts the row under the pointer, shared by tool and turn rows
|
|
9
|
+
* message-frame.ts compaction / branch / skill / custom / user boxes
|
|
10
|
+
* user-message.ts the default "rail" user message
|
|
11
|
+
* bash-mode-frame.ts the user's own `!` / `!!` bash runs
|
|
12
|
+
* error-lines.ts pi's own error rows: one framed row per failure, `×N`
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export { stripBackgroundFills } from "./draw/frame-draw.ts";
|
|
16
|
+
export { patchToolBoxFrames, type ToolFrameOptions } from "./tools/tool-frame.ts";
|
|
17
|
+
export { patchContainerBoxes, patchMessageBoxes, type ContainerBoxOptions } from "./messages/message-frame.ts";
|
|
18
|
+
export { patchBashExecutions, type BashModeOptions } from "./messages/bash-mode-frame.ts";
|
|
19
|
+
export { installErrorLines, patchErrorLines, type ErrorLineOptions } from "./messages/error-lines.ts";
|
|
20
|
+
export { patchUserMessages, USER_RAIL_GLYPH, type UserMessageOptions, type UserMessageStyle } from "./messages/user-message.ts";
|
package/src/hover.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { TuiAltScreen } from "@earendil-works/pi-tui";
|
|
2
|
+
import type { CodemodeSection } from "./tools/codemode-body.ts";
|
|
3
|
+
import { padToWidth } from "./draw/frame-draw.ts";
|
|
4
|
+
import type { ThemeLike } from "./theme-access.ts";
|
|
5
|
+
|
|
6
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
7
|
+
// Hover
|
|
8
|
+
//
|
|
9
|
+
// `move` packets (1003 all-motion tracking, which pi enables outside tmux) are
|
|
10
|
+
// routed to the component under the pointer even with no button down, so a
|
|
11
|
+
// folded row can react to the pointer without a click. The row handler never
|
|
12
|
+
// consumes the event: pi still gets it for text selection, and the repaint is
|
|
13
|
+
// requested directly.
|
|
14
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
15
|
+
|
|
16
|
+
export type HoverRow = "header" | "turn-header" | "row" | "title" | `job:${string}` | `codemode:${CodemodeSection}`;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* `ui` is kept as the object, not its `requestRender`: pi's TUI is a class, so
|
|
20
|
+
* an extracted method would lose `this`.
|
|
21
|
+
*/
|
|
22
|
+
type Renderer = { requestRender?(): void };
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Last renderer a tool handed us. Carrier components have no `ui` of their own,
|
|
26
|
+
* and a hovered row needs a repaint, so we borrow the neighbouring tool's.
|
|
27
|
+
*/
|
|
28
|
+
let lastUi: Renderer | undefined;
|
|
29
|
+
|
|
30
|
+
export function rememberRenderer(ui: Renderer): void {
|
|
31
|
+
lastUi = ui;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function lastRenderer(): Renderer | undefined {
|
|
35
|
+
return lastUi;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
let hoverState: { tool: object | null; row: HoverRow | null; ui?: Renderer } = { tool: null, row: null };
|
|
39
|
+
/** Set by a row that wants this packet; the alt-screen wrapper clears otherwise. */
|
|
40
|
+
let hoverClaimed = false;
|
|
41
|
+
/** Only tracked once the clear hook is in place — a stale band is worse than none. */
|
|
42
|
+
let hoverTracking = false;
|
|
43
|
+
|
|
44
|
+
export function hoverIsTracked(): boolean {
|
|
45
|
+
return hoverTracking;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A row wants this packet, so the alt-screen wrapper must not clear the band. */
|
|
49
|
+
export function markHoverClaimed(): void {
|
|
50
|
+
hoverClaimed = true;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Next render pass: which row of which tool the pointer is on, if any. */
|
|
54
|
+
export function setHover(tool: object | null, row: HoverRow | null, ui?: Renderer): boolean {
|
|
55
|
+
if (hoverState.tool === tool && hoverState.row === row) {
|
|
56
|
+
if (ui) hoverState.ui = ui;
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
hoverState = { tool, row, ui: ui ?? hoverState.ui };
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The pointer left our rows (or the app): drop the band and repaint it away. */
|
|
64
|
+
function clearHover(): boolean {
|
|
65
|
+
if (!hoverState.tool) return false;
|
|
66
|
+
hoverState = { tool: null, row: null, ui: hoverState.ui };
|
|
67
|
+
hoverState.ui?.requestRender?.();
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The alt screen that routes the packets: its renderer is the one that repaints. */
|
|
72
|
+
let hoverRenderer: { requestRender?(): void } | undefined;
|
|
73
|
+
|
|
74
|
+
/** Repaint after the pointer entered or left a row that is not a tool row. */
|
|
75
|
+
export function requestHoverRender(): void {
|
|
76
|
+
lastUi?.requestRender?.();
|
|
77
|
+
hoverRenderer?.requestRender?.();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Turn rows share this state with the tool rows: one source for the band, the
|
|
82
|
+
* hand and the clear-on-leave hook. Only claim while move tracking is live.
|
|
83
|
+
*/
|
|
84
|
+
export function claimHover(target: object | null, row: HoverRow | null): boolean {
|
|
85
|
+
if (!hoverTracking) return false;
|
|
86
|
+
if (row) hoverClaimed = true;
|
|
87
|
+
return setHover(row ? target : null, row);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The row of this component the pointer is on, if any. */
|
|
91
|
+
export function hoveredRow(target: object): HoverRow | null {
|
|
92
|
+
return hoverState.tool === target ? hoverState.row : null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Whether the pointer is on this component's row, after the leave hook ran. */
|
|
96
|
+
export function isRowHovered(target: object, row: HoverRow): boolean {
|
|
97
|
+
return hoverState.tool === target && hoverState.row === row;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A codemode body's fold row the pointer is on, if that is where it is. */
|
|
101
|
+
export function codemodeHover(tool: object): CodemodeSection | undefined {
|
|
102
|
+
if (hoverState.tool !== tool) return undefined;
|
|
103
|
+
const row = hoverState.row;
|
|
104
|
+
return row?.startsWith("codemode:") ? (row.slice("codemode:".length) as CodemodeSection) : undefined;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A full-width band behind the row: the whole row is the click target. */
|
|
108
|
+
export function hoverBand(line: string, width: number, theme: ThemeLike): string {
|
|
109
|
+
const padded = padToWidth(line, width);
|
|
110
|
+
return theme.bg ? theme.bg("selectedBg", padded) : padded;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const HOVER_HOOK = Symbol.for("pi-toolbox:hover-hook");
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* OSC 22, the pointer shape, in CSS's cursor names (Ghostty, kitty, foot,
|
|
117
|
+
* WezTerm). A lit row is a click target, so it gets the hand. `default` is the
|
|
118
|
+
* arrow a terminal shows while mouse tracking is on — the shape pi runs under —
|
|
119
|
+
* so it is what the pointer goes back to. Terminals without OSC 22 ignore both.
|
|
120
|
+
*/
|
|
121
|
+
const POINTER_SHAPE = "\x1b]22;pointer\x1b\\";
|
|
122
|
+
const DEFAULT_SHAPE = "\x1b]22;default\x1b\\";
|
|
123
|
+
/** What the terminal was last told, so a move along the same row writes nothing. */
|
|
124
|
+
let pointerShown = false;
|
|
125
|
+
|
|
126
|
+
type TerminalLike = { write?(data: string): void } | undefined;
|
|
127
|
+
|
|
128
|
+
function syncPointer(terminal: TerminalLike, lit: boolean): void {
|
|
129
|
+
if (lit === pointerShown || typeof terminal?.write !== "function") return;
|
|
130
|
+
pointerShown = lit;
|
|
131
|
+
terminal.write(lit ? POINTER_SHAPE : DEFAULT_SHAPE);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Every mouse packet goes through the alt screen. Watching it is what makes
|
|
136
|
+
* hover honest: a pointer that moves off our rows — onto the editor, a message,
|
|
137
|
+
* the scrollbar — produces no event for us at all, so without this hook the
|
|
138
|
+
* last row would stay lit forever. No hook, no hover.
|
|
139
|
+
*
|
|
140
|
+
* The pointer shape follows the band: a hand while a row is lit, the arrow
|
|
141
|
+
* again once nothing is.
|
|
142
|
+
*/
|
|
143
|
+
export function installHoverTracking(): void {
|
|
144
|
+
const proto = (TuiAltScreen as unknown as { prototype?: Record<PropertyKey, any> })?.prototype;
|
|
145
|
+
if (!proto || proto[HOVER_HOOK]) return;
|
|
146
|
+
const original = proto.handleMouseEvent;
|
|
147
|
+
if (typeof original !== "function") return;
|
|
148
|
+
proto.handleMouseEvent = function (this: { terminal?: TerminalLike; requestRender?(): void }, raw: unknown) {
|
|
149
|
+
hoverRenderer = this;
|
|
150
|
+
hoverClaimed = false;
|
|
151
|
+
const result = original.call(this, raw);
|
|
152
|
+
if (!hoverClaimed && clearHover()) requestHoverRender();
|
|
153
|
+
syncPointer(this.terminal, hoverState.tool !== null);
|
|
154
|
+
return result;
|
|
155
|
+
};
|
|
156
|
+
// Leaving the alt screen (exit, suspend, an external editor) must not leave
|
|
157
|
+
// the hand behind. It goes first: once pi turns mouse tracking off, Ghostty
|
|
158
|
+
// puts its own text cursor back, and an arrow written after that would stick.
|
|
159
|
+
const stop = proto.beforeTerminalStop;
|
|
160
|
+
if (typeof stop === "function") {
|
|
161
|
+
proto.beforeTerminalStop = function (this: { terminal?: TerminalLike }, ...args: unknown[]) {
|
|
162
|
+
syncPointer(this.terminal, false);
|
|
163
|
+
return stop.apply(this, args);
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
proto[HOVER_HOOK] = true;
|
|
167
|
+
hoverTracking = true;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Test seam: pretend the packets are being watched. */
|
|
171
|
+
export function enableHoverForTests(): void {
|
|
172
|
+
hoverTracking = true;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Test seam: pretend nothing is watching the packets. */
|
|
176
|
+
export function disableHoverForTests(): void {
|
|
177
|
+
hoverTracking = false;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Test seam: forget what is hovered. */
|
|
181
|
+
export function resetHover(): void {
|
|
182
|
+
hoverState = { tool: null, row: null };
|
|
183
|
+
hoverClaimed = false;
|
|
184
|
+
pointerShown = false;
|
|
185
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-tidy — a tidy transcript for the pi coding agent: a reply's tool calls
|
|
3
|
+
* fold into one clickable line, every box gets a rounded transparent frame.
|
|
4
|
+
*
|
|
5
|
+
* - every tool box (built-in, MCP, other extensions) gets a self-drawn rounded
|
|
6
|
+
* frame with status-aware border colors and no background fill
|
|
7
|
+
* - bash commands are syntax-highlighted
|
|
8
|
+
*
|
|
9
|
+
* Configuration: settings.json → "tidy" (the pre-rename "toolbox" key still
|
|
10
|
+
* works). Every option and when it applies: README, "Configuration".
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
14
|
+
import { keyHint, VERSION } from "@earendil-works/pi-coding-agent";
|
|
15
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
16
|
+
import { formatBashCallHighlighted } from "./tools/bash-highlight.ts";
|
|
17
|
+
import { cleanCopy, installCleanCopy } from "./clean-copy.ts";
|
|
18
|
+
import { patchContainerBoxes, patchMessageBoxes } from "./frame.ts";
|
|
19
|
+
import { collapsedResultBudget, shrinkResultPreview } from "./tools/result-preview.ts";
|
|
20
|
+
import { connectTurns } from "./turns/turn-lifecycle.ts";
|
|
21
|
+
import { codeBlocksAvailable } from "./turns/turn-view.ts";
|
|
22
|
+
import { turnOptions } from "./turns/turn-state.ts";
|
|
23
|
+
import { DEFAULT_BASH_RESULT_LINES, PI_WRITE_PREVIEW_LINES } from "./config.ts";
|
|
24
|
+
import { installForkToolFrames, loadForkConfig } from "../fork/index.ts";
|
|
25
|
+
import { agentRunning, tidyEnabled } from "./live.ts";
|
|
26
|
+
import { patchBashExecutions } from "./messages/bash-mode-frame.ts";
|
|
27
|
+
import { patchErrorLines } from "./messages/error-lines.ts";
|
|
28
|
+
import { patchUserMessages } from "./messages/user-message.ts";
|
|
29
|
+
import { restoreColor, withHexSwatchesCached } from "./messages/hex-swatches.ts";
|
|
30
|
+
import { formatWriteCallText } from "./tools/write-preview.ts";
|
|
31
|
+
import { connectJobs, registerNestedJobs, type EventBusLike } from "./tools/background-jobs.ts";
|
|
32
|
+
import { installGroupBoundaries } from "./tools/tool-group-view.ts";
|
|
33
|
+
import { getTheme, type ThemeLike } from "./theme-access.ts";
|
|
34
|
+
|
|
35
|
+
export { highlightBashCommand, formatBashCallHighlighted } from "./tools/bash-highlight.ts";
|
|
36
|
+
export { stripBackgroundFills, patchContainerBoxes, patchMessageBoxes, patchToolBoxFrames } from "./frame.ts";
|
|
37
|
+
|
|
38
|
+
interface BashRenderState {
|
|
39
|
+
startedAt?: number;
|
|
40
|
+
endedAt?: number;
|
|
41
|
+
/** Our own slot: the execution extension may be using `callText` itself. */
|
|
42
|
+
tidyCallText?: Text;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Decorate bash's rows without registering a replacement tool.
|
|
47
|
+
*
|
|
48
|
+
* Both changes are presentation only: a syntax-highlighted command row, and a
|
|
49
|
+
* smaller budget for the collapsed result preview. Registering `bash` to get
|
|
50
|
+
* them meant any extension that also owns it (a sandbox, for instance) failed
|
|
51
|
+
* to load with "Tool \"bash\" conflicts with …". As a renderer it composes: the
|
|
52
|
+
* active tool keeps execution, schema, shell and result renderer, and `next()`
|
|
53
|
+
* hands us whatever it has (pi's built-in renderers when it defines none).
|
|
54
|
+
*/
|
|
55
|
+
function registerBashRenderers(pi: ExtensionAPI, resultLines: number, highlight: boolean): void {
|
|
56
|
+
if (!hasRendererApi(pi)) return;
|
|
57
|
+
|
|
58
|
+
pi.registerToolRenderer((toolName, next) => {
|
|
59
|
+
const renderers = next();
|
|
60
|
+
if (toolName !== "bash" || !renderers) return renderers;
|
|
61
|
+
|
|
62
|
+
const renderCall = (args: any, theme: ThemeLike, context: any) => {
|
|
63
|
+
const state = context.state as BashRenderState;
|
|
64
|
+
// The built-in renderResult reads these for the "Took Xs" footer. We
|
|
65
|
+
// replaced the call renderer that normally sets them.
|
|
66
|
+
if (context.executionStarted && state.startedAt === undefined) {
|
|
67
|
+
state.startedAt = Date.now();
|
|
68
|
+
state.endedAt = undefined;
|
|
69
|
+
}
|
|
70
|
+
const text = state.tidyCallText ?? new Text("", 0, 0);
|
|
71
|
+
state.tidyCallText = text;
|
|
72
|
+
// 折叠态(默认)只留命令首行 + `+N more lines`,和 pi 其它工具的折叠行为一致;
|
|
73
|
+
// ctrl+o 展开后恢复整条命令(heredoc 之类)。
|
|
74
|
+
text.setText(
|
|
75
|
+
formatBashCallHighlighted(args, theme, {
|
|
76
|
+
expanded: context.expanded,
|
|
77
|
+
hint: keyHint("app.tools.expand", "to expand"),
|
|
78
|
+
}),
|
|
79
|
+
);
|
|
80
|
+
return text;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
// The budget has nothing to do with highlighting: with `highlightBash` off the
|
|
84
|
+
// command row stays whoever owns it, and the result is still budgeted.
|
|
85
|
+
const call = highlight ? { renderCall } : {};
|
|
86
|
+
// No result renderer downstream means nothing to budget; leave it absent
|
|
87
|
+
// rather than inventing a bare component.
|
|
88
|
+
const downstream = renderers.renderResult;
|
|
89
|
+
if (!downstream) return { ...renderers, ...call };
|
|
90
|
+
|
|
91
|
+
return {
|
|
92
|
+
...renderers,
|
|
93
|
+
...call,
|
|
94
|
+
renderResult(result: any, options: any, theme: any, context: any) {
|
|
95
|
+
// Whatever the execution extension draws stays: we only lower the
|
|
96
|
+
// preview budget inside it.
|
|
97
|
+
const component = downstream(result, options, theme, context);
|
|
98
|
+
// 内置 bash 结果预览固定 5 行(BASH_PREVIEW_LINES),pi 没给配置项。
|
|
99
|
+
// 折叠态下把它的行数预算改小;展开态和报错时保持原样(一行 traceback 没用)。
|
|
100
|
+
const budget = collapsedResultBudget(resultLines, context.isError);
|
|
101
|
+
if (!options.expanded && budget !== undefined) shrinkResultPreview(component, budget);
|
|
102
|
+
return component;
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Oldest pi everything works on: component mouse events (0.86), the bash
|
|
110
|
+
* preview budget (1.0) and tool durations (1.1). Checked at load rather than
|
|
111
|
+
* as a peer range — pi asks for `"*"` peers, and a peer conflict blocks every
|
|
112
|
+
* npm install in pi's package directory, not just this one.
|
|
113
|
+
*/const MIN_PI = "1.1.0";
|
|
114
|
+
|
|
115
|
+
function olderThan(version: string, min: string): boolean {
|
|
116
|
+
const parse = (v: string) => v.split(/[.-]/).slice(0, 3).map((part) => Number.parseInt(part, 10) || 0);
|
|
117
|
+
const [a, b] = [parse(version), parse(min)];
|
|
118
|
+
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] < b[i];
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Decorate write's call preview without registering a replacement tool. The
|
|
124
|
+
* active tool (e.g. pi-playpen's sandboxed write) keeps ownership of execution,
|
|
125
|
+
* and next() preserves its shell and result renderer, including error output.
|
|
126
|
+
*/
|
|
127
|
+
function registerWritePreview(pi: ExtensionAPI, lines: number): void {
|
|
128
|
+
// No fallback to a tool override: a duplicate registration takes down
|
|
129
|
+
// whoever else owns `write`. The caller has already warned (see entry point).
|
|
130
|
+
if (!hasRendererApi(pi)) return;
|
|
131
|
+
|
|
132
|
+
pi.registerToolRenderer((toolName, next) => {
|
|
133
|
+
const renderers = next();
|
|
134
|
+
if (toolName !== "write") return renderers;
|
|
135
|
+
|
|
136
|
+
return {
|
|
137
|
+
...renderers,
|
|
138
|
+
renderCall(args, theme, context) {
|
|
139
|
+
// Rendering state is shared with the execution extension's renderers.
|
|
140
|
+
// Use our own key so its cached components are not overwritten.
|
|
141
|
+
const state = context.state as { tidyWriteCallText?: Text };
|
|
142
|
+
const text = state.tidyWriteCallText ?? new Text("", 0, 0);
|
|
143
|
+
state.tidyWriteCallText = text;
|
|
144
|
+
const writeArgs = args as Parameters<typeof formatWriteCallText>[0];
|
|
145
|
+
text.setText(formatWriteCallText(writeArgs, theme, { expanded: context.expanded, lines }));
|
|
146
|
+
return text;
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** `registerToolRenderer` arrived in pi 1.3; peer ranges stay `*` (see MIN_PI). */
|
|
153
|
+
function hasRendererApi(pi: ExtensionAPI): boolean {
|
|
154
|
+
return typeof (pi as { registerToolRenderer?: unknown }).registerToolRenderer === "function";
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Say once, at session start, which renderer-backed features this pi cannot
|
|
159
|
+
* have. Only features the user actually asked for — warning someone who left
|
|
160
|
+
* `writeLines` at pi's own default would be pure noise.
|
|
161
|
+
*/
|
|
162
|
+
function warnUnavailableRenderers(pi: ExtensionAPI, features: string[]): void {
|
|
163
|
+
if (features.length === 0) return;
|
|
164
|
+
pi.on("session_start", (_event, ctx) => {
|
|
165
|
+
const list = features.join(" and ");
|
|
166
|
+
ctx.ui.notify(
|
|
167
|
+
`pi-tidy: ${list} need pi.registerToolRenderer (pi 1.3 or newer). Upgrade pi to turn ${features.length === 1 ? "it" : "them"} on.`,
|
|
168
|
+
"warning",
|
|
169
|
+
);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Pi extension entry point. */
|
|
174
|
+
export default function (pi: ExtensionAPI): void {
|
|
175
|
+
const config = loadForkConfig();
|
|
176
|
+
if (typeof VERSION === "string" && olderThan(VERSION, MIN_PI)) {
|
|
177
|
+
pi.on("session_start", (_event, ctx) => {
|
|
178
|
+
ctx.ui.notify(`pi-tidy needs pi ≥ ${MIN_PI} (this is ${VERSION}): clicks and durations won't work.`, "warning");
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
// The code-block rail hangs on a private method of pi's Markdown component.
|
|
182
|
+
// A pi that renames it keeps its own code blocks, and the setting is inert.
|
|
183
|
+
if (config.codeBlocks && !codeBlocksAvailable()) {
|
|
184
|
+
pi.on("session_start", (_event, ctx) => {
|
|
185
|
+
ctx.ui.notify("pi-tidy: this pi's Markdown draws code blocks itself, so `tidy.codeBlocks` does nothing on it.", "warning");
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
// Patches installed by an earlier load (before a /reload) read this live,
|
|
189
|
+
// so turning the extension off takes effect without a restart.
|
|
190
|
+
turnOptions.set({
|
|
191
|
+
collapseTurns: config.collapseTurns,
|
|
192
|
+
frameFinalReply: config.finalReplyStyle !== "off",
|
|
193
|
+
replyStyle: config.finalReplyStyle === "off" ? "frame" : config.finalReplyStyle,
|
|
194
|
+
icons: config.icons,
|
|
195
|
+
assistantColor: config.messageBorderColors.assistant,
|
|
196
|
+
timeFormat: config.messageTimeFormat,
|
|
197
|
+
headerStyle: config.messageHeaderStyle,
|
|
198
|
+
codeBlocks: config.codeBlocks,
|
|
199
|
+
splitDiff: config.splitDiff,
|
|
200
|
+
splitDiffMinWidth: config.splitDiffMinWidth,
|
|
201
|
+
});
|
|
202
|
+
tidyEnabled.set(config.enabled);
|
|
203
|
+
agentRunning.set(false);
|
|
204
|
+
if (!config.enabled) return;
|
|
205
|
+
if (config.collapseTurns !== "off" || config.finalReplyStyle !== "off") connectTurns(pi);
|
|
206
|
+
|
|
207
|
+
// The thinking row's "is this still arriving" cannot trust pi's private
|
|
208
|
+
// `isStreaming` flag (it is not always settled), and a text-growth window
|
|
209
|
+
// alone would keep spinning for a moment after the turn. The run's own
|
|
210
|
+
// boundaries are the authority: set on start, cleared when the loop ends.
|
|
211
|
+
pi.on("agent_start", () => agentRunning.set(true));
|
|
212
|
+
pi.on("agent_end", () => agentRunning.set(false));
|
|
213
|
+
pi.on("agent_settled", () => agentRunning.set(false));
|
|
214
|
+
// The group boundaries are a wrapper on the message renders, and it only sees
|
|
215
|
+
// anything while it is the outermost layer. Another extension may restyle a
|
|
216
|
+
// message after this load without calling down; put the wrapper back on top
|
|
217
|
+
// before a reply starts, not at its first tool, when half its calls have
|
|
218
|
+
// already joined a group. A no-op while it is still on top.
|
|
219
|
+
pi.on("before_agent_start", () => installGroupBoundaries());
|
|
220
|
+
|
|
221
|
+
const unavailable: string[] = [];
|
|
222
|
+
if (!hasRendererApi(pi)) {
|
|
223
|
+
if (config.highlightBash) unavailable.push("bash highlighting and the `bashResultLines` budget");
|
|
224
|
+
else if (config.bashResultLines !== DEFAULT_BASH_RESULT_LINES) unavailable.push("the `bashResultLines` budget");
|
|
225
|
+
if (config.writeLines !== PI_WRITE_PREVIEW_LINES) unavailable.push("the custom write preview (`writeLines`)");
|
|
226
|
+
}
|
|
227
|
+
warnUnavailableRenderers(pi, unavailable);
|
|
228
|
+
|
|
229
|
+
try {
|
|
230
|
+
installForkToolFrames(config, pi);
|
|
231
|
+
// Live job updates (pi-processes broadcasts on the shared extension bus).
|
|
232
|
+
connectJobs(config.backgroundJobs ? (pi as { events?: EventBusLike }).events : undefined);
|
|
233
|
+
if (config.backgroundJobs) registerNestedJobs(pi);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
console.debug("[pi-tidy] tool box frame patch failed:", error);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
try {
|
|
239
|
+
// Called even when off: `enabled: false` turns patches from an earlier
|
|
240
|
+
// load into pass-throughs.
|
|
241
|
+
patchMessageBoxes(config.messageBorderColors, config.icons, config.frameMessages);
|
|
242
|
+
patchContainerBoxes(config.messageBorderColors, {
|
|
243
|
+
icons: config.icons,
|
|
244
|
+
includeUser: config.userMessageStyle === "frame",
|
|
245
|
+
userAlign: config.userMessageAlign,
|
|
246
|
+
userMaxWidth: config.userMessageMaxWidth,
|
|
247
|
+
userTime: config.userMessageTime,
|
|
248
|
+
timeFormat: config.messageTimeFormat,
|
|
249
|
+
headerStyle: config.messageHeaderStyle,
|
|
250
|
+
enabled: config.frameMessages,
|
|
251
|
+
});
|
|
252
|
+
patchUserMessages({
|
|
253
|
+
style: config.userMessageStyle,
|
|
254
|
+
railColor: config.userMessageColors.rail,
|
|
255
|
+
ruleColor: config.userMessageColors.rule,
|
|
256
|
+
paddingY: config.userMessagePaddingY,
|
|
257
|
+
icons: config.icons,
|
|
258
|
+
time: config.userMessageTime,
|
|
259
|
+
align: config.userMessageAlign,
|
|
260
|
+
timeFormat: config.messageTimeFormat,
|
|
261
|
+
headerStyle: config.messageHeaderStyle,
|
|
262
|
+
});
|
|
263
|
+
patchBashExecutions({
|
|
264
|
+
enabled: config.frameMessages,
|
|
265
|
+
icons: config.icons,
|
|
266
|
+
// The user's own commands wear the user's color, whichever style draws them.
|
|
267
|
+
color:
|
|
268
|
+
config.userMessageStyle === "rail" ? config.userMessageColors.rail : config.messageBorderColors.user,
|
|
269
|
+
});
|
|
270
|
+
// pi's non-tool error rows: one framed row per failure instead of one per
|
|
271
|
+
// retry attempt.
|
|
272
|
+
patchErrorLines({ enabled: config.dedupeErrors });
|
|
273
|
+
} catch (error) {
|
|
274
|
+
console.debug("[pi-tidy] message box frame patch failed:", error);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
cleanCopy.set(config.cleanCopy);
|
|
278
|
+
if (config.cleanCopy && !installCleanCopy()) {
|
|
279
|
+
pi.on("session_start", (_event, ctx) => {
|
|
280
|
+
ctx.ui.notify("pi-tidy: this pi has no selection text to clean, so copies keep their frames.", "warning");
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// The user message rail and frame above draw on their own and never call
|
|
285
|
+
// down, so they bury the boundary wrapper `patchToolBoxFrames` installed. A
|
|
286
|
+
// buried wrapper used to come back only at the first grouped tool's render,
|
|
287
|
+
// mid-reply: the first reply of every process then split into two groups.
|
|
288
|
+
try {
|
|
289
|
+
installGroupBoundaries();
|
|
290
|
+
} catch (error) {
|
|
291
|
+
console.debug("[pi-tidy] group boundary install failed:", error);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
try {
|
|
295
|
+
registerBashRenderers(pi, config.bashResultLines, config.highlightBash);
|
|
296
|
+
} catch (error) {
|
|
297
|
+
console.debug("[pi-tidy] bash renderer failed:", error);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
try {
|
|
301
|
+
registerWritePreview(pi, config.writeLines);
|
|
302
|
+
} catch (error) {
|
|
303
|
+
console.debug("[pi-tidy] write preview renderer failed:", error);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// A hex color in a message gets a swatch painted with the color it names.
|
|
307
|
+
// Display only: the transformer runs before pi's own Markdown renderer and
|
|
308
|
+
// never reaches the session or the model context. Thinking is skipped — the
|
|
309
|
+
// box is dim and a swatch in it reads as a misplaced highlight.
|
|
310
|
+
if (config.hexSwatches) {
|
|
311
|
+
try {
|
|
312
|
+
pi.registerMarkdownTransformer((markdown, { messageType }) => {
|
|
313
|
+
if (messageType === "assistant-thinking" || !tidyEnabled.get()) return markdown;
|
|
314
|
+
const theme = getTheme();
|
|
315
|
+
if (!theme) return markdown;
|
|
316
|
+
return withHexSwatchesCached(markdown, restoreColor(theme, messageType), theme);
|
|
317
|
+
});
|
|
318
|
+
} catch (error) {
|
|
319
|
+
console.debug("[pi-tidy] hex swatch transformer failed:", error);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
package/src/live.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options the prototype patches read at call time.
|
|
3
|
+
*
|
|
4
|
+
* pi's components are one shared module, so each prototype is patched once per
|
|
5
|
+
* process. `/reload` re-runs the extension in a fresh module, though, and a
|
|
6
|
+
* patch that captured its options in a closure would keep the old ones — the
|
|
7
|
+
* "already patched" guard would drop the new settings on the floor. Keeping the
|
|
8
|
+
* options in a global slot lets a reload reach the patches already installed.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export interface LiveSlot<T> {
|
|
12
|
+
get(): T;
|
|
13
|
+
set(value: T): void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The slot that holds the revision counter itself; writing it must not bump it. */
|
|
17
|
+
const REVISION = "options-revision";
|
|
18
|
+
let revision: LiveSlot<number> | undefined;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A number that changes whenever a slot is written.
|
|
22
|
+
*
|
|
23
|
+
* The render caches hold what a box drew between frames. Keying them off the
|
|
24
|
+
* options they read means naming every option in every cache, and one missed
|
|
25
|
+
* name leaves the old frame on screen after a `/reload` with new settings — the
|
|
26
|
+
* bug class that made 0.9.4's split diff ignore a theme switch. A frame either
|
|
27
|
+
* sees the same revision it cached under, or it sees every new option at once.
|
|
28
|
+
*
|
|
29
|
+
* Reloading and re-patching are the only things that write a slot, so this bumps
|
|
30
|
+
* a handful of times per session, not per frame.
|
|
31
|
+
*/
|
|
32
|
+
export const optionsRevision = (): number => (revision ??= liveSlot<number>(REVISION, 0)).get();
|
|
33
|
+
|
|
34
|
+
function bumpRevision(): void {
|
|
35
|
+
revision ??= liveSlot<number>(REVISION, 0);
|
|
36
|
+
revision.set(revision.get() + 1);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function liveSlot<T>(name: string, initial: T): LiveSlot<T> {
|
|
40
|
+
// Still `pi-toolbox:`, on purpose: with the old package and pi-tidy both
|
|
41
|
+
// installed, they share one set of patches instead of framing twice.
|
|
42
|
+
const key = Symbol.for(`pi-toolbox:${name}`);
|
|
43
|
+
const store = globalThis as unknown as Record<symbol, LiveBox<T> | T | undefined>;
|
|
44
|
+
// The value lives in a box that every module instance shares, rather than
|
|
45
|
+
// directly in the global slot. `get` runs several times per rendered row, and
|
|
46
|
+
// reading a field off one small object is cheaper than a `globalThis[symbol]`
|
|
47
|
+
// lookup; a `/reload` still reaches patches left behind by the previous
|
|
48
|
+
// module, because it swaps the value inside the shared box.
|
|
49
|
+
const existing = store[key];
|
|
50
|
+
const box: LiveBox<T> = isLiveBox<T>(existing) ? existing : { value: existing === undefined ? initial : (existing as T) };
|
|
51
|
+
store[key] = box;
|
|
52
|
+
return {
|
|
53
|
+
get: () => box.value,
|
|
54
|
+
set: (value) => {
|
|
55
|
+
box.value = value;
|
|
56
|
+
// An older build sharing the symbol writes a bare value back into the
|
|
57
|
+
// slot; putting the box back keeps the two on the same object.
|
|
58
|
+
if (store[key] !== box) store[key] = box;
|
|
59
|
+
if (name !== REVISION) bumpRevision();
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
interface LiveBox<T> {
|
|
65
|
+
value: T;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** An older build may have left a bare value in the slot; adopt it as the box. */
|
|
69
|
+
function isLiveBox<T>(value: unknown): value is LiveBox<T> {
|
|
70
|
+
return typeof value === "object" && value !== null && "value" in value;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** `tidy.enabled`: false turns every installed patch into a pass-through. */
|
|
74
|
+
export const tidyEnabled = liveSlot("enabled", true);
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* An agent run is in flight: `agent_start` … `agent_end`/`agent_settled`. This
|
|
78
|
+
* is the only signal about pi's work that cannot go stale, so the thinking rows
|
|
79
|
+
* use it to stop animating the moment the run is over.
|
|
80
|
+
*
|
|
81
|
+
* A slot rather than a module variable: `/reload` builds a new module while the
|
|
82
|
+
* patches from the old one keep rendering, and both have to see the same value.
|
|
83
|
+
*/
|
|
84
|
+
export const agentRunning = liveSlot("agent-running", false);
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* `tidy.groupOpen`: whether a new tool group is born open. A slot for the same
|
|
88
|
+
* reason: `/reload` pushes the setting from a fresh module instance, while the
|
|
89
|
+
* render patch installed by the previous one is what asks for new groups.
|
|
90
|
+
*/
|
|
91
|
+
export const groupOpen = liveSlot("group-open", false);
|