@herbertgao/pi-extensions 2026.11.14 → 2026.11.16

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 (51) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +7 -7
  3. package/THIRD_PARTY_NOTICES.md +3 -3
  4. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
  5. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +3 -2
  6. package/node_modules/@herbertgao/pi-cc-extensions/README.md +3 -2
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +5 -0
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +9 -0
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/index.ts +32 -2
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/markdown-enhance.ts +26 -21
  11. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/table-copy.ts +753 -0
  12. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/fullscreen-detect.ts +11 -0
  13. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  14. package/node_modules/@herbertgao/pi-impeccable/CHANGELOG.md +6 -0
  15. package/node_modules/@herbertgao/pi-impeccable/README.md +2 -2
  16. package/node_modules/@herbertgao/pi-impeccable/package.json +4 -4
  17. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/SKILL.md +5 -5
  18. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/audit.md +8 -1
  19. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/audit.native.md +8 -1
  20. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/craft-floor.md +3 -3
  21. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/critique.md +8 -6
  22. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/degraded/finish-reviewer.md +2 -2
  23. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/doctor.md +5 -1
  24. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/init.md +2 -0
  25. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/live.md +1 -1
  26. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/new-work.md +8 -9
  27. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/polish.md +1 -1
  28. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/VERSION +1 -1
  29. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/engine-checksums.txt +5 -5
  30. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/live-browser.js +55 -32
  31. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
  32. package/node_modules/@herbertgao/pi-subagents/README.md +18 -16
  33. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
  34. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  35. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +18 -5
  36. package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +88 -0
  37. package/node_modules/@herbertgao/pi-subagents/src/index.ts +16 -92
  38. package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +6 -2
  39. package/node_modules/@herbertgao/pi-subagents/src/nested-tools.ts +18 -2
  40. package/node_modules/@herbertgao/pi-subagents/src/prompts.ts +25 -3
  41. package/node_modules/pi-commandcode-provider/CHANGELOG.md +20 -0
  42. package/node_modules/pi-commandcode-provider/README.md +1 -1
  43. package/node_modules/pi-commandcode-provider/index.ts +2 -1
  44. package/node_modules/pi-commandcode-provider/package.json +1 -1
  45. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +9 -2
  46. package/node_modules/pi-commandcode-provider/src/pricing.ts +5 -1
  47. package/node_modules/pi-commandcode-provider/src/responses-compat.ts +24 -1
  48. package/node_modules/pi-commandcode-provider/src/responses-stream.ts +99 -6
  49. package/node_modules/pi-provider-qoder/dist/index.js +50 -10
  50. package/node_modules/pi-provider-qoder/package.json +1 -1
  51. package/package.json +6 -6
@@ -0,0 +1,753 @@
1
+ /**
2
+ * Add Grok-style whole-table copy actions to Pi's Markdown tables.
3
+ *
4
+ * Pi's transformer supplies provenance; a removable Markdown prototype patch
5
+ * adds mouse actions only to fullscreen assistant-body instances. This module
6
+ * deliberately does not implement cell selection or geometry.
7
+ */
8
+ import { randomUUID } from "node:crypto";
9
+ import { appendFileSync, mkdirSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import {
12
+ copyToClipboard,
13
+ getAgentDir,
14
+ VERSION,
15
+ type ExtensionAPI,
16
+ type ExtensionContext,
17
+ type MarkdownTransformContext,
18
+ } from "@earendil-works/pi-coding-agent";
19
+ import {
20
+ Markdown,
21
+ TuiAltScreen,
22
+ stripTerminalSequences,
23
+ visibleWidth,
24
+ type TUI,
25
+ type TuiMouseEvent,
26
+ type TuiMouseEventResult,
27
+ } from "@earendil-works/pi-tui";
28
+ import { walkComponentTree } from "../utils/component-tree.ts";
29
+ import { isFullscreenTui } from "../utils/fullscreen-detect.ts";
30
+ import { isTranscriptComponent, markTranscriptComponent } from "./transcript-scope.ts";
31
+
32
+ const PATCH = Symbol.for("pi.ccstyle.markdown-table-copy");
33
+ const ACTIONS_KEY = Symbol.for("pi.ccstyle.markdown-table-copy.actions");
34
+ const FORMATS = ["tsv", "csv", "markdown"] as const;
35
+
36
+ type Format = (typeof FORMATS)[number];
37
+ type CopyText = (text: string) => Promise<void>;
38
+ type Notify = (message: string, isError: boolean) => void;
39
+ type Paint = (color: "dim" | "text", text: string) => string;
40
+
41
+ export interface TableCopyOptions {
42
+ tui: { readonly mode?: string };
43
+ paint: Paint;
44
+ copy?: CopyText;
45
+ notify?: Notify;
46
+ /** Compatibility diagnostics; defaults to an agent-directory debug log, never stdout. */
47
+ debug?: (message: string) => void;
48
+ }
49
+
50
+ export interface TableCopyInstallation {
51
+ /** Called by the entry point's combined transformer; never changes the source. */
52
+ noteSource(context: MarkdownTransformContext): void;
53
+ dispose(): void;
54
+ }
55
+
56
+ interface TableCopyOwner extends TableCopyOptions {
57
+ copy: CopyText;
58
+ notify: Notify;
59
+ debug: (message: string) => void;
60
+ }
61
+
62
+ interface InlineToken {
63
+ type?: string;
64
+ text?: string;
65
+ raw?: string;
66
+ tokens?: InlineToken[];
67
+ }
68
+
69
+ interface TableCell {
70
+ text: string;
71
+ tokens?: InlineToken[];
72
+ }
73
+
74
+ interface TableToken {
75
+ type: "table";
76
+ raw: string;
77
+ header: TableCell[];
78
+ rows: TableCell[][];
79
+ tokens?: MarkdownToken[];
80
+ items?: MarkdownToken[];
81
+ }
82
+
83
+ interface MarkdownToken {
84
+ type?: string;
85
+ raw?: string;
86
+ tokens?: MarkdownToken[];
87
+ items?: Array<{ tokens?: MarkdownToken[] }>;
88
+ }
89
+
90
+ interface MarkdownInternals {
91
+ cachedTokens?: { deref(): { tokens: MarkdownToken[] } | undefined };
92
+ clearRenderCache?: () => void;
93
+ }
94
+
95
+ interface ActionHit {
96
+ y: number;
97
+ start: number;
98
+ end: number;
99
+ format: Format;
100
+ marker: string;
101
+ text: string;
102
+ table: TableToken;
103
+ }
104
+
105
+ interface ActionState {
106
+ owner: TableCopyOwner;
107
+ lines: string[];
108
+ hits: ActionHit[];
109
+ hover?: { y: number; format: Format };
110
+ }
111
+
112
+ interface MarkdownWithActions extends Markdown {
113
+ [ACTIONS_KEY]?: ActionState;
114
+ }
115
+
116
+ type Render = (this: MarkdownWithActions, width: number) => string[];
117
+ type RenderTable = (
118
+ this: MarkdownWithActions,
119
+ token: TableToken,
120
+ availableWidth: number,
121
+ nextTokenType?: string,
122
+ styleContext?: unknown,
123
+ ) => string[];
124
+ type HandleMouse = (
125
+ this: MarkdownWithActions,
126
+ event: TuiMouseEvent,
127
+ ) => TuiMouseEventResult | undefined;
128
+
129
+ interface SelectionPoint {
130
+ row: number;
131
+ col: number;
132
+ scrollView?: unknown;
133
+ }
134
+
135
+ interface SelectionBounds {
136
+ start: SelectionPoint;
137
+ end: SelectionPoint;
138
+ }
139
+
140
+ interface SelectionInternals {
141
+ getSelectionBounds(): SelectionBounds | undefined;
142
+ getSelectionSourceLine(point: SelectionPoint): string;
143
+ }
144
+
145
+ type SelectionText = (this: SelectionInternals) => string | undefined;
146
+ type SelectionColumns = (
147
+ this: SelectionInternals,
148
+ line: string,
149
+ row: number,
150
+ selection: SelectionBounds,
151
+ minColumn?: number,
152
+ maxColumn?: number,
153
+ ) => { start: number; end: number };
154
+
155
+ interface Patch {
156
+ version: 3;
157
+ active: boolean;
158
+ markerPrefix: string;
159
+ selectionTarget: Prototype;
160
+ originalSelectionText: SelectionText;
161
+ originalSelectionColumns: SelectionColumns;
162
+ wrappedSelectionText: SelectionText;
163
+ wrappedSelectionColumns: SelectionColumns;
164
+ owners: Set<TableCopyOwner>;
165
+ components: Set<WeakRef<MarkdownWithActions>>;
166
+ componentRefs: WeakMap<MarkdownWithActions, WeakRef<MarkdownWithActions>>;
167
+ componentOwners: WeakMap<MarkdownWithActions, TableCopyOwner>;
168
+ rendering?: { component: MarkdownWithActions; transcript: boolean };
169
+ originalRender: Render;
170
+ originalRenderTable: RenderTable;
171
+ originalHandleMouse?: HandleMouse;
172
+ wrappedRender: Render;
173
+ wrappedRenderTable: RenderTable;
174
+ wrappedHandleMouse: HandleMouse;
175
+ }
176
+
177
+ type Prototype = Record<PropertyKey, unknown>;
178
+
179
+ function label(format: Format, compact = false): string {
180
+ if (compact) return `[${format === "markdown" ? "MD" : format.toUpperCase()}]`;
181
+ return `[Copy ${format === "markdown" ? "Markdown" : format.toUpperCase()}]`;
182
+ }
183
+
184
+ /** Zero-width APC markers survive caches; real terminals require ST, not BEL. */
185
+ function marker(patch: Patch, kind: string): string {
186
+ return `${patch.markerPrefix}${kind}\x1b\\`;
187
+ }
188
+
189
+ function isActionRow(patch: Patch, line: string): boolean {
190
+ return FORMATS.some((format) => line.includes(marker(patch, `action:${format}`)));
191
+ }
192
+
193
+ function diagnostics(options: TableCopyOptions): (message: string) => void {
194
+ const reported = new Set<string>();
195
+ return (message) => {
196
+ if (reported.has(message)) return;
197
+ reported.add(message);
198
+ const entry = `[table-copy] Pi ${VERSION}: ${message}`;
199
+ try {
200
+ if (options.debug) options.debug(entry);
201
+ else {
202
+ const directory = join(getAgentDir(), "logs");
203
+ mkdirSync(directory, { recursive: true });
204
+ appendFileSync(
205
+ join(directory, "pi-cc-extensions-table-copy.log"),
206
+ `${new Date().toISOString()} ${entry}\n`,
207
+ );
208
+ }
209
+ } catch {
210
+ // A read-only log directory or custom logger must not break rendering.
211
+ }
212
+ };
213
+ }
214
+
215
+ /** Inline Markdown copies as readable cell text, without ANSI or formatting markers. */
216
+ function inlineText(tokens: InlineToken[] | undefined, fallback: string): string {
217
+ if (!tokens?.length) return fallback;
218
+ return tokens
219
+ .map((token) => {
220
+ if (token.type === "br") return " ";
221
+ if (token.tokens?.length) return inlineText(token.tokens, "");
222
+ return token.text ?? token.raw ?? "";
223
+ })
224
+ .join("");
225
+ }
226
+
227
+ function cellText(cell: TableCell): string {
228
+ return inlineText(cell.tokens, cell.text).replaceAll("\r\n", "\n").replaceAll("\r", "\n");
229
+ }
230
+
231
+ function tableRows(token: TableToken): string[][] {
232
+ return [token.header, ...token.rows].map((row) => row.map(cellText));
233
+ }
234
+
235
+ function csvCell(text: string): string {
236
+ return /[",\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
237
+ }
238
+
239
+ /** Serialize the parsed table, never the terminal border or its wrapping. */
240
+ export function serializeTable(token: TableToken, format: Format): string {
241
+ if (format === "markdown") return token.raw.replace(/(?:\r?\n)+$/, "");
242
+ const rows = tableRows(token);
243
+ if (format === "tsv") {
244
+ return rows.map((row) => row.map((cell) => cell.replace(/[\t\n]/g, " ")).join("\t")).join("\n");
245
+ }
246
+ return rows.map((row) => row.map(csvCell).join(",")).join("\n");
247
+ }
248
+
249
+ function actionLines(patch: Patch, availableWidth: number): string[] {
250
+ const compact = visibleWidth(label("markdown")) > availableWidth;
251
+ const labels = FORMATS.map((format) => label(format, compact));
252
+ // Even the compact labels need five columns. Hide actions rather than render
253
+ // a broken label or an unidentifiable one-character button below that width.
254
+ if (labels.some((text) => visibleWidth(text) > availableWidth)) return [];
255
+ const actions = FORMATS.map(
256
+ (format, index) =>
257
+ `${marker(patch, `action:${format}`)}${labels[index]}${marker(patch, "end")}`,
258
+ );
259
+ if (visibleWidth(actions.join(" ")) <= availableWidth) return [actions.join(" ")];
260
+ if (visibleWidth(actions.join(" ")) <= availableWidth) return [actions.join(" ")];
261
+ return actions;
262
+ }
263
+
264
+ function collectTables(tokens: MarkdownToken[], output: TableToken[] = []): TableToken[] {
265
+ for (const token of tokens) {
266
+ if (token.type === "table") {
267
+ const table = token as TableToken;
268
+ if (table.header.length > 0) output.push(table);
269
+ }
270
+ if (token.tokens?.length) collectTables(token.tokens, output);
271
+ for (const item of token.items ?? []) {
272
+ if (item.tokens?.length) collectTables(item.tokens, output);
273
+ }
274
+ }
275
+ return output;
276
+ }
277
+
278
+ function parsedTokens(component: MarkdownWithActions): MarkdownToken[] | undefined {
279
+ const cache = (component as unknown as MarkdownInternals).cachedTokens;
280
+ const tokens = typeof cache?.deref === "function" ? cache.deref()?.tokens : undefined;
281
+ return Array.isArray(tokens) ? tokens : undefined;
282
+ }
283
+
284
+ function paintActions(
285
+ patch: Patch,
286
+ lines: string[],
287
+ hits: ActionHit[],
288
+ hover: ActionState["hover"],
289
+ paint: Paint,
290
+ ): void {
291
+ const byLine = new Map<number, ActionHit[]>();
292
+ for (const hit of hits) {
293
+ const row = byLine.get(hit.y) ?? [];
294
+ row.push(hit);
295
+ byLine.set(hit.y, row);
296
+ }
297
+ for (const [y, row] of byLine) {
298
+ const replacements = row
299
+ .map((hit) => ({ hit, index: lines[y]!.indexOf(hit.marker) }))
300
+ .filter(({ index }) => index >= 0)
301
+ .sort((a, b) => b.index - a.index);
302
+ for (const { hit, index } of replacements) {
303
+ const start = index + hit.marker.length;
304
+ const end = lines[y]!.indexOf(marker(patch, "end"), start);
305
+ if (end < 0) continue;
306
+ const hovered = hover?.y === hit.y && hover.format === hit.format;
307
+ const styled = paint(hovered ? "text" : "dim", hit.text);
308
+ lines[y] = `${lines[y]!.slice(0, start)}${styled}${lines[y]!.slice(end)}`;
309
+ }
310
+ }
311
+ }
312
+
313
+ /** Rebuild hit regions after every new render; identical cached lines reuse them. */
314
+ function bindActions(
315
+ patch: Patch,
316
+ component: MarkdownWithActions,
317
+ lines: string[],
318
+ owner: TableCopyOwner,
319
+ ): void {
320
+ if (component[ACTIONS_KEY]?.lines === lines && component[ACTIONS_KEY]?.owner === owner) return;
321
+ const hits: ActionHit[] = [];
322
+ const tokens = parsedTokens(component);
323
+ const tables = tokens ? collectTables(tokens) : [];
324
+ let tableIndex = -1;
325
+ for (let y = 0; y < lines.length; y++) {
326
+ const line = lines[y]!;
327
+ if (line.includes(marker(patch, "table"))) tableIndex++;
328
+ const table = tables[tableIndex];
329
+ if (!table) continue;
330
+ for (const format of FORMATS) {
331
+ const actionMarker = marker(patch, `action:${format}`);
332
+ const index = line.indexOf(actionMarker);
333
+ if (index < 0) continue;
334
+ const contentStart = index + actionMarker.length;
335
+ const contentEnd = line.indexOf(marker(patch, "end"), contentStart);
336
+ if (contentEnd < 0) continue;
337
+ const text = stripTerminalSequences(line.slice(contentStart, contentEnd));
338
+ const start = visibleWidth(line.slice(0, contentStart));
339
+ hits.push({
340
+ y,
341
+ start,
342
+ end: start + visibleWidth(text),
343
+ format,
344
+ marker: actionMarker,
345
+ text,
346
+ table,
347
+ });
348
+ }
349
+ }
350
+ // Only internal markers are anchors. Model-written labels never affect the
351
+ // count, while hidden narrow actions still have a marked table in the order.
352
+ if (tableIndex + 1 !== tables.length) {
353
+ hits.length = 0;
354
+ owner.debug(
355
+ "Table actions skipped: Markdown.cachedTokens and internal table markers disagree.",
356
+ );
357
+ }
358
+ const previousHover = component[ACTIONS_KEY]?.hover;
359
+ const hover = hits.some(
360
+ (hit) => hit.y === previousHover?.y && hit.format === previousHover?.format,
361
+ )
362
+ ? previousHover
363
+ : undefined;
364
+ paintActions(patch, lines, hits, hover, owner.paint);
365
+ component[ACTIONS_KEY] = { owner, lines, hits, hover };
366
+ }
367
+
368
+ function currentPatch(target: Prototype): Patch | undefined {
369
+ const held = target[PATCH] as Partial<Patch> | undefined;
370
+ return held?.version === 3 ? (held as Patch) : undefined;
371
+ }
372
+
373
+ function eligibleOwner(patch: Patch, component: MarkdownWithActions): TableCopyOwner | undefined {
374
+ const owner = patch.componentOwners.get(component);
375
+ return patch.active &&
376
+ owner &&
377
+ patch.owners.has(owner) &&
378
+ isFullscreenTui(owner.tui) &&
379
+ !isTranscriptComponent(component)
380
+ ? owner
381
+ : undefined;
382
+ }
383
+
384
+ /** Hover changes only row colors, not block layout or syntax highlighting. */
385
+ function clearLineCache(component: MarkdownWithActions): void {
386
+ const clear = (component as unknown as MarkdownInternals).clearRenderCache;
387
+ if (typeof clear === "function") clear.call(component);
388
+ else component.invalidate();
389
+ }
390
+
391
+ /** Cached messages may have rendered before session_start and missed our marker. */
392
+ function invalidateMountedMarkdown(tui: unknown): void {
393
+ walkComponentTree(tui, (component) => {
394
+ if (component instanceof Markdown) component.invalidate();
395
+ });
396
+ }
397
+
398
+ function trackComponent(patch: Patch, component: MarkdownWithActions): void {
399
+ if (patch.componentRefs.has(component)) return;
400
+ if (patch.components.size >= 100) {
401
+ for (const ref of patch.components) if (!ref.deref()) patch.components.delete(ref);
402
+ }
403
+ const ref = new WeakRef(component);
404
+ patch.componentRefs.set(component, ref);
405
+ patch.components.add(ref);
406
+ }
407
+
408
+ const NO_INSTALLATION: TableCopyInstallation = { noteSource() {}, dispose() {} };
409
+
410
+ /**
411
+ * Install only for a fullscreen owner. Shared wrappers stay inert after the last
412
+ * owner releases them, even if another extension still holds a wrapper above us.
413
+ */
414
+ export function installTableCopy(options: TableCopyOptions): TableCopyInstallation {
415
+ if (!isFullscreenTui(options.tui)) return NO_INSTALLATION;
416
+ const debug = diagnostics(options);
417
+ const target = Markdown.prototype as unknown as Prototype;
418
+ const selectionTarget = TuiAltScreen.prototype as unknown as Prototype;
419
+ let patch = currentPatch(target);
420
+ if (!patch?.active) {
421
+ const required = [
422
+ [target, "Markdown", "render"],
423
+ [target, "Markdown", "renderTable"],
424
+ [target, "Markdown", "clearRenderCache"],
425
+ [selectionTarget, "TuiAltScreen", "getActiveSelectionText"],
426
+ [selectionTarget, "TuiAltScreen", "getSelectionColumns"],
427
+ [selectionTarget, "TuiAltScreen", "getSelectionBounds"],
428
+ [selectionTarget, "TuiAltScreen", "getSelectionSourceLine"],
429
+ ] as const;
430
+ const missing = required.filter(
431
+ ([prototype, _name, key]) => typeof prototype[key] !== "function",
432
+ );
433
+ if (missing.length > 0) {
434
+ debug(
435
+ `Table copy not installed: incompatible private API (${missing.map(([_prototype, name, key]) => `${name}.${key}`).join(", ")}).`,
436
+ );
437
+ return NO_INSTALLATION;
438
+ }
439
+ const originalRender = target.render as Render;
440
+ const originalRenderTable = target.renderTable as RenderTable;
441
+ const created: Patch = {
442
+ version: 3,
443
+ active: true,
444
+ markerPrefix: `\x1b_pi:ccstyle-table-copy:${randomUUID()}:`,
445
+ selectionTarget,
446
+ originalSelectionText: selectionTarget.getActiveSelectionText as SelectionText,
447
+ originalSelectionColumns: selectionTarget.getSelectionColumns as SelectionColumns,
448
+ wrappedSelectionColumns(line, row, selection, minColumn, maxColumn) {
449
+ const columns = created.originalSelectionColumns.call(
450
+ this,
451
+ line,
452
+ row,
453
+ selection,
454
+ minColumn,
455
+ maxColumn,
456
+ );
457
+ return created.active && isActionRow(created, line)
458
+ ? { start: columns.start, end: columns.start }
459
+ : columns;
460
+ },
461
+ wrappedSelectionText() {
462
+ const text = created.originalSelectionText.call(this);
463
+ if (!created.active || text === undefined) return text;
464
+ const selection = this.getSelectionBounds();
465
+ if (!selection) return text;
466
+ const lines = text.split("\n");
467
+ if (lines.length !== selection.end.row - selection.start.row + 1) return text;
468
+ // Keep Pi's grapheme slicing, scroll coordinates and ordinary blank
469
+ // lines. Only remove rows inserted by this active patch, never labels.
470
+ const selectable = lines.filter(
471
+ (_line, offset) =>
472
+ !isActionRow(
473
+ created,
474
+ this.getSelectionSourceLine({
475
+ ...selection.start,
476
+ row: selection.start.row + offset,
477
+ }),
478
+ ),
479
+ );
480
+ const selected = selectable.join("\n");
481
+ return selected.length > 0 ? selected : undefined;
482
+ },
483
+ owners: new Set(),
484
+ components: new Set(),
485
+ componentRefs: new WeakMap(),
486
+ componentOwners: new WeakMap(),
487
+ originalRender,
488
+ originalRenderTable,
489
+ originalHandleMouse: target.handleMouse as HandleMouse | undefined,
490
+ wrappedRenderTable(token, availableWidth, nextTokenType, styleContext) {
491
+ const lines = created.originalRenderTable.call(
492
+ this,
493
+ token,
494
+ availableWidth,
495
+ nextTokenType,
496
+ styleContext,
497
+ );
498
+ const owner = eligibleOwner(created, this);
499
+ if (!owner || token.header.length === 0) return lines;
500
+ if (!parsedTokens(this)) {
501
+ owner.debug("Table actions skipped: incompatible private API (Markdown.cachedTokens).");
502
+ return lines;
503
+ }
504
+ if (lines.length > 0) lines[0] = marker(created, "table") + lines[0];
505
+ const trailingBlank = lines.at(-1) === "" ? lines.pop() : undefined;
506
+ lines.push(...actionLines(created, availableWidth));
507
+ if (trailingBlank !== undefined) lines.push(trailingBlank);
508
+ return lines;
509
+ },
510
+ wrappedRender(width) {
511
+ if (!created.active) return created.originalRender.call(this, width);
512
+ const previous = created.rendering;
513
+ const transcript = isTranscriptComponent(this);
514
+ if (transcript) markTranscriptComponent(this);
515
+ created.rendering = { component: this, transcript };
516
+ try {
517
+ // Eligibility affects cached table blocks, unlike hover. Rebuild only
518
+ // when it changes (including runtime regular/fullscreen switches).
519
+ if (Boolean(this[ACTIONS_KEY]) !== Boolean(eligibleOwner(created, this))) {
520
+ delete this[ACTIONS_KEY];
521
+ this.invalidate();
522
+ }
523
+ const lines = created.originalRender.call(this, width);
524
+ const owner = eligibleOwner(created, this);
525
+ if (owner) {
526
+ trackComponent(created, this);
527
+ bindActions(created, this, lines, owner);
528
+ }
529
+ return lines;
530
+ } finally {
531
+ created.rendering = previous;
532
+ }
533
+ },
534
+ wrappedHandleMouse(event) {
535
+ const owner = eligibleOwner(created, this);
536
+ const state = this[ACTIONS_KEY];
537
+ if (!owner || state?.owner !== owner) return created.originalHandleMouse?.call(this, event);
538
+ const hit = state.hits.find(
539
+ (action) => action.y === event.y && event.x >= action.start && event.x < action.end,
540
+ );
541
+ if (event.type === "move") {
542
+ const hover = hit ? { y: hit.y, format: hit.format } : undefined;
543
+ if (state.hover?.y !== hover?.y || state.hover?.format !== hover?.format) {
544
+ state.hover = hover;
545
+ clearLineCache(this);
546
+ return { handled: true, render: true };
547
+ }
548
+ }
549
+ // Fullscreen release synthesizes click only after capturing this press.
550
+ if (event.type === "press" && event.button === "left" && hit) return { handled: true };
551
+ if (event.type === "click" && event.button === "left" && hit) {
552
+ const text = serializeTable(hit.table, hit.format);
553
+ const name = hit.format === "markdown" ? "Markdown" : hit.format.toUpperCase();
554
+ // Capture the clicked component's owner, never the newest session.
555
+ void Promise.resolve()
556
+ .then(() => owner.copy(text))
557
+ .then(
558
+ () => {
559
+ if (created.owners.has(owner)) owner.notify(`Copied table as ${name}`, false);
560
+ },
561
+ (error) => {
562
+ if (created.owners.has(owner))
563
+ owner.notify(
564
+ `Table copy failed: ${error instanceof Error ? error.message : String(error)}`,
565
+ true,
566
+ );
567
+ },
568
+ );
569
+ return { handled: true };
570
+ }
571
+ return created.originalHandleMouse?.call(this, event);
572
+ },
573
+ };
574
+ target.renderTable = created.wrappedRenderTable;
575
+ target.render = created.wrappedRender;
576
+ target.handleMouse = created.wrappedHandleMouse;
577
+ selectionTarget.getActiveSelectionText = created.wrappedSelectionText;
578
+ selectionTarget.getSelectionColumns = created.wrappedSelectionColumns;
579
+ target[PATCH] = created;
580
+ patch = created;
581
+ }
582
+ const owner: TableCopyOwner = {
583
+ ...options,
584
+ copy: options.copy ?? copyToClipboard,
585
+ notify: options.notify ?? (() => {}),
586
+ debug,
587
+ };
588
+ patch.owners.add(owner);
589
+ invalidateMountedMarkdown(owner.tui);
590
+ const held = patch;
591
+ return {
592
+ noteSource(context) {
593
+ const frame = held.rendering;
594
+ if (!held.active || !held.owners.has(owner) || !frame) return;
595
+ const component = frame.component;
596
+ const next = context.messageType === "assistant" && !frame.transcript ? owner : undefined;
597
+ const previous = held.componentOwners.get(component);
598
+ if (previous === next) return;
599
+ const wasEligible = Boolean(eligibleOwner(held, component));
600
+ if (next) {
601
+ held.componentOwners.set(component, next);
602
+ trackComponent(held, component);
603
+ } else held.componentOwners.delete(component);
604
+ if (wasEligible !== Boolean(eligibleOwner(held, component))) {
605
+ delete component[ACTIONS_KEY];
606
+ component.invalidate();
607
+ }
608
+ },
609
+ dispose() {
610
+ if (!held.owners.delete(owner)) return;
611
+ if (held.owners.size === 0) held.active = false;
612
+ for (const ref of held.components) {
613
+ const component = ref.deref();
614
+ if (!component) {
615
+ held.components.delete(ref);
616
+ continue;
617
+ }
618
+ if (held.owners.size > 0 && held.componentOwners.get(component) !== owner) continue;
619
+ held.componentOwners.delete(component);
620
+ held.componentRefs.delete(component);
621
+ held.components.delete(ref);
622
+ delete component[ACTIONS_KEY];
623
+ component.invalidate();
624
+ }
625
+ if (held.active) return;
626
+ if (target.render === held.wrappedRender) target.render = held.originalRender;
627
+ if (target.renderTable === held.wrappedRenderTable)
628
+ target.renderTable = held.originalRenderTable;
629
+ if (target.handleMouse === held.wrappedHandleMouse) {
630
+ if (held.originalHandleMouse) target.handleMouse = held.originalHandleMouse;
631
+ else delete target.handleMouse;
632
+ }
633
+ if (held.selectionTarget.getActiveSelectionText === held.wrappedSelectionText)
634
+ held.selectionTarget.getActiveSelectionText = held.originalSelectionText;
635
+ if (held.selectionTarget.getSelectionColumns === held.wrappedSelectionColumns)
636
+ held.selectionTarget.getSelectionColumns = held.originalSelectionColumns;
637
+ if (currentPatch(target) === held) delete target[PATCH];
638
+ held.componentOwners = new WeakMap();
639
+ },
640
+ };
641
+ }
642
+
643
+ interface FlashTui {
644
+ flash(message: string): void;
645
+ }
646
+
647
+ /** Capture Pi's native flash through an empty below-editor widget. */
648
+ export function createTableCopyNotifier(
649
+ ctx: ExtensionContext,
650
+ onTuiReady?: (tui: TUI, notify: Notify) => void,
651
+ ): {
652
+ notify: Notify;
653
+ dispose: () => void;
654
+ } {
655
+ let flashTui: FlashTui | undefined;
656
+ let disposed = false;
657
+ const key = "ccstyle-table-copy-flash";
658
+ const notify: Notify = (message, isError) => {
659
+ if (disposed) return;
660
+ try {
661
+ if (!isError && flashTui) {
662
+ flashTui.flash(message);
663
+ return;
664
+ }
665
+ ctx.ui?.notify?.(message, isError ? "error" : "info");
666
+ } catch {
667
+ // Copying must not fail merely because the host has no notification UI.
668
+ }
669
+ };
670
+ try {
671
+ ctx.ui?.setWidget?.(
672
+ key,
673
+ (tui) => {
674
+ const candidate = tui as unknown as FlashTui;
675
+ flashTui = typeof candidate.flash === "function" ? candidate : undefined;
676
+ const sync = () => {
677
+ if (!disposed) onTuiReady?.(tui, notify);
678
+ };
679
+ sync();
680
+ return {
681
+ render: () => {
682
+ sync();
683
+ return [];
684
+ },
685
+ invalidate: sync,
686
+ dispose: () => {
687
+ if (flashTui === candidate) flashTui = undefined;
688
+ },
689
+ };
690
+ },
691
+ { placement: "belowEditor" },
692
+ );
693
+ } catch {
694
+ // Without a captured TUI, provenance/mode checks fail closed.
695
+ }
696
+ return {
697
+ notify,
698
+ dispose: () => {
699
+ if (disposed) return;
700
+ disposed = true;
701
+ flashTui = undefined;
702
+ try {
703
+ ctx.ui?.setWidget?.(key, undefined);
704
+ } catch {
705
+ // The host may already have disposed its UI during shutdown.
706
+ }
707
+ },
708
+ };
709
+ }
710
+
711
+ /** Lifecycle only; the package entry point composes our marker with enhancement. */
712
+ export default function tableCopyExtension(
713
+ pi: ExtensionAPI,
714
+ ): Pick<TableCopyInstallation, "noteSource"> {
715
+ let installation: TableCopyInstallation | undefined;
716
+ let installedTui: TUI | undefined;
717
+ let disposeNotifier: (() => void) | undefined;
718
+ let active = false;
719
+ const cleanup = () => {
720
+ active = false;
721
+ installation?.dispose();
722
+ installation = undefined;
723
+ installedTui = undefined;
724
+ disposeNotifier?.();
725
+ disposeNotifier = undefined;
726
+ };
727
+ pi.on("session_start", (_event, ctx: ExtensionContext) => {
728
+ cleanup();
729
+ if (ctx.mode !== "tui" || !ctx.hasUI) return;
730
+ active = true;
731
+ const notifier = createTableCopyNotifier(ctx, (tui, notify) => {
732
+ if (!active) return;
733
+ const fullscreen = isFullscreenTui(tui);
734
+ if (fullscreen && installation && installedTui === tui) return;
735
+ if (!fullscreen && !installation) return;
736
+ installation?.dispose();
737
+ installation = undefined;
738
+ installedTui = undefined;
739
+ if (fullscreen) {
740
+ installation = installTableCopy({
741
+ tui,
742
+ notify,
743
+ paint: (color, text) => ctx.ui.theme.fg(color, text),
744
+ });
745
+ installedTui = tui;
746
+ }
747
+ tui.requestRender();
748
+ });
749
+ disposeNotifier = notifier.dispose;
750
+ });
751
+ pi.on("session_shutdown", cleanup);
752
+ return { noteSource: (context) => installation?.noteSource(context) };
753
+ }