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
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { getLanguageFromPath } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { highlightLines, type HighlightFn } from "./highlight.ts";
|
|
3
|
+
import { renderToolPath } from "./render-path.ts";
|
|
4
|
+
import { replaceTabs } from "./render-utils.ts";
|
|
5
|
+
import { TOKEN, type StyleTheme } from "./tokens.ts";
|
|
6
|
+
|
|
7
|
+
// The built-in write renderer shows 10 lines when collapsed; any other number is
|
|
8
|
+
// a visible difference against stock pi.
|
|
9
|
+
const COLLAPSED_LINES = 10;
|
|
10
|
+
|
|
11
|
+
// While the argument is still streaming the tail is repainted on every frame and
|
|
12
|
+
// tokenizing it costs more than it shows: the prefix is what the reader watches.
|
|
13
|
+
const PARTIAL_HIGHLIGHT_LINES = 60;
|
|
14
|
+
|
|
15
|
+
const INVALID_CONTENT = "[invalid content arg - expected string]";
|
|
16
|
+
|
|
17
|
+
export interface WriteResultInput {
|
|
18
|
+
output: string;
|
|
19
|
+
isError: boolean;
|
|
20
|
+
theme: StyleTheme;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface WriteCallInput {
|
|
24
|
+
/** The argument's path, "" when the call does not carry one. */
|
|
25
|
+
path: string;
|
|
26
|
+
/** "" is an argument that has not arrived yet, null one that is not a string. */
|
|
27
|
+
content: string | null;
|
|
28
|
+
argsComplete: boolean;
|
|
29
|
+
expanded: boolean;
|
|
30
|
+
theme: StyleTheme;
|
|
31
|
+
expandHint: string;
|
|
32
|
+
highlight: HighlightFn;
|
|
33
|
+
cwd: string | undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// The tool reports a success with no text at all, so only a failure has a body
|
|
37
|
+
// to paint; the caller drops the empty string instead of drawing a blank row.
|
|
38
|
+
export function buildWriteResultText(input: WriteResultInput): string {
|
|
39
|
+
if (!input.isError || input.output === "") return "";
|
|
40
|
+
return `\n${input.theme.fg(TOKEN.broken, input.output)}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function trimTrailingEmptyLines(lines: string[]): string[] {
|
|
44
|
+
let end = lines.length;
|
|
45
|
+
while (end > 0 && lines[end - 1] === "") end -= 1;
|
|
46
|
+
return lines.slice(0, end);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function previewLines(lines: string[], language: string | undefined, input: WriteCallInput): string[] {
|
|
50
|
+
const fallback = (line: string): string => input.theme.fg(TOKEN.plain, line);
|
|
51
|
+
if (language === undefined) return lines.map(fallback);
|
|
52
|
+
const head = input.argsComplete ? lines : lines.slice(0, PARTIAL_HIGHLIGHT_LINES);
|
|
53
|
+
const highlighted = highlightLines(head.join("\n"), language, fallback, input.highlight);
|
|
54
|
+
return [...highlighted, ...lines.slice(head.length).map(fallback)];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// The header the built-in writes, plus the preview of what is about to be
|
|
58
|
+
// written. The pipeline is the built-in's, with the streaming case bounded: the
|
|
59
|
+
// trailing blank lines go before the count and the tab expansion, the content is
|
|
60
|
+
// tokenized as one block, and the footer keeps its wording.
|
|
61
|
+
export function buildWriteCallText(input: WriteCallInput): string {
|
|
62
|
+
const theme = input.theme;
|
|
63
|
+
const title = `${theme.fg("toolTitle", theme.bold("write"))} ${renderToolPath(input.path, theme, input.cwd)}`;
|
|
64
|
+
if (input.content === null) return `${title}\n\n${theme.fg(TOKEN.broken, INVALID_CONTENT)}`;
|
|
65
|
+
if (input.content === "") return title;
|
|
66
|
+
// Carriage returns go before anything is measured, so a CRLF argument does not
|
|
67
|
+
// show as an extra blank line; the three spaces of a tab are the indent the
|
|
68
|
+
// rest of the package renders against.
|
|
69
|
+
const content = replaceTabs(input.content.replace(/\r/g, ""));
|
|
70
|
+
const lines = trimTrailingEmptyLines(content.split("\n"));
|
|
71
|
+
const language = input.path === "" ? undefined : getLanguageFromPath(input.path);
|
|
72
|
+
const styled = previewLines(lines, language, input);
|
|
73
|
+
const total = lines.length;
|
|
74
|
+
const limit = input.expanded ? total : COLLAPSED_LINES;
|
|
75
|
+
let text = `${title}\n\n${styled.slice(0, limit).join("\n")}`;
|
|
76
|
+
const hidden = total - limit;
|
|
77
|
+
if (hidden > 0) {
|
|
78
|
+
text += `${theme.fg("muted", `\n... (${hidden} more lines, ${total} total,`)} ${input.expandHint}${theme.fg("muted", ")")}`;
|
|
79
|
+
}
|
|
80
|
+
return text;
|
|
81
|
+
}
|
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
import { keyHint } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { AgentToolResult, Theme, ToolRenderers, ToolRenderResultOptions } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { Container, Spacer, Text, type Component } from "@earendil-works/pi-tui";
|
|
4
|
+
import { captureTheme } from "./active-theme.ts";
|
|
5
|
+
import { highlight, syncHighlightTheme } from "./highlight.ts";
|
|
6
|
+
import { buildBashBody, createBashPreview, type BashInput } from "./render-bash.ts";
|
|
7
|
+
import { buildEditDiffText, buildEditErrorText } from "./render-edit.ts";
|
|
8
|
+
import { buildFindResultText, type PathListInput } from "./render-find.ts";
|
|
9
|
+
import { buildGenericResultText } from "./render-generic.ts";
|
|
10
|
+
import { buildGrepResultText, type GrepInput } from "./render-grep.ts";
|
|
11
|
+
import { buildLsResultText, type LsInput } from "./render-ls.ts";
|
|
12
|
+
import {
|
|
13
|
+
buildReadCallText,
|
|
14
|
+
buildReadResultText,
|
|
15
|
+
readLimit,
|
|
16
|
+
readOffset,
|
|
17
|
+
readPath,
|
|
18
|
+
type ReadResultInput,
|
|
19
|
+
} from "./render-read.ts";
|
|
20
|
+
import { buildWriteCallText, buildWriteResultText } from "./render-write.ts";
|
|
21
|
+
import { reuseText, textOutput, type RenderContext } from "./render-utils.ts";
|
|
22
|
+
import { TOKEN } from "./tokens.ts";
|
|
23
|
+
|
|
24
|
+
type GrepDetails = GrepInput["details"];
|
|
25
|
+
type FindDetails = PathListInput["details"];
|
|
26
|
+
type LsDetails = LsInput["details"];
|
|
27
|
+
|
|
28
|
+
type ResultRenderer = NonNullable<ToolRenderers["renderResult"]>;
|
|
29
|
+
type CallRenderer = NonNullable<ToolRenderers["renderCall"]>;
|
|
30
|
+
|
|
31
|
+
// The last resort when a body cannot be styled still has to fit the collapsed
|
|
32
|
+
// transcript, so it keeps the line count the list renderers use.
|
|
33
|
+
const COLLAPSED_FALLBACK_LINES = 15;
|
|
34
|
+
|
|
35
|
+
// The host types `details` as `any`; every field this package reads is optional,
|
|
36
|
+
// so a shape carrying extra members still renders.
|
|
37
|
+
function shellDetails(details: unknown): BashInput["details"] {
|
|
38
|
+
return details as BashInput["details"];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function readDetails(details: unknown): ReadResultInput["details"] {
|
|
42
|
+
return details as ReadResultInput["details"];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// The display diff of `edit`, or "" when the result carries none: the tool only
|
|
46
|
+
// records it on success.
|
|
47
|
+
function editDiff(details: unknown): string {
|
|
48
|
+
const diff = typeof details === "object" && details !== null ? (details as { diff?: unknown }).diff : undefined;
|
|
49
|
+
return typeof diff === "string" ? diff : "";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// An image result is not file text: the body loses both the gutter and the
|
|
53
|
+
// grammar, which is the branch the built-in takes too.
|
|
54
|
+
function hasImageBlock(result: AgentToolResult<unknown>): boolean {
|
|
55
|
+
return result.content.some((block) => block.type === "image");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// The content argument of `write`: "" while the argument has not arrived, null
|
|
59
|
+
// when what arrived is not a string (the built-in reports that as an invalid arg).
|
|
60
|
+
function writeContent(args: unknown): string | null {
|
|
61
|
+
if (typeof args !== "object" || args === null) return "";
|
|
62
|
+
const content = (args as { content?: unknown }).content;
|
|
63
|
+
if (content === undefined || content === null) return "";
|
|
64
|
+
return typeof content === "string" ? content : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Every styled list result turns plain text into themed text from the same
|
|
68
|
+
// render inputs. The call arguments come last because only grep reads them
|
|
69
|
+
// today: its pattern drives the match emphasis. `isError` follows them because
|
|
70
|
+
// only the renderers that paint a failure differently read it.
|
|
71
|
+
type ResultTextBuilder<TDetails> = (
|
|
72
|
+
output: string,
|
|
73
|
+
details: TDetails,
|
|
74
|
+
expanded: boolean,
|
|
75
|
+
theme: Theme,
|
|
76
|
+
expandHint: string,
|
|
77
|
+
args: unknown,
|
|
78
|
+
isError: boolean,
|
|
79
|
+
) => string;
|
|
80
|
+
|
|
81
|
+
// `keyHint` reads the live keybindings and throws outside a session (export,
|
|
82
|
+
// headless). The hint is decoration: a stable fallback beats losing the row.
|
|
83
|
+
function expandHint(): string {
|
|
84
|
+
try {
|
|
85
|
+
return keyHint("app.tools.expand", "to expand");
|
|
86
|
+
} catch {
|
|
87
|
+
return "ctrl+o to expand";
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function grepArgs(args: unknown): GrepInput["pattern"] {
|
|
92
|
+
return typeof args === "object" && args !== null ? (args as GrepInput["pattern"]) : {};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function wrapResultRenderer<TDetails>(build: ResultTextBuilder<TDetails>): ResultRenderer {
|
|
96
|
+
return (result, options, theme, context) => {
|
|
97
|
+
// The last theme seen is what the paths outside a renderer paint with.
|
|
98
|
+
captureTheme(theme);
|
|
99
|
+
// The cached highlight lines were painted with the previous theme, if any.
|
|
100
|
+
syncHighlightTheme(theme);
|
|
101
|
+
const component = reuseText(context);
|
|
102
|
+
const output = textOutput(result, context.showImages);
|
|
103
|
+
// The TUI hands the failure through the context; the result it passes to the
|
|
104
|
+
// renderer carries no `isError`, so reading it there would always be false.
|
|
105
|
+
const isError = context.isError === true;
|
|
106
|
+
try {
|
|
107
|
+
component.setText(
|
|
108
|
+
build(output, result.details, options.expanded, theme, expandHint(), context.args, isError),
|
|
109
|
+
);
|
|
110
|
+
} catch {
|
|
111
|
+
// Losing the colors is recoverable; losing the output is not.
|
|
112
|
+
component.setText(fallbackBody(output, options.expanded, theme));
|
|
113
|
+
}
|
|
114
|
+
return component;
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Losing the colors is recoverable; losing the output is not. The same token as
|
|
119
|
+
// the body keeps the fallback from looking like another tool, and a collapsed
|
|
120
|
+
// view is cut so it cannot flood the frame.
|
|
121
|
+
function fallbackBody(output: string, expanded: boolean, theme: Theme): string {
|
|
122
|
+
const lines = output.split("\n");
|
|
123
|
+
const visible = expanded ? lines : lines.slice(0, COLLAPSED_FALLBACK_LINES);
|
|
124
|
+
return visible.map((line) => theme.fg(TOKEN.content, line)).join("\n");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const GREP_RESULT = wrapResultRenderer<GrepDetails>((output, details, expanded, theme, expandHint, args) =>
|
|
128
|
+
buildGrepResultText({ output, details, expanded, pattern: grepArgs(args), theme, expandHint, highlight }),
|
|
129
|
+
);
|
|
130
|
+
|
|
131
|
+
const FIND_RESULT = wrapResultRenderer<FindDetails>((output, details, expanded, theme, expandHint, _args, isError) =>
|
|
132
|
+
buildFindResultText({ output, details, expanded, isError, theme, expandHint }),
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
const LS_RESULT = wrapResultRenderer<LsDetails>((output, details, expanded, theme, expandHint, _args, isError) =>
|
|
136
|
+
buildLsResultText({ output, details, expanded, isError, theme, expandHint }),
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
// Fallback for every tool this package does not style: the body is painted, the
|
|
140
|
+
// header stays whatever the tool brought (usually nothing).
|
|
141
|
+
const GENERIC_RESULT = wrapResultRenderer<unknown>(
|
|
142
|
+
(output, _details, expanded, theme, expandHint, _args, isError) =>
|
|
143
|
+
buildGenericResultText({ output, expanded, isError, theme, expandHint }),
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
const READ_RESULT: ResultRenderer = (result, options, theme, context) => {
|
|
147
|
+
captureTheme(theme);
|
|
148
|
+
// The cached highlight lines were painted with the previous theme, if any.
|
|
149
|
+
syncHighlightTheme(theme);
|
|
150
|
+
const component = reuseText(context);
|
|
151
|
+
const output = textOutput(result, context.showImages);
|
|
152
|
+
try {
|
|
153
|
+
component.setText(
|
|
154
|
+
buildReadResultText({
|
|
155
|
+
output,
|
|
156
|
+
path: readPath(context.args),
|
|
157
|
+
offset: readOffset(context.args),
|
|
158
|
+
details: readDetails(result.details),
|
|
159
|
+
expanded: options.expanded,
|
|
160
|
+
// The TUI hands the failure through the context; the result it passes to
|
|
161
|
+
// the renderer carries no `isError`, so reading it there would always be
|
|
162
|
+
// false.
|
|
163
|
+
isError: context.isError === true,
|
|
164
|
+
hasImage: hasImageBlock(result),
|
|
165
|
+
theme,
|
|
166
|
+
expandHint: expandHint(),
|
|
167
|
+
highlight,
|
|
168
|
+
}),
|
|
169
|
+
);
|
|
170
|
+
} catch {
|
|
171
|
+
component.setText(fallbackBody(output, options.expanded, theme));
|
|
172
|
+
}
|
|
173
|
+
return component;
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// A success has no body at all (the tool reports it with no text), so the slot is
|
|
177
|
+
// cleared back to the container the host reuses instead of holding an empty text.
|
|
178
|
+
function emptyResult(context: RenderContext): Container {
|
|
179
|
+
const component = context.lastComponent instanceof Container ? context.lastComponent : new Container();
|
|
180
|
+
component.clear();
|
|
181
|
+
return component;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const WRITE_RESULT: ResultRenderer = (result, _options, theme, context) => {
|
|
185
|
+
captureTheme(theme);
|
|
186
|
+
syncHighlightTheme(theme);
|
|
187
|
+
const output = textOutput(result, context.showImages);
|
|
188
|
+
const text = buildWriteResultText({ output, isError: context.isError === true, theme });
|
|
189
|
+
if (text === "") return emptyResult(context);
|
|
190
|
+
const component = reuseText(context);
|
|
191
|
+
component.setText(text);
|
|
192
|
+
return component;
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
// The built-in `renderCall` of edit keeps its `Box` in the renderer state, and
|
|
196
|
+
// the built-in `renderResult` writes the diff into that same box. Only the two
|
|
197
|
+
// members this package touches are declared: a host that drops one loses the
|
|
198
|
+
// background and the in-box body, never the diff.
|
|
199
|
+
interface EditCallBox extends Component {
|
|
200
|
+
children: Component[];
|
|
201
|
+
addChild(component: Component): void;
|
|
202
|
+
removeChild(component: Component): void;
|
|
203
|
+
setBgFn(bgFn?: (text: string) => string): void;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function editCallBox(state: Record<string, unknown>): EditCallBox | undefined {
|
|
207
|
+
const candidate = state.callComponent as Partial<EditCallBox> | null | undefined;
|
|
208
|
+
if (candidate === undefined || candidate === null) return undefined;
|
|
209
|
+
const usable =
|
|
210
|
+
Array.isArray(candidate.children) &&
|
|
211
|
+
typeof candidate.addChild === "function" &&
|
|
212
|
+
typeof candidate.removeChild === "function" &&
|
|
213
|
+
typeof candidate.setBgFn === "function" &&
|
|
214
|
+
typeof candidate.render === "function";
|
|
215
|
+
return usable ? (candidate as EditCallBox) : undefined;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// The first child is the header the built-in `renderCall` left in place, with its
|
|
219
|
+
// path and hyperlink; every child after it is the preview this result replaces.
|
|
220
|
+
function replaceEditBody(box: EditCallBox, isError: boolean, body: string, theme: Theme): void {
|
|
221
|
+
for (const child of box.children.slice(1)) box.removeChild(child);
|
|
222
|
+
box.setBgFn((text) => theme.bg(isError ? "toolErrorBg" : "toolSuccessBg", text));
|
|
223
|
+
if (body === "") return;
|
|
224
|
+
box.addChild(new Spacer(1));
|
|
225
|
+
box.addChild(new Text(body, 0, 0));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const EDIT_RESULT: ResultRenderer = (result, _options, theme, context) => {
|
|
229
|
+
captureTheme(theme);
|
|
230
|
+
syncHighlightTheme(theme);
|
|
231
|
+
const isError = context.isError === true;
|
|
232
|
+
const body = isError
|
|
233
|
+
? buildEditErrorText(textOutput(result, context.showImages), theme)
|
|
234
|
+
: buildEditDiffText({ diff: editDiff(result.details), path: readPath(context.args), theme, highlight });
|
|
235
|
+
const box = editCallBox(context.state);
|
|
236
|
+
if (box !== undefined) {
|
|
237
|
+
replaceEditBody(box, isError, body, theme);
|
|
238
|
+
// The diff lives inside the box now, so the result slot stays empty.
|
|
239
|
+
return emptyResult(context);
|
|
240
|
+
}
|
|
241
|
+
// Degradation: with no box to fill, the body goes below the header the way the
|
|
242
|
+
// built-in draws it when its own call renderer did not run.
|
|
243
|
+
const component = emptyResult(context);
|
|
244
|
+
if (body !== "") {
|
|
245
|
+
component.addChild(new Spacer(1));
|
|
246
|
+
component.addChild(new Text(body, context.outputPad, 0));
|
|
247
|
+
}
|
|
248
|
+
return component;
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
const READ_CALL: CallRenderer = (args, theme, context) => {
|
|
252
|
+
captureTheme(theme);
|
|
253
|
+
const component = reuseText(context);
|
|
254
|
+
component.setText(
|
|
255
|
+
buildReadCallText({
|
|
256
|
+
path: readPath(args),
|
|
257
|
+
offset: readOffset(args),
|
|
258
|
+
limit: readLimit(args),
|
|
259
|
+
compact: !context.expanded,
|
|
260
|
+
theme,
|
|
261
|
+
cwd: context.cwd,
|
|
262
|
+
}),
|
|
263
|
+
);
|
|
264
|
+
return component;
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
const WRITE_CALL: CallRenderer = (args, theme, context) => {
|
|
268
|
+
captureTheme(theme);
|
|
269
|
+
// The preview tokenizes through the shared cache, which is keyed by language
|
|
270
|
+
// and code alone: a theme switch has to invalidate it here as well.
|
|
271
|
+
syncHighlightTheme(theme);
|
|
272
|
+
const component = reuseText(context);
|
|
273
|
+
component.setText(
|
|
274
|
+
buildWriteCallText({
|
|
275
|
+
path: readPath(args),
|
|
276
|
+
content: writeContent(args),
|
|
277
|
+
argsComplete: context.argsComplete,
|
|
278
|
+
expanded: context.expanded,
|
|
279
|
+
theme,
|
|
280
|
+
expandHint: expandHint(),
|
|
281
|
+
highlight,
|
|
282
|
+
cwd: context.cwd,
|
|
283
|
+
}),
|
|
284
|
+
);
|
|
285
|
+
return component;
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
// Keyed by name because the resolver is the single entry point for every tool;
|
|
289
|
+
// only the slots named here are overridden, and the rest come from the base
|
|
290
|
+
// chain. `edit` keeps its built-in `renderCall`: the preview it draws comes from
|
|
291
|
+
// a helper the host does not export, and its box is what our body fills.
|
|
292
|
+
const STYLED_SLOTS = new Map<string, ToolRenderers>([
|
|
293
|
+
["grep", { renderResult: GREP_RESULT }],
|
|
294
|
+
["find", { renderResult: FIND_RESULT }],
|
|
295
|
+
["ls", { renderResult: LS_RESULT }],
|
|
296
|
+
["read", { renderCall: READ_CALL, renderResult: READ_RESULT }],
|
|
297
|
+
["write", { renderCall: WRITE_CALL, renderResult: WRITE_RESULT }],
|
|
298
|
+
["edit", { renderResult: EDIT_RESULT }],
|
|
299
|
+
]);
|
|
300
|
+
|
|
301
|
+
// The shell body is a component tree, not a text block: the collapsed view cuts
|
|
302
|
+
// visual lines at render time, so it cannot be built once at module load.
|
|
303
|
+
const SHELL_TOOLS = new Set(["bash", "powershell"]);
|
|
304
|
+
|
|
305
|
+
// The host keeps the row's clock in `context.state` between renders; these are
|
|
306
|
+
// the three fields this renderer reads and writes.
|
|
307
|
+
type ShellTimerState = {
|
|
308
|
+
startedAt?: number;
|
|
309
|
+
endedAt?: number;
|
|
310
|
+
interval?: ReturnType<typeof setInterval>;
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
function shellTimerState(context: RenderContext): ShellTimerState {
|
|
314
|
+
return context.state as ShellTimerState;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// Same child order as the built-in renderer: body, then warnings, then timer.
|
|
318
|
+
function buildShellComponent(
|
|
319
|
+
result: AgentToolResult<unknown>,
|
|
320
|
+
options: ToolRenderResultOptions,
|
|
321
|
+
theme: Theme,
|
|
322
|
+
context: RenderContext,
|
|
323
|
+
): Component {
|
|
324
|
+
const container = context.lastComponent instanceof Container ? context.lastComponent : new Container();
|
|
325
|
+
container.clear();
|
|
326
|
+
const timer = shellTimerState(context);
|
|
327
|
+
// A final result ends the row's clock: an interval left running would keep
|
|
328
|
+
// invalidating a row that no longer changes, and the end time is stamped once.
|
|
329
|
+
if (timer.interval !== undefined) {
|
|
330
|
+
clearInterval(timer.interval);
|
|
331
|
+
delete timer.interval;
|
|
332
|
+
}
|
|
333
|
+
timer.endedAt ??= Date.now();
|
|
334
|
+
// A recorded duration wins because it survives reloads; the clock the row
|
|
335
|
+
// started from is the fallback for results stored without one.
|
|
336
|
+
const duration =
|
|
337
|
+
context.durationMs ?? (timer.startedAt !== undefined ? Date.now() - timer.startedAt : undefined);
|
|
338
|
+
const built = buildBashBody({
|
|
339
|
+
output: textOutput(result, context.showImages),
|
|
340
|
+
details: shellDetails(result.details),
|
|
341
|
+
durationMs: duration,
|
|
342
|
+
isPartial: options.isPartial,
|
|
343
|
+
theme,
|
|
344
|
+
});
|
|
345
|
+
if (built.body !== "") {
|
|
346
|
+
if (options.expanded) {
|
|
347
|
+
container.addChild(new Text(`\n${built.body}`, 0, 0));
|
|
348
|
+
} else {
|
|
349
|
+
container.addChild(new Spacer(1));
|
|
350
|
+
container.addChild(createBashPreview(built.body, expandHint(), theme));
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
if (built.warnings !== undefined) {
|
|
354
|
+
container.addChild(new Text(`\n${theme.fg(TOKEN.notice, `[${built.warnings}]`)}`, 0, 0));
|
|
355
|
+
}
|
|
356
|
+
if (built.timer !== undefined) {
|
|
357
|
+
container.addChild(new Text(`\n${theme.fg("muted", `Took ${built.timer}`)}`, 0, 0));
|
|
358
|
+
}
|
|
359
|
+
return container;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function buildShellFallback(result: AgentToolResult<unknown>, theme: Theme, context: RenderContext): Text {
|
|
363
|
+
const component = reuseText(context);
|
|
364
|
+
const output = textOutput(result, context.showImages);
|
|
365
|
+
component.setText(output.split("\n").map((line) => theme.fg(TOKEN.content, line)).join("\n"));
|
|
366
|
+
return component;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// The shell renderer is created per resolution, not baked into the map above,
|
|
370
|
+
// because it needs the base chain at call time.
|
|
371
|
+
function createShellResultRenderer(base: ToolRenderers | undefined): ResultRenderer {
|
|
372
|
+
return (result, options, theme, context) => {
|
|
373
|
+
captureTheme(theme);
|
|
374
|
+
syncHighlightTheme(theme);
|
|
375
|
+
const inherited = base?.renderResult;
|
|
376
|
+
// Streaming stays on the built-in path when there is one: it owns the elapsed
|
|
377
|
+
// line and the repaint interval, which a final result cannot reproduce. With
|
|
378
|
+
// no `base.renderResult` the chain has nowhere to fall through, so the builder
|
|
379
|
+
// runs in partial mode: the full-output block stays in the body and no timer
|
|
380
|
+
// line is added.
|
|
381
|
+
if (options.isPartial && inherited !== undefined) return inherited(result, options, theme, context);
|
|
382
|
+
try {
|
|
383
|
+
return buildShellComponent(result, options, theme, context);
|
|
384
|
+
} catch {
|
|
385
|
+
// Losing the colors is recoverable; losing the output is not.
|
|
386
|
+
return buildShellFallback(result, theme, context);
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// Overlay only the slots this package owns: `next()` is the host's own chain
|
|
392
|
+
// (later resolvers, then the tool definition), so whatever it returns for
|
|
393
|
+
// `renderCall` and `renderShell` is passed through untouched. `next()` is always
|
|
394
|
+
// spread into a fresh object because returning `undefined` would end the chain
|
|
395
|
+
// with no fallback at all.
|
|
396
|
+
export function resolveToolRenderers(toolName: string, next: () => ToolRenderers | undefined): ToolRenderers | undefined {
|
|
397
|
+
const base = next();
|
|
398
|
+
const slots = STYLED_SLOTS.get(toolName);
|
|
399
|
+
if (slots !== undefined) return { ...base, ...slots };
|
|
400
|
+
if (SHELL_TOOLS.has(toolName)) return { ...base, renderResult: createShellResultRenderer(base) };
|
|
401
|
+
// Everything else (MCP servers, codemode, names the host does not know) keeps
|
|
402
|
+
// its own renderer when it has one; only a tool with no result renderer at all
|
|
403
|
+
// gets the generic overlay. Deleting this branch rolls E6 back to a no-op.
|
|
404
|
+
if (base?.renderResult === undefined) return { ...base, renderResult: GENERIC_RESULT };
|
|
405
|
+
return { ...base };
|
|
406
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { fileTypeToken, TOKEN, type StyleTheme } from "./tokens.ts";
|
|
2
|
+
|
|
3
|
+
export type PathLine =
|
|
4
|
+
| { kind: "dir"; path: string }
|
|
5
|
+
| { kind: "file"; path: string }
|
|
6
|
+
| { kind: "notice"; text: string }
|
|
7
|
+
| { kind: "plain"; text: string };
|
|
8
|
+
|
|
9
|
+
const PLAIN_SENTINELS = new Set([
|
|
10
|
+
"No matches found",
|
|
11
|
+
"No files found matching pattern",
|
|
12
|
+
"(empty directory)",
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
// `find` and `ls` append their limit block as one bracketed line, and stock pi
|
|
16
|
+
// counts it as a body line, so it is classified apart from a plain one.
|
|
17
|
+
const NOTICE_LINE = /^\[.*\]$/;
|
|
18
|
+
|
|
19
|
+
export function classifyPathLine(line: string): PathLine {
|
|
20
|
+
if (NOTICE_LINE.test(line)) return { kind: "notice", text: line };
|
|
21
|
+
if (PLAIN_SENTINELS.has(line) || line.trim() === "") return { kind: "plain", text: line };
|
|
22
|
+
return line.endsWith("/") ? { kind: "dir", path: line } : { kind: "file", path: line };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Directories keep the dim path color; only the entry named last gets a type
|
|
26
|
+
// color, which is what makes a nested path readable at a glance. That name is
|
|
27
|
+
// also bold, the one weight the terminal keeps when two theme colors land close
|
|
28
|
+
// together.
|
|
29
|
+
export function stylePath(path: string, theme: StyleTheme): string {
|
|
30
|
+
if (path === "") return "";
|
|
31
|
+
const segments = path.split("/");
|
|
32
|
+
const lastIndex = segments.length - 1;
|
|
33
|
+
const isDirectory = path.endsWith("/");
|
|
34
|
+
// The closing slash of a directory leaves a trailing empty segment, so the
|
|
35
|
+
// name to color is the last non-empty one.
|
|
36
|
+
const lastNameIndex = segments.reduce((acc, segment, index) => (segment === "" ? acc : index), -1);
|
|
37
|
+
const styled = segments.map((segment, index) => {
|
|
38
|
+
const slash = index < lastIndex ? "/" : "";
|
|
39
|
+
if (index === lastNameIndex) {
|
|
40
|
+
const color = isDirectory ? "dim" : fileTypeToken(segment);
|
|
41
|
+
return `${theme.bold(theme.fg(color, segment))}${slash}`;
|
|
42
|
+
}
|
|
43
|
+
// An empty segment is the leading slash of an absolute path.
|
|
44
|
+
if (segment === "") return slash;
|
|
45
|
+
return `${theme.fg(TOKEN.dirPath, segment)}${slash}`;
|
|
46
|
+
});
|
|
47
|
+
return styled.join("");
|
|
48
|
+
}
|
package/src/tokens.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { ThemeBg, ThemeColor } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
// Renderers receive the host's `Theme`; they only need these three members, so
|
|
4
|
+
// the structural subset keeps every module testable without constructing one.
|
|
5
|
+
export interface StyleTheme {
|
|
6
|
+
fg(color: ThemeColor, text: string): string;
|
|
7
|
+
bg(color: ThemeBg, text: string): string;
|
|
8
|
+
bold(text: string): string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// The subset the markdown pass needs. `fg()` wraps a whole string in the color
|
|
12
|
+
// and closes it at the end, which cannot recolor a span inside a line the host
|
|
13
|
+
// already painted: that pass has to build the escape sequence itself and close
|
|
14
|
+
// it at an exact position. Declared apart from `StyleTheme` for the same reason
|
|
15
|
+
// that one exists: a module only asks for the members it reads.
|
|
16
|
+
export interface AnsiTheme {
|
|
17
|
+
getFgAnsi(color: ThemeColor): string;
|
|
18
|
+
getBgAnsi(color: ThemeBg): string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Colors named by the role they play in tool output, so retheming the package
|
|
22
|
+
// is one edit here instead of a hunt through every renderer.
|
|
23
|
+
export interface SyntaxTokens {
|
|
24
|
+
path: ThemeColor;
|
|
25
|
+
dirPath: ThemeColor;
|
|
26
|
+
lineNumber: ThemeColor;
|
|
27
|
+
context: ThemeColor;
|
|
28
|
+
content: ThemeColor;
|
|
29
|
+
// A body printed flat, with no syntax pass: the host paints those with
|
|
30
|
+
// `toolOutput`, which is not the `text` the rest of the bodies use.
|
|
31
|
+
plain: ThemeColor;
|
|
32
|
+
notice: ThemeColor;
|
|
33
|
+
empty: ThemeColor;
|
|
34
|
+
broken: ThemeColor;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const TOKEN = {
|
|
38
|
+
path: "accent",
|
|
39
|
+
dirPath: "muted",
|
|
40
|
+
lineNumber: "syntaxNumber",
|
|
41
|
+
context: "dim",
|
|
42
|
+
content: "text",
|
|
43
|
+
plain: "toolOutput",
|
|
44
|
+
notice: "warning",
|
|
45
|
+
empty: "dim",
|
|
46
|
+
broken: "error",
|
|
47
|
+
} as const satisfies SyntaxTokens;
|
|
48
|
+
|
|
49
|
+
// The markdown tokens this package paints itself. The host's markdown theme is
|
|
50
|
+
// not extensible, so the tokens whose color the pass can reach are named here
|
|
51
|
+
// instead of being read from a theme entry the host decides.
|
|
52
|
+
export const MD_TOKEN = { quote: "accent" } as const satisfies { quote: ThemeColor };
|
|
53
|
+
|
|
54
|
+
// `Theme.bold()` wraps a whole string in both codes, which cannot emphasize a
|
|
55
|
+
// span inside an already rendered line: emphasis needs each marker on its own.
|
|
56
|
+
export const BOLD_ON = "\x1b[1m";
|
|
57
|
+
export const BOLD_OFF = "\x1b[22m";
|
|
58
|
+
|
|
59
|
+
// The same constraint for the attributes the markdown pass injects: each marker
|
|
60
|
+
// travels alone and closes only what it opened, so the host's style survives the
|
|
61
|
+
// span. No `\x1b[0m` reset is ever emitted, because it would drop that style too.
|
|
62
|
+
export const ITALIC_ON = "\x1b[3m";
|
|
63
|
+
export const ITALIC_OFF = "\x1b[23m";
|
|
64
|
+
export const UNDERLINE_ON = "\x1b[4m";
|
|
65
|
+
export const UNDERLINE_OFF = "\x1b[24m";
|
|
66
|
+
export const INVERSE_ON = "\x1b[7m";
|
|
67
|
+
export const INVERSE_OFF = "\x1b[27m";
|
|
68
|
+
export const FG_DEFAULT = "\x1b[39m";
|
|
69
|
+
export const BG_DEFAULT = "\x1b[49m";
|
|
70
|
+
// `\x1b[22m` closes both bold and dim, which is why `BOLD_OFF` and `DIM_OFF`
|
|
71
|
+
// share the sequence and why the only place dim is re-opened is a span that
|
|
72
|
+
// knows the host left it off.
|
|
73
|
+
export const DIM_ON = "\x1b[2m";
|
|
74
|
+
export const DIM_OFF = "\x1b[22m";
|
|
75
|
+
|
|
76
|
+
const CODE_EXTENSIONS = new Set([
|
|
77
|
+
"ts", "tsx", "js", "jsx", "mjs", "cjs", "mts", "cts",
|
|
78
|
+
"go", "rs", "py", "rb", "php", "java", "kt", "kts", "swift",
|
|
79
|
+
"c", "h", "cc", "cpp", "cxx", "hpp", "cs", "scala", "lua", "pl", "pm",
|
|
80
|
+
"ex", "exs", "erl", "hs", "zig", "dart", "sql", "graphql", "gql",
|
|
81
|
+
]);
|
|
82
|
+
|
|
83
|
+
const CONFIG_EXTENSIONS = new Set(["json", "jsonc", "yaml", "yml", "toml", "ini", "conf", "env"]);
|
|
84
|
+
|
|
85
|
+
const DOC_EXTENSIONS = new Set(["md", "mdx", "txt", "rst"]);
|
|
86
|
+
|
|
87
|
+
const SHELL_EXTENSIONS = new Set(["sh", "bash", "zsh", "fish", "ksh", "ps1"]);
|
|
88
|
+
|
|
89
|
+
const WEB_EXTENSIONS = new Set(["css", "scss", "less", "html", "htm", "vue", "svelte"]);
|
|
90
|
+
|
|
91
|
+
const IMAGE_EXTENSIONS = new Set(["png", "jpg", "jpeg", "gif", "svg", "webp", "bmp", "ico", "avif"]);
|
|
92
|
+
|
|
93
|
+
const BUILD_FILE_NAMES = new Set(["Makefile", "makefile", "GNUmakefile", "Dockerfile", "dockerfile"]);
|
|
94
|
+
|
|
95
|
+
// One implementation for every caller, so `".gitignore"` cannot be an extension
|
|
96
|
+
// in one module and a dotfile in another.
|
|
97
|
+
export function splitExtension(name: string): string | undefined {
|
|
98
|
+
const dot = name.lastIndexOf(".");
|
|
99
|
+
return dot > 0 ? name.slice(dot + 1).toLowerCase() : undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function fileTypeToken(fileName: string): ThemeColor {
|
|
103
|
+
if (BUILD_FILE_NAMES.has(fileName)) return "syntaxFunction";
|
|
104
|
+
const extension = splitExtension(fileName);
|
|
105
|
+
if (extension === undefined) return "toolOutput";
|
|
106
|
+
if (extension === "mk") return "syntaxFunction";
|
|
107
|
+
if (CODE_EXTENSIONS.has(extension)) return "syntaxType";
|
|
108
|
+
if (CONFIG_EXTENSIONS.has(extension)) return "syntaxString";
|
|
109
|
+
if (DOC_EXTENSIONS.has(extension)) return "toolOutput";
|
|
110
|
+
if (SHELL_EXTENSIONS.has(extension)) return "syntaxKeyword";
|
|
111
|
+
if (WEB_EXTENSIONS.has(extension)) return "syntaxFunction";
|
|
112
|
+
if (IMAGE_EXTENSIONS.has(extension)) return "syntaxNumber";
|
|
113
|
+
return "toolOutput";
|
|
114
|
+
}
|