@each1024/pi-mini-mode 2.0.20 → 2.0.21

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.
@@ -15,6 +15,8 @@ import { addUsage, cacheWaste, EMPTY_USAGE, finiteNumber, formatSpeed, sessionUs
15
15
  import { statusLine } from "../lib/footer-line.ts";
16
16
  import { contentText, minimalTurnsFromBranch, processText, pushProcess, skillNames, type MinimalTurn } from "../lib/minimal-turns.ts";
17
17
  import { minimalOutputComponent } from "../lib/minimal-output.ts";
18
+ import { createDecisionDock, extractDecisionPrompt } from "../lib/decision-dock.ts";
19
+ import { appendTriageGuidance, isBadgeStyle } from "../lib/semantic-badges.ts";
18
20
  import { createThinkingStream } from "../lib/thinking-stream.ts";
19
21
  import { PACKAGE_VERSION, isNewerVersion } from "../lib/update-banner.ts";
20
22
 
@@ -26,6 +28,8 @@ export { SPEED_REFRESH_MS } from "../lib/token-speed.ts";
26
28
  export { isPlannotatorPlanningStatus, planCapsule, settingsPreviewLine, statusLine } from "../lib/footer-line.ts";
27
29
  export { formatElapsed, formatToolElapsed, formatThinkingElapsed, minimalTurnsFromBranch, type MinimalTurn, type ThinkingClock } from "../lib/minimal-turns.ts";
28
30
  export { minimalOutputComponent } from "../lib/minimal-output.ts";
31
+ export { isBadgeStyle, parseSemanticBadge, renderSemanticBadge, transformSemanticBadges, appendTriageGuidance, type BadgeStyle, type BadgeTone } from "../lib/semantic-badges.ts";
32
+ export { extractDecisionPrompt, createDecisionDock, type DecisionChoice, type DecisionPrompt } from "../lib/decision-dock.ts";
29
33
  export { PACKAGE_VERSION, UPDATE_RELEASE_DATE, isNewerVersion, renderUpdateBanner } from "../lib/update-banner.ts";
30
34
 
31
35
  /** Pi /model and other selectors own Ctrl+S; the editor exposes getText. */
@@ -87,6 +91,7 @@ export default function (pi: ExtensionAPI) {
87
91
  let speedTimer: ReturnType<typeof setInterval> | undefined;
88
92
  let settings: MiniLensSettings = { ...DEFAULT_SETTINGS };
89
93
  let cleanupInputEnhancements: InputEnhancementsCleanup | undefined;
94
+ let liveCtx: ExtensionContext | undefined;
90
95
  let messageCwd = process.cwd();
91
96
  const messageLinks = (text: string) => settings["pi-mini-mode-input-enhancements"] ? linkMessageFiles(text, messageCwd) : text;
92
97
  pi.registerMarkdownTransformer?.(messageLinks);
@@ -99,7 +104,22 @@ export default function (pi: ExtensionAPI) {
99
104
 
100
105
  const refresh = () => refreshFooter?.();
101
106
  const refreshMinimalOutput = () => refreshMinimal?.();
107
+ const decisionDock = createDecisionDock({
108
+ language: () => uiLanguage(settings),
109
+ isEditorEmpty: () => (liveCtx?.ui.getEditorText?.() ?? "").trim() === "",
110
+ onSubmit: (replyText) => pi.sendUserMessage?.(replyText),
111
+ requestRender: () => refreshMinimalOutput(),
112
+ });
113
+ const syncDecisionDock = () => {
114
+ const lastTurn = minimalTurns.at(-1);
115
+ const enabled = settings["pi-mini-mode-minimal-show"] && settings["pi-mini-mode-semantic-badges"] && !nativeOutput && liveCtx?.mode === "tui";
116
+ const prompt = enabled && !activeMinimalTurn?.running && lastTurn && !lastTurn.running
117
+ ? extractDecisionPrompt(lastTurn.final, minimalTurns.length - 1)
118
+ : undefined;
119
+ if (decisionDock.sync(prompt)) refreshMinimalOutput();
120
+ };
102
121
  const mountMinimalOutput = (ctx: ExtensionContext) => {
122
+ liveCtx = ctx;
103
123
  persistAgentStatuses = undefined;
104
124
  if (waitingTimer) clearInterval(waitingTimer);
105
125
  waitingTimer = undefined;
@@ -115,6 +135,15 @@ export default function (pi: ExtensionAPI) {
115
135
  const nativeKey = matchesKey(data, "ctrl+alt+o");
116
136
  const subAgentKey = matchesKey(data, "ctrl+s");
117
137
  if (!nativeKey && focusedSelectorOwnsKeys(minimalTui)) return;
138
+ if (!nativeKey && restoreTranscript && decisionDock.isActive) {
139
+ const dockNav = matchesKey(data, "escape")
140
+ || (((liveCtx?.ui.getEditorText?.() ?? "").trim() === "")
141
+ && (matchesKey(data, "up") || matchesKey(data, "down") || matchesKey(data, "enter") || matchesKey(data, "return")));
142
+ if (dockNav) {
143
+ if (isKeyRelease(data) || isKeyRepeat(data)) return { consume: true };
144
+ return decisionDock.handleTerminalInput(data);
145
+ }
146
+ }
118
147
  if (!nativeKey && (!restoreTranscript || (!subAgentKey && !matchesKey(data, "ctrl+o")))) return;
119
148
  // Input listeners run before Pi filters Kitty release/repeat events.
120
149
  if (isKeyRelease(data) || isKeyRepeat(data)) return { consume: true };
@@ -132,6 +161,8 @@ export default function (pi: ExtensionAPI) {
132
161
  if (nativeOutput || !settings["pi-mini-mode-minimal-show"] || ctx.mode !== "tui") {
133
162
  minimalTui = undefined;
134
163
  lastAttachMode = undefined;
164
+ decisionDock.sync(undefined);
165
+ ctx.ui.setWidget?.("pi-mini-mode-decision", undefined);
135
166
  ctx.ui.setWidget?.("pi-mini-mode-minimal-output", undefined);
136
167
  refreshMinimalOutput();
137
168
  refreshMinimal = undefined;
@@ -196,6 +227,10 @@ export default function (pi: ExtensionAPI) {
196
227
  },
197
228
  }
198
229
  : undefined,
230
+ semanticBadges: () => ({
231
+ enabled: settings["pi-mini-mode-semantic-badges"],
232
+ style: settings["pi-mini-mode-badge-style"],
233
+ }),
199
234
  }, () => settings["pi-mini-mode-minimal-record-limit"], () => uiLanguage(settings));
200
235
  // Native info notifications use dim; warning/error notifications retain
201
236
  // their position in the transcript. No plugin names or message matching.
@@ -274,6 +309,13 @@ export default function (pi: ExtensionAPI) {
274
309
  }, 100);
275
310
  waitingTimer.unref();
276
311
  }
312
+ if (restoreTranscript && settings["pi-mini-mode-semantic-badges"]) {
313
+ ctx.ui.setWidget?.("pi-mini-mode-decision", (_dockTui, dockTheme) => decisionDock.component(dockTheme), { placement: "aboveEditor" });
314
+ syncDecisionDock();
315
+ } else {
316
+ decisionDock.sync(undefined);
317
+ ctx.ui.setWidget?.("pi-mini-mode-decision", undefined);
318
+ }
277
319
  tui.requestRender();
278
320
  // Factory acquires the renderer only; never duplicate content in the dock.
279
321
  return { render: () => [], invalidate() {} };
@@ -372,6 +414,8 @@ export default function (pi: ExtensionAPI) {
372
414
  || entry.some(id => typeof id !== "string" || !(FOOTER_FIELDS as readonly string[]).includes(id))) throw new TypeError("Invalid order");
373
415
  } else if (key === "pi-mini-mode-image-preview") {
374
416
  if (entry !== "hover" && entry !== "inline") throw new TypeError("Invalid preview mode");
417
+ } else if (key === "pi-mini-mode-badge-style") {
418
+ if (!isBadgeStyle(entry)) throw new TypeError("Invalid badge style");
375
419
  } else if (key === "pi-mini-mode-minimal-record-limit") {
376
420
  if (!isRecordLimit(entry)) throw new TypeError("Invalid record limit");
377
421
  } else if (key === "pi-mini-mode-language") {
@@ -554,6 +598,7 @@ export default function (pi: ExtensionAPI) {
554
598
  minimalTurns = minimalTurnsFromBranch(ctx.sessionManager.getBranch());
555
599
  activeMinimalTurn = undefined;
556
600
  pendingMinimalFinal = "";
601
+ decisionDock.clearAll();
557
602
  thinkingStream.reset();
558
603
  minimalToolOutputIndices.clear();
559
604
  mountMinimalOutput(ctx);
@@ -567,9 +612,13 @@ export default function (pi: ExtensionAPI) {
567
612
  syncMinimalBranch(event, ctx);
568
613
  });
569
614
  pi.on("before_agent_start", (event) => {
570
- if (!activeMinimalTurn) return;
571
- for (const name of skillNames(event.prompt)) pushProcess(activeMinimalTurn, "skill", name);
572
- refreshMinimalOutput();
615
+ if (activeMinimalTurn) {
616
+ for (const name of skillNames(event.prompt)) pushProcess(activeMinimalTurn, "skill", name);
617
+ refreshMinimalOutput();
618
+ }
619
+ if (settings["pi-mini-mode-minimal-show"] && settings["pi-mini-mode-semantic-badges"] && !nativeOutput && typeof event.systemPrompt === "string" && event.systemPrompt) {
620
+ return { systemPrompt: appendTriageGuidance(event.systemPrompt) };
621
+ }
573
622
  });
574
623
  pi.on("ui_prompt_start", (event) => {
575
624
  activeUIPrompt = event;
@@ -583,6 +632,7 @@ export default function (pi: ExtensionAPI) {
583
632
  pi.on("thinking_level_select", refresh);
584
633
  pi.on("message_start", (event) => {
585
634
  if (event.message.role === "user") {
635
+ decisionDock.sync(undefined);
586
636
  if (activeMinimalTurn) {
587
637
  thinkingStream.stop(activeMinimalTurn, "aborted");
588
638
  activeMinimalTurn.final = pendingMinimalFinal;
@@ -762,11 +812,15 @@ export default function (pi: ExtensionAPI) {
762
812
  pendingMinimalFinal = "";
763
813
  thinkingStream.reset();
764
814
  minimalToolOutputIndices.clear();
815
+ syncDecisionDock();
765
816
  refreshMinimalOutput();
766
817
  });
767
818
  pi.on("session_shutdown", () => {
768
819
  thinkingStream.stop(activeMinimalTurn, "aborted");
769
820
  thinkingStream.reset();
821
+ decisionDock.clearAll();
822
+ liveCtx?.ui.setWidget?.("pi-mini-mode-decision", undefined);
823
+ liveCtx = undefined;
770
824
  restoreScrollbar?.();
771
825
  restoreScrollbar = undefined;
772
826
  scrollbarRoot = undefined;
@@ -0,0 +1,243 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { matchesKey, truncateToWidth, type Component, type TuiMouseEvent } from "@earendil-works/pi-tui";
3
+ import { stripVTControlCharacters } from "node:util";
4
+ import { isDecisionBadgeText, parseSemanticBadge } from "./semantic-badges.ts";
5
+ import type { UiLanguage } from "./settings.ts";
6
+
7
+ export interface DecisionChoice {
8
+ number: number;
9
+ label: string;
10
+ recommended: boolean;
11
+ }
12
+
13
+ export interface DecisionPrompt {
14
+ key: string;
15
+ choices: DecisionChoice[];
16
+ defaultIndex: number;
17
+ }
18
+
19
+ const DOCK_COPY: Record<UiLanguage, { title: string; nav: string; confirm: string; cancel: string; typeHint: string }> = {
20
+ zh: {
21
+ title: "选择处置方案(上下键或点击切换,回车发送)",
22
+ nav: "切换",
23
+ confirm: "确认",
24
+ cancel: "关闭",
25
+ typeHint: "直接打字可自由补充",
26
+ },
27
+ en: {
28
+ title: "Choose an option (Up/Down or click, Enter to send)",
29
+ nav: "navigate",
30
+ confirm: "select",
31
+ cancel: "dismiss",
32
+ typeHint: "or type freely below",
33
+ },
34
+ };
35
+
36
+ function stripFences(markdown: string): string {
37
+ const lines = markdown.split("\n");
38
+ const kept: string[] = [];
39
+ let fenceChar = "";
40
+ let fenceLen = 0;
41
+ for (const line of lines) {
42
+ const match = /^ {0,3}(`{3,}|~{3,})/.exec(line);
43
+ if (match) {
44
+ const marker = match[1];
45
+ if (!fenceChar) {
46
+ fenceChar = marker[0];
47
+ fenceLen = marker.length;
48
+ continue;
49
+ }
50
+ if (marker[0] === fenceChar && marker.length >= fenceLen && /^ {0,3}[`~]+[ \t]*$/.test(line)) {
51
+ fenceChar = "";
52
+ fenceLen = 0;
53
+ }
54
+ continue;
55
+ }
56
+ if (!fenceChar) kept.push(line);
57
+ }
58
+ return kept.join("\n");
59
+ }
60
+
61
+ function cleanOptionLine(raw: string): { label: string; recommended: boolean } {
62
+ let recommended = false;
63
+ let cleaned = stripVTControlCharacters(raw)
64
+ .replace(/`?(\[[^\]\r\n`]{1,32}\])`?/g, (full, bracketed: string) => {
65
+ const badge = parseSemanticBadge(bracketed);
66
+ if (!badge) return full;
67
+ if (badge.tone === "success" && /推荐|recommended|★/i.test(badge.label)) recommended = true;
68
+ return `[${badge.label}]`;
69
+ })
70
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
71
+ .replace(/(\*\*|__|~~|\*|`)/g, "")
72
+ .replace(/\s+/g, " ")
73
+ .trim();
74
+ if (/★|推荐|recommended/i.test(cleaned)) recommended = true;
75
+ cleaned = cleaned.replace(/^[-::—–\s]+/, "");
76
+ return { label: cleaned, recommended };
77
+ }
78
+
79
+ /** Extract a 2..5 numbered option group when the assistant reply explicitly asks for a decision. */
80
+ export function extractDecisionPrompt(markdown: string | undefined, turnId: string | number = 0): DecisionPrompt | undefined {
81
+ if (!markdown) return undefined;
82
+ const prose = stripFences(markdown);
83
+ if (!isDecisionBadgeText(prose)) return undefined;
84
+
85
+ const groups: DecisionChoice[][] = [];
86
+ let current: DecisionChoice[] = [];
87
+ for (const rawLine of prose.split(/\r?\n/)) {
88
+ const trimmed = rawLine.trim();
89
+ if (!trimmed) continue;
90
+ const match = /^(\d{1,2})[.)、]\s+(.+)$/.exec(trimmed);
91
+ if (match) {
92
+ const num = Number(match[1]);
93
+ const { label, recommended } = cleanOptionLine(match[2]);
94
+ if (!label) continue;
95
+ if (current.length === 0 && num === 1) {
96
+ current = [{ number: 1, label, recommended }];
97
+ } else if (current.length > 0 && num === current.length + 1 && current.length < 5) {
98
+ current.push({ number: num, label, recommended });
99
+ } else if (num === 1) {
100
+ if (current.length >= 2) groups.push(current);
101
+ current = [{ number: 1, label, recommended }];
102
+ }
103
+ } else if (current.length > 0 && !rawLine.startsWith(" ") && !rawLine.startsWith("\t")) {
104
+ if (current.length >= 2) groups.push(current);
105
+ current = [];
106
+ }
107
+ }
108
+ if (current.length >= 2) groups.push(current);
109
+ const choices = groups.at(-1);
110
+ if (!choices || choices.length < 2) return undefined;
111
+ const recIdx = choices.findIndex((item) => item.recommended);
112
+ return {
113
+ key: `${turnId}:${choices.map((item) => item.label).join("|")}`,
114
+ choices,
115
+ defaultIndex: recIdx >= 0 ? recIdx : 0,
116
+ };
117
+ }
118
+
119
+ export interface DecisionDockOptions {
120
+ language: () => UiLanguage;
121
+ isEditorEmpty: () => boolean;
122
+ onSubmit: (replyText: string) => void;
123
+ requestRender: () => void;
124
+ }
125
+
126
+ export function createDecisionDock(options: DecisionDockOptions) {
127
+ let activePrompt: DecisionPrompt | undefined;
128
+ let selectedIndex = 0;
129
+ const dismissedKeys = new Set<string>();
130
+ let optionStartRow = 2;
131
+
132
+ const sync = (prompt: DecisionPrompt | undefined): boolean => {
133
+ if (!prompt || dismissedKeys.has(prompt.key)) {
134
+ if (!activePrompt) return false;
135
+ activePrompt = undefined;
136
+ return true;
137
+ }
138
+ if (activePrompt?.key === prompt.key) return false;
139
+ activePrompt = prompt;
140
+ selectedIndex = prompt.defaultIndex;
141
+ return true;
142
+ };
143
+
144
+ const dismiss = (): boolean => {
145
+ if (!activePrompt) return false;
146
+ dismissedKeys.add(activePrompt.key);
147
+ activePrompt = undefined;
148
+ options.requestRender();
149
+ return true;
150
+ };
151
+
152
+ const clearAll = (): void => {
153
+ activePrompt = undefined;
154
+ dismissedKeys.clear();
155
+ };
156
+
157
+ const choose = (index: number): void => {
158
+ if (!activePrompt) return;
159
+ const choice = activePrompt.choices[index];
160
+ if (!choice) return;
161
+ dismissedKeys.add(activePrompt.key);
162
+ activePrompt = undefined;
163
+ options.onSubmit(`${choice.number}. ${choice.label}`);
164
+ options.requestRender();
165
+ };
166
+
167
+ const handleTerminalInput = (data: string): { consume?: boolean } | undefined => {
168
+ if (!activePrompt) return undefined;
169
+ if (matchesKey(data, "escape")) {
170
+ dismiss();
171
+ return { consume: true };
172
+ }
173
+ if (!options.isEditorEmpty()) return undefined;
174
+ if (matchesKey(data, "up")) {
175
+ selectedIndex = selectedIndex <= 0 ? activePrompt.choices.length - 1 : selectedIndex - 1;
176
+ options.requestRender();
177
+ return { consume: true };
178
+ }
179
+ if (matchesKey(data, "down")) {
180
+ selectedIndex = selectedIndex >= activePrompt.choices.length - 1 ? 0 : selectedIndex + 1;
181
+ options.requestRender();
182
+ return { consume: true };
183
+ }
184
+ if (matchesKey(data, "enter") || matchesKey(data, "return")) {
185
+ choose(selectedIndex);
186
+ return { consume: true };
187
+ }
188
+ return undefined;
189
+ };
190
+
191
+ const component = (theme: ExtensionContext["ui"]["theme"]): Component => ({
192
+ invalidate() {},
193
+ handleMouse(event: TuiMouseEvent) {
194
+ if (!activePrompt) return undefined;
195
+ const idx = event.y - optionStartRow;
196
+ if (idx < 0 || idx >= activePrompt.choices.length) return undefined;
197
+ if (event.type === "move" || event.type === "press") {
198
+ if (selectedIndex !== idx) {
199
+ selectedIndex = idx;
200
+ return { handled: true, render: true };
201
+ }
202
+ return { handled: true };
203
+ }
204
+ if (event.type === "click" && event.button === "left") {
205
+ choose(idx);
206
+ return { handled: true, render: true };
207
+ }
208
+ return undefined;
209
+ },
210
+ render(width: number): string[] {
211
+ if (!activePrompt || width < 16 || !options.isEditorEmpty()) return [];
212
+ const copy = DOCK_COPY[options.language()] ?? DOCK_COPY.zh;
213
+ const rule = theme.fg("borderMuted" as "muted", "─".repeat(width));
214
+ const pad = width >= 40 ? " " : "";
215
+ const rows: string[] = [
216
+ rule,
217
+ truncateToWidth(pad + theme.fg("accent", theme.bold(copy.title)), width, "…"),
218
+ ];
219
+ optionStartRow = rows.length;
220
+ for (const [index, item] of activePrompt.choices.entries()) {
221
+ const selected = index === selectedIndex;
222
+ const prefix = selected ? "→ " : " ";
223
+ const body = `${item.number}. ${item.label}`;
224
+ const fitted = truncateToWidth(pad + prefix + body, width, "…");
225
+ rows.push(selected ? theme.fg("accent", fitted) : theme.fg("text", fitted));
226
+ }
227
+ const hints = `${theme.bold("↑↓")} ${copy.nav} ${theme.bold("enter")} ${copy.confirm} ${theme.bold("esc")} ${copy.cancel} · ${copy.typeHint}`;
228
+ rows.push(truncateToWidth(pad + theme.fg("muted", hints), width, "…"));
229
+ return rows;
230
+ },
231
+ });
232
+
233
+ return {
234
+ get isActive() {
235
+ return Boolean(activePrompt);
236
+ },
237
+ sync,
238
+ dismiss,
239
+ clearAll,
240
+ handleTerminalInput,
241
+ component,
242
+ };
243
+ }
@@ -1,5 +1,6 @@
1
1
  import { Marked, Markdown, visibleWidth, type DefaultTextStyle, type MarkdownTheme } from "@earendil-works/pi-tui";
2
2
  import { render } from "grok-mermaid";
3
+ import { renderSemanticBadge, transformSemanticBadges, type BadgeStyle, type BadgeThemeLike } from "./semantic-badges.ts";
3
4
 
4
5
  const parser = new Marked();
5
6
 
@@ -15,7 +16,16 @@ const REGISTERED_LANGUAGES = new Set([
15
16
  ]);
16
17
  const ANSI_FOREGROUND = /\x1b\[(?:38;(?:2;\d+;\d+;\d+|5;\d+)|3[0-9]|9[0-7])m/g;
17
18
 
18
- export function minimalMarkdownTheme(base: MarkdownTheme, codeBackground = ""): MarkdownTheme {
19
+ export interface SemanticBadgeRenderOptions {
20
+ theme: BadgeThemeLike;
21
+ style?: BadgeStyle;
22
+ }
23
+
24
+ export function minimalMarkdownTheme(
25
+ base: MarkdownTheme,
26
+ codeBackground = "",
27
+ badges?: SemanticBadgeRenderOptions,
28
+ ): MarkdownTheme {
19
29
  // Inline prose arrives with its default foreground already applied. Remove
20
30
  // those foreground codes before wrapping, otherwise they override emphasis.
21
31
  const emphasis = (text: string) => base.heading(text.replace(/\x1b\[(?:38;(?:2;\d+;\d+;\d+|5;\d+)|3[0-9]|9[0-7])m/g, ""));
@@ -23,6 +33,7 @@ export function minimalMarkdownTheme(base: MarkdownTheme, codeBackground = ""):
23
33
  const neutralCode = (text: string) => base.codeBlock(text).replace(ANSI_FOREGROUND, "");
24
34
  return {
25
35
  ...base,
36
+ code: text => (badges ? renderSemanticBadge(text, badges.theme, badges.style ?? "round") : undefined) ?? base.code(text),
26
37
  bold: text => emphasis(base.bold(text)),
27
38
  italic: text => emphasis(base.italic(text)),
28
39
  codeBlock: neutralCode,
@@ -40,9 +51,16 @@ export function minimalMarkdownTheme(base: MarkdownTheme, codeBackground = ""):
40
51
 
41
52
  /** Render Markdown with A's code-only background, after native wrapping has settled. */
42
53
  export function renderMinimalMarkdown(source: string, width: number, base: MarkdownTheme, codeBackground: string,
43
- defaultTextStyle?: DefaultTextStyle, transform?: (source: string, available: number) => string): string[] {
44
- const rows = new Markdown(source, 0, 0, minimalMarkdownTheme(base, codeBackground), defaultTextStyle,
45
- transform ? { transform } : undefined).render(width);
54
+ defaultTextStyle?: DefaultTextStyle, transform?: (source: string, available: number) => string,
55
+ badges?: SemanticBadgeRenderOptions): string[] {
56
+ const combinedTransform = badges
57
+ ? (raw: string, available: number) => {
58
+ const next = transform ? transform(raw, available) : raw;
59
+ return transformSemanticBadges(next);
60
+ }
61
+ : transform;
62
+ const rows = new Markdown(source, 0, 0, minimalMarkdownTheme(base, codeBackground, badges), defaultTextStyle,
63
+ combinedTransform ? { transform: combinedTransform } : undefined).render(width);
46
64
  if (!codeBackground) return rows;
47
65
  return rows.map(row => row.startsWith(codeBackground)
48
66
  ? `${row}${" ".repeat(Math.max(0, width - visibleWidth(row)))}\x1b[49m`
@@ -6,6 +6,7 @@ import { assistantImageSpans, clearAssistantImageCaches, createAssistantImages,
6
6
  import { clearFileLinkCaches, linkToolFiles } from "./file-links.ts";
7
7
  import { createLinkHover } from "./link-hover.ts";
8
8
  import { diagramMarkdown, isFencedMarkdown, renderMinimalMarkdown } from "./minimal-markdown.ts";
9
+ import type { BadgeStyle } from "./semantic-badges.ts";
9
10
  import { minimalSurface, paintExpandedHeading } from "./minimal-theme.ts";
10
11
  import { formatElapsed, formatThinkingElapsed, formatToolElapsed, piLoopSummary, type MinimalTurn } from "./minimal-turns.ts";
11
12
  import { clearPrintAgentCaches } from "./print-agent.ts";
@@ -123,21 +124,26 @@ export interface MinimalOutputOptions {
123
124
  requestRender(): void;
124
125
  write?(data: string): void;
125
126
  updateBanner?: () => UpdateBannerState | undefined;
127
+ semanticBadges?: () => { enabled: boolean; style: BadgeStyle };
126
128
  }
127
129
 
128
130
  export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showUsage: () => boolean = () => true, subAgentsExpanded: () => boolean = () => false, agentDeadlines = new Map<string, number>(), transformText: (text: string) => string = text => text, imageOptions?: MinimalOutputOptions, getRecordLimit: () => number = () => DEFAULT_SETTINGS["pi-mini-mode-minimal-record-limit"], getLanguage: () => UiLanguage = () => "zh", getUpdateBanner?: () => UpdateBannerState | undefined) {
129
131
  const resolveUpdateBanner = getUpdateBanner ?? imageOptions?.updateBanner;
132
+ const resolveBadges = () => imageOptions?.semanticBadges ? imageOptions.semanticBadges() : { enabled: true, style: "round" as BadgeStyle };
130
133
  const markdownCache = new Map<string, string[]>();
131
134
  const assistantMdCache = new Map<string, string[]>();
132
135
  const callDisplayCache = new Map<string, { tool?: string; name: string; action?: string; state: string; task: string; output?: string; value: { summary: string; detail: string } }>();
133
136
  const turnCache = new Map<number, { key: readonly unknown[]; value: TurnRenderResult }>();
134
137
  const placeholderText = (text: string) => imageOptions ? imagePlaceholders(text, imageOptions.cwd()) : text;
135
138
  const markdown = (text: string, width: number, process = false): string[] => {
136
- const key = `${process ? 1 : 0}|${width}|${text}`;
139
+ const badgeCfg = !process ? resolveBadges() : { enabled: false, style: "round" as BadgeStyle };
140
+ const badgeKey = badgeCfg.enabled ? badgeCfg.style : "off";
141
+ const key = `${process ? 1 : 0}|${badgeKey}|${width}|${text}`;
137
142
  const hit = lruGet(markdownCache, key);
138
143
  if (hit !== undefined) return [...hit];
139
144
  const rows = renderMinimalMarkdown(text, width, getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
140
- { color: (value) => theme.fg(process ? "muted" : "text", value) }, (source, available) => transformText(placeholderText(diagramMarkdown(source, available))));
145
+ { color: (value) => theme.fg(process ? "muted" : "text", value) }, (source, available) => transformText(placeholderText(diagramMarkdown(source, available))),
146
+ badgeCfg.enabled ? { theme, style: badgeCfg.style } : undefined);
141
147
  lruSet(markdownCache, key, rows);
142
148
  return [...rows];
143
149
  };
@@ -154,7 +160,8 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
154
160
  const assistantImages = imageOptions && createAssistantImages(imageOptions.cwd, () => { turnCache.clear(); imageOptions.requestRender(); }, imageOptions.write);
155
161
  const assistantMarkdown = (text: string, width: number, owner: string): string[] => {
156
162
  if (!assistantImages) return markdown(text, width);
157
- const key = `${width}|${text}`;
163
+ const badgeCfg = resolveBadges();
164
+ const key = `${badgeCfg.enabled ? badgeCfg.style : "off"}|${width}|${text}`;
158
165
  const hit = lruGet(assistantMdCache, key);
159
166
  if (hit !== undefined) return [...hit];
160
167
  if (!assistantImageSpans(text, imageOptions!.cwd()).length) {
@@ -450,6 +457,7 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
450
457
  const elapsedSec = turn.startedAt != null && turn.endedAt == null
451
458
  ? Math.floor((now - turn.startedAt) / 1000)
452
459
  : (turn.endedAt ?? -1);
460
+ const badgeCfg = resolveBadges();
453
461
  const key: unknown[] = [
454
462
  width,
455
463
  exp,
@@ -457,6 +465,7 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
457
465
  usageShown,
458
466
  recLimit,
459
467
  lang,
468
+ badgeCfg.enabled ? badgeCfg.style : "off",
460
469
  agentModes.get(index),
461
470
  expandedPrompts.get(index),
462
471
  turnExpandedTools,
@@ -1,7 +1,7 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
 
3
- type RGB = [number, number, number];
4
- function ansiColor(ansi: string): RGB | undefined {
3
+ export type RGB = [number, number, number];
4
+ export function ansiColor(ansi: string): RGB | undefined {
5
5
  const rgb = ansi.match(/(?:38|48);2;(\d+);(\d+);(\d+)/);
6
6
  if (rgb) return [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])];
7
7
  const indexed = ansi.match(/(?:38|48);5;(\d+)/);
@@ -0,0 +1,274 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { ansiColor, type RGB } from "./minimal-theme.ts";
3
+
4
+ export type BadgeStyle = "round" | "square";
5
+ export type BadgeTone = "success" | "error" | "warning" | "action" | "info" | "muted";
6
+
7
+ export type BadgeThemeLike = Pick<ExtensionContext["ui"]["theme"], "fg" | "bold"> & {
8
+ getBgAnsi?(token: "userMessageBg" | "selectedBg"): string;
9
+ getColorMode?(): string;
10
+ };
11
+
12
+ export interface ParsedSemanticBadge {
13
+ tone: BadgeTone;
14
+ label: string;
15
+ }
16
+
17
+ const CAP_LEFT = "\uE0B6";
18
+ const CAP_RIGHT = "\uE0B4";
19
+
20
+ export function isBadgeStyle(value: unknown): value is BadgeStyle {
21
+ return value === "round" || value === "square";
22
+ }
23
+
24
+ const KEYWORD_TONES = new Map<string, { tone: BadgeTone; prefix?: string }>([
25
+ ["亲眼确认", { tone: "success" }],
26
+ ["已确认", { tone: "success" }],
27
+ ["已观测", { tone: "success" }],
28
+ ["实测", { tone: "success" }],
29
+ ["实锤", { tone: "success" }],
30
+ ["正常", { tone: "success" }],
31
+ ["通过", { tone: "success" }],
32
+ ["完成", { tone: "success" }],
33
+ ["推荐", { tone: "success", prefix: "★ " }],
34
+ ["observed", { tone: "success" }],
35
+ ["verified", { tone: "success" }],
36
+ ["confirmed", { tone: "success" }],
37
+ ["done", { tone: "success" }],
38
+ ["passed", { tone: "success" }],
39
+ ["recommended", { tone: "success", prefix: "★ " }],
40
+
41
+ ["失败", { tone: "error" }],
42
+ ["卡住", { tone: "error" }],
43
+ ["阻断", { tone: "error" }],
44
+ ["高风险", { tone: "error", prefix: "! " }],
45
+ ["高危", { tone: "error", prefix: "! " }],
46
+ ["破坏性", { tone: "error", prefix: "! " }],
47
+ ["failed", { tone: "error" }],
48
+ ["blocked", { tone: "error" }],
49
+ ["destructive", { tone: "error", prefix: "! " }],
50
+ ["high risk", { tone: "error", prefix: "! " }],
51
+ ["high-risk", { tone: "error", prefix: "! " }],
52
+
53
+ ["还没查", { tone: "warning", prefix: "? " }],
54
+ ["未验证", { tone: "warning", prefix: "? " }],
55
+ ["待核实", { tone: "warning", prefix: "? " }],
56
+ ["待查", { tone: "warning", prefix: "? " }],
57
+ ["盲区", { tone: "warning", prefix: "? " }],
58
+ ["unverified", { tone: "warning", prefix: "? " }],
59
+ ["unchecked", { tone: "warning", prefix: "? " }],
60
+
61
+ ["等你定", { tone: "action", prefix: "● " }],
62
+ ["待拍板", { tone: "action", prefix: "● " }],
63
+ ["待决策", { tone: "action", prefix: "● " }],
64
+ ["需确认", { tone: "action", prefix: "● " }],
65
+ ["decision", { tone: "action" }],
66
+ ["needs you", { tone: "action", prefix: "● " }],
67
+ ["needs-you", { tone: "action", prefix: "● " }],
68
+
69
+ ["合理推测", { tone: "info" }],
70
+ ["推断", { tone: "info" }],
71
+ ["推测", { tone: "info" }],
72
+ ["排查完毕", { tone: "info" }],
73
+ ["共享", { tone: "info" }],
74
+ ["共享表", { tone: "info" }],
75
+ ["跨服务共享", { tone: "info" }],
76
+ ["影响用户", { tone: "info" }],
77
+ ["影响范围", { tone: "info" }],
78
+ ["关联影响", { tone: "info" }],
79
+ ["外部影响", { tone: "info" }],
80
+ ["折中", { tone: "info" }],
81
+ ["inferred", { tone: "info" }],
82
+ ["investigate", { tone: "info" }],
83
+ ["shared", { tone: "info" }],
84
+ ["impact", { tone: "info" }],
85
+
86
+ ["跳过", { tone: "muted", prefix: "» " }],
87
+ ["未执行", { tone: "muted", prefix: "» " }],
88
+ ["skipped", { tone: "muted", prefix: "» " }],
89
+ ]);
90
+
91
+ const HAS_WORD_CHAR = /[\p{L}\u4e00-\u9fff]/u;
92
+
93
+ export function parseSemanticBadge(raw: string): ParsedSemanticBadge | undefined {
94
+ const trimmed = raw.trim();
95
+ if (!trimmed.startsWith("[") || !trimmed.endsWith("]")) return undefined;
96
+ const inner = trimmed.slice(1, -1).trim();
97
+ if (!inner || inner.length > 32 || /[\r\n`[\]"]/.test(inner) || !HAS_WORD_CHAR.test(inner)) return undefined;
98
+
99
+ if (/^(?:✓|✔|★)\s*\S/.test(inner)) return { tone: "success", label: inner.replace(/^(✓|✔|★)\s*/, "$1 ") };
100
+ if (/^(?:×|✕)\s*\S/.test(inner)) return { tone: "error", label: inner.replace(/^(×|✕)\s*/, "$1 ") };
101
+ if (/^[??]\s*\S/.test(inner)) return { tone: "warning", label: `? ${inner.slice(1).trim()}` };
102
+ if (/^(?:●|⑂)\s*\S/.test(inner)) return { tone: "action", label: inner.replace(/^(●|⑂)\s*/, "$1 ") };
103
+ if (/^~\s*\S/.test(inner)) return { tone: "info", label: `~ ${inner.slice(1).trim()}` };
104
+ if (/^(?:»|⏭)\s*\S/.test(inner)) return { tone: "muted", label: `» ${inner.slice(1).trim()}` };
105
+ if (/^!\s+\S/.test(inner)) return { tone: "error", label: `! ${inner.slice(1).trim()}` };
106
+
107
+ if (inner.startsWith("!")) {
108
+ const body = inner.slice(1).trim();
109
+ if (!body) return undefined;
110
+ const hit = KEYWORD_TONES.get(body.toLowerCase());
111
+ if (hit) return { tone: hit.tone, label: hit.prefix && !body.startsWith(hit.prefix.trim()) ? `${hit.prefix}${body}` : body };
112
+ }
113
+ return undefined;
114
+ }
115
+
116
+ export function isDecisionBadgeText(source: string): boolean {
117
+ for (const match of source.matchAll(/\[[^\]\r\n`]{1,32}\]/g)) {
118
+ if (parseSemanticBadge(match[0])?.tone === "action") return true;
119
+ }
120
+ return false;
121
+ }
122
+
123
+ function transformInlineSegment(line: string): string {
124
+ let result = "";
125
+ let index = 0;
126
+ while (index < line.length) {
127
+ if (line[index] === "`") {
128
+ let ticks = 1;
129
+ while (line[index + ticks] === "`") ticks++;
130
+ const fence = "`".repeat(ticks);
131
+ const close = line.indexOf(fence, index + ticks);
132
+ if (close < 0) {
133
+ result += line.slice(index);
134
+ break;
135
+ }
136
+ result += line.slice(index, close + ticks);
137
+ index = close + ticks;
138
+ continue;
139
+ }
140
+ if (line[index] === "[" && line[index - 1] !== "!" && line[index - 1] !== "\\") {
141
+ const close = line.indexOf("]", index + 1);
142
+ if (close > index + 1 && close - index <= 34) {
143
+ const next = line[close + 1] ?? "";
144
+ const candidate = line.slice(index, close + 1);
145
+ if (next !== "(" && next !== "[" && next !== ":" && parseSemanticBadge(candidate)) {
146
+ result += `\`${candidate}\``;
147
+ index = close + 1;
148
+ continue;
149
+ }
150
+ }
151
+ }
152
+ result += line[index];
153
+ index++;
154
+ }
155
+ return result;
156
+ }
157
+
158
+ /** Wrap standalone semantic badge tokens outside code fences and links into inline code spans. */
159
+ export function transformSemanticBadges(source: string): string {
160
+ if (!source.includes("[")) return source;
161
+ const lines = source.split("\n");
162
+ let fenceChar = "";
163
+ let fenceLen = 0;
164
+ for (let i = 0; i < lines.length; i++) {
165
+ const line = lines[i];
166
+ const fenceMatch = /^ {0,3}(`{3,}|~{3,})/.exec(line);
167
+ if (fenceMatch) {
168
+ const marker = fenceMatch[1];
169
+ if (!fenceChar) {
170
+ fenceChar = marker[0];
171
+ fenceLen = marker.length;
172
+ continue;
173
+ }
174
+ if (marker[0] === fenceChar && marker.length >= fenceLen && /^ {0,3}[`~]+[ \t]*$/.test(line)) {
175
+ fenceChar = "";
176
+ fenceLen = 0;
177
+ }
178
+ continue;
179
+ }
180
+ if (fenceChar || /^ {0,3}\[[^\]]+\]:/.test(line) || !line.includes("[")) continue;
181
+ lines[i] = transformInlineSegment(line);
182
+ }
183
+ return lines.join("\n");
184
+ }
185
+
186
+ const DARK_PALETTE: Record<BadgeTone, { bg: RGB; fg: RGB }> = {
187
+ success: { bg: [22, 56, 40], fg: [134, 239, 172] },
188
+ error: { bg: [67, 25, 36], fg: [253, 164, 175] },
189
+ warning: { bg: [63, 43, 18], fg: [253, 224, 71] },
190
+ action: { bg: [59, 38, 20], fg: [253, 186, 116] },
191
+ info: { bg: [23, 46, 77], fg: [147, 197, 253] },
192
+ muted: { bg: [39, 38, 48], fg: [212, 212, 216] },
193
+ };
194
+
195
+ const LIGHT_PALETTE: Record<BadgeTone, { bg: RGB; fg: RGB }> = {
196
+ success: { bg: [220, 252, 231], fg: [20, 83, 45] },
197
+ error: { bg: [255, 228, 230], fg: [136, 19, 55] },
198
+ warning: { bg: [254, 243, 199], fg: [120, 53, 15] },
199
+ action: { bg: [255, 237, 213], fg: [124, 45, 18] },
200
+ info: { bg: [219, 234, 254], fg: [30, 58, 138] },
201
+ muted: { bg: [236, 234, 242], fg: [63, 61, 71] },
202
+ };
203
+
204
+ const FALLBACK_TOKEN: Record<BadgeTone, "success" | "error" | "warning" | "accent" | "muted"> = {
205
+ success: "success",
206
+ error: "error",
207
+ warning: "warning",
208
+ action: "warning",
209
+ info: "accent",
210
+ muted: "muted",
211
+ };
212
+
213
+ function mixRgb(a: RGB, b: RGB, weight: number): RGB {
214
+ return [
215
+ Math.round(a[0] * (1 - weight) + b[0] * weight),
216
+ Math.round(a[1] * (1 - weight) + b[1] * weight),
217
+ Math.round(a[2] * (1 - weight) + b[2] * weight),
218
+ ];
219
+ }
220
+
221
+ function toCube256(rgb: RGB): number {
222
+ const levels = [0, 95, 135, 175, 215, 255];
223
+ const indices = rgb.map((value) =>
224
+ levels.reduce((best, level, i) => (Math.abs(level - value) < Math.abs(levels[best] - value) ? i : best), 0),
225
+ );
226
+ return 16 + indices[0] * 36 + indices[1] * 6 + indices[2];
227
+ }
228
+
229
+ function ansiFg(rgb: RGB, mode?: string): string {
230
+ return mode === "256color" ? `\x1b[38;5;${toCube256(rgb)}m` : `\x1b[38;2;${rgb.join(";")}m`;
231
+ }
232
+
233
+ function ansiBg(rgb: RGB, mode?: string): string {
234
+ return mode === "256color" ? `\x1b[48;5;${toCube256(rgb)}m` : `\x1b[48;2;${rgb.join(";")}m`;
235
+ }
236
+
237
+ export function renderSemanticBadge(raw: string, theme: BadgeThemeLike, style: BadgeStyle = "round"): string | undefined {
238
+ const parsed = parseSemanticBadge(raw);
239
+ if (!parsed) return undefined;
240
+ const token = FALLBACK_TOKEN[parsed.tone];
241
+ const themeAccentRgb = ansiColor(theme.fg(token, ""));
242
+ const surfaceRgb = ansiColor(theme.getBgAnsi?.("userMessageBg") ?? "");
243
+ if (!themeAccentRgb && !surfaceRgb) {
244
+ return theme.fg(token, theme.bold(`[${parsed.label}]`));
245
+ }
246
+ const isLight = surfaceRgb ? (0.299 * surfaceRgb[0] + 0.587 * surfaceRgb[1] + 0.114 * surfaceRgb[2]) >= 140 : false;
247
+ const preset = (isLight ? LIGHT_PALETTE : DARK_PALETTE)[parsed.tone];
248
+ const bg = themeAccentRgb ? mixRgb(preset.bg, themeAccentRgb, 0.15) : preset.bg;
249
+ const fg = themeAccentRgb ? mixRgb(preset.fg, themeAccentRgb, 0.2) : preset.fg;
250
+ const mode = theme.getColorMode?.();
251
+ const bgCode = ansiBg(bg, mode);
252
+ const fgCode = ansiFg(fg, mode);
253
+ if (style === "round") {
254
+ const capFg = ansiFg(bg, mode);
255
+ return `\x1b[49m${capFg}${CAP_LEFT}${bgCode}${fgCode}\x1b[1m${parsed.label}\x1b[22m\x1b[49m${capFg}${CAP_RIGHT}\x1b[39m`;
256
+ }
257
+ return `${bgCode}${fgCode}\x1b[1m ${parsed.label} \x1b[22m\x1b[49m\x1b[39m`;
258
+ }
259
+
260
+ export const TRIAGE_PROMPT_MARKER = "<!-- pi-mini-mode:semantic-triage -->";
261
+
262
+ export const TRIAGE_SYSTEM_PROMPT = `${TRIAGE_PROMPT_MARKER}
263
+ ## Diagnostic & Trade-off Reporting (on-demand only)
264
+ Keep routine edits, coding tasks, and simple Q&A completely normal—do not add scoreboards, badges, or option menus to ordinary replies.
265
+ ONLY when investigating a failure/bug, auditing deployment/change risks, or presenting trade-off options that require a user decision:
266
+ 1. Open with a one-sentence plain conclusion stating what stopped/happened and whether the current system is safe.
267
+ 2. When multiple checks/stages apply, summarize status on one line with inline badge spans: \`[✓ 正常 N]\` \`[× 失败 N]\` \`[? 还没查 N]\` \`[● 等你定 1]\` (or English \`[✓ Done N]\` \`[× Failed N]\` \`[? Unverified N]\` \`[● Needs you 1]\`).
268
+ 3. Separate evidence certainty in a \`├─\` / \`└─\` list using \`[!亲眼确认]\` (\`[!Observed]\`), \`[!合理推测]\` (\`[!Inferred]\`), and \`[? 还没查]\` (\`[? Unverified]\`), and flag cross-module impact with \`[!影响范围]\` (\`[!Shared]\`).
269
+ 4. When asking the user to choose between 2–4 options, include \`[● 等你定 1]\` (or \`[● Needs you 1]\`), list numbered options \`1. **Title** \`[★ 推荐]\` — trade-off\` (mark risky ones \`[! 高风险]\` / \`[! Destructive]\`), and propose a safe, reversible next step.`;
270
+
271
+ export function appendTriageGuidance(systemPrompt: string): string {
272
+ if (!systemPrompt || systemPrompt.includes(TRIAGE_PROMPT_MARKER)) return systemPrompt;
273
+ return `${systemPrompt}\n\n${TRIAGE_SYSTEM_PROMPT}`;
274
+ }
package/lib/settings.html CHANGED
@@ -42,16 +42,19 @@ const I18N={
42
42
  fieldsHeading:{zh:'状态栏字段与预览(示例数据)',en:'Status bar items & preview (sample data)'},
43
43
  optionsHeading:{zh:'状态栏样式',en:'Status bar style'},
44
44
  on:{zh:'开启',en:'On'},off:{zh:'关闭',en:'Off'},previewModeLabel:{zh:'图片预览方式',en:'Image preview mode'},previewHover:{zh:'光标浮窗',en:'Cursor popup'},previewInline:{zh:'内联卡片(多图排列)',en:'Inline cards (multiple images)'},previewModeHint:{zh:'卡片显示在输入框上方;终端不支持图片时显示占位。',en:'Cards appear above the editor; unsupported terminals show placeholders.'},
45
+ badgeStyleLabel:{zh:'胶囊样式',en:'Capsule style'},badgeRound:{zh:'圆角胶囊(Ghostty / Nerd Font)',en:'Rounded pills (Ghostty / Nerd Font)'},badgeSquare:{zh:'方角纯色块(通用终端)',en:'Square color blocks (universal)'},
45
46
  recordLimitLabel:{zh:'折叠时记录数',en:'Collapsed record limit'},
46
47
  recordLimitHint:{zh:'默认 6 条。子代理始终显示,每个占一条;剩余额度显示最新执行记录。子代理超过上限时,仅显示全部子代理。',en:'Defaults to 6. Every subagent stays visible and uses one record; remaining slots show the latest execution records. When subagents exceed the limit, only their rows remain.'},
47
48
  featureList:{
48
49
  zh:[
49
50
  {id:'minimal',setting:'pi-mini-mode-minimal-show',title:'极简输出',body:'在全屏模式下,把思考、工具与技能记录收进一棵可折叠过程树,保留完整回复。',points:['长用户消息显示前四行,点击展开全文','子代理始终显示,可展开活动记录与输出','Ctrl+O 展开或收起过程树,新问题默认收起','最终 Markdown 流畅呈现,失败与中断明确标记']},
51
+ {id:'semantic-badges',setting:'pi-mini-mode-semantic-badges',title:'语义诊断胶囊',body:'排障调查、风险审查与多方案决策时,将证据可信度渲染为彩色胶囊,并在输入框上方提供快速选方案。',points:['区分「亲眼确认」「合理推测」与「? 还没查」,一眼看清未验证盲区','存在多方案待拍板时,上下键或点击即可确认发送,直接打字互不干扰','日常改代码与普通问答保持原样,不产生额外标签']},
50
52
  {id:'input-enhancements',setting:'pi-mini-mode-input-enhancements',title:'输入增强',body:'让输入框和消息里的图片、技能与文件路径直接可用。',points:['图片默认以内联卡片陈列于输入框上方,亦可切换光标悬停','图片路径收纳为 [image1] 标签,提交时保留原图','空白后输入 / 就地搜索技能并插入光标处','左键用系统默认应用打开,全屏右键在文件管理器中定位并选中'],hint:'Ctrl+V 粘贴图片(Windows/WSL 使用 Alt+V)'},
51
53
  {id:'themes',title:'明暗主题',body:'主题让 Markdown、代码高亮、表格与 Mermaid 图表跟随明暗切换。',points:['用户消息使用主题用户背景色,与正文区分','不支持、不完整或过宽的图表保留源文本'],hint:'回到 Pi,输入 /settings → Theme,选择 cc-dark / cc-light'}
52
54
  ],
53
55
  en:[
54
56
  {id:'minimal',setting:'pi-mini-mode-minimal-show',title:'Minimal transcript',body:'In fullscreen mode, fold thinking, tools and skill reads into one process tree while keeping the full reply.',points:['Long user messages show four rendered rows; click to expand','Subagents stay visible; click to expand activity and output','Ctrl+O expands or collapses the full process tree; new questions start collapsed','Final Markdown streams plainly; failures and interrupts are marked']},
57
+ {id:'semantic-badges',setting:'pi-mini-mode-semantic-badges',title:'Semantic diagnostic pills',body:'During root-cause investigations and trade-off decisions, highlight evidence certainty as colored pills with a quick option picker above the editor.',points:['Separates Observed facts, Inferred deductions and Unverified blind spots','Up/Down or click to send a numbered option; typing freely in the editor stays unobstructed','Routine coding tasks and simple Q&A stay plain without extra badges']},
55
58
  {id:'input-enhancements',setting:'pi-mini-mode-input-enhancements',title:'Input enhancements',body:'Makes images, skills and file paths usable right where you type.',points:['Images appear as inline cards above the editor by default, with optional cursor hover','Image paths collapse to [image1] labels while keeping the original path on submit','Type / after a space to search skills and insert at the cursor','Left-click opens in the default app; fullscreen right-click reveals and selects the file'],hint:'Ctrl+V pastes images (Windows/WSL: Alt+V)'},
56
59
  {id:'themes',title:'Light and dark themes',body:'Themes keep Markdown, code highlighting, tables and Mermaid diagrams in step with light and dark.',points:['User messages use the theme user background to stand out','Unsupported, incomplete or overly wide diagrams keep their source text'],hint:'In Pi, enter /settings → Theme and choose cc-dark or cc-light'}
57
60
  ]
@@ -221,6 +224,15 @@ function feature(item){
221
224
  const hint=document.createElement('p');hint.className='feature-hint';hint.textContent=t('recordLimitHint');card.append(hint);
222
225
  head.querySelector('input').addEventListener('change',()=>{input.disabled=!state[item.setting]});
223
226
  }
227
+ if(item.id==='semantic-badges'){
228
+ const label=document.createElement('label');label.className='preview-mode';label.htmlFor='pi-mini-mode-badge-style';
229
+ const text=document.createElement('span');text.textContent=t('badgeStyleLabel');
230
+ const select=document.createElement('select');select.id=label.htmlFor;select.disabled=!state[item.setting];
231
+ for(const [value,key] of [['round','badgeRound'],['square','badgeSquare']]){const option=document.createElement('option');option.value=value;option.textContent=t(key);select.append(option)}
232
+ select.value=state[select.id]||'round';select.onchange=()=>{state[select.id]=select.value;change()};
233
+ label.append(text,select);card.append(label);
234
+ head.querySelector('input').addEventListener('change',()=>{select.disabled=!state[item.setting]});
235
+ }
224
236
  if(item.id==='input-enhancements'){
225
237
  const label=document.createElement('label');label.className='preview-mode';label.htmlFor='pi-mini-mode-image-preview';
226
238
  const text=document.createElement('span');text.textContent=t('previewModeLabel');
package/lib/settings.ts CHANGED
@@ -3,6 +3,7 @@ import type { SettingItem } from "@earendil-works/pi-tui";
3
3
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
+ import { isBadgeStyle, type BadgeStyle } from "./semantic-badges.ts";
6
7
 
7
8
  export const SETTINGS_FILE_NAME = "pi-mini-mode.json";
8
9
 
@@ -24,6 +25,8 @@ export interface MiniLensSettings {
24
25
  "pi-mini-mode-speed-unit-show": boolean;
25
26
  "pi-mini-mode-minimal-show": boolean;
26
27
  "pi-mini-mode-minimal-record-limit": number;
28
+ "pi-mini-mode-semantic-badges": boolean;
29
+ "pi-mini-mode-badge-style": BadgeStyle;
27
30
  "pi-mini-mode-input-enhancements": boolean;
28
31
  "pi-mini-mode-image-preview": "hover" | "inline";
29
32
  onboardingCompleted: boolean;
@@ -65,6 +68,8 @@ export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
65
68
  "pi-mini-mode-speed-unit-show": true,
66
69
  "pi-mini-mode-minimal-show": true,
67
70
  "pi-mini-mode-minimal-record-limit": 6,
71
+ "pi-mini-mode-semantic-badges": true,
72
+ "pi-mini-mode-badge-style": "round",
68
73
  "pi-mini-mode-input-enhancements": true,
69
74
  "pi-mini-mode-image-preview": "inline",
70
75
  onboardingCompleted: false,
@@ -75,10 +80,11 @@ export const FOOTER_FIELDS = ["project-branch", "model", "thinking", "branch", "
75
80
  export const FOOTER_STYLE_OPTIONS = ["context-dots", "speed-unit"] as const;
76
81
 
77
82
  export const COPY = {
78
- preview: "预览(示例数据)", minimal: "极简输出",
83
+ preview: "预览(示例数据)", minimal: "极简输出", semanticBadges: "语义诊断胶囊",
79
84
  model: "显示模型", thinking: "显示思考等级", total: "显示会话总 token", cached: "显示会话缓存 token", miss: "显示缓存 miss", totalLabel: "Total", cachedLabel: "Cached", cacheHitLabel: "CH", cacheHit: "显示缓存命中率 (CH)", price: "显示会话价格", mcp: "显示已启用 MCP 服务器", context: "显示上下文 token 与进度条", dots: "↳ 使用点阵进度条", percent: "显示上下文百分比", speed: "显示最近生成速度", speedUnit: "↳ 显示 tok/s 单位", inputEnhancements: "输入增强",
80
85
  totalDescription: "Total:当前会话分支上的全部 token,含工具上报的 LLM 用量。", cachedDescription: "Cached:累计 cache-read + cache-write token(包含在 Total 中)。", cacheHitDescription: "CH(cache hit):cache-read / (input + cache-read)。Cache write 不计入此比率。",
81
86
  enableMinimalDescription: "开启统一折叠思考、工具和技能过程;关闭恢复 Pi 默认会话历史。",
87
+ semanticBadgesDescription: "排障与多方案决策时渲染圆角语义胶囊(亲眼确认 / 合理推测 / 还没查),并在底部提供方案快速选择;日常对话保持原样。",
82
88
  inputEnhancementsDescription: "原生 Ctrl+V 粘贴图片(Windows/WSL:Alt+V);图片显示为 [image1] 标签,默认在输入框上方显示内联卡片(可切换光标悬停模式)。空白后 / 选择技能并在光标处插入。左键用系统默认应用打开图片标签或文件路径;全屏右键在文件管理器中定位并选中该文件。预览及点击需终端支持。关闭仅恢复原生行为。",
83
89
  tuiRequired: "/pi-mini-mode-settings 需要 TUI 模式", saveFailed: "无法保存 Pi Mini Mode 设置", onboarding: "默认开启输入增强和极简输出;极简输出需要全屏模式。仅显示分支、缓存 token 和 MCP 服务数默认关闭。选择「打开浏览器设置」可调整字段、预览方式和功能开关;推荐配置会保存主题和全屏模式。以后可用 /pi-mini-mode-settings 修改。", keepDefaults: "保留默认", configureNow: "打开浏览器设置", applyRecommended: "应用推荐配置", chooseTheme: "选择主题(主题立即应用;全屏模式需重启 Pi)", themeSaved: "已保存主题和全屏模式。请重启 Pi 以启用全屏;项目设置或命令行参数可能覆盖全局设置。", themeSaveFailed: "无法保存推荐的 Pi 主题和全屏模式;未完成首次配置。", themeApplyFailed: "推荐设置已保存,但当前主题未能立即应用;请重启 Pi。",
84
90
  } as const;
@@ -104,6 +110,8 @@ export function parseSettings(value: unknown): MiniLensSettings {
104
110
  for (const id of SETTING_IDS) {
105
111
  if (id === "pi-mini-mode-image-preview") {
106
112
  if (candidate[id] === "hover" || candidate[id] === "inline") settings[id] = candidate[id];
113
+ } else if (id === "pi-mini-mode-badge-style") {
114
+ if (isBadgeStyle(candidate[id])) settings[id] = candidate[id];
107
115
  } else if (id === "pi-mini-mode-minimal-record-limit") {
108
116
  if (isRecordLimit(candidate[id])) settings[id] = candidate[id];
109
117
  } else if (isBoolean(candidate[id])) settings[id] = candidate[id];
@@ -161,14 +169,14 @@ export function isLegacyMinimalSetting(id: string): boolean {
161
169
 
162
170
  export function settingsItems(settings: MiniLensSettings): SettingItem[] {
163
171
  const values = ["on", "off"];
164
- const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted" | "lastSeenVersion" | "footerOrder" | "pi-mini-mode-language" | "pi-mini-mode-image-preview" | "pi-mini-mode-minimal-record-limit">, string> = {
172
+ const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted" | "lastSeenVersion" | "footerOrder" | "pi-mini-mode-language" | "pi-mini-mode-image-preview" | "pi-mini-mode-badge-style" | "pi-mini-mode-minimal-record-limit">, string> = {
165
173
  "pi-mini-mode-project-branch-show": "显示项目名称和分支(互斥)",
166
174
  "pi-mini-mode-branch-show": "仅显示分支(思考等级后,互斥)",
167
- "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-cache-miss-show": COPY.miss, "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,
175
+ "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-cache-miss-show": COPY.miss, "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-semantic-badges": COPY.semanticBadges, "pi-mini-mode-input-enhancements": COPY.inputEnhancements,
168
176
  };
169
177
  return (Object.keys(labels) as Array<keyof typeof labels>).map((id) => ({
170
178
  id, label: labels[id],
171
- 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,
179
+ description: id === "pi-mini-mode-minimal-show" ? COPY.enableMinimalDescription : id === "pi-mini-mode-semantic-badges" ? COPY.semanticBadgesDescription : 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,
172
180
  currentValue: settings[id] ? values[0] : values[1], values,
173
181
  }));
174
182
  }
@@ -3,7 +3,7 @@ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works
3
3
  import { readFileSync } from "node:fs";
4
4
  import type { UiLanguage } from "./settings.ts";
5
5
 
6
- export const UPDATE_RELEASE_DATE = "2026-11-05";
6
+ export const UPDATE_RELEASE_DATE = "2026-11-17";
7
7
  const MIN_BANNER_VERSION = "2.0.19";
8
8
 
9
9
  export function isNewerVersion(current: string, previous?: string): boolean {
@@ -46,6 +46,24 @@ interface ReleaseEntry {
46
46
  }
47
47
 
48
48
  export const RELEASE_HISTORY: readonly ReleaseEntry[] = [
49
+ {
50
+ version: "2.0.21",
51
+ date: "2026-11-17",
52
+ zh: {
53
+ highlights: "排障调查与多方案决策支持圆角语义胶囊与底部快速选方案,日常对话保持零干扰。",
54
+ features: [
55
+ "语义诊断胶囊:按需高亮「亲眼确认」「合理推测」「? 还没查」等可信度标签,支持圆角胶囊与方角纯色块切换",
56
+ "底部方案速选栏:存在多方案待拍板时支持上下键或点击一键发送,直接打字互不干扰",
57
+ ],
58
+ },
59
+ en: {
60
+ highlights: "On-demand semantic diagnostic pills and a quick option picker for investigations, keeping normal chat untouched.",
61
+ features: [
62
+ "Semantic diagnostic pills highlight Observed, Inferred, and Unverified claims with rounded or square terminal styles",
63
+ "Bottom decision dock lets you pick numbered options via Up/Down or click without blocking freeform typing",
64
+ ],
65
+ },
66
+ },
49
67
  {
50
68
  version: "2.0.20",
51
69
  date: "2026-11-05",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@each1024/pi-mini-mode",
3
- "version": "2.0.20",
3
+ "version": "2.0.21",
4
4
  "description": "A compact Pi footer with live usage metrics, theme-aware settings previews, and configurable progress bars.",
5
5
  "type": "module",
6
6
  "scripts": {