@each1024/pi-mini-mode 1.3.6 → 1.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,7 @@ A compact, configurable footer for [Pi](https://pi.dev). Your model, usage, cost
10
10
 
11
11
  ## Minimal output
12
12
 
13
- `/pi-mini-mode-settings` now has **Lens**, a separate **Collapse replies** switch, and **Minimal output**. Collapsed replies are off by default, so Pi's conversation history stays native until you turn them on. While the switch is off, Minimal output options stay disabled.
13
+ `/pi-mini-mode-settings` has one **Minimal output** switch, off by default. On collapses the process; off restores Pi's native history. Legacy per-item controls are hidden and no longer filter content. Lens settings are unchanged.
14
14
 
15
15
  - `/pi-mini-mode-minimal on` shows the user's Markdown on an accent-tinted surface, a background-free process summary, and the final reply without a heading or extra background. No duplicate dock panel.
16
16
  - Each turn uses one shared tree showing the latest **ten summary entries**: available thinking, tool calls, streaming tool output, and skill reads. `Ctrl+O` expands the full Markdown process and toggles it closed again; new questions start collapsed; tools without output show an elapsed wait counter, and empty progress events never overwrite existing content; there are no section headings, collapsed counts, or completion labels. Original session messages remain intact.
@@ -25,6 +25,17 @@ The user surface blends the active Pi accent with its user background. Process a
25
25
 
26
26
  Checks: `npm run check && npm test`. Real terminal smoke test: `python3 test/minimal-pty.py` (Python 3, Node, and the installed dependency's bundled Pi CLI). It uses temporary fixtures, tests regular/fullscreen, toggling, ten-entry process and Ctrl+O expand/collapse, restored results, and narrow terminals, without model calls.
27
27
 
28
+ ## Input enhancements
29
+
30
+ One **Input enhancements** switch (on by default) adds image-path previews, inline skill completion/expansion, and message file links. Turning it off leaves Pi's native clipboard behavior intact.
31
+
32
+ - Paste images with native `Ctrl+V` (`Alt+V` on Windows/WSL); forwarded `Cmd+V` key events are also supported when the terminal sends them.
33
+ - Move the editing cursor into an image path, or hover it in fullscreen, to preview it. Requires a terminal image protocol; otherwise a path hint is shown. Esc dismisses it. Reads are limited to 20 MB.
34
+ - Type `/` at the beginning or after whitespace to select a skill at the current cursor. Inline `/skill:name` tokens expand on submission; URL/path slashes keep native behavior.
35
+ - Images appear as underlined `[image1]` labels in the editor and messages. Cmd+click opens the original file with its default application; other file paths remain clickable too. Fullscreen editor hover requests a link pointer and restores it on exit. Quoted paths support spaces.
36
+
37
+ Link modifiers depend on the terminal: usually Cmd+click on macOS and Ctrl+click on Windows/Linux; Ghostty fullscreen may require Shift+Cmd/Shift+Ctrl. Pi fullscreen also handles direct link clicks. Deleted temporary images cannot be reopened. See [Pi terminal setup](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/docs/terminal-setup.md).
38
+
28
39
  ## Install
29
40
 
30
41
  ```bash
@@ -135,13 +146,8 @@ Settings are stored globally at Pi's agent directory (normally `~/.pi/agent/pi-m
135
146
  | `pi-mini-mode-context-percent-show` | `true` | Context-use percentage |
136
147
  | `pi-mini-mode-speed-show` | `true` | Generation speed at the far right |
137
148
  | `pi-mini-mode-speed-unit-show` | `true` | Generation-speed sub-setting: append `tok/s` to the numeric value |
138
- | `pi-mini-mode-minimal-show` | `false` | Collapse replies; off keeps Pi's default conversation history |
139
- | `pi-mini-mode-minimal-thinking-show` | `true` | Show thinking in collapsed replies |
140
- | `pi-mini-mode-minimal-tools-show` | `true` | Show tool calls and agent calls |
141
- | `pi-mini-mode-minimal-output-show` | `true` | Show process output |
142
- | `pi-mini-mode-minimal-skills-show` | `true` | Show skill reads |
143
- | `pi-mini-mode-agent-usage-show` | `true` | Show Agent token usage |
144
- | `pi-mini-mode-agent-shortcut-show` | `true` | Show the temporary `Ctrl+O` hint for new Agents |
149
+ | `pi-mini-mode-minimal-show` | `false` | Minimal output; off keeps Pi's default conversation history |
150
+ | `pi-mini-mode-input-enhancements` | `true` | Image previews, inline skills, and message file links |
145
151
  | `onboardingCompleted` | `false` initially | Internal marker that prevents another first-run prompt |
146
152
 
147
153
  - **Generation speed**
package/README.zh-CN.md CHANGED
@@ -14,7 +14,20 @@
14
14
 
15
15
  ## 极简输出
16
16
 
17
- `/pi-mini-mode-settings` 现在包含 **Lens**、独立的 **Collapse replies(折叠回复)** 和 **Minimal output(极简输出)** 设置。折叠回复默认关闭;关闭时,极简输出选项也会禁用,因此 Pi 的对话历史会保持原生显示。
17
+ `/pi-mini-mode-settings` 中,**极简输出**只保留一个开关,默认关闭。开启后统一折叠过程,关闭恢复 Pi 原生历史;旧的思考、工具、技能等细项不再单独展示或过滤内容。Lens 页脚设置保持不变。
18
+
19
+ ## 输入增强
20
+
21
+ 同一设置列表中的 **输入增强**默认开启,一个开关控制以下功能(关闭不影响 Pi 原生粘贴):
22
+
23
+ - `Ctrl+V` 粘贴剪贴板图片,Windows/WSL 使用 `Alt+V`;终端实际发送 `Cmd+V` 按键时也可转发原生粘贴。
24
+ - 编辑光标移入图片路径即可预览,全屏模式也支持鼠标悬停。预览使用终端原生图片协议,不支持时显示路径提示;按 Esc 关闭,图片读取上限 20 MB。
25
+ - 输入起点或空白后输入 `/` 搜索技能,选择后在当前光标处插入 `/skill:name`,提交时展开行内技能;不抢占 URL 或路径中的斜杠。
26
+ - 输入框及消息中的图片显示为 `[image1]` 等带下划线的标签;Cmd+点击图片标签及其他文件路径,使用系统默认应用打开原文件。全屏悬停标签会切换为链接指针,移出恢复。支持绝对路径、相对路径和引号/反引号包裹的含空格路径。
27
+
28
+ 点击修饰键由终端决定,通常为 macOS `Cmd+点击`、Windows/Linux `Ctrl+点击`;Ghostty 全屏可能需要 `Shift+Cmd` / `Shift+Ctrl`。Pi 全屏自身也支持直接点击链接。图片文件被清理后不能再预览或打开。图片与链接兼容性参见 [Pi 终端设置](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/docs/terminal-setup.md)。
29
+
30
+ ### 极简输出行为
18
31
 
19
32
  - `/pi-mini-mode-minimal on` 显示带主题色背景的用户 Markdown、无背景的过程摘要,以及没有标题或额外背景的最终回复,不会重复显示停靠面板。
20
33
  - 每轮使用一棵共享树,显示最新 **10 条摘要**,包括可用的思考、工具调用、流式工具输出和技能读取。按 `Ctrl+O` 可展开完整 Markdown 过程,再按一次收起;新问题默认收起。没有输出的工具会显示已等待时间,空的进度事件不会覆盖已有内容,也不会显示分组标题、折叠数量或完成标签。原始会话消息保持不变。
@@ -104,13 +117,8 @@ deepseek-v4-flash high Total 45K Cached 25K CH 40.0% $0.012 500/1.0M █
104
117
  | `pi-mini-mode-context-percent-show` | `true` | 显示上下文使用百分比 |
105
118
  | `pi-mini-mode-speed-show` | `true` | 显示最新生成速度 |
106
119
  | `pi-mini-mode-speed-unit-show` | `true` | 速度子设置:在数字后追加 `tok/s` |
107
- | `pi-mini-mode-minimal-show` | `false` | 折叠回复;关闭则使用 Pi 默认历史显示 |
108
- | `pi-mini-mode-minimal-thinking-show` | `true` | 显示折叠回复中的思考 |
109
- | `pi-mini-mode-minimal-tools-show` | `true` | 显示工具调用和 Agent 调用 |
110
- | `pi-mini-mode-minimal-output-show` | `true` | 显示过程输出 |
111
- | `pi-mini-mode-minimal-skills-show` | `true` | 显示技能读取 |
112
- | `pi-mini-mode-agent-usage-show` | `true` | 显示 Agent token 用量 |
113
- | `pi-mini-mode-agent-shortcut-show` | `true` | 新 Agent 显示临时 `Ctrl+O` 提示 |
120
+ | `pi-mini-mode-minimal-show` | `false` | 极简输出总开关;关闭则使用 Pi 默认历史显示 |
121
+ | `pi-mini-mode-input-enhancements` | `true` | 图片预览、行内技能补全与展开、消息文件链接 |
114
122
  | `onboardingCompleted` | 初始为 `false` | 防止再次显示首次设置提示的内部标记 |
115
123
 
116
124
  生成速度设置中的 **显示 tok/s 单位** 是 **显示最新生成速度** 下方的缩进子设置。关闭它只会移除 `tok/s`,保留速度数字;即使隐藏生成速度,该子设置仍会保留。
@@ -1,10 +1,12 @@
1
1
  import { AGENT_STATUS_ENTRY, savedAgentStatuses, retainAgentStatuses, agentChildren, agentCall, agentCallDisplay, agentStatusesByTurn, attachAgentWidgets, isAgentTool, liveAgentView, readAgentStatuses, runningGlyph, type AgentCall } from "../lib/agent-view.ts";
2
2
  import { CONFIG_DIR_NAME, getSettingsListTheme, getMarkdownTheme, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import { attachTranscript, type NoticeRows, type TurnNotices } from "../lib/transcript-adapter.ts";
4
- import { diagramMarkdown, minimalMarkdownTheme } from "../lib/minimal-markdown.ts";
4
+ import { diagramMarkdown, isFencedMarkdown, minimalMarkdownTheme } from "../lib/minimal-markdown.ts";
5
5
  import { minimalSurface } from "../lib/minimal-theme.ts";
6
6
  import { Container, Markdown, matchesKey, isKeyRelease, isKeyRepeat, sliceByColumn, type SettingItem, SettingsList, Text, type TuiMouseEvent, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
7
7
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
+ import type { InputEnhancementsCleanup } from "../lib/input-enhancements.ts";
9
+ import { linkMessageFiles } from "../lib/file-links.ts";
8
10
  import { homedir } from "node:os";
9
11
  import { stripVTControlCharacters } from "node:util";
10
12
  import { dirname, join } from "node:path";
@@ -27,6 +29,7 @@ export interface MiniLensSettings {
27
29
  "pi-mini-mode-speed-show": boolean;
28
30
  "pi-mini-mode-speed-unit-show": boolean;
29
31
  "pi-mini-mode-minimal-show": boolean;
32
+ "pi-mini-mode-input-enhancements": boolean;
30
33
  "pi-mini-mode-minimal-thinking-show": boolean;
31
34
  "pi-mini-mode-minimal-tools-show": boolean;
32
35
  "pi-mini-mode-minimal-output-show": boolean;
@@ -50,6 +53,7 @@ export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
50
53
  "pi-mini-mode-speed-show": true,
51
54
  "pi-mini-mode-speed-unit-show": true,
52
55
  "pi-mini-mode-minimal-show": false,
56
+ "pi-mini-mode-input-enhancements": true,
53
57
  "pi-mini-mode-minimal-thinking-show": true,
54
58
  "pi-mini-mode-minimal-tools-show": true,
55
59
  "pi-mini-mode-minimal-output-show": true,
@@ -63,11 +67,11 @@ const SETTING_IDS = Object.keys(DEFAULT_SETTINGS) as Array<keyof MiniLensSetting
63
67
 
64
68
  const COPY = {
65
69
  title: "Pi Mini Mode 设置", preview: "预览(示例数据)", lens: "设置", minimal: "极简输出",
66
- model: "显示模型", thinking: "显示思考等级", total: "显示会话总 token", cached: "显示会话缓存 token", totalLabel: "Total", cachedLabel: "Cached", cacheHitLabel: "CH", cacheHit: "显示缓存命中率 (CH)", price: "显示会话价格", mcp: "显示已启用 MCP 服务器", context: "显示上下文 token 与进度条", dots: "↳ 使用点阵进度条", percent: "显示上下文百分比", speed: "显示最近生成速度", speedUnit: "↳ 显示 tok/s 单位", enableMinimal: "折叠回复", showThinking: "显示思考", tools: "显示工具调用", output: "显示过程输出", skills: "显示技能", agentUsage: "显示 Agent token 用量", shortcut: "新 Agent 显示 Ctrl+O 提示(6 秒)",
70
+ model: "显示模型", thinking: "显示思考等级", total: "显示会话总 token", cached: "显示会话缓存 token", totalLabel: "Total", cachedLabel: "Cached", cacheHitLabel: "CH", cacheHit: "显示缓存命中率 (CH)", price: "显示会话价格", mcp: "显示已启用 MCP 服务器", context: "显示上下文 token 与进度条", dots: "↳ 使用点阵进度条", percent: "显示上下文百分比", speed: "显示最近生成速度", speedUnit: "↳ 显示 tok/s 单位", inputEnhancements: "输入增强", showThinking: "显示思考", tools: "显示工具调用", output: "显示过程输出", skills: "显示技能", agentUsage: "显示 Agent token 用量", shortcut: "新 Agent 显示 Ctrl+O 提示(6 秒)",
67
71
  totalDescription: "Total:当前会话分支上的全部 token,含工具上报的 LLM 用量。", cachedDescription: "Cached:累计 cache-read + cache-write token(包含在 Total 中)。", cacheHitDescription: "CH(cache hit):cache-read / (input + cache-read)。Cache write 不计入此比率。",
68
- enableMinimalDescription: "关闭后保留 Pi 默认会话历史。",
69
- minimalLocked: "打开「折叠回复」后才能配置这些选项。",
70
- tuiRequired: "/pi-mini-mode-settings 需要 TUI 模式", saveFailed: "无法保存 Pi Mini Mode 设置", minimalRequired: "/pi-mini-mode-minimal 需要 TUI 模式", minimalUsage: "用法:/pi-mini-mode-minimal [on|off]", minimalState: "Pi Mini Mode 折叠回复:", onboarding: "MCP 数量、点阵样式和折叠回复默认关闭;其余项默认开启。", keepDefaults: "保留默认", configureNow: "立即配置",
72
+ enableMinimalDescription: "开启统一折叠思考、工具和技能过程;关闭恢复 Pi 默认会话历史。",
73
+ inputEnhancementsDescription: "原生 Ctrl+V 粘贴图片(Windows/WSL:Alt+V);图片显示为 [image1] 标签,光标移入或全屏悬停可预览。空白后 / 选择技能并在光标处插入。Cmd+点击带下划线的图片标签或消息文件路径,用系统默认应用打开;预览及点击需终端支持。关闭仅恢复原生行为。",
74
+ tuiRequired: "/pi-mini-mode-settings 需要 TUI 模式", saveFailed: "无法保存 Pi Mini Mode 设置", minimalRequired: "/pi-mini-mode-minimal 需要 TUI 模式", minimalUsage: "用法:/pi-mini-mode-minimal [on|off]", minimalState: "Pi Mini Mode 极简输出:", onboarding: "MCP 数量、点阵样式和极简输出默认关闭;其余项默认开启。", keepDefaults: "保留默认", configureNow: "立即配置",
71
75
  } as const;
72
76
 
73
77
  export function settingsPath(agentDir = process.env.PI_MINI_MODE_AGENT_DIR ?? join(homedir(), CONFIG_DIR_NAME, "agent")): string {
@@ -84,6 +88,8 @@ export function parseSettings(value: unknown): MiniLensSettings {
84
88
  for (const id of SETTING_IDS) {
85
89
  if (isBoolean(candidate[id])) settings[id] = candidate[id];
86
90
  }
91
+ // 折叠回复的旧细项已合并进极简输出总开关:旧值不再暗中过滤内容,始终按默认全开。
92
+ for (const id of LEGACY_MINIMAL_SETTING_IDS) settings[id] = true;
87
93
  return settings;
88
94
  }
89
95
 
@@ -363,19 +369,30 @@ export function statusLine(
363
369
  return truncateToWidth(`${content}${content ? gap : ""}${right}`, width, "");
364
370
  }
365
371
 
372
+ const LEGACY_MINIMAL_SETTING_IDS = [
373
+ "pi-mini-mode-minimal-thinking-show", "pi-mini-mode-minimal-tools-show", "pi-mini-mode-minimal-output-show",
374
+ "pi-mini-mode-minimal-skills-show", "pi-mini-mode-agent-usage-show", "pi-mini-mode-agent-shortcut-show",
375
+ ] as const satisfies ReadonlyArray<keyof MiniLensSettings>;
376
+
377
+ /** 模式总开关:设置列表顶部只展示这两项,旧细分项不再展示但仍保留兼容。 */
378
+ const MODE_SETTING_IDS = ["pi-mini-mode-minimal-show", "pi-mini-mode-input-enhancements"] as const;
379
+
380
+ function isModeSetting(id: string): boolean {
381
+ return (MODE_SETTING_IDS as readonly string[]).includes(id);
382
+ }
383
+
366
384
  export function isCollapsedReplyChildSetting(id: string): boolean {
367
- return id === "pi-mini-mode-minimal-thinking-show" || id === "pi-mini-mode-minimal-tools-show" || id === "pi-mini-mode-minimal-output-show"
368
- || id === "pi-mini-mode-minimal-skills-show" || id === "pi-mini-mode-agent-usage-show" || id === "pi-mini-mode-agent-shortcut-show";
385
+ return (LEGACY_MINIMAL_SETTING_IDS as readonly string[]).includes(id);
369
386
  }
370
387
 
371
388
  export function settingsItems(settings: MiniLensSettings): SettingItem[] {
372
389
  const values = ["on", "off"];
373
390
  const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted">, string> = {
374
- "pi-mini-mode-model-show": COPY.model, "pi-mini-mode-thinking-show": COPY.thinking, "pi-mini-mode-session-tokens-show": COPY.total, "pi-mini-mode-cache-tokens-show": COPY.cached, "pi-mini-mode-ch-show": COPY.cacheHit, "pi-mini-mode-cost-show": COPY.price, "pi-mini-mode-mcp-show": COPY.mcp, "pi-mini-mode-context-show": COPY.context, "pi-mini-mode-context-dots-show": COPY.dots, "pi-mini-mode-context-percent-show": COPY.percent, "pi-mini-mode-speed-show": COPY.speed, "pi-mini-mode-speed-unit-show": COPY.speedUnit, "pi-mini-mode-minimal-show": COPY.enableMinimal, "pi-mini-mode-minimal-thinking-show": COPY.showThinking, "pi-mini-mode-minimal-tools-show": COPY.tools, "pi-mini-mode-minimal-output-show": COPY.output, "pi-mini-mode-minimal-skills-show": COPY.skills, "pi-mini-mode-agent-usage-show": COPY.agentUsage, "pi-mini-mode-agent-shortcut-show": COPY.shortcut,
391
+ "pi-mini-mode-model-show": COPY.model, "pi-mini-mode-thinking-show": COPY.thinking, "pi-mini-mode-session-tokens-show": COPY.total, "pi-mini-mode-cache-tokens-show": COPY.cached, "pi-mini-mode-ch-show": COPY.cacheHit, "pi-mini-mode-cost-show": COPY.price, "pi-mini-mode-mcp-show": COPY.mcp, "pi-mini-mode-context-show": COPY.context, "pi-mini-mode-context-dots-show": COPY.dots, "pi-mini-mode-context-percent-show": COPY.percent, "pi-mini-mode-speed-show": COPY.speed, "pi-mini-mode-speed-unit-show": COPY.speedUnit, "pi-mini-mode-minimal-show": COPY.minimal, "pi-mini-mode-input-enhancements": COPY.inputEnhancements, "pi-mini-mode-minimal-thinking-show": COPY.showThinking, "pi-mini-mode-minimal-tools-show": COPY.tools, "pi-mini-mode-minimal-output-show": COPY.output, "pi-mini-mode-minimal-skills-show": COPY.skills, "pi-mini-mode-agent-usage-show": COPY.agentUsage, "pi-mini-mode-agent-shortcut-show": COPY.shortcut,
375
392
  };
376
393
  return (Object.keys(labels) as Array<keyof typeof labels>).map((id) => ({
377
394
  id, label: labels[id],
378
- description: id === "pi-mini-mode-minimal-show" ? COPY.enableMinimalDescription : id === "pi-mini-mode-session-tokens-show" ? COPY.totalDescription : id === "pi-mini-mode-cache-tokens-show" ? COPY.cachedDescription : id === "pi-mini-mode-ch-show" ? COPY.cacheHitDescription : undefined,
395
+ description: id === "pi-mini-mode-minimal-show" ? COPY.enableMinimalDescription : id === "pi-mini-mode-input-enhancements" ? COPY.inputEnhancementsDescription : id === "pi-mini-mode-session-tokens-show" ? COPY.totalDescription : id === "pi-mini-mode-cache-tokens-show" ? COPY.cachedDescription : id === "pi-mini-mode-ch-show" ? COPY.cacheHitDescription : undefined,
379
396
  currentValue: settings[id] ? values[0] : values[1], values,
380
397
  }));
381
398
  }
@@ -555,9 +572,9 @@ function visibleMinimalTurns(settings: MiniLensSettings, turns: MinimalTurn[]):
555
572
  });
556
573
  }
557
574
 
558
- export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showShortcut: (turn: MinimalTurn) => boolean = () => true, showUsage: () => boolean = () => true, subAgentsExpanded: () => boolean = () => false, agentDeadlines = new Map<string, number>()) {
575
+ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showShortcut: (turn: MinimalTurn) => boolean = () => true, showUsage: () => boolean = () => true, subAgentsExpanded: () => boolean = () => false, agentDeadlines = new Map<string, number>(), transformText: (text: string) => string = text => text) {
559
576
  const markdown = (text: string, width: number, process = false) => new Markdown(text, 0, 0, minimalMarkdownTheme(getMarkdownTheme()),
560
- { color: (value) => theme.fg(process ? "muted" : "text", value) }, { transform: (source, available) => diagramMarkdown(source, available) }).render(width);
577
+ { color: (value) => theme.fg(process ? "muted" : "text", value) }, { transform: (source, available) => transformText(diagramMarkdown(source, available)) }).render(width);
561
578
  const surface = (rows: string[], width: number, user: boolean) => {
562
579
  const padding = Math.min(2, Math.floor((width - 1) / 2));
563
580
  return ["", ...rows, ""].map((row) => {
@@ -692,10 +709,12 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
692
709
  const questionRows = markdown(turn.question, inner);
693
710
  const loopSummary = piLoopSummary(turn.question);
694
711
  const expanded = expandedPrompts.get(index) === turn.question;
712
+ // A fence is one visual unit; slicing it mid-block looks like raw source.
713
+ const keepFence = !loopSummary && isFencedMarkdown(turn.question);
695
714
  // Loop wakeups are system-generated user messages. Collapse them even when
696
715
  // their short prompt would otherwise fit the normal four-row allowance.
697
- const userRows = expanded ? [...questionRows] : loopSummary ? markdown(loopSummary, inner) : questionRows.slice(0, 4);
698
- if (loopSummary || questionRows.length > 4) {
716
+ const userRows = expanded || keepFence ? [...questionRows] : loopSummary ? markdown(loopSummary, inner) : questionRows.slice(0, 4);
717
+ if (!keepFence && (loopSummary || questionRows.length > 4)) {
699
718
  const label = expanded ? "▴ 收起" : loopSummary ? "▾ 展开" : `▾ 展开 (${questionRows.length} 行)`;
700
719
  const control = truncateToWidth(label, inner, "");
701
720
  promptControls.push({ index, question: turn.question, y: lines.length + 1 + userRows.length,
@@ -858,6 +877,10 @@ export default function (pi: ExtensionAPI) {
858
877
  const minimalToolOutputIndices = new Map<string, number>();
859
878
  let speedTimer: ReturnType<typeof setInterval> | undefined;
860
879
  let settings: MiniLensSettings = { ...DEFAULT_SETTINGS };
880
+ let cleanupInputEnhancements: InputEnhancementsCleanup | undefined;
881
+ let messageCwd = process.cwd();
882
+ const messageLinks = (text: string) => settings["pi-mini-mode-input-enhancements"] ? linkMessageFiles(text, messageCwd) : text;
883
+ pi.registerMarkdownTransformer?.(messageLinks);
861
884
  let saveChain: Promise<void> = Promise.resolve();
862
885
  const configPath = settingsPath();
863
886
 
@@ -926,6 +949,7 @@ export default function (pi: ExtensionAPI) {
926
949
  handledRunIds.clear();
927
950
  return minimalTurns.map((turn, index) => {
928
951
  const turnAgents = assigned.get(index) ?? [];
952
+ for (const status of turnAgents) if (status.runId) handledRunIds.add(String(status.runId));
929
953
  const withNotices = agentChildren(turnAgents).map(sub => {
930
954
  if (sub.runId) handledRunIds.add(String(sub.runId));
931
955
  const n = supervisorNotices.get(String(sub.runId));
@@ -934,7 +958,7 @@ export default function (pi: ExtensionAPI) {
934
958
  return { ...turn, subAgents: withNotices };
935
959
  });
936
960
  };
937
- const view = minimalOutputComponent(theme, () => visibleMinimalTurns(settings, turnsWithAgents()), () => processExpanded, turn => settings["pi-mini-mode-agent-shortcut-show"] && Date.now() < (turn.shortcutHintUntil ?? 0), () => settings["pi-mini-mode-agent-usage-show"], () => subAgentsExpanded, agentDeadlines);
961
+ const view = minimalOutputComponent(theme, () => visibleMinimalTurns(settings, turnsWithAgents()), () => processExpanded, turn => settings["pi-mini-mode-agent-shortcut-show"] && Date.now() < (turn.shortcutHintUntil ?? 0), () => settings["pi-mini-mode-agent-usage-show"], () => subAgentsExpanded, agentDeadlines, messageLinks);
938
962
  const hintRemaining = (activeMinimalTurn?.shortcutHintUntil ?? 0) - Date.now();
939
963
  if (hintRemaining > 0) {
940
964
  shortcutTimer = setTimeout(() => tui.requestRender(), hintRemaining);
@@ -1055,7 +1079,7 @@ export default function (pi: ExtensionAPI) {
1055
1079
  const onChange = (id: string, value: string) => {
1056
1080
  settings = { ...settings, [id]: value === "on", onboardingCompleted: true };
1057
1081
  items = settingsItems(settings);
1058
- applyCollapseState();
1082
+ cleanupInputEnhancements?.refresh();
1059
1083
  preview.setText(settingsPreviewLine(theme, settings));
1060
1084
  mountMinimalOutput(ctx);
1061
1085
  void persistSettings(ctx);
@@ -1069,31 +1093,16 @@ export default function (pi: ExtensionAPI) {
1069
1093
  label: (text: string, selected: boolean) => {
1070
1094
  const name = text.trimEnd();
1071
1095
  if (selected) highlighted = items.find((item) => item.label === name)?.id as keyof MiniLensSettings | undefined;
1072
- const disabled = name === COPY.minimal && !settings["pi-mini-mode-minimal-show"];
1073
1096
  if (selected) return theme.bg("selectedBg", theme.fg("accent", theme.bold(text)));
1074
- return theme.fg(disabled ? "muted" : "text", text);
1097
+ return theme.fg("text", text);
1075
1098
  },
1076
1099
  value: (text: string, selected: boolean) =>
1077
1100
  selected ? theme.bg("selectedBg", theme.fg("accent", theme.bold(text))) : theme.fg("muted", text),
1078
1101
  };
1079
- const minimalItems = () => settingsItems(settings).filter((item) => isCollapsedReplyChildSetting(item.id));
1080
- const collapseItem: SettingItem = {
1081
- id: "pi-mini-mode-minimal-show", label: COPY.enableMinimal, description: COPY.enableMinimalDescription,
1082
- currentValue: settings["pi-mini-mode-minimal-show"] ? "on" : "off", values: ["on", "off"],
1083
- };
1084
- const minimalGroup: SettingItem = { id: "minimal", label: COPY.minimal, currentValue: "›" };
1085
1102
  const separator: SettingItem = { id: "settings-separator", label: "────────────", currentValue: "" };
1086
- const applyCollapseState = () => {
1087
- const enabled = settings["pi-mini-mode-minimal-show"];
1088
- collapseItem.currentValue = enabled ? "on" : "off";
1089
- minimalGroup.currentValue = enabled ? "›" : "off";
1090
- minimalGroup.description = enabled ? undefined : COPY.minimalLocked;
1091
- if (enabled) minimalGroup.submenu = (_value, back) => new SettingsList(minimalItems(), 8, settingsTheme, onChange, () => back(), { enableSearch: true });
1092
- else delete minimalGroup.submenu;
1093
- };
1094
- applyCollapseState();
1095
- const smallItems = settingsItems(settings).filter((item) => item.id !== "pi-mini-mode-minimal-show" && !isCollapsedReplyChildSetting(item.id));
1096
- const settingsList = new SettingsList([collapseItem, minimalGroup, separator, ...smallItems], 14, settingsTheme, onChange, () => done(undefined), { enableSearch: true });
1103
+ const modeItems = items.filter((item) => isModeSetting(item.id));
1104
+ const lensItems = items.filter((item) => !isModeSetting(item.id) && !isCollapsedReplyChildSetting(item.id));
1105
+ const settingsList = new SettingsList([...modeItems, separator, ...lensItems], 14, settingsTheme, onChange, () => done(undefined), { enableSearch: true });
1097
1106
  container.addChild(settingsList);
1098
1107
  return {
1099
1108
  render: (width: number) => {
@@ -1114,7 +1123,7 @@ export default function (pi: ExtensionAPI) {
1114
1123
  };
1115
1124
 
1116
1125
  pi.registerCommand("pi-mini-mode-minimal", {
1117
- description: "Toggle collapsed replies (off keeps Pi's default conversation history)",
1126
+ description: "Toggle minimal output (off keeps Pi's default conversation history)",
1118
1127
  handler: async (args, ctx) => {
1119
1128
  const normalized = args.trim().toLowerCase();
1120
1129
  if (ctx.mode !== "tui") {
@@ -1178,6 +1187,10 @@ export default function (pi: ExtensionAPI) {
1178
1187
  pi.on("session_start", async (_event, ctx) => {
1179
1188
  const loaded = await loadSettings(configPath);
1180
1189
  settings = loaded.settings;
1190
+ messageCwd = ctx.cwd;
1191
+ // 输入增强只在会话中生效,会话开始时再加载;传 getter 让开关变更即时生效,重复调用是幂等的。
1192
+ const { installInputEnhancements } = await import("../lib/input-enhancements.ts");
1193
+ cleanupInputEnhancements = installInputEnhancements(pi, ctx, () => settings["pi-mini-mode-input-enhancements"]);
1181
1194
  minimalTurns = minimalTurnsFromBranch(ctx.sessionManager.getBranch());
1182
1195
  activeMinimalTurn = undefined;
1183
1196
  pendingMinimalFinal = "";
@@ -1428,6 +1441,8 @@ export default function (pi: ExtensionAPI) {
1428
1441
  refreshMinimalOutput();
1429
1442
  });
1430
1443
  pi.on("session_shutdown", () => {
1444
+ cleanupInputEnhancements?.();
1445
+ cleanupInputEnhancements = undefined;
1431
1446
  persistAgentStatuses?.();
1432
1447
  persistAgentStatuses = undefined;
1433
1448
  agentDeadlines.clear();
package/lib/agent-view.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { diagramMarkdown, isMarkdownProse, minimalMarkdownTheme } from "./minimal-markdown.ts";
2
- import { supervisorNoticeBody } from "./transcript-adapter.ts";
2
+ import { extractNoticeBody, supervisorNoticeBody } from "./transcript-adapter.ts";
3
3
  import { readdirSync, readFileSync, statSync } from "node:fs";
4
4
  import { join, resolve } from "node:path";
5
5
  import { tmpdir } from "node:os";
@@ -57,8 +57,16 @@ export function agentCallRows(calls: AgentCall[], theme: Theme, width: number, e
57
57
 
58
58
  const plain = (text: string) => text.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").trim();
59
59
 
60
- /** Recover structured final text and raw tool inputs from the child session, never from activity previews. */
61
- const childSessionCache = new Map<string, { stamp: string; thinking: string; finalOutput: string; inputs: Array<{ name: string; value: string }> }>();
60
+ /** Child gate JSON is for the runtime, not the transcript. */
61
+ export function stripAcceptanceReport(output: string): string {
62
+ return output
63
+ .replace(/\n?```acceptance[-_]report\s*\n[\s\S]*?```\s*$/i, "")
64
+ .replace(/\n?ACCEPTANCE_REPORT\s*:\s*\{[\s\S]*\}\s*$/i, "")
65
+ .trimEnd();
66
+ }
67
+
68
+ /** Recover the child's own prose and raw tool inputs from its session, never from activity previews. */
69
+ const childSessionCache = new Map<string, { stamp: string; thinking: string; finalOutput: string; latestText: string; inputs: Array<{ name: string; value: string }> }>();
62
70
  const singleLine = (value: string) => plain(value).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ");
63
71
  function childSessionData(sessionFile: unknown) {
64
72
  if (typeof sessionFile !== "string") return undefined;
@@ -70,6 +78,7 @@ function childSessionData(sessionFile: unknown) {
70
78
  const inputs: Array<{ name: string; value: string }> = [];
71
79
  let thinking = "";
72
80
  let finalOutput = "";
81
+ let latestText = "";
73
82
  for (const line of readFileSync(sessionFile, "utf8").split(/\r?\n/)) {
74
83
  try {
75
84
  const entry = JSON.parse(line) as { type?: string; thinkingLevel?: string; message?: { role?: string; stopReason?: string; channel?: string; content?: Array<{ type?: string; text?: string; name?: string; input?: Record<string, unknown>; arguments?: Record<string, unknown> } | null> } };
@@ -77,11 +86,15 @@ function childSessionData(sessionFile: unknown) {
77
86
  if (entry.message?.role !== "assistant") continue;
78
87
  const message = entry.message;
79
88
  const content = Array.isArray(message.content) ? message.content : [];
89
+ const text = content.filter(block => block?.type === "text" && typeof block.text === "string").map(block => block!.text).join("\n\n").trim();
80
90
  // Pi persists no channel: only a stopped assistant text reply is a final answer.
81
91
  finalOutput = entry.type === "message" && message.stopReason === "stop"
82
92
  && (message.channel === undefined || message.channel === "final")
83
93
  && !content.some(block => block?.type === "toolCall")
84
- ? content.filter(block => block?.type === "text" && typeof block.text === "string").map(block => block!.text).join("\n\n").trim() : "";
94
+ ? text : "";
95
+ // Narration attached to a tool call is still the child's own prose; it
96
+ // is the only body a running or tool-ended child has.
97
+ if (entry.type === "message" && text) latestText = text;
85
98
  for (const call of content) {
86
99
  if (!call) continue;
87
100
  if (call.type !== "toolCall" || typeof call.name !== "string") continue;
@@ -92,7 +105,7 @@ function childSessionData(sessionFile: unknown) {
92
105
  }
93
106
  } catch { /* A concurrently written session can end with a partial line. */ }
94
107
  }
95
- cached = { stamp, thinking, finalOutput, inputs };
108
+ cached = { stamp, thinking, finalOutput, latestText, inputs };
96
109
  childSessionCache.set(sessionFile, cached);
97
110
  }
98
111
  return cached;
@@ -154,6 +167,14 @@ export function restyleAgentWidget(lines: string[], theme: Theme, width: number,
154
167
  return rows;
155
168
  }
156
169
 
170
+ /** Expanded heading: full-width selectedBg, keeping inner fg after resets.
171
+ * theme.bg only wraps the ends; older themes without getBgAnsi lose fill after \x1b[0m. */
172
+ function paintExpandedHeading(theme: Theme, line: string): string {
173
+ const background = theme.getBgAnsi?.("selectedBg") ?? "";
174
+ return background
175
+ ? background + line.replace(/\x1b\[(?:0|49)?m/g, reset => reset + background) + "\x1b[49m"
176
+ : theme.bg("selectedBg", line);
177
+ }
157
178
  function agentSummary(theme: Theme, width: number, running: number, done: number, errors: number, expanded: boolean): string {
158
179
  const label = `Sub Agent · running ${running}${done ? ` · done ${done}` : ""}${errors ? ` · failed ${errors}` : ""}${done ? ` · Ctrl+S ${expanded ? "collapse" : "expand"}` : ""}`;
159
180
  const summary = truncateToWidth(theme.fg(errors ? "error" : "muted", label), width);
@@ -320,20 +341,14 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
320
341
  const rows: string[] = [];
321
342
  const text = (value: unknown) => typeof value === "string" ? plain(value).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ") : "";
322
343
  const bodyText = (value: unknown) => typeof value === "string"
323
- ? plain(value).replace(/[\x00-\x09\x0b\x0c\x0e-\x1f\x7f]/g, " ").trim() : "";
344
+ ? stripAcceptanceReport(plain(value).replace(/[\x00-\x09\x0b\x0c\x0e-\x1f\x7f]/g, " ")).trim() : "";
324
345
  const renderBody = (source: string, available: number) => {
346
+ const width = Math.max(1, available);
325
347
  if (isMarkdownProse(source)) return new Markdown(source, 0, 0, minimalMarkdownTheme(getMarkdownTheme()),
326
- { color: value => theme.fg("muted", value) }, { transform: diagramMarkdown }).render(Math.max(1, available));
327
- const rows: string[] = [];
328
- for (const sourceLine of source.split(/\r?\n/)) {
329
- let line = sourceLine;
330
- do {
331
- const row = truncateToWidth(line, Math.max(1, available), "");
332
- rows.push(theme.fg("muted", row));
333
- line = line.slice(row.length);
334
- } while (line);
335
- }
336
- return rows;
348
+ { color: value => theme.fg("muted", value) }, { transform: diagramMarkdown }).render(width);
349
+ // Wrap by visible columns. Do not re-slice truncateToWidth: it appends a
350
+ // reset, so slice(row.length) would drop source characters on every wrap.
351
+ return wrapTextWithAnsi(source, width).map(row => theme.fg("muted", row));
337
352
  };
338
353
  if (width > 0) all.forEach((child, index) => {
339
354
  const runKey = String(child.runId ?? child.displayId);
@@ -369,36 +384,67 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
369
384
  const endedAt = terminal ? timestamp(child.endedAt) ?? deadlines.get(`${elapsedKey}:ended`) ?? now : now;
370
385
  if (terminal) deadlines.set(`${elapsedKey}:ended`, endedAt);
371
386
  const elapsed = formatAgentElapsed(startedAt, endedAt);
372
- const heading = truncateToWidth(theme.fg("dim", `${index === all.length - 1 ? "└─" : "├─"} `)
387
+ const identity = isChildExpanded ? "accent" : color;
388
+ const heading = truncateToWidth(theme.fg(isChildExpanded ? "accent" : "dim", `${index === all.length - 1 ? "└─" : "├─"} `)
373
389
  + theme.fg(failedAgent(child) || notice?.color === "error" ? "error" : notice?.color === "warning" ? "warning" : isRunning && !terminal ? "accent" : "muted", `${glyph} `)
374
- + theme.fg("text", theme.bold("SubAgent"))
375
- + theme.fg(color, ` • ${suffix ? model.slice(0, -suffix[0].length) : model}`)
376
- + (level ? theme.fg("muted", ` ${level}`) : "") + theme.fg(terminal ? "muted" : "success", ` ${elapsed}`) + theme.fg(color, " : "), width, "…");
390
+ + theme.fg(identity, theme.bold("SubAgent"))
391
+ + theme.fg(identity, ` • ${suffix ? model.slice(0, -suffix[0].length) : model}`)
392
+ + (level ? theme.fg("muted", ` ${level}`) : "") + theme.fg(terminal ? "muted" : "success", ` ${elapsed}`) + theme.fg(identity, " : "), width, "…");
377
393
  const bodyBudget = Math.max(0, width - visibleWidth(heading));
378
394
  const progress = !bodyBudget ? "" : truncateToWidth(body, bodyBudget, "…");
379
- const row = heading + theme.fg("muted", progress);
380
- const line = row + " ".repeat(Math.max(0, width - visibleWidth(row)));
395
+ const row = heading + theme.fg(isChildExpanded ? "accent" : "muted", progress);
396
+ const padded = row + " ".repeat(Math.max(0, width - visibleWidth(row)));
397
+ const line = isChildExpanded ? paintExpandedHeading(theme, padded) : padded;
381
398
  subagentControls?.push({ runId: runKey, y: rows.length, width, line });
382
399
  rows.push(line);
383
400
  if (isChildExpanded) {
384
- // Live activity is literal text, not a final answer or Markdown tool output.
401
+ let processShown = false;
385
402
  if (!terminal) {
386
- const details = wrapTextWithAnsi(`当前活动:${text(activity)}`, Math.max(1, width - 3));
387
- rows.push(...details.map(line => truncateToWidth(` ${theme.fg("muted", line)}`, width)));
403
+ const process: Array<{ name: string; args: string }> = tools.slice(-6).map(tool => ({
404
+ name: text(tool.tool) || "tool",
405
+ args: rawToolInput(child.sessionFile, tool.tool, text(tool.args)),
406
+ }));
407
+ if (!process.length && child.currentTool) {
408
+ process.push({ name: text(child.currentTool), args: text(child.currentPath || child.currentToolArgs) });
409
+ }
410
+ for (const item of process) {
411
+ const prefix = ` ${theme.fg("muted", "●")} ${theme.fg("text", theme.bold(item.name))}${item.args ? " " : ""}`;
412
+ rows.push(truncateToWidth(prefix + (item.args ? theme.fg("muted", item.args) : ""), width, "…"));
413
+ processShown = true;
414
+ }
388
415
  }
389
416
  const messages = Array.isArray(child.noticeMessages) ? child.noticeMessages : [];
390
417
  const bodies: string[] = [];
418
+ let latestProgress = "";
391
419
  for (const msg of messages) {
420
+ const item = msg && typeof msg === "object" ? msg as Record<string, unknown> : undefined;
421
+ const details = item?.details && typeof item.details === "object" ? item.details as Record<string, unknown> : undefined;
422
+ if (item?.customType === "subagent_supervisor_request" && details?.reason === "progress_update") {
423
+ const progress = extractNoticeBody(msg);
424
+ if (progress) latestProgress = progress;
425
+ continue;
426
+ }
392
427
  const b = supervisorNoticeBody(msg);
393
428
  if (b && !bodies.includes(b)) bodies.push(b);
394
429
  }
395
- const finalOutput = terminal ? bodyText(childSessionData(child.sessionFile)?.finalOutput ?? child.finalOutput) : "";
430
+ const session = childSessionData(child.sessionFile);
431
+ if (!bodies.length && latestProgress) bodies.push(latestProgress);
432
+ const latestText = bodyText(session?.latestText);
433
+ if (!terminal && latestText && !bodies.length) bodies.push(latestText);
434
+ // A stopped answer outranks the running narration; the narration still
435
+ // covers a child that ended between turns or without a stopped reply.
436
+ const finalOutput = terminal ? bodyText(session?.finalOutput || latestText || child.finalOutput) : "";
396
437
  if (finalOutput && !bodies.includes(finalOutput)) bodies.push(finalOutput);
397
438
  const error = bodyText(child.error);
398
439
  if (error && !bodies.includes(error)) bodies.push(error);
399
- for (const textBody of bodies) {
440
+ if (!terminal && !processShown && !bodies.length) {
441
+ rows.push(truncateToWidth(` ${theme.fg("muted", "●")} ${theme.fg("text", theme.bold(text(state)))}`, width, "…"));
442
+ processShown = true;
443
+ }
444
+ for (const [index, textBody] of bodies.entries()) {
400
445
  // Child/supervisor bodies are Markdown prose; tool logs and JSON are
401
446
  // not placed in this semantic body channel.
447
+ if (processShown || index > 0) rows.push("");
402
448
  for (const line of renderBody(textBody, Math.max(1, width - 3))) {
403
449
  rows.push(truncateToWidth(` ${line}`, width));
404
450
  }
@@ -0,0 +1,80 @@
1
+ import { existsSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, isAbsolute, resolve } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { getCapabilities, sliceByColumn, stripTerminalSequences, visibleWidth } from "@earendil-works/pi-tui";
6
+
7
+ /** Pi 0.85's allowlist predates Otty; preserve explicit opt-outs and multiplexer detection. */
8
+ export function inputCapabilities(env = process.env) {
9
+ const caps = getCapabilities();
10
+ if (env.TERM_PROGRAM?.toLowerCase() !== "otty" || env.TMUX || /^(screen|tmux)/.test(env.TERM ?? "")) return caps;
11
+ return { ...caps, hyperlinks: env.PI_HYPERLINKS === "0" ? false : true,
12
+ images: env.PI_IMAGE_PROTOCOL === "0" || env.PI_IMAGE_PROTOCOL === "none" ? null : caps.images ?? "kitty" as const };
13
+ }
14
+
15
+ export function localPath(path: string, cwd: string): string {
16
+ return path.startsWith("~/") ? resolve(homedir(), path.slice(2)) : isAbsolute(path) ? path : resolve(cwd, path);
17
+ }
18
+
19
+ /** Opening/closing fences must stay intact; quoted paths inside them are not links. */
20
+ function fenceRanges(text: string): Array<[number, number]> {
21
+ const ranges: Array<[number, number]> = [];
22
+ const open = /(^|\n)( {0,3})(`{3,}|~{3,})[^\n]*\n/g;
23
+ for (let match = open.exec(text); match; match = open.exec(text)) {
24
+ const start = match.index + match[1].length;
25
+ const escaped = match[3].replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
26
+ // Search only after the opener, then resume after the closer, so a closing
27
+ // fence can never be read as the next opener and swallow the text behind it.
28
+ const close = new RegExp(`(?:^|\\n) {0,3}${escaped}[ \\t]*(?:\\n|$)`).exec(text.slice(open.lastIndex));
29
+ if (!close) {
30
+ ranges.push([start, text.length]);
31
+ break;
32
+ }
33
+ open.lastIndex += close.index + close[0].length;
34
+ ranges.push([start, open.lastIndex]);
35
+ }
36
+ return ranges;
37
+ }
38
+
39
+ /** Quoted paths may contain spaces; unquoted paths end at prose delimiters. */
40
+ export function filePaths(text: string) {
41
+ const matches: Array<{ path: string; start: number; end: number }> = [];
42
+ const fences = fenceRanges(text);
43
+ const pattern = /(["'`])([^\r\n]*?)\1|[^\s"'`<>()[\]{},。;!?]+/g;
44
+ for (const match of text.matchAll(pattern)) {
45
+ const path = (match[2] ?? match[0]).replace(/[.,;:!?]+$/, "");
46
+ if (!path || /[\x00-\x1f\x7f]/.test(path) || /^[a-z][\w+.-]*:\/\//i.test(path)) continue;
47
+ if (!/^(?:\/|~\/|\.{1,2}\/|[a-z]:[\\/])|[\\/]|\.[a-z\d]{1,12}$/i.test(path)) continue;
48
+ const start = match.index + (match[1] ? 1 : 0);
49
+ const end = start + path.length;
50
+ if (fences.some(([from, to]) => start < to && end > from)) continue;
51
+ matches.push({ path, start, end });
52
+ }
53
+ return matches;
54
+ }
55
+
56
+ // BEL survives Markdown's backslash-escape parsing, unlike the ST terminator.
57
+ export const fileLink = (text: string, path: string) => `\x1b]8;;${pathToFileURL(path).href}\x07\x1b[4m${text}\x1b[24m\x1b]8;;\x07`;
58
+
59
+ /** Display-only: never change persisted messages, existing links, or remote URLs. */
60
+ export function linkMessageFiles(text: string, cwd: string): string {
61
+ if (!inputCapabilities().hyperlinks) return text;
62
+ let imageNumber = 0;
63
+ return text.split(/(\x1b\]8;[^\x07]*(?:\x07)[\s\S]*?\x1b\]8;;\x07|\[[^\]\n]*\]\([^\n]*?\))/g).map((part, index) => {
64
+ if (index % 2) return part;
65
+ const matches = filePaths(part).map(match => ({ ...match, label: /\.(png|jpe?g|gif|webp)$/i.test(match.path) && existsSync(localPath(match.path, cwd)) ? `[image${++imageNumber}]` : match.path }));
66
+ for (const match of matches.reverse()) {
67
+ const path = localPath(match.path, cwd);
68
+ if (!existsSync(path)) continue;
69
+ part = part.slice(0, match.start) + fileLink(match.label, path) + part.slice(match.end);
70
+ }
71
+ return part;
72
+ }).join("");
73
+ }
74
+
75
+ /** Decorate rendered columns without removing the editor's ANSI cursor marker. */
76
+ export function linkRenderedPath(line: string, start: number, end: number, path: string, directory = false): string {
77
+ if (!inputCapabilities().hyperlinks || end <= start) return line;
78
+ return sliceByColumn(line, 0, start) + fileLink(sliceByColumn(line, start, end - start), directory ? dirname(path) : path)
79
+ + sliceByColumn(line, end, Math.max(0, visibleWidth(stripTerminalSequences(line)) - end));
80
+ }