@each1024/pi-mini-mode 2.0.9 → 2.0.10

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.
@@ -0,0 +1,129 @@
1
+ import { diagramMarkdown, renderMinimalMarkdown } from "./minimal-markdown.ts";
2
+ import { plain } from "./agent-state.ts";
3
+ import { agentSummary, liveAgentRows, runningGlyph, type AgentDeadlines } from "./agent-render.ts";
4
+ import { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-coding-agent";
5
+ import { truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui";
6
+
7
+ type Theme = ExtensionContext["ui"]["theme"];
8
+
9
+ const isAgentWidget = (source: string) => /^(?:[●○◉✓✗×\u2800-\u28ff]\s*)?(?:async subagent|Async agents|subagents\b|[│├└─\s]*async workflow)/i.test(source);
10
+ /** Presentation adapter for pi-subagents' independently updated widget.
11
+ * Unknown widget formats pass through unchanged; no task state is inferred.
12
+ */
13
+ export function restyleAgentWidget(lines: string[], theme: Theme, width: number, expanded: boolean): string[] {
14
+ const content = lines.map(plain).filter(Boolean);
15
+ if (!content.length || !isAgentWidget(content[0])) return lines;
16
+ const details = content.slice(1).map(line => line
17
+ .replace(/^[│├└─\s]+/, "")
18
+ .replace(/(?:[·•]\s*)?Press\s+ctrl\+.*$/i, "")
19
+ .replace(/(?:[·•]\s*)?Ctrl\+Alt\+F\s+Fleet.*$/i, "").trim())
20
+ .filter(line => line && !/^async workflow\b|^[…+] .*lines hidden\b/i.test(line));
21
+ const isHeading = (line: string) => /^(?:[└├]─\s*)?[●○◉✓✗×◦■\u2800-\u28ff]\s/.test(line)
22
+ && !/^[│⎿]/.test(line);
23
+ const blocks: string[][] = [];
24
+ for (const line of details) {
25
+ if (!blocks.length || isHeading(line)) blocks.push([line]);
26
+ else blocks[blocks.length - 1].push(line);
27
+ }
28
+ const isDone = (block: string[]) => /\b(complete|completed|done|success|succeeded)\b/i.test(block[0]) || /^✓/.test(block[0]);
29
+ const isFailed = (block: string[]) => /\b(failed|error|rejected|stopped|cancelled|canceled|aborted)\b/i.test(block[0]) || /^[✗×]/.test(block[0]);
30
+ const done = blocks.filter(block => isDone(block) && !isFailed(block)).length;
31
+ const errors = blocks.filter(isFailed).length;
32
+ const visible = blocks.filter(block => expanded || isFailed(block) || !isDone(block));
33
+ const rows = [agentSummary(theme, width, blocks.length - done - errors, done, errors, expanded)];
34
+ if (!blocks.length) rows.push(truncateToWidth(theme.fg("text", content[0]), width));
35
+ const markdown = (text: string, available: number) => renderMinimalMarkdown(text, Math.max(1, available), getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
36
+ { color: value => theme.fg("text", value) }, diagramMarkdown);
37
+ // ponytail: native widget exposes bounded live previews, not the full child transcript.
38
+ visible.forEach((block, index) => {
39
+ const heading = block[0].replace(/^(?:[└├]─\s*)?[●○◉✓✗×◦■\u2800-\u28ff]\s*/, "");
40
+ const badge = heading.match(/\(([^()]+?)(?:\s*·\s*thinking\s+|[ :]+)(off|minimal|low|medium|high|xhigh|max)\)/)
41
+ ?? heading.match(/\(([^()]+)\)(?=\s*(?:·|$))/);
42
+ const title = heading.split(" · ")[0].replace(/\s*\([^()]*\)\s*$/, "");
43
+ const identity = badge ? theme.fg("accent", theme.bold(title)) + theme.fg("muted", " · ") + theme.fg("accent", theme.bold(badge[1])) + (badge[2] ? theme.fg("muted", ` ${badge[2]}`) : "")
44
+ : theme.fg("accent", theme.bold(heading.split(" · ")[0]));
45
+ const activity = block.slice(1).filter(line => !/^(?:task|output)\s*:/i.test(line));
46
+ const latest = activity.at(-1)?.replace(/^[⎿│]\s*/, "") || block.slice(1).find(line => /^task\s*:/i.test(line)) || heading;
47
+ const glyph = /\b(failed|error|rejected)\b/i.test(heading) || /^[✗×]/.test(block[0]) ? "×"
48
+ : /\b(running|active|starting|queued|pending)\b/i.test(heading) || /^[\u2800-\u28ff]/.test(block[0]) ? runningGlyph() : "●";
49
+ const prefix = theme.fg("accent", index === visible.length - 1 ? "└─ " : "├─ ")
50
+ + theme.fg(glyph === "×" ? "error" : "accent", glyph + " ") + identity + theme.fg("text", " : ");
51
+ const summary = /\b(failed|error)\b/i.test(heading + " " + latest)
52
+ ? theme.fg("error", latest)
53
+ : markdown(latest, Math.max(1, visibleWidth(latest) + 1)).join(" ");
54
+ rows.push(truncateToWidth(prefix + summary, width));
55
+ });
56
+ return rows;
57
+ }
58
+
59
+ // Only hide the passive native agent summary, preserving the interactive fleet and external jobs/panes.
60
+ const isAgentFleetSummary = (lines: string[]) => {
61
+ const content = lines.map(plain).filter(Boolean);
62
+ return content.length === 1 && /^\d+ active agents?\b/.test(content[0])
63
+ && !/\b(?:jobs?|panes?)\b/.test(content[0]);
64
+ };
65
+
66
+ /** Pi 0.85 widget containers: preserve unrelated widgets and their lifecycle. */
67
+ export function attachAgentWidgets(tui: unknown, theme: Theme, expanded: () => boolean, statuses?: () => Record<string, unknown>[], inline = false): () => void {
68
+ const host = tui as { children?: Array<Component & { children?: Component[] }> };
69
+ if (host.children?.length !== 7) return () => {};
70
+ const restores: Array<() => void> = [];
71
+ const deadlines: AgentDeadlines = new Map();
72
+ for (const index of [3, 5]) {
73
+ const container = host.children[index];
74
+ if (!Array.isArray(container?.children)) continue;
75
+ const descriptor = Object.getOwnPropertyDescriptor(container, "render");
76
+ const mouseDescriptor = Object.getOwnPropertyDescriptor(container, "handleMouse");
77
+ const render = (width: number) => {
78
+ const live = !inline && statuses ? liveAgentRows(statuses(), theme, width, expanded(), deadlines) : [];
79
+ let inserted = false;
80
+ const rows = container.children!.flatMap(child => {
81
+ const original = child.render(width);
82
+ if (inline && (isAgentWidget(original.map(plain).find(Boolean) ?? "") || isAgentFleetSummary(original))) return [];
83
+ if (statuses && live.length && isAgentFleetSummary(original)) return [];
84
+ const source = original.map(plain).find(Boolean) ?? "";
85
+ const agentWidget = isAgentWidget(source);
86
+ if (statuses && agentWidget) {
87
+ if (inserted || index !== 3) return [];
88
+ inserted = true;
89
+ return live;
90
+ }
91
+ return restyleAgentWidget(original, theme, width, expanded());
92
+ });
93
+ if (index === 3 && !inserted) rows.push(...live);
94
+ return rows;
95
+ };
96
+ const mouse: NonNullable<Component["handleMouse"]> = (event) => {
97
+ let y = 0;
98
+ let inserted = false;
99
+ const live = !inline && statuses ? liveAgentRows(statuses(), theme, event.width, expanded(), deadlines) : [];
100
+
101
+ for (const child of container.children!) {
102
+ const original = child.render(event.width);
103
+ if (inline && (isAgentWidget(original.map(plain).find(Boolean) ?? "") || isAgentFleetSummary(original))) continue;
104
+ if (statuses && live.length && isAgentFleetSummary(original)) continue;
105
+ const agentWidget = isAgentWidget(original.map(plain).find(Boolean) ?? "");
106
+ const shown = statuses && agentWidget ? (index === 3 && !inserted ? live : [])
107
+ : restyleAgentWidget(original, theme, event.width, expanded());
108
+ if (agentWidget) inserted = true;
109
+ if (event.y >= y && event.y < y + shown.length) {
110
+ // Do not route clicks into native controls hidden by the compact view.
111
+ return shown === original ? child.handleMouse?.({ ...event, y: event.y - y, height: shown.length }) : undefined;
112
+ }
113
+ y += shown.length;
114
+ }
115
+ };
116
+ container.render = render;
117
+ container.handleMouse = mouse;
118
+ restores.push(() => {
119
+ if (container.handleMouse === mouse) {
120
+ if (mouseDescriptor) Object.defineProperty(container, "handleMouse", mouseDescriptor);
121
+ else delete container.handleMouse;
122
+ }
123
+ if (container.render !== render) return;
124
+ if (descriptor) Object.defineProperty(container, "render", descriptor);
125
+ else delete (container as Partial<Component>).render;
126
+ });
127
+ }
128
+ return () => { deadlines.clear(); restores.forEach(restore => restore()); };
129
+ }
@@ -0,0 +1,206 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
+ import { basename } from "node:path";
4
+ import { stripVTControlCharacters } from "node:util";
5
+ import { COPY, type MiniLensSettings } from "./settings.ts";
6
+ import { cacheHit, finiteNumber, formatSpeed, formatTokens, formatUsd, speedColor, type CacheWaste, type SessionUsage } from "./usage.ts";
7
+
8
+ const PLANNOTATOR_STATUS_KEY = "plannotator";
9
+ const PLANNOTATOR_PLANNING_LABEL = "⏸ plan";
10
+ const PLAN_CAP_LEFT = "\uE0B6";
11
+ const PLAN_CAP_RIGHT = "\uE0B4";
12
+ const PLAN_BG = "250;204;21";
13
+ const PLAN_FG = "19;18;23";
14
+
15
+ function plannotatorStatusText(text: string | undefined): string {
16
+ return stripVTControlCharacters(text ?? "").replace(/\s+/g, " ").trim();
17
+ }
18
+
19
+ /** Exact plannotator planning label from @plannotator/pi-extension (`⏸ plan`). */
20
+ export function isPlannotatorPlanningStatus(text: string | undefined): boolean {
21
+ return plannotatorStatusText(text) === PLANNOTATOR_PLANNING_LABEL;
22
+ }
23
+
24
+ /** Scheme B PLAN capsule. visibleWidth===1 only protects columns; it is not a font check. */
25
+ export function planCapsule(): string {
26
+ const paint = (text: string) => `\x1b[48;2;${PLAN_BG}m\x1b[38;2;${PLAN_FG}m${text}\x1b[39m\x1b[49m`;
27
+ if (visibleWidth(PLAN_CAP_LEFT) === 1 && visibleWidth(PLAN_CAP_RIGHT) === 1) {
28
+ const cap = (ch: string) => `\x1b[38;2;${PLAN_BG}m${ch}\x1b[39m`;
29
+ return `${cap(PLAN_CAP_LEFT)}${paint("PLAN")}${cap(PLAN_CAP_RIGHT)}`;
30
+ }
31
+ return paint(" PLAN ");
32
+ }
33
+
34
+ function plannotatorPlanTag(statuses: ReadonlyMap<string, string> | undefined): string {
35
+ const text = statuses?.get(PLANNOTATOR_STATUS_KEY);
36
+ return isPlannotatorPlanningStatus(text) ? planCapsule() : "";
37
+ }
38
+
39
+ function progressBar(percent: number, dots: boolean, width: number): string {
40
+ const filled = Math.round(width * Math.max(0, Math.min(100, percent)) / 100);
41
+ return (dots ? "⣿" : "█").repeat(filled) + (dots ? "⣀" : "░").repeat(width - filled);
42
+ }
43
+
44
+ function renderRight(
45
+ theme: ExtensionContext["ui"]["theme"],
46
+ settings: MiniLensSettings,
47
+ percentText: string,
48
+ speed: number | undefined,
49
+ highlighted?: keyof MiniLensSettings,
50
+ ): string {
51
+ const fields: string[] = [];
52
+ if (settings["pi-mini-mode-context-percent-show"] && percentText) fields.push(highlighted === "pi-mini-mode-context-percent-show" ? theme.bg("selectedBg", theme.fg("accent", theme.bold(percentText))) : theme.fg("accent", percentText));
53
+ if (settings["pi-mini-mode-speed-show"] && speed !== undefined) {
54
+ const text = formatSpeed(speed, settings["pi-mini-mode-speed-unit-show"]);
55
+ fields.push(highlighted === "pi-mini-mode-speed-show" || highlighted === "pi-mini-mode-speed-unit-show"
56
+ ? theme.bg("selectedBg", theme.fg("accent", theme.bold(text)))
57
+ : theme.fg(speedColor(speed), text));
58
+ }
59
+ return fields.join(" ");
60
+ }
61
+
62
+ const SETTINGS_PREVIEW_CONTEXT = {
63
+ cwd: "/work/pi-mini-mode",
64
+ model: { id: "deepseek-v4-flash" },
65
+ thinkingLevel: "high",
66
+ getContextUsage: () => ({ tokens: 500, contextWindow: 1_000_000, percent: 1 }),
67
+ } as unknown as ExtensionContext;
68
+
69
+ const SETTINGS_PREVIEW_USAGE: SessionUsage = {
70
+ totalTokens: 45_000,
71
+ input: 15_000,
72
+ output: 5_000,
73
+ cacheRead: 10_000,
74
+ cacheWrite: 15_000,
75
+ cost: 0.012,
76
+ };
77
+
78
+ export function settingsPreviewLine(
79
+ theme: ExtensionContext["ui"]["theme"],
80
+ settings: MiniLensSettings,
81
+ width = 140,
82
+ highlighted?: keyof MiniLensSettings,
83
+ ): string {
84
+ return statusLine(SETTINGS_PREVIEW_CONTEXT, theme, width, SETTINGS_PREVIEW_USAGE, settings, 120, highlighted, 3, undefined, "main");
85
+ }
86
+
87
+ export function statusLine(
88
+ ctx: ExtensionContext,
89
+ theme: ExtensionContext["ui"]["theme"],
90
+ width: number,
91
+ usageTotals: SessionUsage,
92
+ settings: MiniLensSettings,
93
+ speed: number | undefined,
94
+ highlighted?: keyof MiniLensSettings,
95
+ mcpCount?: number,
96
+ statuses?: ReadonlyMap<string, string>,
97
+ gitBranch?: string | null,
98
+ waste?: CacheWaste,
99
+ ): string {
100
+ if (highlighted === "pi-mini-mode-context-dots-show") highlighted = "pi-mini-mode-context-show";
101
+ const field = (id: keyof MiniLensSettings, color: Parameters<typeof theme.fg>[0], text: string) =>
102
+ id === highlighted ? theme.bg("selectedBg", theme.fg("accent", theme.bold(text))) : theme.fg(color, text);
103
+ if (width <= 0) return "";
104
+ const model = ctx.model?.id ?? "";
105
+ const thinking = ctx.thinkingLevel ?? "";
106
+ const hit = cacheHit(usageTotals);
107
+ const hitText = hit === undefined ? "" : `${COPY.cacheHitLabel} ${hit.toFixed(1)}%`;
108
+ const cachedTokens = usageTotals.cacheRead + usageTotals.cacheWrite;
109
+ const missText = settings["pi-mini-mode-cache-miss-show"] && waste && waste.missCount > 0 ? `Miss ${formatTokens(waste.missedTokens)}` : "";
110
+ const price = usageTotals.cost > 0 ? formatUsd(usageTotals.cost) : "";
111
+ const contextUsage = ctx.getContextUsage();
112
+ const tokens = finiteNumber(contextUsage?.tokens);
113
+ const contextWindow = finiteNumber(contextUsage?.contextWindow);
114
+ const rawPercent = finiteNumber(contextUsage?.percent);
115
+ const percent = rawPercent === undefined ? undefined : Math.max(0, Math.min(100, rawPercent));
116
+ const percentText = percent === undefined ? "" : `${Math.round(percent)}%`;
117
+ const tokenText = tokens === undefined || contextWindow === undefined ? "" : `${formatTokens(Math.max(0, tokens))}/${formatTokens(Math.max(0, contextWindow))}`;
118
+ const showContext = settings["pi-mini-mode-context-show"] && Boolean(tokenText);
119
+ const mcpText = settings["pi-mini-mode-mcp-show"] && mcpCount !== undefined ? `◇ MCP ${mcpCount}` : "";
120
+ const planTag = plannotatorPlanTag(statuses);
121
+ const branchOnly = settings["pi-mini-mode-branch-show"];
122
+ const branchSetting = branchOnly ? "pi-mini-mode-branch-show" : "pi-mini-mode-project-branch-show";
123
+ const branchText = gitBranch && settings[branchSetting]
124
+ ? stripVTControlCharacters(branchOnly ? gitBranch : `${basename(ctx.cwd)}(${gitBranch})`).replace(/[\x00-\x1f\x7f-\x9f]/g, "") : "";
125
+
126
+ if (settings.footerOrder) {
127
+ const values: Record<string, string> = {
128
+ "project-branch": !branchOnly ? branchText : "", branch: branchOnly ? branchText : "",
129
+ model, thinking,
130
+ "session-tokens": usageTotals.totalTokens > 0 ? `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}` : "",
131
+ "cache-tokens": cachedTokens > 0 ? `${COPY.cachedLabel} ${formatTokens(cachedTokens)}` : "",
132
+ "cache-miss": missText,
133
+ ch: hitText, cost: price, mcp: mcpText,
134
+ context: tokenText,
135
+ "context-percent": percentText, speed: speed === undefined ? "" : formatSpeed(speed, settings["pi-mini-mode-speed-unit-show"]),
136
+ };
137
+ const visible = settings.footerOrder.filter(id => settings[`pi-mini-mode-${id}-show` as keyof MiniLensSettings] && values[id]);
138
+ const usedWidth = visibleWidth([planTag, ...visible.map(id => values[id])].filter(Boolean).join(" "));
139
+ const barWidth = Math.max(0, width - usedWidth - 1);
140
+ if (visible.includes("context") && percent !== undefined && barWidth > 0) {
141
+ values.context += ` ${progressBar(percent, settings["pi-mini-mode-context-dots-show"], barWidth)}`;
142
+ }
143
+ return truncateToWidth([planTag, ...settings.footerOrder.map(id => {
144
+ const key = `pi-mini-mode-${id}-show` as keyof MiniLensSettings;
145
+ const color = id === "speed" ? speedColor(speed) : id === "cache-miss" ? "warning" : id === "model" || id === "context-percent" ? "accent" : "muted";
146
+ return settings[key] && values[id] ? field(key, color, values[id]) : "";
147
+ })].filter(Boolean).join(" "), width, "…");
148
+ }
149
+ const right = renderRight(theme, settings, percentText, speed, highlighted);
150
+ const rightWidth = visibleWidth(right);
151
+ if (right && width <= rightWidth) {
152
+ const compactRight = settings["pi-mini-mode-speed-show"] && speed !== undefined
153
+ ? theme.fg(speedColor(speed), formatSpeed(speed, settings["pi-mini-mode-speed-unit-show"]))
154
+ : right;
155
+ return truncateToWidth(compactRight, width, "");
156
+ }
157
+
158
+ const leftParts = [
159
+ planTag,
160
+ !branchOnly && branchText && field(branchSetting, "muted", branchText),
161
+ settings["pi-mini-mode-model-show"] && model && field("pi-mini-mode-model-show", "accent", model),
162
+ settings["pi-mini-mode-thinking-show"] && thinking && field("pi-mini-mode-thinking-show", "muted", thinking),
163
+ branchOnly && branchText && field(branchSetting, "muted", branchText),
164
+ settings["pi-mini-mode-session-tokens-show"] && usageTotals.totalTokens > 0 && field("pi-mini-mode-session-tokens-show", "text", `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`),
165
+ settings["pi-mini-mode-cache-tokens-show"] && cachedTokens > 0 && field("pi-mini-mode-cache-tokens-show", "text", `${COPY.cachedLabel} ${formatTokens(cachedTokens)}`),
166
+ missText && field("pi-mini-mode-cache-miss-show", "warning", missText),
167
+ settings["pi-mini-mode-ch-show"] && hitText && field("pi-mini-mode-ch-show", "text", hitText),
168
+ settings["pi-mini-mode-cost-show"] && price && field("pi-mini-mode-cost-show", "muted", price),
169
+ mcpText && field("pi-mini-mode-mcp-show", "muted", mcpText),
170
+ ].filter((part): part is string => Boolean(part));
171
+ const unstyledLeft = [
172
+ planTag && stripVTControlCharacters(planTag),
173
+ !branchOnly && branchText,
174
+ settings["pi-mini-mode-model-show"] && model,
175
+ settings["pi-mini-mode-thinking-show"] && thinking,
176
+ branchOnly && branchText,
177
+ settings["pi-mini-mode-session-tokens-show"] && usageTotals.totalTokens > 0 && `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`,
178
+ settings["pi-mini-mode-cache-tokens-show"] && cachedTokens > 0 && `${COPY.cachedLabel} ${formatTokens(cachedTokens)}`,
179
+ missText,
180
+ settings["pi-mini-mode-ch-show"] && hitText,
181
+ settings["pi-mini-mode-cost-show"] && price,
182
+ mcpText,
183
+ ].filter(Boolean).join(" ");
184
+ const leftBudget = Math.min(visibleWidth(unstyledLeft), Math.max(1, width - rightWidth - (showContext ? 20 : 1)), Math.max(0, width - rightWidth - 1));
185
+ const left = leftParts.length > 0 ? truncateToWidth(leftParts.join(" "), leftBudget, "…") : "";
186
+ const leftWidth = visibleWidth(left);
187
+ const middleBudget = showContext ? Math.max(0, width - leftWidth - rightWidth - (left && right ? 4 : left || right ? 1 : 0)) : 0;
188
+
189
+ let middle = "";
190
+ if (middleBudget > 0) {
191
+ const visibleToken = truncateToWidth(tokenText, middleBudget, "…");
192
+ const visibleTokenWidth = visibleWidth(visibleToken);
193
+ const barWidth = middleBudget - visibleTokenWidth - 1;
194
+ const filledCell = settings["pi-mini-mode-context-dots-show"] ? "⣿" : "█";
195
+ const emptyCell = settings["pi-mini-mode-context-dots-show"] ? "⣀" : "░";
196
+ const bar = barWidth >= 2 && percent !== undefined
197
+ ? `${field("pi-mini-mode-context-show", "accent", filledCell.repeat(Math.round(barWidth * percent / 100)))}${field("pi-mini-mode-context-show", "borderMuted", emptyCell.repeat(barWidth - Math.round(barWidth * percent / 100)))}`
198
+ : "";
199
+ middle = `${field("pi-mini-mode-context-show", "muted", visibleToken)}${bar ? ` ${bar}` : ""}`;
200
+ }
201
+
202
+ const content = [left, middle].filter(Boolean).join(" ");
203
+ if (!right) return truncateToWidth(content, width, "");
204
+ const gap = " ".repeat(Math.max(1, width - visibleWidth(content) - rightWidth));
205
+ return truncateToWidth(`${content}${content ? gap : ""}${right}`, width, "");
206
+ }
@@ -0,0 +1,79 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { CURSOR_MARKER, getOsc8LinkAtColumn, sliceByColumn, stripTerminalSequences, visibleWidth, type EditorComponent } from "@earendil-works/pi-tui";
3
+ import { inputCapabilities, linkRenderedPath, localPath, webPaths } from "./file-links.ts";
4
+ import { imagePathsInLine, type ImagePathMatch } from "./input-image-paths.ts";
5
+
6
+ // ponytail: Pi 0.85 editor layout mapping; unknown editors use visible-line matching.
7
+ export function editorImagePaths(editor: EditorComponent, text: string): ImagePathMatch[] {
8
+ const attachments = (editor as EditorComponent & { imageAttachments?: Map<string, string> }).imageAttachments;
9
+ const paths = imagePathsInLine(text);
10
+ for (const match of text.matchAll(/\[img\d+\]/g)) {
11
+ const path = attachments?.get(match[0]);
12
+ if (path) paths.push({ path, start: match.index, end: match.index + match[0].length, startCol: visibleWidth(text.slice(0, match.index)), endCol: visibleWidth(text.slice(0, match.index + match[0].length)) });
13
+ }
14
+ return paths.sort((a, b) => a.start - b.start);
15
+ }
16
+
17
+ export function editorPaths(editor: EditorComponent, row: number, width: number, includeWeb = false, compactImages = false) {
18
+ const core = editor as EditorComponent & { lastWidth?: number; scrollOffset?: number; renderedVisibleLineCount?: number; getPaddingX?(): number; buildVisualLineMap?(width: number): Array<{ logicalLine: number; startCol: number; length: number }> };
19
+ if (!core.buildVisualLineMap || !core.lastWidth) return imagePathsInLine(editor.render(width)[row] ?? "");
20
+ if (row < 1 || row > (core.renderedVisibleLineCount ?? 0)) return [];
21
+ const chunk = core.buildVisualLineMap(core.lastWidth)[(core.scrollOffset ?? 0) + row - 1];
22
+ if (!chunk) return [];
23
+ const source = editor.getText().split("\n")[chunk.logicalLine] ?? "";
24
+ const padding = Math.min(core.getPaddingX?.() ?? 0, Math.max(0, Math.floor((width - 1) / 2)));
25
+ return [...editorImagePaths(editor, source), ...(includeWeb ? webPaths(source) : [])].filter(match => match.end > chunk.startCol && match.start < chunk.startCol + chunk.length).map(match => ({
26
+ ...match,
27
+ startCol: padding + visibleWidth(source.slice(chunk.startCol, Math.max(chunk.startCol, match.start)))
28
+ + (compactImages && /^\[img\d+\]$/.test(source.slice(match.start, match.end)) ? 1 : 0),
29
+ endCol: padding + visibleWidth(source.slice(chunk.startCol, Math.min(chunk.startCol + chunk.length, compactImages && /^\[img\d+\]$/.test(source.slice(match.start, match.end))
30
+ ? match.start + 1 + visibleWidth(` #${source.slice(match.start + 4, match.end - 1)}`) : match.end))),
31
+ }));
32
+ }
33
+
34
+ export function hideImageLabels(line: string, labels: Set<string>, theme: ExtensionContext["ui"]["theme"], original: string): string {
35
+ const markerIndex = original.indexOf(CURSOR_MARKER);
36
+ const cursorCol = markerIndex < 0 ? -1 : visibleWidth(original.slice(0, markerIndex));
37
+ const plain = stripTerminalSequences(line);
38
+ const clean = line.replaceAll(CURSOR_MARKER, "").replaceAll("\x1b[7m", "");
39
+ const reset = "\x1b]8;;\x07\x1b[0m";
40
+ const caret = (cell: string) => reset + CURSOR_MARKER + `\x1b[7m${cell}\x1b[27m`;
41
+ const textSlice = (start: number, length: number) => {
42
+ const part = sliceByColumn(clean, start, length, true);
43
+ if (getOsc8LinkAtColumn(clean, start)) return part;
44
+ return part.replace(/^(?:\x1b\[[0-?]*[ -/]*[@-~]|\x1b[\]_][^\x07\x1b]*(?:\x07|\x1b\\))*/,
45
+ leading => leading.replace(/\x1b\]8;[^\x07\x1b]*(?:\x07|\x1b\\)/g, ""));
46
+ };
47
+ const textSpan = (start: number, end: number) => {
48
+ if (cursorCol < start || cursorCol >= end) return textSlice(start, end - start);
49
+ const cell = stripTerminalSequences(sliceByColumn(clean, cursorCol, 1));
50
+ return textSlice(start, cursorCol - start) + caret(cell)
51
+ + textSlice(cursorCol + visibleWidth(cell), end - cursorCol - visibleWidth(cell));
52
+ };
53
+ const parts: string[] = [];
54
+ let previous = 0;
55
+ for (const match of plain.matchAll(/\[img\d+\]/g)) {
56
+ if (!labels.has(match[0])) continue;
57
+ const start = visibleWidth(plain.slice(0, match.index));
58
+ const end = start + visibleWidth(match[0]);
59
+ const icon = theme.fg("accent", ` #${match[0].slice(4, -1)}`);
60
+ const url = getOsc8LinkAtColumn(line, start);
61
+ const chip = url ? `\x1b]8;;${url}\x07${icon}\x1b]8;;\x07` : icon;
62
+ // [imgN] fits exactly one insertion cell plus the visible chip; no hidden padding.
63
+ // Emit the caret before styling the chip: slicing styled output replays stale ANSI resets.
64
+ parts.push(textSpan(previous, start), reset, cursorCol === start ? caret(" ") : " ", chip);
65
+ previous = end;
66
+ }
67
+ parts.push(textSpan(previous, visibleWidth(plain)), reset);
68
+ return parts.join("");
69
+ }
70
+
71
+ export function linkImagePaths(lines: string[], editor: EditorComponent, cwd: string, width: number): string[] {
72
+ if (!inputCapabilities().hyperlinks) return lines;
73
+ return lines.map((line, row) => {
74
+ for (const match of editorPaths(editor, row, width, true).reverse()) line = linkRenderedPath(line, match.startCol, match.endCol, /^https?:\/\//i.test(match.path) ? match.path : localPath(match.path, cwd));
75
+ // Isolate editor rows from inherited terminal link/color state.
76
+ const reset = "\x1b]8;;\x07\x1b[0m";
77
+ return reset + line + reset;
78
+ });
79
+ }
@@ -0,0 +1,184 @@
1
+ import { CustomEditor, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { matchesKey, type EditorComponent, type TuiMouseEvent, type TUI } from "@earendil-works/pi-tui";
3
+ import type { CursorEditor, EditorFactoryFunction, Enhancements } from "./input-enhancements-types.ts";
4
+ import { editorImagePaths, editorPaths, hideImageLabels, linkImagePaths } from "./input-editor-paths.ts";
5
+ import { imagePathsInLine } from "./input-image-paths.ts";
6
+ import { handleTerminalInput, positionPreview, requestPreview, setPointer } from "./input-hover-preview.ts";
7
+ import { inlinePreviewLines, syncInlineImages } from "./input-inline-images.ts";
8
+ import { SKILL_PREFIX } from "./input-skill-completion.ts";
9
+
10
+ let viewportHook: { restore(): void } | undefined;
11
+
12
+ /** TUI survives /new; detach any previous instance's mouse hook before wrapping again. */
13
+ function unhookViewportInput(): void {
14
+ viewportHook?.restore();
15
+ viewportHook = undefined;
16
+ }
17
+
18
+ function hookViewportInput(tui: TUI, onInput: (data: string) => void): () => void {
19
+ unhookViewportInput();
20
+ const viewport = tui as TUI & { handleViewportInput?(data: string): { consume?: boolean } | undefined };
21
+ const original = viewport.handleViewportInput;
22
+ if (!original) return () => {};
23
+ const observe = (data: string) => {
24
+ onInput(data);
25
+ return original.call(tui, data);
26
+ };
27
+ viewport.handleViewportInput = observe;
28
+ const hook = {
29
+ restore() {
30
+ if (viewport.handleViewportInput === observe) viewport.handleViewportInput = original;
31
+ },
32
+ };
33
+ viewportHook = hook;
34
+ return () => {
35
+ if (viewportHook !== hook) return;
36
+ unhookViewportInput();
37
+ };
38
+ }
39
+
40
+
41
+ export function liveUI(ctx?: ExtensionContext): ExtensionContext["ui"] | undefined {
42
+ if (!ctx) return undefined;
43
+ try {
44
+ return ctx.ui;
45
+ } catch {
46
+ return undefined;
47
+ }
48
+ }
49
+
50
+ /** Compact image attachments without losing their paths on submit, reload, or external editing. */
51
+ function wrapEditor(inner: EditorComponent, cwd: string, isEnabled: () => boolean, isInline: () => boolean, theme: ExtensionContext["ui"]["theme"], inlineState: Enhancements, onCursor: () => void, onHoverEditor: (editor: EditorComponent, event: TuiMouseEvent) => void, onEditorRender: () => void = () => {}): EditorComponent {
52
+ const attachments = new Map<string, string>();
53
+ const sources = new Map<string, string>();
54
+ const expand = (text: string) => text.replace(/\[img\d+\]/g, (label, index) => {
55
+ const path = sources.get(label) ?? attachments.get(label);
56
+ const next = /^\[img\d+\]/.exec(text.slice(index + label.length));
57
+ return path === undefined ? label : path + (next && attachments.has(next[0]) ? " " : "");
58
+ });
59
+ const compact = (text: string) => {
60
+ if (!isEnabled()) return text;
61
+ const replacements = imagePathsInLine(text).map(match => {
62
+ const source = text.slice(match.start, match.end);
63
+ let label = [...attachments].find(([label, path]) => path === match.path && (sources.get(label) ?? path) === source)?.[0];
64
+ if (!label) {
65
+ label = `[img${attachments.size + 1}]`;
66
+ attachments.set(label, match.path);
67
+ sources.set(label, source);
68
+ }
69
+ return { ...match, label };
70
+ });
71
+ for (const match of replacements.reverse()) text = text.slice(0, match.start) + match.label + text.slice(match.end);
72
+ return text;
73
+ };
74
+ // ponytail: Pi 0.87 image paste calls the private inserter, bypassing the public proxy; replace with a public attachment API when available.
75
+ const core = inner as EditorComponent & { expandPasteMarkers?(text: string): string; insertTextAtCursorInternal?(text: string): void; setTextInternal?(text: string, placement?: "start" | "end"): void; segment?(text: string, mode?: string): Array<{ segment: string; index: number; input: string }>; imageAttachments?: Map<string, string>; state?: { lines: string[] } };
76
+ core.imageAttachments = attachments;
77
+ // Rendering reads the stored lines directly, so the submit expansion must not put the temp path back on screen.
78
+ if (core.state) core.state.lines = compact(core.state.lines.join("\n")).split("\n");
79
+ if (core.expandPasteMarkers) { const original = core.expandPasteMarkers.bind(core); core.expandPasteMarkers = text => expand(original(text)); }
80
+ if (core.insertTextAtCursorInternal) { const insert = core.insertTextAtCursorInternal.bind(core); core.insertTextAtCursorInternal = text => insert(compact(text)); }
81
+ // Native history navigation bypasses setText; compact the restored draft before its onChange/render.
82
+ if (core.setTextInternal) { const restore = core.setTextInternal.bind(core); core.setTextInternal = (text, placement) => restore(compact(text), placement); }
83
+ const pasteEditor = inner as EditorComponent & { handlePaste?(text: string): void };
84
+ if (pasteEditor.handlePaste) { const paste = pasteEditor.handlePaste.bind(inner); pasteEditor.handlePaste = text => paste(compact(text)); }
85
+ if (core.segment) {
86
+ const original = core.segment.bind(core);
87
+ core.segment = (text, mode) => {
88
+ const spans = [...text.matchAll(/\[img\d+\]/g)].filter(match => attachments.has(match[0]));
89
+ return [...original(text, mode)].flatMap(segment => {
90
+ const span = spans.find(match => segment.index >= match.index && segment.index < match.index + match[0].length);
91
+ return !span ? [segment] : segment.index === span.index ? [{ segment: span[0], index: span.index, input: text }] : [];
92
+ });
93
+ };
94
+ }
95
+ let onChange: ((text: string) => void) | undefined;
96
+ return new Proxy(inner, {
97
+ get(target, property, receiver) {
98
+ if (property === "getText") return () => expand(target.getText());
99
+ if (property === "setText" || property === "insertTextAtCursor" || property === "insertTextAtCursorInternal") return (text: string) => { const insert = (target as EditorComponent & { insertTextAtCursorInternal?(value: string): void })[property] as ((value: string) => void) | undefined; insert?.call(target, compact(text)); onEditorRender(); };
100
+ if (property === "render") {
101
+ return (width: number) => {
102
+ const lines = target.render(width);
103
+ onEditorRender();
104
+ const linked = isEnabled() ? linkImagePaths(lines, target, cwd, width) : lines;
105
+ if (!isInline()) return linked;
106
+ const cards = inlinePreviewLines(inlineState, theme, width);
107
+ if (!cards.length) return linked;
108
+ // ponytail: Pi's editor has no rich image nodes; keep its cursor/text layout and mask owned tokens only in render. Replace with native attachment nodes when available.
109
+ const labels = new Set(attachments.keys());
110
+ const body = linked.map((line, row) => row > 0 && row <= ((target as EditorComponent & { renderedVisibleLineCount?: number }).renderedVisibleLineCount ?? 0) ? hideImageLabels(line, labels, theme, lines[row]) : line);
111
+ return [...cards, ...body];
112
+ };
113
+ }
114
+ if (property === "handleMouse") {
115
+ return (event: TuiMouseEvent) => {
116
+ const offset = isInline() ? inlinePreviewLines(inlineState, theme, event.width).length : 0;
117
+ const adjusted = offset ? { ...event, y: event.y - offset } : event;
118
+ const result = !offset || event.y >= offset ? target.handleMouse?.(adjusted) : undefined;
119
+ if (event.type === "move") onHoverEditor(target, adjusted);
120
+ else if (event.type === "click") void requestPreview(inlineState, undefined);
121
+ return result;
122
+ };
123
+ }
124
+ if (property === "handleInput") {
125
+ return (data: string) => {
126
+ if (isEnabled() && matchesKey(data, "super+v")) { (target as CustomEditor).onPasteImage?.(); return; }
127
+ target.handleInput(data);
128
+ // Pi explicitly excludes '/' from provider triggerCharacters; request inline completions ourselves.
129
+ const native = target as CursorEditor & { tryTriggerAutocomplete?(): void };
130
+ const cursor = native.getCursor?.();
131
+ if (isEnabled() && cursor && data.length === 1 && /[\w/:-]/.test(data)
132
+ && SKILL_PREFIX.test((target.getText().split("\n")[cursor.line] ?? "").slice(0, cursor.col))) native.tryTriggerAutocomplete?.();
133
+ onCursor();
134
+ };
135
+ }
136
+ return Reflect.get(target, property, receiver);
137
+ },
138
+ set(target, property, value) {
139
+ if (property === "onChange") {
140
+ onChange = value as ((text: string) => void) | undefined;
141
+ return Reflect.set(target, property, (text: string) => {
142
+ onChange?.(expand(text));
143
+ onEditorRender();
144
+ onCursor();
145
+ });
146
+ }
147
+ return Reflect.set(target, property, value);
148
+ },
149
+ }) as EditorComponent;
150
+ }
151
+
152
+ /** Wrap the current editor factory (or the default editor) so enhancements ride on top of it. */
153
+ export function installEditor(ctx: ExtensionContext, state: Enhancements, base?: EditorFactoryFunction): void {
154
+ const create: EditorFactoryFunction = base ?? ((tui, theme, keybindings) => new CustomEditor(tui, theme, keybindings, { embedWorkingStatus: true }));
155
+ const factory: EditorFactoryFunction = (tui, theme, keybindings) => {
156
+ state.tui = tui;
157
+ state.previewTui = tui;
158
+ // ponytail: fullscreen's first input listener consumes mouse events before extension listeners.
159
+ // Observe its entry point until Pi exposes a pre-dispatch mouse subscription.
160
+ state.restoreViewportInput = hookViewportInput(tui, (data) => handleTerminalInput(state, data));
161
+ const inner: CursorEditor = create(tui, theme, keybindings);
162
+ const editor = wrapEditor(inner, state.cwd ?? process.cwd(), () => state.enabled(), () => state.enabled() && state.previewMode() === "inline", state.theme!, state, () => {
163
+ const cursor = inner.getCursor?.();
164
+ const path = cursor ? editorImagePaths(inner, inner.getText().split("\n")[cursor.line] ?? "").find(match => cursor.col >= match.start && cursor.col <= match.end)?.path : undefined;
165
+ if (state.previewMode() === "hover") void requestPreview(state, state.enabled() ? path : undefined);
166
+ }, (target, event) => {
167
+ const match = state.enabled() && event.y >= 1 ? editorPaths(target, event.y, event.width, false, state.previewMode() === "inline").find(path => event.x >= path.startCol && event.x < path.endCol) : undefined;
168
+ const screenStart = match ? event.screenX - event.x + match.startCol : 0;
169
+ const screenEnd = match ? event.screenX - event.x + match.endCol : 0;
170
+ if (match && (match.path !== state.requestedPath || state.previewAnchor?.y !== event.screenY
171
+ || state.previewAnchor.x < screenStart || state.previewAnchor.x >= screenEnd)) {
172
+ state.previewAnchor = { x: event.screenX, y: event.screenY };
173
+ if (match.path === state.requestedPath && state.preview.path) { positionPreview(state); state.previewTui?.requestRender(); }
174
+ }
175
+ setPointer(state, !!match);
176
+ void requestPreview(state, match?.path);
177
+ }, () => syncInlineImages(state));
178
+ state.editor = editor;
179
+ return editor;
180
+ };
181
+ state.baseFactory = base;
182
+ state.editorFactory = factory;
183
+ ctx.ui.setEditorComponent(factory);
184
+ }
@@ -0,0 +1,49 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { EditorComponent, OverlayHandle, OverlayOptions, renderImage, TUI } from "@earendil-works/pi-tui";
3
+ import type { Preview } from "./input-image-paths.ts";
4
+
5
+ export interface PreviewState {
6
+ path?: string;
7
+ note?: string;
8
+ graphic?: NonNullable<ReturnType<typeof renderImage>>;
9
+ }
10
+
11
+ export type EditorFactoryFunction = NonNullable<Parameters<ExtensionContext["ui"]["setEditorComponent"]>[0]>;
12
+ export type CursorEditor = EditorComponent & { getCursor?(): { line: number; col: number } };
13
+
14
+ export interface InputEnhancementsCleanup {
15
+ (): void;
16
+ refresh(): void;
17
+ }
18
+
19
+ export interface Enhancements {
20
+ pi: ExtensionAPI;
21
+ enabled: () => boolean;
22
+ ctx?: ExtensionContext;
23
+ cwd?: string;
24
+ theme?: ExtensionContext["ui"]["theme"];
25
+ generation?: unknown;
26
+ preview: PreviewState;
27
+ previewSource?: Preview;
28
+ previewLayout?: string;
29
+ previewToken: number;
30
+ overlayReady: boolean;
31
+ previewTui?: { requestRender(): void };
32
+ previewHandle?: OverlayHandle;
33
+ tui?: TUI;
34
+ requestedPath?: string;
35
+ pointer?: boolean;
36
+ previewAnchor?: { x: number; y: number };
37
+ hoverLink?: { row: number; start: number; end: number; path: string };
38
+ previewOptions?: OverlayOptions;
39
+ previewMode: () => "hover" | "inline";
40
+ inlineImages: Map<string, Preview | undefined>;
41
+ inlinePending: Map<string, Promise<Preview | undefined>>;
42
+ inlineGraphics: Map<string, { layout: string } & NonNullable<ReturnType<typeof renderImage>>>;
43
+ baseFactory?: EditorFactoryFunction;
44
+ editor?: EditorComponent;
45
+ editorFactory?: EditorFactoryFunction;
46
+ unsubscribeInput?: () => void;
47
+ restoreViewportInput?: () => void;
48
+ cleanup: InputEnhancementsCleanup;
49
+ }