pi-syntax-highlight 0.1.1 → 0.2.1

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 (49) hide show
  1. package/CHANGELOG.md +73 -58
  2. package/DEVELOPER.md +61 -34
  3. package/LICENSE +21 -0
  4. package/README.md +19 -18
  5. package/extensions/index.ts +5 -10
  6. package/package.json +5 -4
  7. package/src/detect-language.ts +205 -8
  8. package/src/emphasis.ts +82 -1
  9. package/src/highlight.ts +25 -9
  10. package/src/lru-cache.ts +30 -0
  11. package/src/markdown-fence-lang.ts +20 -87
  12. package/src/render-bash.ts +29 -2
  13. package/src/render-edit.ts +0 -6
  14. package/src/render-generic.ts +10 -21
  15. package/src/render-read.ts +8 -149
  16. package/src/render-utils.ts +8 -17
  17. package/src/resolve-renderers.ts +181 -240
  18. package/src/tokens.ts +1 -34
  19. package/assets/icon.png +0 -0
  20. package/assets/icon.svg +0 -36
  21. package/src/active-theme.ts +0 -26
  22. package/src/markdown-style.ts +0 -134
  23. package/src/markdown-theme.ts +0 -53
  24. package/src/render-path.ts +0 -54
  25. package/src/render-write.ts +0 -81
  26. package/test/unit/active-theme.test.ts +0 -38
  27. package/test/unit/bash-preview.test.ts +0 -57
  28. package/test/unit/detect-language.test.ts +0 -124
  29. package/test/unit/emphasis.test.ts +0 -113
  30. package/test/unit/extensions-index.test.ts +0 -116
  31. package/test/unit/grep-parse.test.ts +0 -125
  32. package/test/unit/highlight.test.ts +0 -107
  33. package/test/unit/markdown-fence-lang.test.ts +0 -131
  34. package/test/unit/markdown-pipeline.test.ts +0 -153
  35. package/test/unit/markdown-render-parity.test.ts +0 -127
  36. package/test/unit/markdown-style.test.ts +0 -152
  37. package/test/unit/markdown-theme.test.ts +0 -86
  38. package/test/unit/render-bash.test.ts +0 -194
  39. package/test/unit/render-edit.test.ts +0 -214
  40. package/test/unit/render-find.test.ts +0 -139
  41. package/test/unit/render-generic.test.ts +0 -152
  42. package/test/unit/render-grep.test.ts +0 -338
  43. package/test/unit/render-ls.test.ts +0 -132
  44. package/test/unit/render-read.test.ts +0 -375
  45. package/test/unit/render-utils.test.ts +0 -324
  46. package/test/unit/render-write.test.ts +0 -143
  47. package/test/unit/resolve-renderers.test.ts +0 -474
  48. package/test/unit/style-path.test.ts +0 -74
  49. package/tsconfig.json +0 -15
@@ -1,23 +1,23 @@
1
- import { keyHint } from "@earendil-works/pi-coding-agent";
1
+ import {
2
+ createBashToolDefinition,
3
+ createEditToolDefinition,
4
+ createFindToolDefinition,
5
+ createGrepToolDefinition,
6
+ createLsToolDefinition,
7
+ createPowerShellToolDefinition,
8
+ createReadToolDefinition,
9
+ rawKeyHint,
10
+ } from "@earendil-works/pi-coding-agent";
2
11
  import type { AgentToolResult, Theme, ToolRenderers, ToolRenderResultOptions } from "@earendil-works/pi-coding-agent";
3
12
  import { Container, Spacer, Text, type Component } from "@earendil-works/pi-tui";
4
- import { captureTheme } from "./active-theme.ts";
5
13
  import { highlight, syncHighlightTheme } from "./highlight.ts";
6
14
  import { buildBashBody, createBashPreview, type BashInput } from "./render-bash.ts";
7
- import { buildEditDiffText, buildEditErrorText } from "./render-edit.ts";
15
+ import { buildEditDiffText } from "./render-edit.ts";
8
16
  import { buildFindResultText, type PathListInput } from "./render-find.ts";
9
17
  import { buildGenericResultText } from "./render-generic.ts";
10
18
  import { buildGrepResultText, type GrepInput } from "./render-grep.ts";
11
19
  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";
20
+ import { buildReadResultText, readPath, type ReadResultInput } from "./render-read.ts";
21
21
  import { reuseText, textOutput, type RenderContext } from "./render-utils.ts";
22
22
  import { TOKEN } from "./tokens.ts";
23
23
 
@@ -26,7 +26,6 @@ type FindDetails = PathListInput["details"];
26
26
  type LsDetails = LsInput["details"];
27
27
 
28
28
  type ResultRenderer = NonNullable<ToolRenderers["renderResult"]>;
29
- type CallRenderer = NonNullable<ToolRenderers["renderCall"]>;
30
29
 
31
30
  // The last resort when a body cannot be styled still has to fit the collapsed
32
31
  // transcript, so it keeps the line count the list renderers use.
@@ -49,53 +48,56 @@ function editDiff(details: unknown): string {
49
48
  return typeof diff === "string" ? diff : "";
50
49
  }
51
50
 
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.
51
+ // An image result is not file text: the body loses the grammar, which is the
52
+ // branch the built-in takes too.
54
53
  function hasImageBlock(result: AgentToolResult<unknown>): boolean {
55
54
  return result.content.some((block) => block.type === "image");
56
55
  }
57
56
 
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;
57
+ // Every styled result turns plain text into themed text from the same render
58
+ // inputs. Only grep reads the call arguments (its pattern drives the match
59
+ // emphasis); only the renderers that paint a failure differently read `isError`.
60
+ // The builders read `result.details` themselves, inside the guarded region.
61
+ interface ResultTextInput {
62
+ output: string;
63
+ result: AgentToolResult<unknown>;
64
+ expanded: boolean;
65
+ theme: Theme;
66
+ expandHint: string;
67
+ args: unknown;
68
+ isError: boolean;
65
69
  }
66
70
 
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
- }
71
+ type ResultTextBuilder = (input: ResultTextInput) => string;
72
+
73
+ // `rawKeyHint` takes no keybinding lookup, so the fallback cannot throw outside
74
+ // a session (export, headless).
75
+ function expandHint(context: RenderContext): string {
76
+ return context.keyHint?.("app.tools.expand", "to expand") ?? rawKeyHint("ctrl+o", "to expand");
89
77
  }
90
78
 
91
79
  function grepArgs(args: unknown): GrepInput["pattern"] {
92
80
  return typeof args === "object" && args !== null ? (args as GrepInput["pattern"]) : {};
93
81
  }
94
82
 
95
- function wrapResultRenderer<TDetails>(build: ResultTextBuilder<TDetails>): ResultRenderer {
83
+ // Ours first; when it throws, the host's own renderer takes the result, with a
84
+ // fresh slot because ours may have left the previous component half-built. With
85
+ // no host renderer to fall back to (generic overlay) the plain body is the floor.
86
+ function withStockFallback(ours: ResultRenderer, stock: ResultRenderer | undefined): ResultRenderer {
87
+ return (result, options, theme, context) => {
88
+ try {
89
+ return ours(result, options, theme, context);
90
+ } catch {
91
+ // Nothing is logged: a write to stdout/stderr would corrupt the TUI frame.
92
+ // The contract and stock-parity tests are the detection path.
93
+ if (stock !== undefined) return stock(result, options, theme, { ...context, lastComponent: undefined });
94
+ return new Text(fallbackBody(textOutput(result, context.showImages), options.expanded, theme), 0, 0);
95
+ }
96
+ };
97
+ }
98
+
99
+ function wrapResultRenderer(build: ResultTextBuilder): ResultRenderer {
96
100
  return (result, options, theme, context) => {
97
- // The last theme seen is what the paths outside a renderer paint with.
98
- captureTheme(theme);
99
101
  // The cached highlight lines were painted with the previous theme, if any.
100
102
  syncHighlightTheme(theme);
101
103
  const component = reuseText(context);
@@ -103,14 +105,9 @@ function wrapResultRenderer<TDetails>(build: ResultTextBuilder<TDetails>): Resul
103
105
  // The TUI hands the failure through the context; the result it passes to the
104
106
  // renderer carries no `isError`, so reading it there would always be false.
105
107
  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
- }
108
+ component.setText(
109
+ build({ output, result, expanded: options.expanded, theme, expandHint: expandHint(context), args: context.args, isError }),
110
+ );
114
111
  return component;
115
112
  };
116
113
  }
@@ -124,83 +121,54 @@ function fallbackBody(output: string, expanded: boolean, theme: Theme): string {
124
121
  return visible.map((line) => theme.fg(TOKEN.content, line)).join("\n");
125
122
  }
126
123
 
127
- const GREP_RESULT = wrapResultRenderer<GrepDetails>((output, details, expanded, theme, expandHint, args) =>
128
- buildGrepResultText({ output, details, expanded, pattern: grepArgs(args), theme, expandHint, highlight }),
124
+ const GREP_RESULT = wrapResultRenderer(({ output, result, expanded, theme, expandHint, args }) =>
125
+ buildGrepResultText({
126
+ output,
127
+ details: result.details as GrepDetails,
128
+ expanded,
129
+ pattern: grepArgs(args),
130
+ theme,
131
+ expandHint,
132
+ highlight,
133
+ }),
129
134
  );
130
135
 
131
- const FIND_RESULT = wrapResultRenderer<FindDetails>((output, details, expanded, theme, expandHint, _args, isError) =>
132
- buildFindResultText({ output, details, expanded, isError, theme, expandHint }),
136
+ const FIND_RESULT = wrapResultRenderer(({ output, result, expanded, theme, expandHint, isError }) =>
137
+ buildFindResultText({ output, details: result.details as FindDetails, expanded, isError, theme, expandHint }),
133
138
  );
134
139
 
135
- const LS_RESULT = wrapResultRenderer<LsDetails>((output, details, expanded, theme, expandHint, _args, isError) =>
136
- buildLsResultText({ output, details, expanded, isError, theme, expandHint }),
140
+ const LS_RESULT = wrapResultRenderer(({ output, result, expanded, theme, expandHint, isError }) =>
141
+ buildLsResultText({ output, details: result.details as LsDetails, expanded, isError, theme, expandHint }),
137
142
  );
138
143
 
139
144
  // Fallback for every tool this package does not style: the body is painted, the
140
145
  // 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 }),
146
+ const GENERIC_RESULT = wrapResultRenderer(({ output, expanded, theme, expandHint, isError }) =>
147
+ buildGenericResultText({ output, expanded, isError, theme, expandHint }),
144
148
  );
145
149
 
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
- };
150
+ const READ_RESULT = wrapResultRenderer(({ output, result, expanded, theme, expandHint, args, isError }) =>
151
+ buildReadResultText({
152
+ output,
153
+ path: readPath(args),
154
+ details: readDetails(result.details),
155
+ expanded,
156
+ isError,
157
+ hasImage: hasImageBlock(result),
158
+ theme,
159
+ expandHint,
160
+ highlight,
161
+ }),
162
+ );
194
163
 
195
164
  // 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.
165
+ // the built-in `renderResult` writes the diff into that same box. The header the
166
+ // built-in left is the first child; the members declared are the ones this
167
+ // package touches, so a host that drops one loses the highlight, never the diff.
199
168
  interface EditCallBox extends Component {
200
169
  children: Component[];
201
170
  addChild(component: Component): void;
202
171
  removeChild(component: Component): void;
203
- setBgFn(bgFn?: (text: string) => string): void;
204
172
  }
205
173
 
206
174
  function editCallBox(state: Record<string, unknown>): EditCallBox | undefined {
@@ -208,99 +176,73 @@ function editCallBox(state: Record<string, unknown>): EditCallBox | undefined {
208
176
  if (candidate === undefined || candidate === null) return undefined;
209
177
  const usable =
210
178
  Array.isArray(candidate.children) &&
179
+ candidate.children.length > 0 &&
211
180
  typeof candidate.addChild === "function" &&
212
181
  typeof candidate.removeChild === "function" &&
213
- typeof candidate.setBgFn === "function" &&
214
182
  typeof candidate.render === "function";
215
183
  return usable ? (candidate as EditCallBox) : undefined;
216
184
  }
217
185
 
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));
186
+ function replaceChildrenAfter(container: Pick<EditCallBox, "children" | "addChild" | "removeChild">, keep: number, body: Component): void {
187
+ for (const child of container.children.slice(keep)) container.removeChild(child);
188
+ container.addChild(new Spacer(1));
189
+ container.addChild(body);
226
190
  }
227
191
 
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
- };
192
+ // Stock draws everything; only a successful diff is replaced by the highlighted
193
+ // one, in the box stock filled or, with no box, in the container it returned.
194
+ function editSlot(base: { renderResult: ResultRenderer }): ToolRenderers {
195
+ const stock = base.renderResult;
196
+ const ours: ResultRenderer = (result, options, theme, context) => {
197
+ syncHighlightTheme(theme);
198
+ const stockOut = stock(result, options, theme, context);
199
+ const diff = editDiff(result.details);
200
+ if (context.isError === true || diff === "") return stockOut;
201
+ const body = buildEditDiffText({ diff, path: readPath(context.args), theme, highlight });
202
+ const box = editCallBox(context.state);
203
+ if (box !== undefined) {
204
+ replaceChildrenAfter(box, 1, new Text(body, 0, 0));
205
+ return stockOut;
206
+ }
207
+ if (!(stockOut instanceof Container)) return stockOut;
208
+ replaceChildrenAfter(stockOut, 0, new Text(body, context.outputPad, 0));
209
+ return stockOut;
210
+ };
211
+ return { renderResult: withStockFallback(ours, stock) };
212
+ }
250
213
 
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
- };
214
+ const stockResultCache = new Map<string, ResultRenderer | undefined>();
266
215
 
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
- };
216
+ function stockResult(toolName: string): ResultRenderer | undefined {
217
+ if (stockResultCache.has(toolName)) return stockResultCache.get(toolName);
218
+ let stock: ResultRenderer | undefined;
219
+ try {
220
+ stock = (STYLED_TOOLS.get(toolName)?.stockDefinition(process.cwd()) as ToolRenderers | undefined)?.renderResult;
221
+ } catch {
222
+ stock = undefined;
223
+ }
224
+ stockResultCache.set(toolName, stock);
225
+ return stock;
226
+ }
287
227
 
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
- ]);
228
+ // The built-in `bash` and `powershell` renderers are built per definition, so
229
+ // identity fails and the source text is the second test. Anything undecidable
230
+ // counts as foreign: the look the tool brought is the safe one.
231
+ function isStockSlot(toolName: string, renderResult: ResultRenderer): boolean {
232
+ const stock = stockResult(toolName);
233
+ if (stock === undefined) return false;
234
+ try {
235
+ return renderResult === stock || renderResult.toString() === stock.toString();
236
+ } catch {
237
+ return false;
238
+ }
239
+ }
240
+
241
+ type SlotFactory = (base: ToolRenderers & { renderResult: ResultRenderer }) => ToolRenderers;
300
242
 
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"]);
243
+ const resultSlot =
244
+ (ours: ResultRenderer): SlotFactory =>
245
+ (base) => ({ renderResult: withStockFallback(ours, base.renderResult) });
304
246
 
305
247
  // The host keeps the row's clock in `context.state` between renders; these are
306
248
  // the three fields this renderer reads and writes.
@@ -331,10 +273,13 @@ function buildShellComponent(
331
273
  delete timer.interval;
332
274
  }
333
275
  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.
276
+ // A recorded duration wins because it survives reloads; the row's own clock
277
+ // is the fallback, frozen at the stamped end so later renders do not grow it.
336
278
  const duration =
337
- context.durationMs ?? (timer.startedAt !== undefined ? Date.now() - timer.startedAt : undefined);
279
+ context.durationMs ??
280
+ (typeof timer.startedAt === "number" && typeof timer.endedAt === "number"
281
+ ? timer.endedAt - timer.startedAt
282
+ : undefined);
338
283
  const built = buildBashBody({
339
284
  output: textOutput(result, context.showImages),
340
285
  details: shellDetails(result.details),
@@ -347,7 +292,7 @@ function buildShellComponent(
347
292
  container.addChild(new Text(`\n${built.body}`, 0, 0));
348
293
  } else {
349
294
  container.addChild(new Spacer(1));
350
- container.addChild(createBashPreview(built.body, expandHint(), theme));
295
+ container.addChild(createBashPreview(built.body, expandHint(context), theme));
351
296
  }
352
297
  }
353
298
  if (built.warnings !== undefined) {
@@ -359,48 +304,44 @@ function buildShellComponent(
359
304
  return container;
360
305
  }
361
306
 
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
- }
307
+ // The shell renderer is created per resolution because it needs the host's
308
+ // renderer at call time.
309
+ function shellSlot(base: { renderResult: ResultRenderer }): ToolRenderers {
310
+ const stock = base.renderResult;
311
+ const final = withStockFallback(buildShellComponent, stock);
312
+ // Streaming stays on the built-in path: it owns the elapsed line and the
313
+ // repaint interval, which a final result cannot reproduce.
314
+ return {
315
+ renderResult: (result, options, theme, context) => {
316
+ syncHighlightTheme(theme);
317
+ return options.isPartial ? stock(result, options, theme, context) : final(result, options, theme, context);
318
+ },
388
319
  };
389
320
  }
390
321
 
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.
322
+ // Keyed by name because the resolver is the single entry point for every tool.
323
+ // The slot is overlaid only when the base renderResult is the one of the host's
324
+ // own `stockDefinition`.
325
+ const STYLED_TOOLS: ReadonlyMap<string, { stockDefinition: (cwd: string) => unknown; slot: SlotFactory }> = new Map([
326
+ ["grep", { stockDefinition: createGrepToolDefinition, slot: resultSlot(GREP_RESULT) }],
327
+ ["find", { stockDefinition: createFindToolDefinition, slot: resultSlot(FIND_RESULT) }],
328
+ ["ls", { stockDefinition: createLsToolDefinition, slot: resultSlot(LS_RESULT) }],
329
+ ["read", { stockDefinition: createReadToolDefinition, slot: resultSlot(READ_RESULT) }],
330
+ ["edit", { stockDefinition: createEditToolDefinition, slot: editSlot }],
331
+ ["bash", { stockDefinition: createBashToolDefinition, slot: shellSlot }],
332
+ ["powershell", { stockDefinition: createPowerShellToolDefinition, slot: shellSlot }],
333
+ ]);
334
+
335
+ // `undefined` ends the chain the way the host expects, so it passes through. A
336
+ // renderResult this package does not recognise is left exactly as it came (same
337
+ // object); only a stock slot is overlaid, and only a tool that brings no result
338
+ // renderer at all gets the generic body.
396
339
  export function resolveToolRenderers(toolName: string, next: () => ToolRenderers | undefined): ToolRenderers | undefined {
397
340
  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 };
341
+ if (base === undefined) return undefined;
342
+ const current = base.renderResult;
343
+ if (current === undefined) return { ...base, renderResult: withStockFallback(GENERIC_RESULT, undefined) };
344
+ const slot = STYLED_TOOLS.get(toolName)?.slot;
345
+ if (slot === undefined || !isStockSlot(toolName, current)) return base;
346
+ return { ...base, ...slot({ ...base, renderResult: current }) };
406
347
  }
package/src/tokens.ts CHANGED
@@ -8,16 +8,6 @@ export interface StyleTheme {
8
8
  bold(text: string): string;
9
9
  }
10
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
11
  // Colors named by the role they play in tool output, so retheming the package
22
12
  // is one edit here instead of a hunt through every renderer.
23
13
  export interface SyntaxTokens {
@@ -26,9 +16,6 @@ export interface SyntaxTokens {
26
16
  lineNumber: ThemeColor;
27
17
  context: ThemeColor;
28
18
  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
19
  notice: ThemeColor;
33
20
  empty: ThemeColor;
34
21
  broken: ThemeColor;
@@ -39,39 +26,19 @@ export const TOKEN = {
39
26
  dirPath: "muted",
40
27
  lineNumber: "syntaxNumber",
41
28
  context: "dim",
42
- content: "text",
43
- plain: "toolOutput",
29
+ content: "toolOutput",
44
30
  notice: "warning",
45
31
  empty: "dim",
46
32
  broken: "error",
47
33
  } as const satisfies SyntaxTokens;
48
34
 
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
35
  // `Theme.bold()` wraps a whole string in both codes, which cannot emphasize a
55
36
  // span inside an already rendered line: emphasis needs each marker on its own.
56
37
  export const BOLD_ON = "\x1b[1m";
57
38
  export const BOLD_OFF = "\x1b[22m";
58
39
 
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
40
  export const INVERSE_ON = "\x1b[7m";
67
41
  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
42
 
76
43
  const CODE_EXTENSIONS = new Set([
77
44
  "ts", "tsx", "js", "jsx", "mjs", "cjs", "mts", "cts",
package/assets/icon.png DELETED
Binary file
package/assets/icon.svg DELETED
@@ -1,36 +0,0 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" width="1200" height="750" viewBox="0 0 1200 750">
2
- <rect width="1200" height="750" fill="#0E1726"/>
3
- <circle cx="600" cy="375" r="420" fill="#12202F"/>
4
- <!-- terminal window -->
5
- <rect x="286" y="146" width="628" height="458" rx="28" fill="#0B1220" stroke="#2F7C93" stroke-width="14"/>
6
- <line x1="286" y1="222" x2="914" y2="222" stroke="#2F7C93" stroke-width="12"/>
7
- <g fill="#19C7D4">
8
- <circle cx="340" cy="184" r="14"/>
9
- <circle cx="388" cy="184" r="14" fill="#2F7C93"/>
10
- <circle cx="436" cy="184" r="14" fill="#2F7C93"/>
11
- </g>
12
- <!-- one highlighted line -->
13
- <rect x="308" y="356" width="584" height="52" rx="10" fill="#19C7D4" opacity="0.16"/>
14
- <rect x="308" y="356" width="6" height="52" rx="3" fill="#19C7D4"/>
15
- <!-- code, one bar per token -->
16
- <g rx="8">
17
- <rect x="340" y="264" width="104" height="26" rx="13" fill="#C792EA"/>
18
- <rect x="458" y="264" width="196" height="26" rx="13" fill="#82AAFF"/>
19
- <rect x="668" y="264" width="164" height="26" rx="13" fill="#A5E075"/>
20
- <rect x="392" y="312" width="86" height="26" rx="13" fill="#F78C6C"/>
21
- <rect x="492" y="312" width="238" height="26" rx="13" fill="#D6DEEB"/>
22
- <rect x="340" y="370" width="72" height="26" rx="13" fill="#82AAFF"/>
23
- <rect x="426" y="370" width="150" height="26" rx="13" fill="#A5E075"/>
24
- <rect x="590" y="370" width="112" height="26" rx="13" fill="#C792EA"/>
25
- <rect x="392" y="426" width="196" height="26" rx="13" fill="#D6DEEB"/>
26
- <rect x="602" y="426" width="84" height="26" rx="13" fill="#F78C6C"/>
27
- <rect x="340" y="484" width="58" height="26" rx="13" fill="#19C7D4"/>
28
- <rect x="412" y="484" width="148" height="26" rx="13" fill="#D6DEEB"/>
29
- <rect x="574" y="484" width="96" height="26" rx="13" fill="#A5E075"/>
30
- <rect x="684" y="484" width="120" height="26" rx="13" fill="#2F7C93"/>
31
- <rect x="340" y="542" width="96" height="26" rx="13" fill="#2F7C93"/>
32
- <rect x="450" y="542" width="64" height="26" rx="13" fill="#C792EA"/>
33
- </g>
34
- <!-- caret at the end of the last line -->
35
- <rect x="530" y="532" width="16" height="46" fill="#19C7D4"/>
36
- </svg>