pi-syntax-highlight 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 +60 -0
- package/README.md +68 -2
- package/extensions/index.ts +22 -0
- package/package.json +35 -4
- package/src/active-theme.ts +26 -0
- package/src/detect-language.ts +294 -0
- package/src/emphasis.ts +160 -0
- package/src/grep-parse.ts +42 -0
- package/src/highlight.ts +109 -0
- package/src/markdown-fence-lang.ts +180 -0
- package/src/markdown-style.ts +134 -0
- package/src/markdown-theme.ts +53 -0
- package/src/render-bash.ts +180 -0
- package/src/render-edit.ts +207 -0
- package/src/render-find.ts +64 -0
- package/src/render-generic.ts +86 -0
- package/src/render-grep.ts +142 -0
- package/src/render-ls.ts +66 -0
- package/src/render-path.ts +54 -0
- package/src/render-read.ts +277 -0
- package/src/render-utils.ts +219 -0
- package/src/render-write.ts +81 -0
- package/src/resolve-renderers.ts +406 -0
- package/src/style-path.ts +48 -0
- package/src/tokens.ts +114 -0
- package/test/unit/active-theme.test.ts +38 -0
- package/test/unit/bash-preview.test.ts +57 -0
- package/test/unit/detect-language.test.ts +124 -0
- package/test/unit/emphasis.test.ts +113 -0
- package/test/unit/extensions-index.test.ts +116 -0
- package/test/unit/grep-parse.test.ts +125 -0
- package/test/unit/highlight.test.ts +107 -0
- package/test/unit/markdown-fence-lang.test.ts +131 -0
- package/test/unit/markdown-pipeline.test.ts +153 -0
- package/test/unit/markdown-render-parity.test.ts +127 -0
- package/test/unit/markdown-style.test.ts +152 -0
- package/test/unit/markdown-theme.test.ts +86 -0
- package/test/unit/render-bash.test.ts +194 -0
- package/test/unit/render-edit.test.ts +214 -0
- package/test/unit/render-find.test.ts +139 -0
- package/test/unit/render-generic.test.ts +152 -0
- package/test/unit/render-grep.test.ts +338 -0
- package/test/unit/render-ls.test.ts +132 -0
- package/test/unit/render-read.test.ts +375 -0
- package/test/unit/render-utils.test.ts +324 -0
- package/test/unit/render-write.test.ts +143 -0
- package/test/unit/resolve-renderers.test.ts +474 -0
- package/test/unit/style-path.test.ts +74 -0
- package/tsconfig.json +15 -0
package/src/render-ls.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { buildListBody, truncatedNotice } from "./render-utils.ts";
|
|
2
|
+
import { classifyPathLine, stylePath } from "./style-path.ts";
|
|
3
|
+
import { TOKEN, type StyleTheme } from "./tokens.ts";
|
|
4
|
+
|
|
5
|
+
// The built-in ls renderer shows 20 lines when collapsed; any other number is
|
|
6
|
+
// a visible difference against stock pi.
|
|
7
|
+
const COLLAPSED_LINES = 20;
|
|
8
|
+
|
|
9
|
+
export interface LsInput {
|
|
10
|
+
output: string;
|
|
11
|
+
expanded: boolean;
|
|
12
|
+
/**
|
|
13
|
+
* A failed listing is painted flat: styling it by file family would read as a
|
|
14
|
+
* normal listing, and stock pi leaves the failure in the content color.
|
|
15
|
+
*/
|
|
16
|
+
isError: boolean;
|
|
17
|
+
details:
|
|
18
|
+
| {
|
|
19
|
+
entryLimitReached?: number;
|
|
20
|
+
truncation?: { truncated?: boolean; maxBytes?: number };
|
|
21
|
+
}
|
|
22
|
+
| undefined;
|
|
23
|
+
theme: StyleTheme;
|
|
24
|
+
expandHint: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// ls prints bare entry names, so `dir/` has no leading segments to dim and every
|
|
28
|
+
// non-sentinel line is a single entry.
|
|
29
|
+
function styleLsLine(line: string, theme: StyleTheme): string {
|
|
30
|
+
const entry = classifyPathLine(line);
|
|
31
|
+
switch (entry.kind) {
|
|
32
|
+
case "dir":
|
|
33
|
+
case "file":
|
|
34
|
+
return stylePath(entry.path, theme);
|
|
35
|
+
case "notice":
|
|
36
|
+
return theme.fg(TOKEN.notice, entry.text);
|
|
37
|
+
case "plain":
|
|
38
|
+
return theme.fg(TOKEN.empty, entry.text);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function buildLsResultText(input: LsInput): string {
|
|
43
|
+
// `ls` ends its output with its own "[N entries limit reached. Use limit=...]"
|
|
44
|
+
// block, and stock pi counts it as one more body line: it is painted as a
|
|
45
|
+
// notice and it counts toward the collapsed cut.
|
|
46
|
+
let text = buildListBody({
|
|
47
|
+
body: input.output.trim(),
|
|
48
|
+
expanded: input.expanded,
|
|
49
|
+
collapsedLines: COLLAPSED_LINES,
|
|
50
|
+
theme: input.theme,
|
|
51
|
+
expandHint: input.expandHint,
|
|
52
|
+
styleLine: (line) =>
|
|
53
|
+
input.isError ? input.theme.fg(TOKEN.content, line) : styleLsLine(line, input.theme),
|
|
54
|
+
});
|
|
55
|
+
// Stock pi paints the details-derived warning last, so it is appended instead
|
|
56
|
+
// of passed into the body builder.
|
|
57
|
+
text += truncatedNotice(
|
|
58
|
+
{
|
|
59
|
+
limitCount: input.details?.entryLimitReached,
|
|
60
|
+
limitLabel: "entries limit",
|
|
61
|
+
truncation: input.details?.truncation,
|
|
62
|
+
},
|
|
63
|
+
input.theme,
|
|
64
|
+
);
|
|
65
|
+
return text;
|
|
66
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { getCapabilities, hyperlink } from "@earendil-works/pi-tui";
|
|
5
|
+
import { TOKEN, type StyleTheme } from "./tokens.ts";
|
|
6
|
+
|
|
7
|
+
// The path display the built-in tool headers share. The host does not export
|
|
8
|
+
// `renderToolPath`, `shortenPath` or `linkPath`, so a header of this package has
|
|
9
|
+
// to reproduce them from the primitives it does export (`hyperlink`, the
|
|
10
|
+
// terminal capabilities and the two colors below). Everything here is display:
|
|
11
|
+
// the text is shortened for the eye while the link still targets the absolute
|
|
12
|
+
// path, so a click opens the file the tool actually read.
|
|
13
|
+
|
|
14
|
+
// Only the home directory is shortened. The built-in never makes the path
|
|
15
|
+
// relative to the cwd, so a file outside the home directory keeps its full path.
|
|
16
|
+
export function shortenPath(path: string): string {
|
|
17
|
+
const home = homedir();
|
|
18
|
+
return path.startsWith(home) ? `~${path.slice(home.length)}` : path;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// The target of the link: the argument as the tool itself resolves it, with `~`
|
|
22
|
+
// expanded and a relative path anchored at the cwd. A path that is already
|
|
23
|
+
// absolute passes through `resolve` untouched.
|
|
24
|
+
export function absolutePath(rawPath: string, cwd: string | undefined): string {
|
|
25
|
+
const expanded = rawPath === "~" || rawPath.startsWith("~/") ? `${homedir()}${rawPath.slice(1)}` : rawPath;
|
|
26
|
+
return resolve(cwd ?? process.cwd(), expanded);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// OSC 8, gated on the terminal capability exactly like the built-in, so a
|
|
30
|
+
// terminal without hyperlink support shows the styled text alone.
|
|
31
|
+
export function linkPath(styledText: string, rawPath: string, cwd: string | undefined): string {
|
|
32
|
+
if (!getCapabilities().hyperlinks) return styledText;
|
|
33
|
+
return hyperlink(styledText, pathToFileURL(absolutePath(rawPath, cwd)).href);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// An empty path is the argument that has not arrived yet, which the built-in
|
|
37
|
+
// renders as a placeholder instead of an empty slot.
|
|
38
|
+
export function renderToolPath(rawPath: string, theme: StyleTheme, cwd: string | undefined): string {
|
|
39
|
+
if (rawPath === "") return theme.fg(TOKEN.plain, "...");
|
|
40
|
+
return linkPath(theme.fg(TOKEN.path, shortenPath(rawPath)), rawPath, cwd);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// The one cwd-relative form the built-in shows: a path inside the cwd becomes
|
|
44
|
+
// relative, anything else stays absolute, and the separators are made posix so
|
|
45
|
+
// the label reads the same on every platform.
|
|
46
|
+
export function relativeToCwdOrAbsolute(filePath: string, cwd: string | undefined): string {
|
|
47
|
+
const base = resolve(cwd ?? process.cwd());
|
|
48
|
+
const absolute = resolve(filePath);
|
|
49
|
+
const relativePath = relative(base, absolute);
|
|
50
|
+
const inside =
|
|
51
|
+
relativePath === "" ||
|
|
52
|
+
(relativePath !== ".." && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath));
|
|
53
|
+
return (inside ? relativePath || "." : absolute).split(sep).join("/");
|
|
54
|
+
}
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
2
|
+
import {
|
|
3
|
+
DEFAULT_MAX_BYTES,
|
|
4
|
+
DEFAULT_MAX_LINES,
|
|
5
|
+
formatReadLineRange,
|
|
6
|
+
formatSize,
|
|
7
|
+
getLanguageFromPath,
|
|
8
|
+
getPackageDir,
|
|
9
|
+
keyText,
|
|
10
|
+
} from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import { highlightLines, type HighlightFn } from "./highlight.ts";
|
|
12
|
+
import { absolutePath, relativeToCwdOrAbsolute, renderToolPath } from "./render-path.ts";
|
|
13
|
+
import { moreLinesFooter, replaceTabs } from "./render-utils.ts";
|
|
14
|
+
import { BOLD_OFF, BOLD_ON, TOKEN, type StyleTheme } from "./tokens.ts";
|
|
15
|
+
|
|
16
|
+
// The built-in read renderer shows 10 lines when collapsed; any other number is
|
|
17
|
+
// a visible difference against stock pi.
|
|
18
|
+
const COLLAPSED_LINES = 10;
|
|
19
|
+
|
|
20
|
+
// The notices the tool appends after a blank line, matched in full. Anchoring is
|
|
21
|
+
// what keeps a file whose last line merely opens with a bracket as body text.
|
|
22
|
+
const READ_NOTICES = [
|
|
23
|
+
/^\[\d+ more lines in file\. Use offset=\d+ to continue\.\]$/,
|
|
24
|
+
// The byte limit is spelled by `formatSize`, which prints whole bytes without a
|
|
25
|
+
// decimal and the larger units with one (`512B`, `50.0KB`, `1.5MB`), always
|
|
26
|
+
// followed by " limit".
|
|
27
|
+
/^\[Showing lines \d+-\d+ of \d+( \(\d+(?:\.\d+)?(?:B|KB|MB) limit\))?\. Use offset=\d+ to continue\.\]$/,
|
|
28
|
+
];
|
|
29
|
+
const NOTICE_SEPARATOR = "\n\n";
|
|
30
|
+
|
|
31
|
+
// The compact header the built-in prints instead of the full path for the files
|
|
32
|
+
// the agent reads about itself.
|
|
33
|
+
const COMPACT_RESOURCE_FILE_NAMES = new Set(["AGENTS.override.md", "AGENTS.md", "AGENTS.MD", "CLAUDE.md", "CLAUDE.MD"]);
|
|
34
|
+
const SKILL_FILE_NAME = "SKILL.md";
|
|
35
|
+
const PI_DOC_PREFIXES = ["docs/", "examples/"];
|
|
36
|
+
const PI_DOC_README = "README.md";
|
|
37
|
+
|
|
38
|
+
// `keyText` reads the live keybinding table, which is empty outside a session;
|
|
39
|
+
// the built-in default keeps the hint readable instead of " ( to expand)".
|
|
40
|
+
const EXPAND_KEYBINDING = "app.tools.expand";
|
|
41
|
+
const DEFAULT_EXPAND_KEY = "ctrl+o";
|
|
42
|
+
|
|
43
|
+
// The truncation the host records for a read; every field is optional because a
|
|
44
|
+
// result restored from a session may carry an older shape.
|
|
45
|
+
export interface ReadTruncation {
|
|
46
|
+
truncated?: boolean;
|
|
47
|
+
truncatedBy?: "lines" | "bytes" | null;
|
|
48
|
+
firstLineExceedsLimit?: boolean;
|
|
49
|
+
outputLines?: number;
|
|
50
|
+
totalLines?: number;
|
|
51
|
+
maxLines?: number;
|
|
52
|
+
maxBytes?: number;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface ReadResultInput {
|
|
56
|
+
output: string;
|
|
57
|
+
/** The argument's path, "" when the call does not carry one. */
|
|
58
|
+
path: string;
|
|
59
|
+
/** 1-based first line the tool read, which is also the first line number shown. */
|
|
60
|
+
offset: number | undefined;
|
|
61
|
+
details: { truncation?: ReadTruncation } | undefined;
|
|
62
|
+
expanded: boolean;
|
|
63
|
+
isError: boolean;
|
|
64
|
+
/** The result carries an image block, so the body is not file text. */
|
|
65
|
+
hasImage: boolean;
|
|
66
|
+
theme: StyleTheme;
|
|
67
|
+
expandHint: string;
|
|
68
|
+
highlight: HighlightFn;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface ReadCallInput {
|
|
72
|
+
path: string;
|
|
73
|
+
offset: number | undefined;
|
|
74
|
+
limit: number | undefined;
|
|
75
|
+
/** The transcript is collapsed, so the built-in header is the compact one. */
|
|
76
|
+
compact: boolean;
|
|
77
|
+
theme: StyleTheme;
|
|
78
|
+
cwd: string | undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// The two compact headers the built-in prints: a skill is announced by name, a
|
|
82
|
+
// resource of the agent or of pi by a cwd-relative label.
|
|
83
|
+
type ReadClassification = { kind: "skill" | "resource"; label: string };
|
|
84
|
+
|
|
85
|
+
export function readPath(args: unknown): string {
|
|
86
|
+
if (typeof args !== "object" || args === null) return "";
|
|
87
|
+
const value = (args as { file_path?: unknown; path?: unknown }).file_path ?? (args as { path?: unknown }).path;
|
|
88
|
+
return typeof value === "string" ? value : "";
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Line counts arrive as numbers from the schema and as numeric strings from a
|
|
92
|
+
// restored session, so both are read; a value that is not a finite number leaves
|
|
93
|
+
// the field unset and the caller falls back to the built-in default.
|
|
94
|
+
function lineCount(value: unknown): number | undefined {
|
|
95
|
+
const parsed = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
|
|
96
|
+
if (typeof parsed !== "number" || !Number.isFinite(parsed)) return undefined;
|
|
97
|
+
// Fractional and non-positive offsets do not name a line; the tool itself
|
|
98
|
+
// rejects them, so the clamp only keeps the gutter printable.
|
|
99
|
+
return Math.max(1, Math.floor(parsed));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function readOffset(args: unknown): number | undefined {
|
|
103
|
+
return lineCount(typeof args === "object" && args !== null ? (args as { offset?: unknown }).offset : undefined);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function readLimit(args: unknown): number | undefined {
|
|
107
|
+
return lineCount(typeof args === "object" && args !== null ? (args as { limit?: unknown }).limit : undefined);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// The tool separates its continuation notice from the body with a blank line, so
|
|
111
|
+
// the split both looks for that separator and matches the whole block: a body
|
|
112
|
+
// line that reads like a notice stays in the body. The oversized-first-line
|
|
113
|
+
// message is the whole output and carries no separator at all.
|
|
114
|
+
export function splitReadNotice(
|
|
115
|
+
output: string,
|
|
116
|
+
firstLineExceedsLimit: boolean,
|
|
117
|
+
): { body: string; notice: string | undefined } {
|
|
118
|
+
if (firstLineExceedsLimit) {
|
|
119
|
+
const block = output.trim();
|
|
120
|
+
if (block === "") return { body: "", notice: undefined };
|
|
121
|
+
const unbracketed = block.startsWith("[") && block.endsWith("]") ? block.slice(1, -1) : block;
|
|
122
|
+
return { body: "", notice: unbracketed };
|
|
123
|
+
}
|
|
124
|
+
const start = output.lastIndexOf(NOTICE_SEPARATOR);
|
|
125
|
+
if (start === -1) return { body: output, notice: undefined };
|
|
126
|
+
const block = output.slice(start + NOTICE_SEPARATOR.length).trimEnd();
|
|
127
|
+
if (!block.startsWith("[") || !block.endsWith("]")) return { body: output, notice: undefined };
|
|
128
|
+
if (!READ_NOTICES.some((pattern) => pattern.test(block))) return { body: output, notice: undefined };
|
|
129
|
+
// The blank lines that separate the block are trailing lines of the body, which
|
|
130
|
+
// the body builder trims anyway, so the slice keeps the body verbatim.
|
|
131
|
+
return { body: output.slice(0, start), notice: block.slice(1, -1) };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function trimTrailingEmptyLines(lines: string[]): string[] {
|
|
135
|
+
let end = lines.length;
|
|
136
|
+
while (end > 0 && lines[end - 1] === "") end -= 1;
|
|
137
|
+
return lines.slice(0, end);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function languageOf(path: string): string | undefined {
|
|
141
|
+
return path === "" ? undefined : getLanguageFromPath(path);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// One call for the whole body: a per-line pass would break multi-line
|
|
145
|
+
// constructs, and the cached highlighter already caps how many lines it takes.
|
|
146
|
+
function styleLines(contents: string[], language: string | undefined, input: ReadResultInput): string[] {
|
|
147
|
+
const fallback = (line: string): string => input.theme.fg(TOKEN.plain, line);
|
|
148
|
+
if (language === undefined) return contents.map(fallback);
|
|
149
|
+
return highlightLines(contents.join("\n"), language, fallback, input.highlight);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// The real line numbers of the file: `offset` is where the tool started reading,
|
|
153
|
+
// so the first visible line is not always line 1. Numbers are right-aligned to
|
|
154
|
+
// the widest one on screen, and a blank line has no trailing space to paint.
|
|
155
|
+
// That last decision belongs to the raw line: a colored line never is empty.
|
|
156
|
+
function numbered(rawLines: string[], styledLines: string[], start: number, theme: StyleTheme): string {
|
|
157
|
+
const width = String(start + rawLines.length - 1).length;
|
|
158
|
+
const separator = theme.fg(TOKEN.context, " |");
|
|
159
|
+
return rawLines
|
|
160
|
+
.map((raw, index) => {
|
|
161
|
+
const number = theme.fg(TOKEN.lineNumber, String(start + index).padStart(width));
|
|
162
|
+
return raw === "" ? `${number}${separator}` : `${number}${separator} ${styledLines[index]}`;
|
|
163
|
+
})
|
|
164
|
+
.join("\n");
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// The three wordings the built-in prints, byte for byte, including the built-in
|
|
168
|
+
// default it falls back to when the host recorded no limit.
|
|
169
|
+
function readTruncationNotice(truncation: ReadTruncation | undefined, theme: StyleTheme): string {
|
|
170
|
+
if (truncation?.truncated !== true) return "";
|
|
171
|
+
if (truncation.firstLineExceedsLimit === true) {
|
|
172
|
+
return `\n${theme.fg(TOKEN.notice, `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;
|
|
173
|
+
}
|
|
174
|
+
if (truncation.truncatedBy === "lines") {
|
|
175
|
+
const limit = truncation.maxLines ?? DEFAULT_MAX_LINES;
|
|
176
|
+
return `\n${theme.fg(TOKEN.notice, `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${limit} line limit)]`)}`;
|
|
177
|
+
}
|
|
178
|
+
return `\n${theme.fg(TOKEN.notice, `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function buildReadResultText(input: ReadResultInput): string {
|
|
182
|
+
// Stock pi keeps a collapsed read silent: the header carries the call and the
|
|
183
|
+
// body is not worth a row until it is expanded or failed.
|
|
184
|
+
if (!input.expanded && !input.isError) return "";
|
|
185
|
+
const truncation = input.details?.truncation;
|
|
186
|
+
const firstLineExceedsLimit = truncation?.firstLineExceedsLimit === true;
|
|
187
|
+
const { body, notice } = splitReadNotice(input.output, firstLineExceedsLimit);
|
|
188
|
+
const lines = trimTrailingEmptyLines(body.split("\n"));
|
|
189
|
+
// A failure, an image block and the oversized-first-line message are not file
|
|
190
|
+
// text: no gutter and no grammar, exactly like the built-in.
|
|
191
|
+
const fileText = !input.isError && !input.hasImage && !firstLineExceedsLimit;
|
|
192
|
+
const limit = input.expanded ? lines.length : COLLAPSED_LINES;
|
|
193
|
+
// The tab expansion happens before the grammar and before the gutter: both
|
|
194
|
+
// measure the columns the terminal will show.
|
|
195
|
+
const contents = lines.slice(0, limit).map((line) => replaceTabs(line));
|
|
196
|
+
const styled = styleLines(contents, fileText ? languageOf(input.path) : undefined, input);
|
|
197
|
+
|
|
198
|
+
let text = "";
|
|
199
|
+
if (styled.length > 0) {
|
|
200
|
+
text += `\n${fileText ? numbered(contents, styled, input.offset ?? 1, input.theme) : styled.join("\n")}`;
|
|
201
|
+
}
|
|
202
|
+
// The notice is the last body line of the built-in output, so it stays before
|
|
203
|
+
// the footer even though it is no longer counted as one of the file's lines.
|
|
204
|
+
if (notice !== undefined) text += `\n${input.theme.fg(TOKEN.notice, `[${notice}]`)}`;
|
|
205
|
+
const hidden = lines.length - limit;
|
|
206
|
+
if (hidden > 0) text += moreLinesFooter(hidden, input.theme, input.expandHint);
|
|
207
|
+
return text + readTruncationNotice(truncation, input.theme);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// The label the pi package directory gives a path inside it, or undefined when
|
|
211
|
+
// the path is outside and when the package root cannot be located (a global
|
|
212
|
+
// install with no readable package directory).
|
|
213
|
+
function piDocsLabel(path: string): string | undefined {
|
|
214
|
+
let root: string;
|
|
215
|
+
try {
|
|
216
|
+
root = resolve(getPackageDir());
|
|
217
|
+
} catch {
|
|
218
|
+
return undefined;
|
|
219
|
+
}
|
|
220
|
+
const relativePath = relative(root, resolve(path));
|
|
221
|
+
if (relativePath === "" || relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) {
|
|
222
|
+
return undefined;
|
|
223
|
+
}
|
|
224
|
+
const label = relativePath.split(sep).join("/");
|
|
225
|
+
return label === PI_DOC_README || PI_DOC_PREFIXES.some((prefix) => label.startsWith(prefix)) ? label : undefined;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function classifyReadPath(rawPath: string, cwd: string | undefined): ReadClassification | undefined {
|
|
229
|
+
if (rawPath === "") return undefined;
|
|
230
|
+
const absolute = absolutePath(rawPath, cwd);
|
|
231
|
+
const fileName = basename(absolute);
|
|
232
|
+
if (fileName === SKILL_FILE_NAME) return { kind: "skill", label: basename(dirname(absolute)) || fileName };
|
|
233
|
+
// The built-in also folds pi's own documentation and examples into a label;
|
|
234
|
+
// every other file keeps the full header.
|
|
235
|
+
const docs = piDocsLabel(absolute);
|
|
236
|
+
if (docs !== undefined) return { kind: "resource", label: docs };
|
|
237
|
+
if (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {
|
|
238
|
+
return { kind: "resource", label: relativeToCwdOrAbsolute(absolute, cwd) };
|
|
239
|
+
}
|
|
240
|
+
return undefined;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function expandKey(): string {
|
|
244
|
+
try {
|
|
245
|
+
return keyText(EXPAND_KEYBINDING) || DEFAULT_EXPAND_KEY;
|
|
246
|
+
} catch {
|
|
247
|
+
return DEFAULT_EXPAND_KEY;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// The `:start-end` the header appends, omitted when the call carries no range.
|
|
252
|
+
function lineRange(offset: number | undefined, limit: number | undefined, theme: StyleTheme): string {
|
|
253
|
+
const range = formatReadLineRange(offset, limit);
|
|
254
|
+
return range === "" ? "" : theme.fg(TOKEN.notice, range);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function fullReadCall(input: ReadCallInput): string {
|
|
258
|
+
const title = input.theme.fg("toolTitle", input.theme.bold("read"));
|
|
259
|
+
return `${title} ${renderToolPath(input.path, input.theme, input.cwd)}${lineRange(input.offset, input.limit, input.theme)}`;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function compactReadCall(classification: ReadClassification, input: ReadCallInput): string {
|
|
263
|
+
const range = lineRange(input.offset, input.limit, input.theme);
|
|
264
|
+
const hint = input.theme.fg("dim", ` (${expandKey()} to expand)`);
|
|
265
|
+
if (classification.kind === "skill") {
|
|
266
|
+
// The built-in spells the bold markers itself so the brackets share them.
|
|
267
|
+
const label = input.theme.fg("customMessageLabel", `${BOLD_ON}[skill]${BOLD_OFF} `);
|
|
268
|
+
return `${label}${input.theme.fg("customMessageText", classification.label)}${range}${hint}`;
|
|
269
|
+
}
|
|
270
|
+
const title = input.theme.fg("toolTitle", input.theme.bold(`read ${classification.kind}`));
|
|
271
|
+
return `${title} ${input.theme.fg(TOKEN.path, classification.label)}${range}${hint}`;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export function buildReadCallText(input: ReadCallInput): string {
|
|
275
|
+
const classification = input.compact ? classifyReadPath(input.path, input.cwd) : undefined;
|
|
276
|
+
return classification === undefined ? fullReadCall(input) : compactReadCall(classification, input);
|
|
277
|
+
}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { DEFAULT_MAX_BYTES, formatSize } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import {
|
|
3
|
+
Text,
|
|
4
|
+
getCapabilities,
|
|
5
|
+
getImageDimensions,
|
|
6
|
+
imageFallback,
|
|
7
|
+
stripTerminalSequences,
|
|
8
|
+
type Component,
|
|
9
|
+
} from "@earendil-works/pi-tui";
|
|
10
|
+
import { TOKEN, type StyleTheme } from "./tokens.ts";
|
|
11
|
+
|
|
12
|
+
// Structural stand-in for the host's `ToolRenderContext`, which the package
|
|
13
|
+
// root does not export. Only the fields the renderers actually read
|
|
14
|
+
// are declared, and each one also exists on the host type, so this stays
|
|
15
|
+
// assignable to the real renderer context.
|
|
16
|
+
export interface RenderContext {
|
|
17
|
+
args: unknown;
|
|
18
|
+
lastComponent: Component | undefined;
|
|
19
|
+
state: Record<string, unknown>;
|
|
20
|
+
showImages: boolean;
|
|
21
|
+
durationMs: number | undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Control characters crash `string-width`; tab and newline stay because the body
|
|
25
|
+
// is rendered line by line. The host also drops the interlinear annotation range
|
|
26
|
+
// (`\uFFF9`-`\uFFFB`), which this package does not carry.
|
|
27
|
+
const BINARY_CONTROL_CHARACTERS = /[\x00-\x08\x0B\x0C\x0E-\x1F]/g;
|
|
28
|
+
|
|
29
|
+
// Mirrors the built-in `getTextOutput`: every text block loses the ANSI the tool
|
|
30
|
+
// may have captured and the carriage returns of a progress-style body, and image
|
|
31
|
+
// blocks become the same `[Image: ...]` line stock pi prints when the terminal
|
|
32
|
+
// cannot show them or the caller turned them off.
|
|
33
|
+
export function textOutput(
|
|
34
|
+
result: { content: Array<{ type: string; text?: string; mimeType?: string; data?: string }> } | undefined,
|
|
35
|
+
showImages = true,
|
|
36
|
+
): string {
|
|
37
|
+
if (!result) return "";
|
|
38
|
+
const text = result.content
|
|
39
|
+
.filter((entry) => entry.type === "text")
|
|
40
|
+
.map((entry) =>
|
|
41
|
+
stripTerminalSequences(entry.text ?? "")
|
|
42
|
+
.replace(/\r/g, "")
|
|
43
|
+
.replace(BINARY_CONTROL_CHARACTERS, ""),
|
|
44
|
+
)
|
|
45
|
+
.join("\n");
|
|
46
|
+
const images = result.content.filter((entry) => entry.type === "image");
|
|
47
|
+
if (images.length === 0 || (getCapabilities().images && showImages)) return text;
|
|
48
|
+
const indicators = images.map(imageIndicator).join("\n");
|
|
49
|
+
// With no text block the fallback is the whole output.
|
|
50
|
+
return text === "" ? indicators : `${text}\n${indicators}`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function imageIndicator(block: { mimeType?: string; data?: string }): string {
|
|
54
|
+
const mimeType = block.mimeType ?? "image/unknown";
|
|
55
|
+
const dims =
|
|
56
|
+
block.data && block.mimeType ? (getImageDimensions(block.data, block.mimeType) ?? undefined) : undefined;
|
|
57
|
+
return imageFallback(mimeType, dims);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// The host's text renderer expands a tab to three spaces before painting a read
|
|
61
|
+
// body, so a file indented with tabs keeps the same column geometry this package
|
|
62
|
+
// measures against when it adds its own gutter.
|
|
63
|
+
export function replaceTabs(text: string): string {
|
|
64
|
+
return text.replace(/\t/g, " ");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// The generic overlay receives an output that ends with a notice such as
|
|
68
|
+
// "\n\n[100 matches limit]". The blank line is the only separator, so a block
|
|
69
|
+
// that itself contains a newline is body text, not a notice.
|
|
70
|
+
export function splitTrailingNotice(output: string): { body: string; notice?: string } {
|
|
71
|
+
const start = output.lastIndexOf("\n\n[");
|
|
72
|
+
if (start === -1) return { body: output };
|
|
73
|
+
const block = output.slice(start + 2);
|
|
74
|
+
if (!block.endsWith("]") || block.includes("\n")) return { body: output };
|
|
75
|
+
return { body: output.slice(0, start).trimEnd(), notice: block.slice(1, -1) };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Byte-identical to the built-in footer (renderers/grep.ts, find.ts, ls.ts):
|
|
79
|
+
// any divergence here is a visible difference against stock pi.
|
|
80
|
+
export function moreLinesFooter(hidden: number, theme: StyleTheme, expandHint: string): string {
|
|
81
|
+
return `${theme.fg("muted", `\n... (${hidden} more lines,`)} ${expandHint}${theme.fg("muted", ")")}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// The warnings a truncated result carries, in the order stock pi prints them:
|
|
85
|
+
// the limit the tool reported, the truncation itself, then the caller's own
|
|
86
|
+
// notices. `byteStyle` covers the two wordings pi uses: grep, find and ls print
|
|
87
|
+
// only the limit, the shell also prints how many lines survived.
|
|
88
|
+
export interface TruncationParts {
|
|
89
|
+
limitCount?: number;
|
|
90
|
+
limitLabel?: string;
|
|
91
|
+
truncatedBy?: "lines" | "bytes";
|
|
92
|
+
outputLines?: number;
|
|
93
|
+
totalLines?: number;
|
|
94
|
+
maxBytes?: number;
|
|
95
|
+
extra?: readonly string[];
|
|
96
|
+
byteStyle?: "lines-shown" | "limit-only";
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function truncationWarnings(parts: TruncationParts): string[] {
|
|
100
|
+
const warnings: string[] = [];
|
|
101
|
+
if (parts.limitCount !== undefined) warnings.push(`${parts.limitCount} ${parts.limitLabel ?? "limit"}`);
|
|
102
|
+
if (parts.truncatedBy !== undefined || parts.maxBytes !== undefined || parts.outputLines !== undefined) {
|
|
103
|
+
warnings.push(truncationWarning(parts));
|
|
104
|
+
}
|
|
105
|
+
if (parts.extra !== undefined) warnings.push(...parts.extra);
|
|
106
|
+
return warnings;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// The parts of a details-derived warning the grep, find and ls renderers print.
|
|
110
|
+
// `truncation.truncated` is what decides whether the byte limit is one of them.
|
|
111
|
+
export interface LimitTruncation {
|
|
112
|
+
limitCount?: number;
|
|
113
|
+
limitLabel: string;
|
|
114
|
+
truncation?: { truncated?: boolean; maxBytes?: number };
|
|
115
|
+
extra?: readonly string[];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// The line the list renderers append after the footer, blank when the result
|
|
119
|
+
// carries nothing to report. Both the wording and the position match stock pi:
|
|
120
|
+
// the notice is not part of the body, so it is never counted by the footer.
|
|
121
|
+
export function truncatedNotice(parts: LimitTruncation, theme: StyleTheme): string {
|
|
122
|
+
const byteTruncated = parts.truncation?.truncated === true;
|
|
123
|
+
const warnings = truncationWarnings({
|
|
124
|
+
limitCount: parts.limitCount,
|
|
125
|
+
limitLabel: parts.limitLabel,
|
|
126
|
+
byteStyle: "limit-only",
|
|
127
|
+
truncatedBy: byteTruncated ? "bytes" : undefined,
|
|
128
|
+
maxBytes: byteTruncated ? parts.truncation?.maxBytes : undefined,
|
|
129
|
+
extra: parts.extra,
|
|
130
|
+
});
|
|
131
|
+
if (warnings.length === 0) return "";
|
|
132
|
+
return `\n${theme.fg(TOKEN.notice, `[Truncated: ${warnings.join(", ")}]`)}`;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Returned without the "Truncated: " prefix, which the shell renderer adds
|
|
136
|
+
// itself; the list renderers wrap the whole joined text in brackets instead.
|
|
137
|
+
function truncationWarning(parts: TruncationParts): string {
|
|
138
|
+
if (parts.truncatedBy === "lines") {
|
|
139
|
+
return `showing ${parts.outputLines} of ${parts.totalLines} lines`;
|
|
140
|
+
}
|
|
141
|
+
// The host does not always record the limit it applied, so the built-in
|
|
142
|
+
// default stands in for it.
|
|
143
|
+
const limit = formatSize(parts.maxBytes ?? DEFAULT_MAX_BYTES);
|
|
144
|
+
return parts.byteStyle === "limit-only"
|
|
145
|
+
? `${limit} limit`
|
|
146
|
+
: `${parts.outputLines ?? 0} lines shown (${limit} limit)`;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// A diff is recognized by its first line; how many changed lines are needed
|
|
150
|
+
// before the body counts as one is up to each renderer.
|
|
151
|
+
export const DIFF_HEADER = /^(diff --git|--- |\+\+\+ |@@ )/;
|
|
152
|
+
|
|
153
|
+
// Added and removed lines of a diff: the foreground token alone is a thin strip
|
|
154
|
+
// of color on a dark terminal, so the state is repeated on the background. Both
|
|
155
|
+
// diff-aware renderers share this so the two bodies cannot drift apart.
|
|
156
|
+
export function diffChangeLine(line: string, theme: StyleTheme): string {
|
|
157
|
+
return line.startsWith("+")
|
|
158
|
+
? theme.bg("toolSuccessBg", theme.fg("toolDiffAdded", line))
|
|
159
|
+
: theme.bg("toolErrorBg", theme.fg("toolDiffRemoved", line));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// The three header forms get the function color, added and removed lines the
|
|
163
|
+
// diff tokens over their own background, everything else the content color.
|
|
164
|
+
export function styleDiffLine(line: string, theme: StyleTheme): string {
|
|
165
|
+
if (line.startsWith("@@") || line.startsWith("+++") || line.startsWith("---")) {
|
|
166
|
+
return theme.fg("syntaxFunction", line);
|
|
167
|
+
}
|
|
168
|
+
if (line.startsWith("+") || line.startsWith("-")) return diffChangeLine(line, theme);
|
|
169
|
+
return theme.fg(TOKEN.content, line);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// The opener plus a successful parse, so a log line that merely starts with a
|
|
173
|
+
// brace keeps the flat content color.
|
|
174
|
+
export function isJsonDocument(text: string): boolean {
|
|
175
|
+
const first = text.trimStart().charAt(0);
|
|
176
|
+
if (first !== "{" && first !== "[") return false;
|
|
177
|
+
try {
|
|
178
|
+
JSON.parse(text);
|
|
179
|
+
return true;
|
|
180
|
+
} catch {
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// The "path:line:" prefix every line-numbered output shares. The path arrives
|
|
186
|
+
// already colored so each caller decides its own weight.
|
|
187
|
+
export function colonPrefix(styledPath: string, line: number, theme: StyleTheme): string {
|
|
188
|
+
const separator = theme.fg(TOKEN.context, ":");
|
|
189
|
+
return `${styledPath}${separator}${theme.fg(TOKEN.lineNumber, String(line))}${separator}`;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export interface ListBodyInput {
|
|
193
|
+
body: string;
|
|
194
|
+
expanded: boolean;
|
|
195
|
+
collapsedLines: number;
|
|
196
|
+
theme: StyleTheme;
|
|
197
|
+
expandHint: string;
|
|
198
|
+
styleLine: (raw: string) => string;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// The body every list-shaped result shares (find, ls, and future callers):
|
|
202
|
+
// cut first, style second, so a collapsed view never styles thousands of
|
|
203
|
+
// hidden lines.
|
|
204
|
+
export function buildListBody(input: ListBodyInput): string {
|
|
205
|
+
if (input.body === "") return "";
|
|
206
|
+
const lines = input.body.split("\n");
|
|
207
|
+
const visible = input.expanded ? lines : lines.slice(0, input.collapsedLines);
|
|
208
|
+
let text = `\n${visible.map((line) => input.styleLine(line)).join("\n")}`;
|
|
209
|
+
const hidden = lines.length - visible.length;
|
|
210
|
+
if (hidden > 0) text += moreLinesFooter(hidden, input.theme, input.expandHint);
|
|
211
|
+
return text;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// The host passes back the component it rendered last for this slot, so
|
|
215
|
+
// re-rendering mutates it in place instead of allocating a new one per frame.
|
|
216
|
+
// The caller owns `setText`.
|
|
217
|
+
export function reuseText(ctx: RenderContext): Text {
|
|
218
|
+
return ctx.lastComponent instanceof Text ? ctx.lastComponent : new Text("", 0, 0);
|
|
219
|
+
}
|