@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.
Files changed (40) hide show
  1. package/CHANGELOG.md +1104 -0
  2. package/FORK-CHANGELOG.md +31 -0
  3. package/LICENSE +21 -0
  4. package/README.md +416 -2
  5. package/fork/defaults.ts +77 -0
  6. package/fork/index.ts +2 -0
  7. package/fork/install.ts +58 -0
  8. package/fork/thinking-row.ts +221 -0
  9. package/package.json +68 -3
  10. package/src/clean-copy.ts +313 -0
  11. package/src/clipboard.ts +29 -0
  12. package/src/config.ts +292 -0
  13. package/src/draw/frame-draw.ts +307 -0
  14. package/src/draw/icons.ts +2014 -0
  15. package/src/draw/paint.ts +57 -0
  16. package/src/frame.ts +20 -0
  17. package/src/hover.ts +185 -0
  18. package/src/index.ts +322 -0
  19. package/src/live.ts +91 -0
  20. package/src/messages/bash-mode-frame.ts +112 -0
  21. package/src/messages/error-lines.ts +331 -0
  22. package/src/messages/extension-notice.ts +204 -0
  23. package/src/messages/hex-swatches.ts +245 -0
  24. package/src/messages/message-frame.ts +515 -0
  25. package/src/messages/user-message.ts +207 -0
  26. package/src/theme-access.ts +26 -0
  27. package/src/tools/background-jobs.ts +617 -0
  28. package/src/tools/bash-highlight.ts +330 -0
  29. package/src/tools/codemode-body.ts +602 -0
  30. package/src/tools/result-preview.ts +56 -0
  31. package/src/tools/split-diff.ts +606 -0
  32. package/src/tools/tool-frame.ts +1019 -0
  33. package/src/tools/tool-group-view.ts +1160 -0
  34. package/src/tools/tool-groups.ts +706 -0
  35. package/src/tools/tool-lines.ts +621 -0
  36. package/src/tools/write-preview.ts +81 -0
  37. package/src/turns/code-blocks.ts +273 -0
  38. package/src/turns/turn-lifecycle.ts +43 -0
  39. package/src/turns/turn-state.ts +257 -0
  40. package/src/turns/turn-view.ts +504 -0
@@ -0,0 +1,245 @@
1
+ /**
2
+ * A color swatch in front of a color a message names: `#7f849c`,
3
+ * `rgb(127, 132, 156)`, `hsla(240, 10%, 15%, .8)`. The value keeps its text and
4
+ * gains a `●` painted in that color.
5
+ *
6
+ * Display only — `pi.registerMarkdownTransformer` never touches the session or
7
+ * the model context. The swatch is a foreground glyph, not a background fill:
8
+ * a user message's rows go through `stripBackgroundFills` (the rail and frame
9
+ * styles repaint the fill themselves), and a fill would be painted out there.
10
+ *
11
+ * Fenced code blocks and inline code are left alone. A swatch inside a snippet
12
+ * is noise, and a shell comment that happens to look like a color (`#abc`) is
13
+ * not one. Named CSS colors are left alone as well: `red` and `tomato` are
14
+ * ordinary words in prose.
15
+ */
16
+
17
+ import { paint } from "../draw/paint.ts";
18
+ import type { ThemeLike } from "../theme-access.ts";
19
+
20
+ /**
21
+ * A dot, not a block: one cell wide, present in every monospace font, and it
22
+ * reads as a color chip beside the value instead of a hole punched in the line.
23
+ * Nerd Font private-use glyphs are the alternative, but their real width varies
24
+ * by font (pi-tui measures them as one cell, some draw two).
25
+ */
26
+ export const SWATCH_GLYPH = "●";
27
+
28
+ /** Longest first, so `#7f849cff` does not match as `#7f84` plus a broken tail. */
29
+ const HEX_RE = /#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{4}|[0-9a-fA-F]{3})(?![0-9a-zA-Z])/;
30
+ const HEX_AT = new RegExp(HEX_RE.source, "g");
31
+
32
+ /**
33
+ * `rgb()` / `rgba()` / `hsl()` / `hsla()`, spaces or commas between the parts.
34
+ * No nested parentheses, and a length cap, so a `calc()` inside is not attempted
35
+ * and a runaway match cannot swallow a paragraph.
36
+ */
37
+ const FUNC_RE = /\b(?:rgba?|hsla?)\([^()\n]{1,48}?\)/gi;
38
+ const FUNC_AT = new RegExp(FUNC_RE.source, "gi");
39
+
40
+ /** Up to three spaces of indent, then a run of three or more of one char. */
41
+ const FENCE_RE = /^ {0,3}(`{3,}|~{3,})/;
42
+
43
+ interface Fence {
44
+ char: string;
45
+ length: number;
46
+ }
47
+
48
+ function toHex(channels: [number, number, number]): string {
49
+ return `#${channels
50
+ .map((value) => Math.max(0, Math.min(255, Math.round(value))).toString(16).padStart(2, "0"))
51
+ .join("")}`;
52
+ }
53
+
54
+ /** `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa` as `#rrggbb`; alpha has nothing to blend against. */
55
+ function hexColor(hex: string): string | undefined {
56
+ let body = hex.slice(1);
57
+ if (body.length === 4) body = body.slice(0, 3);
58
+ else if (body.length === 8) body = body.slice(0, 6);
59
+ if (body.length === 3) body = [...body].map((cell) => cell + cell).join("");
60
+ return body.length === 6 ? `#${body.toLowerCase()}` : undefined;
61
+ }
62
+
63
+ function rgbColor(parts: readonly string[]): string | undefined {
64
+ const channels = parts.map((part) => {
65
+ const value = Number.parseFloat(part);
66
+ if (!Number.isFinite(value)) return Number.NaN;
67
+ // `rgb(50%, 0%, 0%)` is the same as `rgb(127.5, 0, 0)`.
68
+ return part.endsWith("%") ? (value * 255) / 100 : value;
69
+ });
70
+ if (channels.some(Number.isNaN)) return undefined;
71
+ return toHex(channels as [number, number, number]);
72
+ }
73
+
74
+ function hslToRgb(hue: number, saturation: number, lightness: number): [number, number, number] {
75
+ const h = ((hue % 360) + 360) % 360;
76
+ const s = Math.max(0, Math.min(100, saturation)) / 100;
77
+ const l = Math.max(0, Math.min(100, lightness)) / 100;
78
+ const chroma = (1 - Math.abs(2 * l - 1)) * s;
79
+ const second = chroma * (1 - Math.abs(((h / 60) % 2) - 1));
80
+ const floor = l - chroma / 2;
81
+ const [r, g, b] =
82
+ h < 60 ? [chroma, second, 0] : h < 120 ? [second, chroma, 0] : h < 180 ? [0, chroma, second] : h < 240 ? [0, second, chroma] : h < 300 ? [second, 0, chroma] : [chroma, 0, second];
83
+ return [(r + floor) * 255, (g + floor) * 255, (b + floor) * 255];
84
+ }
85
+
86
+ function hslColor(parts: readonly string[]): string | undefined {
87
+ const numbers = parts.map((part) => Number.parseFloat(part));
88
+ if (numbers.some((value) => !Number.isFinite(value))) return undefined;
89
+ return toHex(hslToRgb(numbers[0]!, numbers[1]!, numbers[2]!));
90
+ }
91
+
92
+ function functionColor(value: string): string | undefined {
93
+ const open = value.indexOf("(");
94
+ if (open < 0) return undefined;
95
+ const name = value.slice(0, open).trim().toLowerCase();
96
+ const parts = value
97
+ .slice(open + 1)
98
+ .replace(/\)\s*$/, "")
99
+ .split(/[\s,/]+/)
100
+ .filter((part) => part.length > 0);
101
+ // Alpha is the fourth part and is ignored, like the hex forms.
102
+ if (parts.length < 3) return undefined;
103
+ return name.startsWith("rgb") ? rgbColor(parts.slice(0, 3)) : hslColor(parts.slice(0, 3));
104
+ }
105
+
106
+ /** `#rrggbb` for any color value this transformer draws, or `undefined`. */
107
+ export function swatchColor(value: string): string | undefined {
108
+ return value.startsWith("#") ? hexColor(value) : functionColor(value);
109
+ }
110
+
111
+ /**
112
+ * The escape sequence that puts a user message's text color back.
113
+ *
114
+ * pi draws a user message's Markdown with a `defaultTextStyle` that wraps each
115
+ * text token in `userMessageText`, so an SGR reset inside the token drops the
116
+ * color for the rest of it. Assistant text has no default style, so nothing is
117
+ * lost there and this returns "". Built the way pi-tui builds its own
118
+ * `stylePrefix`: style a sentinel, keep what came before it.
119
+ */
120
+ export function restoreColor(theme: ThemeLike, messageType: string): string {
121
+ if (messageType !== "user") return "";
122
+ const sentinel = "\u0000";
123
+ let styled: string;
124
+ try {
125
+ styled = theme.fg("userMessageText", sentinel);
126
+ } catch {
127
+ return "";
128
+ }
129
+ const at = styled.indexOf(sentinel);
130
+ return at > 0 ? styled.slice(0, at) : "";
131
+ }
132
+
133
+ function swatch(value: string, restore: string, theme: ThemeLike): string {
134
+ const color = swatchColor(value);
135
+ if (!color) return value;
136
+ // The dot, then the enclosing style back, then the value itself unpainted:
137
+ // it reads as the sentence it belongs to, not as the label of a chip.
138
+ return `${paint(theme, color, SWATCH_GLYPH)}${restore} ${value}`;
139
+ }
140
+
141
+ /** The index just past a closing run of exactly `length` backticks, or -1. */
142
+ function closingTicks(line: string, from: number, length: number): number {
143
+ let at = line.indexOf("`".repeat(length), from);
144
+ while (at !== -1) {
145
+ // A longer run is that run, not the end of this one.
146
+ if (line[at + length] !== "`") return at + length;
147
+ at = line.indexOf("`".repeat(length), at + length + 1);
148
+ }
149
+ return -1;
150
+ }
151
+
152
+ function swatchesInLine(line: string, restore: string, theme: ThemeLike): string {
153
+ let out = "";
154
+ let i = 0;
155
+ while (i < line.length) {
156
+ const char = line[i]!;
157
+ if (char === "`") {
158
+ let run = 1;
159
+ while (line[i + run] === "`") run++;
160
+ const end = closingTicks(line, i + run, run);
161
+ if (end === -1) return out + line.slice(i);
162
+ out += line.slice(i, end);
163
+ i = end;
164
+ continue;
165
+ }
166
+ const match = colorAt(line, i);
167
+ if (match) {
168
+ out += swatch(match, restore, theme);
169
+ i += match.length;
170
+ continue;
171
+ }
172
+ out += char;
173
+ i++;
174
+ }
175
+ return out;
176
+ }
177
+
178
+ /** The color value that starts exactly at `index`, or undefined. */
179
+ function colorAt(line: string, index: number): string | undefined {
180
+ const char = line[index];
181
+ if (char === "#") {
182
+ HEX_AT.lastIndex = index;
183
+ const match = HEX_AT.exec(line);
184
+ if (match && match.index === index) return match[0];
185
+ return undefined;
186
+ }
187
+ if (char !== "r" && char !== "R" && char !== "h" && char !== "H") return undefined;
188
+ // `myrgb(…)` is not a color, and the regex's `\b` starts one cell later.
189
+ const before = line[index - 1];
190
+ if (before !== undefined && /[0-9A-Za-z_]/.test(before)) return undefined;
191
+ FUNC_AT.lastIndex = index;
192
+ const match = FUNC_AT.exec(line);
193
+ return match && match.index === index ? match[0] : undefined;
194
+ }
195
+
196
+ function mayHaveColor(markdown: string): boolean {
197
+ return markdown.includes("#") || /rgba?\(|hsla?\(/i.test(markdown);
198
+ }
199
+
200
+ /**
201
+ * The markdown with a swatch in front of every color outside code. `restore`
202
+ * is what `restoreColor` returned for this message.
203
+ */
204
+ export function withHexSwatches(markdown: string, restore: string, theme: ThemeLike): string {
205
+ if (!mayHaveColor(markdown)) return markdown;
206
+ const lines = markdown.split("\n");
207
+ let fence: Fence | undefined;
208
+ for (let i = 0; i < lines.length; i++) {
209
+ const line = lines[i]!;
210
+ const opened = FENCE_RE.exec(line);
211
+ if (fence) {
212
+ // The closing fence is the same character, at least as long, and nothing
213
+ // but whitespace after it.
214
+ if (opened && opened[1]![0] === fence.char && opened[1]!.length >= fence.length && line.slice(opened[0].length).trim() === "") {
215
+ fence = undefined;
216
+ }
217
+ continue;
218
+ }
219
+ if (opened) {
220
+ fence = { char: opened[1]![0]!, length: opened[1]!.length };
221
+ continue;
222
+ }
223
+ if (mayHaveColor(line)) lines[i] = swatchesInLine(line, restore, theme);
224
+ }
225
+ return lines.join("\n");
226
+ }
227
+
228
+ /**
229
+ * Streaming re-renders the same markdown several times a second, and a settled
230
+ * reply re-renders on every width change. The swatches of one message do not
231
+ * change until its text does, so the last few results are kept.
232
+ */
233
+ const CACHE_LIMIT = 256;
234
+ const cache = new Map<string, string>();
235
+
236
+ export function withHexSwatchesCached(markdown: string, restore: string, theme: ThemeLike): string {
237
+ if (!mayHaveColor(markdown)) return markdown;
238
+ const key = `${theme.getColorMode?.() ?? "truecolor"}\u0000${restore}\u0000${markdown}`;
239
+ const hit = cache.get(key);
240
+ if (hit !== undefined) return hit;
241
+ const out = withHexSwatches(markdown, restore, theme);
242
+ if (cache.size >= CACHE_LIMIT) cache.delete(cache.keys().next().value!);
243
+ cache.set(key, out);
244
+ return out;
245
+ }