@herbertgao/pi-extensions 2026.11.8 → 2026.11.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +9 -9
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
  5. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +8 -6
  6. package/node_modules/@herbertgao/pi-cc-extensions/README.md +8 -6
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +12 -0
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +36 -13
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/compact-thinking.ts +4 -8
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/context.ts +7 -2
  11. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/footer.ts +115 -6
  12. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +47 -15
  13. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/startup-header.ts +3 -18
  14. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +27 -8
  15. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/default-mode.ts +6 -1
  16. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/markdown-enhance.ts +30 -17
  17. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/scroll.ts +4 -21
  18. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +13 -0
  19. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/names.ts +3 -13
  20. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/transcript-mode.ts +34 -7
  21. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/ansi-text.ts +25 -0
  22. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/keybindings.ts +75 -0
  23. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  24. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
  25. package/node_modules/@herbertgao/pi-subagents/README.md +26 -17
  26. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
  27. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  28. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +71 -8
  29. package/node_modules/@herbertgao/pi-subagents/src/index.ts +83 -34
  30. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +18 -0
  31. package/node_modules/@herbertgao/pi-subagents/src/types.ts +10 -0
  32. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-tree.ts +47 -0
  33. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +7 -5
  34. package/node_modules/@herbertgao/pi-subagents/src/ui/fleet-list.ts +211 -47
  35. package/node_modules/@narumitw/pi-btw/CHANGELOG.md +7 -0
  36. package/node_modules/@narumitw/pi-btw/package.json +2 -2
  37. package/node_modules/@narumitw/pi-caffeinate/CHANGELOG.md +7 -0
  38. package/node_modules/@narumitw/pi-caffeinate/package.json +3 -3
  39. package/node_modules/pi-commandcode-provider/CHANGELOG.md +5 -0
  40. package/node_modules/pi-commandcode-provider/package.json +1 -1
  41. package/node_modules/pi-commandcode-provider/src/pricing.ts +4 -4
  42. package/package.json +7 -7
@@ -19,7 +19,7 @@ import { existsSync } from "node:fs";
19
19
  import { homedir } from "node:os";
20
20
  import { join } from "node:path";
21
21
  import { pathToFileURL } from "node:url";
22
- import { config } from "../../config/config.ts";
22
+ import { config, type FooterContextLimit } from "../../config/config.ts";
23
23
  import { stripAnsi } from "../../utils/ansi-text.ts";
24
24
  import { formatFooterCost } from "./footer-currency.ts";
25
25
  import { formatTokenCount } from "../../utils/format.ts";
@@ -47,6 +47,105 @@ import { currentTtftMs, displayTokenRate, formatTokenRate } from "./token-rate.t
47
47
 
48
48
  export { parseGitStats } from "./git-stats.ts";
49
49
 
50
+ // Pi's built-in compaction.reserveTokens default (pi-coding-agent settings defaults).
51
+ const PI_DEFAULT_COMPACTION_RESERVE_TOKENS = 16_384;
52
+ /** How long a cached compaction limit is reused before settings are read again. */
53
+ export const COMPACTION_LIMIT_REFRESH_MS = 30_000;
54
+
55
+ type CompactionSettingsView = {
56
+ compaction?: {
57
+ enabled?: unknown;
58
+ reserveTokens?: unknown;
59
+ modelOverrides?: Record<string, unknown>;
60
+ };
61
+ };
62
+
63
+ type ModelRef = { provider?: string; id?: string } | undefined;
64
+
65
+ /** A reserve value Pi accepts: a non-negative safe integer; anything else is ignored. */
66
+ function validReserveTokens(value: unknown): number | undefined {
67
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
68
+ }
69
+
70
+ /**
71
+ * Token count at which Pi auto-compacts: it compacts once context tokens exceed
72
+ * contextWindow − reserveTokens, resolving reserveTokens as model override, then
73
+ * compaction.reserveTokens, then Pi's default. Undefined when auto-compaction is
74
+ * off or the window is unknown or not larger than the reserve.
75
+ *
76
+ * Mirrors Pi's SettingsManager.getCompactionSettings and shouldCompact, which
77
+ * extensions cannot call; update this copy when those change. Where Pi throws on
78
+ * an invalid reserve value, this skips it and falls through to the next level.
79
+ */
80
+ export function compactionLimitTokens(
81
+ contextWindow: number,
82
+ settings: CompactionSettingsView | undefined,
83
+ model: ModelRef,
84
+ ): number | undefined {
85
+ const compaction = settings?.compaction;
86
+ if (!(compaction?.enabled ?? true) || !(contextWindow > 0)) return undefined;
87
+ const override = model
88
+ ? compaction?.modelOverrides?.[`${model.provider}/${model.id}`]
89
+ : undefined;
90
+ const overrideReserve =
91
+ typeof override === "object" && override !== null
92
+ ? validReserveTokens((override as { reserveTokens?: unknown }).reserveTokens)
93
+ : undefined;
94
+ const reserve =
95
+ overrideReserve ??
96
+ validReserveTokens(compaction?.reserveTokens) ??
97
+ PI_DEFAULT_COMPACTION_RESERVE_TOKENS;
98
+ const limit = contextWindow - reserve;
99
+ return limit > 0 ? limit : undefined;
100
+ }
101
+
102
+ /**
103
+ * Caches compactionLimitTokens per model (provider/id) and context window, so a footer
104
+ * render does not read settings each frame (Pi's getSettings deep-copies them). The
105
+ * limit is recomputed when the model or window changes, or after
106
+ * COMPACTION_LIMIT_REFRESH_MS, which picks up settings edits.
107
+ */
108
+ export function createCompactionLimitCache(
109
+ readSettings: () => CompactionSettingsView | undefined,
110
+ now: () => number = Date.now,
111
+ ): (contextWindow: number, model: ModelRef) => number | undefined {
112
+ let cached: { key: string; limit: number | undefined; readAt: number } | undefined;
113
+ return (contextWindow, model) => {
114
+ const key = `${model?.provider}/${model?.id}@${contextWindow}`;
115
+ const time = now();
116
+ if (cached?.key !== key || time - cached.readAt >= COMPACTION_LIMIT_REFRESH_MS) {
117
+ cached = {
118
+ key,
119
+ limit: compactionLimitTokens(contextWindow, readSettings(), model),
120
+ readAt: time,
121
+ };
122
+ }
123
+ return cached.limit;
124
+ };
125
+ }
126
+
127
+ /**
128
+ * Percent and denominator label of the context chip. "window" keeps Pi's figures;
129
+ * "compaction" measures against the compaction point; "both" also shows the window in
130
+ * brackets. Without a compaction point every mode falls back to the window.
131
+ */
132
+ export function contextChipFigures(
133
+ usage: { tokens: number | null; contextWindow: number; percent: number | null },
134
+ compactionLimit: number | undefined,
135
+ mode: FooterContextLimit,
136
+ ): { percent: number | null; limitLabel: string } {
137
+ const windowLabel = formatTokenCount(usage.contextWindow);
138
+ if (mode === "window" || compactionLimit === undefined) {
139
+ return { percent: usage.percent, limitLabel: windowLabel };
140
+ }
141
+ const percent = usage.tokens === null ? null : (usage.tokens * 100) / compactionLimit;
142
+ const compactionLabel = formatTokenCount(compactionLimit);
143
+ return {
144
+ percent,
145
+ limitLabel: mode === "both" ? `${compactionLabel} (${windowLabel})` : compactionLabel,
146
+ };
147
+ }
148
+
50
149
  const GIT_REFRESH_INTERVAL_MS = 10_000;
51
150
  const USAGE_REFRESH_INTERVAL_MS = 5 * 60 * 1000;
52
151
  // 后台连接 MCP 服务器不会触发 footer 重绘,靠这个兜底轮询把芯片刷出来
@@ -250,7 +349,8 @@ export function refreshFooterGitStats(): void {
250
349
  let refreshCurrentUsage: (() => void) | undefined;
251
350
  let refreshCurrentMcpChip: (() => void) | undefined;
252
351
  /** 工具/命令列表在 pi API 上,而 footer 工厂只拿得到 ctx,加载时记下来。 */
253
- let extensionApi: Pick<ExtensionAPI, "getAllTools" | "getCommands"> | undefined;
352
+ let extensionApi: Pick<ExtensionAPI, "getAllTools" | "getCommands" | "getSettings"> | undefined;
353
+ const cachedCompactionLimit = createCompactionLimitCache(() => extensionApi?.getSettings?.());
254
354
 
255
355
  const createCustomFooterFactory =
256
356
  (ctx: ExtensionContext) => (tui: any, theme: any, footerData: any) => {
@@ -376,8 +476,6 @@ const createCustomFooterFactory =
376
476
  tui.requestRender();
377
477
  });
378
478
 
379
- const fmt = formatTokenCount;
380
-
381
479
  // ---- pi-cc-status 风格:上下文条形图 ----
382
480
  const BAR_WIDTH = 10;
383
481
  const BAR_WARNING = 80; // >= 80% 转 warning 色
@@ -458,7 +556,18 @@ const createCustomFooterFactory =
458
556
  const model = ctx.model;
459
557
  const { contextUsage, cost, tokens, cachePct } = sessionStats();
460
558
  const contextWindow = contextUsage?.contextWindow ?? model?.contextWindow ?? 0;
461
- const percent = contextUsage?.percent;
559
+ const contextFigures = contextChipFigures(
560
+ {
561
+ tokens: contextUsage?.tokens ?? null,
562
+ contextWindow,
563
+ percent: contextUsage?.percent ?? null,
564
+ },
565
+ config.footerContextLimit === "window"
566
+ ? undefined
567
+ : cachedCompactionLimit(contextWindow, model),
568
+ config.footerContextLimit,
569
+ );
570
+ const percent = contextFigures.percent;
462
571
 
463
572
  // cwd 默认只显示最底层路径(根目录时回退完整路径)
464
573
  const cwdLabel = ctx.cwd.split(/[\\/]/).filter(Boolean).pop() || ctx.cwd;
@@ -538,7 +647,7 @@ const createCustomFooterFactory =
538
647
  ],
539
648
  [
540
649
  FOOTER_CONTEXT_KEY,
541
- barGauge(percent ?? 0) + theme.fg("dim", ` ${pctLabel}/${fmt(contextWindow)}`),
650
+ barGauge(percent ?? 0) + theme.fg("dim", ` ${pctLabel}/${contextFigures.limitLabel}`),
542
651
  ],
543
652
  [FOOTER_CACHE_KEY, cacheLabel ? theme.fg("dim", cacheLabel) : ""],
544
653
  [FOOTER_RATE_KEY, rateLabel ? theme.fg("dim", rateLabel) : ""],
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import { CustomEditor, type ExtensionContext } from "@earendil-works/pi-coding-agent";
17
17
  import { config } from "../../config/config.ts";
18
+ import { setInjectedKeybindings } from "../../utils/keybindings.ts";
18
19
 
19
20
  /** `❯ ` 固定 2 列:glyph + 尾随空格。 */
20
21
  const PROMPT_GLYPH = "❯";
@@ -52,12 +53,28 @@ export class PromptEditor extends CustomEditor {
52
53
 
53
54
  type EditorFactory = Parameters<ExtensionContext["ui"]["setEditorComponent"]>[0];
54
55
 
55
- const promptEditorFactory: EditorFactory = (tui, theme, keybindings) =>
56
- new PromptEditor(tui, theme, keybindings, { embedWorkingStatus: true });
56
+ const promptEditorFactory: EditorFactory = (tui, theme, keybindings) => {
57
+ // pi 把用户的 KeybindingsManager 注进来,顺带作为全扩展的按键提示取源。
58
+ setInjectedKeybindings(keybindings);
59
+ return new PromptEditor(tui, theme, keybindings, { embedWorkingStatus: true });
60
+ };
57
61
 
58
62
  /** 是否正占着插槽;占据前的工厂用于原样还回去。 */
59
63
  let active = false;
60
64
  let previousEditorFactory: EditorFactory | undefined;
65
+ /**
66
+ * 对话框还开着时,强制卸载只是把还原排进队列,插槽看起来仍是本扩展的工厂。
67
+ * 记下这件事,好让同一次面板里再打开时能盖过这个排队,并仍还回原来的工厂。
68
+ */
69
+ let releasePending = false;
70
+
71
+ /** 排队的还原已经落到插槽上时,丢掉这次等待,避免下一轮安装沿用过期工厂。 */
72
+ function noteLandedRelease(ctx: ExtensionContext): void {
73
+ if (!releasePending) return;
74
+ if (ctx.ui.getEditorComponent?.() === promptEditorFactory) return;
75
+ releasePending = false;
76
+ previousEditorFactory = undefined;
77
+ }
61
78
 
62
79
  /**
63
80
  * 撤销本扩展占据的插槽;从未占用就不碰插槽。
@@ -68,39 +85,54 @@ let previousEditorFactory: EditorFactory | undefined;
68
85
  *
69
86
  * 例外:插槽被 pi 重置回占据前的工厂时(/new、/reload 走 resetExtensionUI),
70
87
  * 我们已经不在槽里,再写一次会把 pi 刚重置的结果又覆盖掉;此时只清状态。
88
+ * 用户主动改设置时传 force:pi 1.5 会把对话框开着时的替换排队到关闭后落地,
89
+ * 期间 getEditorComponent() 仍是旧工厂,无法据此判断要不要还回去。
90
+ * 强制卸载先留着占据前的工厂:同一次对话框里再打开时,插槽还没变,不能把
91
+ * 仍显示着的本扩展工厂当成要还回去的那一个。
71
92
  */
72
- function releasePromptEditor(ctx: ExtensionContext): void {
93
+ function releasePromptEditor(ctx: ExtensionContext, force = false): void {
94
+ noteLandedRelease(ctx);
73
95
  if (!active) return;
74
96
  const previous = previousEditorFactory;
97
+ if (!force && ctx.ui.getEditorComponent?.() === previous) {
98
+ active = false;
99
+ previousEditorFactory = undefined;
100
+ releasePending = false;
101
+ return;
102
+ }
75
103
  active = false;
76
- previousEditorFactory = undefined;
77
- if (ctx.ui.getEditorComponent?.() === previous) return;
104
+ releasePending = force;
105
+ if (!force) previousEditorFactory = undefined;
78
106
  ctx.ui.setEditorComponent(previous);
79
107
  }
80
108
 
81
109
  /**
82
110
  * 应用输入框前缀;enableEditorPrefix=false 时只撤自己装的那层。
83
111
  *
84
- * 只在没有扩展对话框开着时调用:pi 的 setEditorComponent 会清空 editorContainer 并
85
- * 抢走焦点,把正在设置面板里的对话框踢出渲染树,对话框的 done() 再也走不到,
86
- * `ctx.ui.custom()` 的 Promise 永不落定,后续输入全部卡死。设置面板自己不做替换,
87
- * 等 `ctx.ui.custom()` 返回后再调本函数。
112
+ * 面板开着时也能直接替换:pi 1.5.0 起 setEditorComponent 不会再把现有对话框踢出渲染树,
113
+ * 新编辑器等对话框关闭后才出现(issue #11431);早于该版本时 `ctx.ui.custom()` 的 Promise
114
+ * 会永不落定,只能在面板关闭后再调用。
88
115
  *
89
116
  * 插槽已经装着本扩展的编辑器时直接返回:重复安装只会重建实例,丢掉撤销栈、
90
117
  * 历史等编辑器状态,还会打断其他扩展包在外层的编辑器。
91
118
  */
92
- export function applyPromptEditor(ctx: ExtensionContext): void {
119
+ export function applyPromptEditor(ctx: ExtensionContext, options?: { force?: boolean }): void {
93
120
  if (!ctx?.hasUI || typeof ctx.ui?.setEditorComponent !== "function") return;
121
+ noteLandedRelease(ctx);
94
122
  if (!config.enableEditorPrefix) {
95
- releasePromptEditor(ctx);
123
+ releasePromptEditor(ctx, options?.force);
96
124
  return;
97
125
  }
98
126
  const current = ctx.ui.getEditorComponent?.();
99
- if (current === promptEditorFactory) return;
127
+ // 插槽已经是本扩展的工厂时不重建,除非刚刚的强制卸载还排在对话框关闭之后。
128
+ // 那种情况下 getEditorComponent() 仍是旧工厂,不盖过队列的话,关闭后面板会执行卸载。
129
+ if (current === promptEditorFactory && !(options?.force && releasePending)) return;
100
130
  try {
101
131
  // pi 的插槽是硬替换、没有栈,先记住是谁占着,撤销时还回去。
102
- previousEditorFactory = current;
132
+ // 强制卸载还没落地时,看得见的工厂仍是我们自己,要还回去的是卸载时留着的那个。
133
+ if (!releasePending) previousEditorFactory = current;
103
134
  active = true;
135
+ releasePending = false;
104
136
  ctx.ui.setEditorComponent(promptEditorFactory);
105
137
  } catch (err) {
106
138
  ctx.ui.notify(
@@ -111,7 +143,7 @@ export function applyPromptEditor(ctx: ExtensionContext): void {
111
143
  }
112
144
 
113
145
  /** 恢复本扩展占据前的编辑器;未占用时不动作。 */
114
- export function clearPromptEditor(ctx: ExtensionContext): void {
146
+ export function clearPromptEditor(ctx: ExtensionContext, options?: { force?: boolean }): void {
115
147
  if (!ctx?.hasUI || typeof ctx.ui?.setEditorComponent !== "function") return;
116
- releasePromptEditor(ctx);
148
+ releasePromptEditor(ctx, options?.force);
117
149
  }
@@ -1,7 +1,7 @@
1
1
  import { InteractiveMode, VERSION, type AppKeybinding } from "@earendil-works/pi-coding-agent";
2
- import { getKeybindings } from "@earendil-works/pi-tui";
3
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
3
  import { config } from "../../config/config.ts";
4
+ import { formatKeyText, keyText, setInjectedKeybindings } from "../../utils/keybindings.ts";
5
5
  import { ansi16ToRgb, ansi256ToRgb } from "../../utils/ansi-color.ts";
6
6
  import { stripAnsi } from "../../utils/ansi-text.ts";
7
7
  import {
@@ -187,23 +187,6 @@ function renderLogoLines(width: number, palette: Rgb[]): string[] {
187
187
 
188
188
  // ---- 右侧:原生默认 header 文本(对齐 pi 内置 startup header,按键文本随用户 keybindings 动态渲染) ----
189
189
 
190
- function formatKeyPart(part: string): string {
191
- // 与 pi 内置 keybinding-hints 一致:macOS 上 alt 显示为 option
192
- return process.platform === "darwin" && part.toLowerCase() === "alt" ? "option" : part;
193
- }
194
-
195
- function formatKeyText(key: string): string {
196
- return key
197
- .split("/")
198
- .map((part) => part.split("+").map(formatKeyPart).join("+"))
199
- .join("/");
200
- }
201
-
202
- function keyText(keybinding: AppKeybinding): string {
203
- const keys = getKeybindings().getKeys(keybinding);
204
- return keys.length === 0 ? "" : formatKeyText(keys.join("/"));
205
- }
206
-
207
190
  function renderNativeLines(theme: {
208
191
  fg(name: string, text: string): string;
209
192
  bold(text: string): string;
@@ -336,6 +319,8 @@ export function installEarlyStartupHeader(): void {
336
319
  active: true,
337
320
  original,
338
321
  installed: async function (this: any, ...args: any[]) {
322
+ // 从这里拿到 pi 注入的按键管理器,启动头与工具卡的按键提示都按它显示。
323
+ setInjectedKeybindings(this?.keybindings);
339
324
  installHeaderContainerSwap(this, patch);
340
325
  return original.apply(this, args);
341
326
  },
@@ -75,6 +75,8 @@ import { formatDisplayPath } from "./tool/names.ts";
75
75
  import {
76
76
  contentRowRange,
77
77
  hasVisibleText,
78
+ imageBlockRows,
79
+ type ImageRowKind,
78
80
  removeStyledRange,
79
81
  stripBackgroundAnsi,
80
82
  stripTerminalSequencesPreservingLayout,
@@ -410,7 +412,17 @@ function layoutExpandedToolCard(
410
412
  let lastBlank = false;
411
413
  /** live 首行被吃掉的前导缩进:续行同步左移同样格数,保持块内相对对齐。 */
412
414
  let liveLead = 0;
413
- const pushRow = (raw: string) => {
415
+ const pushRow = (raw: string, imageKind?: ImageRowKind) => {
416
+ // 内联图片:锚点行原样输出(live 只补 `↳`),占位行保持零宽。
417
+ // 补底色/缩进会让 pi-tui 认不出整块图片,占位行会当成普通行盖在图片上。
418
+ if (imageKind) {
419
+ if (imageKind === "filler") {
420
+ lines.push("");
421
+ return;
422
+ }
423
+ lines.push(live ? `${theme.fg("muted", "↳")} ${raw}` : raw);
424
+ return;
425
+ }
414
426
  if (!live) {
415
427
  // 面板 pad 1 是唯一左边距:剥掉子行 collapsed 态自带的 1 格 lead,
416
428
  // 否则标题行偏到 2、↳ 行偏到 4,左右不再对称。
@@ -457,12 +469,14 @@ function layoutExpandedToolCard(
457
469
  if (!innerCard) pushBlank();
458
470
  const rangeStart = lines.length;
459
471
  // 展开的 thinking 走深色内卡(上下各 1 行 padding),工具卡直接铺在外卡上。
460
- const paintRow = innerCard
461
- ? (line: string) => lines.push(toolCardBgRow(theme, slot, toolBgAnsi, line, width))
462
- : pushRow;
463
- if (innerCard) paintRow("");
464
- for (let i = first; i <= last; i++) paintRow(childLines[i]);
465
- if (innerCard) paintRow("");
472
+ const imageKinds = innerCard ? undefined : imageBlockRows(childLines);
473
+ const paintChild = (line: string, index?: number) =>
474
+ innerCard
475
+ ? lines.push(toolCardBgRow(theme, slot, toolBgAnsi, line, width))
476
+ : pushRow(line, index === undefined ? undefined : imageKinds?.get(index));
477
+ if (innerCard) paintChild("");
478
+ for (let i = first; i <= last; i++) paintChild(childLines[i], i);
479
+ if (innerCard) paintChild("");
466
480
  // 内卡的下 padding 不能当分隔:后面的子卡要再留 1 行外卡空行。
467
481
  lastBlank = false;
468
482
  // thinking 命中自身;工具在展开卡内需要能二次展开时才映射回 tool 组件。
@@ -1104,7 +1118,12 @@ function compactLiveSlot(card: any, pad = 0): any {
1104
1118
  return {
1105
1119
  render(width: number): string[] {
1106
1120
  const indent = " ".repeat(Math.max(0, pad));
1107
- return card.render(innerOf(width)).map((line: string) => `${indent}${line}`);
1121
+ const lines = card.render(innerOf(width));
1122
+ const images = imageBlockRows(lines);
1123
+ // 图片占位行必须零宽:补上缩进空格,pi-tui 就认不出整块图片了。
1124
+ return lines.map((line: string, index: number) =>
1125
+ images.get(index) === "filler" ? "" : `${indent}${line}`,
1126
+ );
1108
1127
  },
1109
1128
  childAtRow(localRow: number, width: number) {
1110
1129
  return card.childAtRow?.(localRow, innerOf(width)) ?? null;
@@ -14,6 +14,7 @@ import {
14
14
  TOOL_EXPANDED_BACKGROUND_PATCH,
15
15
  } from "../utils/patch-keys.ts";
16
16
  import { isToolCallHovered } from "./mouse/hover.ts";
17
+ import { setInjectedKeyText } from "../utils/keybindings.ts";
17
18
  import { isLiveToolCall, toolCardBgSlot } from "./tool/tool-state.ts";
18
19
  import { getMessageDisplayTheme } from "./tool/message-display.ts";
19
20
  import { createCcstyleTool } from "./tool/ccstyle-tool.ts";
@@ -286,9 +287,13 @@ function installGlobalToolRendering(
286
287
  prototype.getCallRenderer = patch.installed.getCallRenderer;
287
288
  prototype.getResultRenderer = patch.installed.getResultRenderer;
288
289
  // 渲染上下文没有 result。ask_user_question 的标题要报问题数,只能从这里补。
290
+ // 同时记下 pi 注入的 keyText:工具卡上的展开提示按它显示。
289
291
  patch.getRenderContext = function (this: any, ...args: any[]) {
290
292
  const context = originalGetRenderContext.apply(this, args);
291
- if (context && typeof context === "object") context.result = this.result;
293
+ if (context && typeof context === "object") {
294
+ context.result = this.result;
295
+ setInjectedKeyText(context.keyText);
296
+ }
292
297
  return context;
293
298
  };
294
299
  prototype.getRenderContext = patch.getRenderContext;
@@ -1,13 +1,14 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { render as renderMermaid, sourceBox } from "grok-mermaid";
2
+ import { diagramKind, render as renderMermaid, sourceBox } from "grok-mermaid";
3
3
 
4
4
  // ============================================================================
5
5
  // Mermaid 方言渲染
6
6
  // ============================================================================
7
7
 
8
- // 内置 mermaid transformer 只认 ```mermaid,这里补上 grok-mermaid 支持的其他方言
8
+ // 标准 ```mermaid 交给 Pi 内置渲染器(1.5.1 起支持饼图、自定义样式、可点击标签,
9
+ // 也会画在展开的 summary 里);这里只补 grok-mermaid 才认的方言 fence。
9
10
  const DIAGRAM_FENCE =
10
- /^(`{3,})\s*(mermaid|statediagram|statediagram-v2|classdiagram|classdiagram-v2|erdiagram|sequencediagram)\s*$/i;
11
+ /^(`{3,})\s*(statediagram|statediagram-v2|classdiagram|classdiagram-v2|erdiagram|sequencediagram)\s*$/i;
11
12
  const FENCE_OPEN = /^(`{3,})/;
12
13
  const FENCE_CLOSE = /^`{3,}\s*$/;
13
14
 
@@ -144,17 +145,29 @@ export default function (pi: ExtensionAPI): void {
144
145
  // 所以剩下的转换合并为一次注册,内部按序链式执行。
145
146
  // 提示框和裸 URL 不接管:pi 的 marked 已自带裸 URL 链接化(带尾标点回退,
146
147
  // 且在链接文本内不再嵌套),提示框交给默认引用块风格。
147
- pi.registerMarkdownTransformer((markdown, context) => {
148
- const { messageType, isStreaming = false } = context ?? {};
149
- // thinking 保持原文;普通回复即使流式中也先关闭跨行链接的空白点击区。
150
- if (messageType === "assistant-thinking") return markdown;
151
- markdown = normalizeMultilineLinks(markdown);
152
- if (isStreaming) return markdown;
153
- // 0. 圈数字转半角括号(Nerd Font 补丁字形缺陷规避)
154
- markdown = deCircled(markdown);
155
- // 1. Mermaid 方言渲染
156
- return renderDiagrams(markdown, context);
157
- });
148
+ // messageTypes:除默认的 user/assistant/thinking,再跟上自定义消息与展开的 summary,
149
+ // 免得圈数字、方言图在那两处变回原样。
150
+ // Pi 1.5.1 起第二个参数才进类型。工作区仍对照 1.5.0 做类型检查:1.5.2 的
151
+ // 信任锁在 Vitest 假时钟下会空转,所以不把锁文件抬到 1.5.2。运行时照样把
152
+ // options 传下去,1.5.1+ 的宿主会用,1.5.0 会忽略。
153
+ const registerMarkdownTransformer = pi.registerMarkdownTransformer as (
154
+ transformer: Parameters<ExtensionAPI["registerMarkdownTransformer"]>[0],
155
+ options?: { messageTypes?: readonly string[] },
156
+ ) => void;
157
+ registerMarkdownTransformer(
158
+ (markdown, context) => {
159
+ const { messageType, isStreaming = false } = context ?? {};
160
+ // thinking 保持原文;普通回复即使流式中也先关闭跨行链接的空白点击区。
161
+ if (messageType === "assistant-thinking") return markdown;
162
+ markdown = normalizeMultilineLinks(markdown);
163
+ if (isStreaming) return markdown;
164
+ // 0. 圈数字转半角括号(Nerd Font 补丁字形缺陷规避)
165
+ markdown = deCircled(markdown);
166
+ // 1. Mermaid 方言渲染
167
+ return renderDiagrams(markdown, context);
168
+ },
169
+ { messageTypes: ["user", "assistant", "assistant-thinking", "custom", "summary"] },
170
+ );
158
171
  }
159
172
 
160
173
  // grok-mermaid 渲染结果缓存:resize/restored 重绘会重复转换,按源码缓存 art。
@@ -194,9 +207,9 @@ function renderDiagrams(
194
207
  const collected = collectFence(lines, i);
195
208
  if (collected) {
196
209
  const { diagram, next } = collected;
197
- // grok-mermaid 需要源码自带类型头,方言头在 fence 标签里时补回去
198
- const label = fence[2];
199
- const src = label.toLowerCase() === "mermaid" ? diagram : `${label}\n${diagram}`;
210
+ // grok-mermaid 需要源码自带类型头:fence 名当类型头补上;正文已带头就别再补,
211
+ // 重复头会解析失败退成源码框,或者把类型头画成一个节点
212
+ const src = diagramKind(diagram) ? diagram : `${fence[2]}\n${diagram}`;
200
213
  const art = getArt(src);
201
214
  const width = availableWidth ?? 80;
202
215
  if (art && art.width <= width) {
@@ -1,12 +1,7 @@
1
- import {
2
- getKeybindings,
3
- matchesKey,
4
- truncateToWidth,
5
- visibleWidth,
6
- type Keybinding,
7
- } from "@earendil-works/pi-tui";
1
+ import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
8
2
  import { config } from "../../config/config.ts";
9
3
  import { isLazyProxyTui } from "../../utils/fullscreen-detect.ts";
4
+ import { keyDisplayText, keybindings } from "../../utils/keybindings.ts";
10
5
  import { parseSgrMousePackets } from "./packets.ts";
11
6
  import {
12
7
  OFFICIAL_SCROLL_TO_END_KEY,
@@ -204,19 +199,7 @@ export function isFullscreenAtBottom(tui: any): boolean {
204
199
 
205
200
  /** 与 Pi 原生浮层同源(keyDisplayText):用户实际绑定,首字母大写,macOS 上 alt 显示为 option。 */
206
201
  function scrollBottomShortcutText(): string {
207
- return getKeybindings()
208
- .getKeys(SCROLL_BOTTOM_KEYBINDING)
209
- .map((key) =>
210
- key
211
- .split("+")
212
- .map((part) => {
213
- const display =
214
- process.platform === "darwin" && part.toLowerCase() === "alt" ? "option" : part;
215
- return display.charAt(0).toUpperCase() + display.slice(1);
216
- })
217
- .join("+"),
218
- )
219
- .join("/");
202
+ return keyDisplayText(SCROLL_BOTTOM_KEYBINDING);
220
203
  }
221
204
 
222
205
  function isScrollNavigationInput(data: string): boolean {
@@ -235,7 +218,7 @@ function isScrollNavigationInput(data: string): boolean {
235
218
  "tui.altScreen.nextPrompt",
236
219
  "tui.altScreen.top",
237
220
  "tui.altScreen.bottom",
238
- ].some((key) => getKeybindings().matches(data, key as Keybinding))
221
+ ].some((key) => keybindings().matches(data, key))
239
222
  ) {
240
223
  return true;
241
224
  }
@@ -27,6 +27,7 @@ import { collapseHintText, isToolTuiFullscreen, showMoreHintText } from "./names
27
27
  import {
28
28
  contentRowRange,
29
29
  hasVisibleText,
30
+ imageBlockRows,
30
31
  imagePlacement,
31
32
  stripAnsi,
32
33
  stripBackgroundAnsi,
@@ -673,11 +674,23 @@ export class ToolGroupComponent extends Container {
673
674
  const branch = last ? "└" : "├";
674
675
  const continuation = last ? " " : "│ ";
675
676
  const rows = panelRows(itemPaints[index], last);
677
+ const imageRows = imageBlockRows(rows);
676
678
  for (let lineIndex = 0; lineIndex < rows.length; lineIndex++) {
677
679
  const prefix =
678
680
  lineIndex === 0
679
681
  ? `${fg("dim", branch)} ${fg(color, statusIcon(item.status))} `
680
682
  : fg("dim", continuation);
683
+ const imageKind = imageRows.get(lineIndex);
684
+ // 图片占位行必须零宽:补空格/底色会盖住图片,pi-tui 也认不出整块图片。
685
+ if (imageKind === "filler") {
686
+ lines.push("");
687
+ continue;
688
+ }
689
+ // 锚点行只带树枝前缀:行尾补的底色空格会画在图片首行上。
690
+ if (imageKind === "anchor") {
691
+ lines.push(prefix + rows[lineIndex]);
692
+ continue;
693
+ }
681
694
  lines.push(paddedBackgroundRow(theme, backgroundSlot, prefix + rows[lineIndex], width));
682
695
  }
683
696
  }
@@ -1,6 +1,7 @@
1
1
  import { posix, win32 } from "node:path";
2
2
  import type { ThemeColor } from "@earendil-works/pi-coding-agent";
3
- import { getKeybindings, visibleWidth } from "@earendil-works/pi-tui";
3
+ import { visibleWidth } from "@earendil-works/pi-tui";
4
+ import { keyText } from "../../utils/keybindings.ts";
4
5
  import { config } from "../../config/config.ts";
5
6
  import { oneLine } from "../../utils/format.ts";
6
7
  import { headTruncateToWidth } from "./result.ts";
@@ -445,20 +446,9 @@ export function isToolTuiFullscreen(): boolean {
445
446
  return toolTuiFullscreen !== false;
446
447
  }
447
448
 
448
- function formatKeyPart(part: string): string {
449
- // 与 pi 内置 keybinding-hints 一致:macOS 上 alt 显示为 option
450
- return process.platform === "darwin" && part.toLowerCase() === "alt" ? "option" : part;
451
- }
452
-
453
449
  /** 默认展开快捷键(app.tools.expand)显示文本;未配置时回退 ctrl+o。 */
454
450
  export function expandShortcutText(): string {
455
- const keys = getKeybindings().getKeys("app.tools.expand");
456
- if (keys.length === 0) return "ctrl+o";
457
- return keys
458
- .join("/")
459
- .split("/")
460
- .map((part) => part.split("+").map(formatKeyPart).join("+"))
461
- .join("/");
451
+ return keyText("app.tools.expand") || "ctrl+o";
462
452
  }
463
453
 
464
454
  export function showMoreHintText(): string {