@each1024/pi-mini-mode 1.3.11 → 1.3.13

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/lib/agent-view.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { diagramMarkdown, isMarkdownProse, minimalMarkdownTheme } from "./minimal-markdown.ts";
1
+ import { diagramMarkdown, isMarkdownProse, renderMinimalMarkdown } from "./minimal-markdown.ts";
2
2
  import { extractNoticeBody, supervisorNoticeBody } from "./transcript-adapter.ts";
3
3
  import { paintExpandedHeading } from "./minimal-theme.ts";
4
4
  import { readdirSync, readFileSync, statSync } from "node:fs";
@@ -144,8 +144,8 @@ export function restyleAgentWidget(lines: string[], theme: Theme, width: number,
144
144
  const visible = blocks.filter(block => expanded || isFailed(block) || !isDone(block));
145
145
  const rows = [agentSummary(theme, width, blocks.length - done - errors, done, errors, expanded)];
146
146
  if (!blocks.length) rows.push(truncateToWidth(theme.fg("text", content[0]), width));
147
- const markdown = (text: string, available: number) => new Markdown(text, 0, 0, minimalMarkdownTheme(getMarkdownTheme()),
148
- { color: value => theme.fg("text", value) }, { transform: diagramMarkdown }).render(Math.max(1, available));
147
+ const markdown = (text: string, available: number) => renderMinimalMarkdown(text, Math.max(1, available), getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
148
+ { color: value => theme.fg("text", value) }, diagramMarkdown);
149
149
  // ponytail: native widget exposes bounded live previews, not the full child transcript.
150
150
  visible.forEach((block, index) => {
151
151
  const heading = block[0].replace(/^(?:[└├]─\s*)?[●○◉✓✗×◦■\u2800-\u28ff]\s*/, "");
@@ -337,8 +337,8 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
337
337
  ? stripAcceptanceReport(plain(value).replace(/[\x00-\x09\x0b\x0c\x0e-\x1f\x7f]/g, " ")).trim() : "";
338
338
  const renderBody = (source: string, available: number) => {
339
339
  const width = Math.max(1, available);
340
- if (isMarkdownProse(source)) return new Markdown(source, 0, 0, minimalMarkdownTheme(getMarkdownTheme()),
341
- { color: value => theme.fg("muted", value) }, { transform: diagramMarkdown }).render(width);
340
+ if (isMarkdownProse(source)) return renderMinimalMarkdown(source, width, getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
341
+ { color: value => theme.fg("muted", value) }, diagramMarkdown);
342
342
  // Wrap by visible columns. Do not re-slice truncateToWidth: it appends a
343
343
  // reset, so slice(row.length) would drop source characters on every wrap.
344
344
  return wrapTextWithAnsi(source, width).map(row => theme.fg("muted", row));
@@ -359,8 +359,7 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
359
359
  || [text(latest?.tool), latestArgs].filter(Boolean).join(" ")
360
360
  || text(child.description) || text(child.status ?? child.state) || "waiting";
361
361
  // Tool inputs are literal code, not Markdown (heredocs can contain HTML-like text).
362
- const body = latest || child.currentTool ? text(activity) : text(new Markdown(activity, 0, 0, minimalMarkdownTheme(getMarkdownTheme()), undefined, { transform: diagramMarkdown })
363
- .render(Math.max(1, visibleWidth(activity) + 1)).join(" "));
362
+ const body = latest || child.currentTool ? text(activity) : text(renderMinimalMarkdown(activity, Math.max(1, visibleWidth(activity) + 1), getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "", undefined, diagramMarkdown).join(" "));
364
363
  const state = text(child.status ?? child.state) || "waiting";
365
364
  const terminal = failedAgent(child) || finishedAgent(state);
366
365
  const isRunning = /^(running|active|starting|queued|pending)$/.test(state);
@@ -391,6 +390,7 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
391
390
  subagentControls?.push({ runId: runKey, y: rows.length, width, line });
392
391
  rows.push(line);
393
392
  if (isChildExpanded) {
393
+ const rail = theme.fg("accent", "│") + " ";
394
394
  let processShown = false;
395
395
  if (!terminal) {
396
396
  const process: Array<{ name: string; args: string }> = tools.slice(-6).map(tool => ({
@@ -401,7 +401,7 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
401
401
  process.push({ name: text(child.currentTool), args: text(child.currentPath || child.currentToolArgs) });
402
402
  }
403
403
  for (const item of process) {
404
- const prefix = ` ${theme.fg("muted", "●")} ${theme.fg("text", theme.bold(item.name))}${item.args ? " " : ""}`;
404
+ const prefix = `${rail}${theme.fg("muted", "●")} ${theme.fg("text", theme.bold(item.name))}${item.args ? " " : ""}`;
405
405
  rows.push(truncateToWidth(prefix + (item.args ? theme.fg("muted", item.args) : ""), width, "…"));
406
406
  processShown = true;
407
407
  }
@@ -431,15 +431,15 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
431
431
  const error = bodyText(child.error);
432
432
  if (error && !bodies.includes(error)) bodies.push(error);
433
433
  if (!terminal && !processShown && !bodies.length) {
434
- rows.push(truncateToWidth(` ${theme.fg("muted", "●")} ${theme.fg("text", theme.bold(text(state)))}`, width, "…"));
434
+ rows.push(truncateToWidth(`${rail}${theme.fg("muted", "●")} ${theme.fg("text", theme.bold(text(state)))}`, width, "…"));
435
435
  processShown = true;
436
436
  }
437
437
  for (const [index, textBody] of bodies.entries()) {
438
438
  // Child/supervisor bodies are Markdown prose; tool logs and JSON are
439
439
  // not placed in this semantic body channel.
440
- if (processShown || index > 0) rows.push("");
440
+ if (processShown || index > 0) rows.push(truncateToWidth(rail, width, ""));
441
441
  for (const line of renderBody(textBody, Math.max(1, width - 3))) {
442
- rows.push(truncateToWidth(` ${line}`, width));
442
+ rows.push(truncateToWidth(`${rail}${line}`, width));
443
443
  }
444
444
  }
445
445
  }
package/lib/file-links.ts CHANGED
@@ -43,7 +43,7 @@ export function filePaths(text: string) {
43
43
  const pattern = /(["'`])([^\r\n]*?)\1|[^\s"'`<>()[\]{},。;!?]+/g;
44
44
  for (const match of text.matchAll(pattern)) {
45
45
  const path = (match[2] ?? match[0]).replace(/[.,;:!?]+$/, "");
46
- if (!path || /[\x00-\x1f\x7f]/.test(path) || /^[a-z][\w+.-]*:\/\//i.test(path)) continue;
46
+ if (!path || /^[\\/]+$/.test(path) || /[\x00-\x1f\x7f]/.test(path) || /^[a-z][\w+.-]*:\/\//i.test(path)) continue;
47
47
  if (!/^(?:\/|~\/|\.{1,2}\/|[a-z]:[\\/])|[\\/]|\.[a-z\d]{1,12}$/i.test(path)) continue;
48
48
  const start = match.index + (match[1] ? 1 : 0);
49
49
  const end = start + path.length;
@@ -1,4 +1,4 @@
1
- import { Marked, type MarkdownTheme } from "@earendil-works/pi-tui";
1
+ import { Marked, Markdown, visibleWidth, type DefaultTextStyle, type MarkdownTheme } from "@earendil-works/pi-tui";
2
2
  import { render } from "grok-mermaid";
3
3
 
4
4
  const parser = new Marked();
@@ -7,21 +7,48 @@ const parser = new Marked();
7
7
  const languageToken = (lang?: string) => lang?.trim().split(/\s+/)[0].toLowerCase() ?? "";
8
8
 
9
9
  /** Theme emphasis remains visible when the terminal's CJK font lacks bold/italic faces. */
10
- export function minimalMarkdownTheme(base: MarkdownTheme): MarkdownTheme {
10
+ const REGISTERED_LANGUAGES = new Set([
11
+ "bash", "sh", "shell", "zsh", "fish", "powershell", "javascript", "js", "typescript", "ts", "jsx", "tsx",
12
+ "python", "ruby", "rust", "go", "java", "kotlin", "swift", "c", "cpp", "csharp", "php", "sql", "html", "css",
13
+ "scss", "sass", "less", "yaml", "yml", "json", "json5", "jsonc", "toml", "xml", "markdown", "md", "lua", "perl",
14
+ "r", "scala", "clojure", "elixir", "erlang", "haskell", "ocaml", "vim", "graphql", "protobuf", "hcl", "dockerfile",
15
+ ]);
16
+ const ANSI_FOREGROUND = /\x1b\[(?:38;(?:2;\d+;\d+;\d+|5;\d+)|3[0-9]|9[0-7])m/g;
17
+
18
+ export function minimalMarkdownTheme(base: MarkdownTheme, codeBackground = ""): MarkdownTheme {
11
19
  // Inline prose arrives with its default foreground already applied. Remove
12
20
  // those foreground codes before wrapping, otherwise they override emphasis.
13
21
  const emphasis = (text: string) => base.heading(text.replace(/\x1b\[(?:38;(?:2;\d+;\d+;\d+|5;\d+)|3[0-9]|9[0-7])m/g, ""));
14
22
  const highlightCode = base.highlightCode;
23
+ const neutralCode = (text: string) => base.codeBlock(text).replace(ANSI_FOREGROUND, "");
15
24
  return {
16
25
  ...base,
17
26
  bold: text => emphasis(base.bold(text)),
18
27
  italic: text => emphasis(base.italic(text)),
19
- // highlight.js knows languages, not info strings, so `ts title=x.ts` would
20
- // otherwise lose highlighting entirely.
21
- ...(highlightCode && { highlightCode: (code: string, lang?: string) => highlightCode(code, languageToken(lang)) }),
28
+ codeBlock: neutralCode,
29
+ // A blank, background-painted row replaces the old language/border text.
30
+ codeBlockBorder: () => codeBackground ? `${codeBackground} ` : "",
31
+ codeBlockIndent: codeBackground ? `${codeBackground} ` : " ",
32
+ // ponytail: reuse installed grammars; only registered languages are sent to it.
33
+ ...(highlightCode && { highlightCode: (code: string, lang?: string) => {
34
+ const language = languageToken(lang);
35
+ if (!REGISTERED_LANGUAGES.has(language) || /^(?:text|txt|plaintext)$/.test(language)) return code.split("\n").map(neutralCode);
36
+ return highlightCode(code, /^json[5c]$/.test(language) ? "javascript" : language);
37
+ } }),
22
38
  };
23
39
  }
24
40
 
41
+ /** Render Markdown with A's code-only background, after native wrapping has settled. */
42
+ 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);
46
+ if (!codeBackground) return rows;
47
+ return rows.map(row => row.startsWith(codeBackground)
48
+ ? `${row}${" ".repeat(Math.max(0, width - visibleWidth(row)))}\x1b[49m`
49
+ : row);
50
+ }
51
+
25
52
  type MarkdownNode = {
26
53
  type?: string;
27
54
  raw?: string;
@@ -27,10 +27,11 @@ export function paintExpandedHeading(theme: ExtensionContext["ui"]["theme"], lin
27
27
  * A row inside an expanded heading (selected) keeps the band instead: the
28
28
  * blended tint and the user surface both collapse into it. */
29
29
  export function minimalSurface(theme: ExtensionContext["ui"]["theme"], text: string, user = false, selected = false): string {
30
- const background = theme.getBgAnsi?.(selected ? "selectedBg" : "userMessageBg") ?? "";
31
- if (user || selected) return background
30
+ if (selected) return paintExpandedHeading(theme, text);
31
+ const background = theme.getBgAnsi?.("userMessageBg") ?? "";
32
+ if (user) return background
32
33
  ? background + text.replace(/\x1b\[(?:0|49)?m/g, (reset) => reset + background) + "\x1b[49m"
33
- : theme.bg(selected ? "selectedBg" : "userMessageBg", text);
34
+ : theme.bg("userMessageBg", text);
34
35
  const base = ansiColor(background);
35
36
  const accent = ansiColor(theme.fg("accent", "")) ?? ansiColor(theme.fg("success", ""));
36
37
  if (!base || !accent) return theme.bg("userMessageBg", text);
@@ -0,0 +1,119 @@
1
+ import { createServer } from "node:http";
2
+ import { randomBytes } from "node:crypto";
3
+ import { readFile } from "node:fs/promises";
4
+
5
+ export interface SettingsWebOptions {
6
+ idleTimeoutMs?: number;
7
+ onClose?: () => void;
8
+ }
9
+
10
+ const DEFAULT_IDLE_TIMEOUT_MS = 300_000;
11
+ const MIN_IDLE_TIMEOUT_MS = 1_000;
12
+ const MAX_IDLE_TIMEOUT_MS = 3_600_000;
13
+
14
+ /** Env override is validated to 1s..1h; a test override wins and is trusted. */
15
+ function configuredIdleTimeout(override: number | undefined): number {
16
+ if (override !== undefined) {
17
+ if (!Number.isFinite(override) || override <= 0) throw new TypeError("Invalid idle timeout");
18
+ return override;
19
+ }
20
+ const raw = process.env.PI_MINI_MODE_SETTINGS_IDLE_MS;
21
+ const value = Number(raw);
22
+ return raw !== undefined && Number.isInteger(value) && value >= MIN_IDLE_TIMEOUT_MS && value <= MAX_IDLE_TIMEOUT_MS
23
+ ? value : DEFAULT_IDLE_TIMEOUT_MS;
24
+ }
25
+
26
+ /** On-demand, loopback-only settings bridge; no polling or third-party runtime. */
27
+ export async function startSettingsWeb(snapshot: () => unknown, update: (value: unknown) => Promise<void>, options: SettingsWebOptions = {}) {
28
+ const token = randomBytes(24).toString("hex");
29
+ const html = await readFile(new URL("./settings.html", import.meta.url));
30
+ const idleTimeoutMs = configuredIdleTimeout(options.idleTimeoutMs);
31
+ let origin = "";
32
+ let queue = Promise.resolve();
33
+ let idleTimer: ReturnType<typeof setTimeout> | undefined;
34
+ let idleDeadline = Date.now() + idleTimeoutMs;
35
+ let closed = false;
36
+ let activeRequests = 0;
37
+ const close = () => {
38
+ if (closed) return;
39
+ closed = true;
40
+ if (idleTimer) clearTimeout(idleTimer);
41
+ idleTimer = undefined;
42
+ server.close();
43
+ server.closeAllConnections();
44
+ options.onClose?.();
45
+ };
46
+ const armIdle = () => {
47
+ if (closed || activeRequests > 0) return;
48
+ if (idleTimer) clearTimeout(idleTimer);
49
+ idleTimer = setTimeout(close, Math.max(0, idleDeadline - Date.now()));
50
+ idleTimer.unref();
51
+ };
52
+ /** Successful authorized traffic renews; failed or anonymous requests keep the old deadline. */
53
+ const touch = () => {
54
+ idleDeadline = Date.now() + idleTimeoutMs;
55
+ armIdle();
56
+ };
57
+ const server = createServer(async (req, res) => {
58
+ res.setHeader("Cache-Control", "no-store");
59
+ res.setHeader("X-Content-Type-Options", "nosniff");
60
+ res.setHeader("Referrer-Policy", "no-referrer");
61
+ res.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'");
62
+ if (req.headers.host !== origin.slice(7) || (req.headers.origin && req.headers.origin !== origin)) {
63
+ res.writeHead(403).end(); return;
64
+ }
65
+ if (req.url === "/" && req.method === "GET") {
66
+ res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(html); return;
67
+ }
68
+ if (req.url !== "/settings" || req.headers.authorization !== `Bearer ${token}`) {
69
+ res.writeHead(403).end(); return;
70
+ }
71
+ // Suspend the idle lease while handling so a slow save cannot be cut off;
72
+ // only a successful response re-arms it.
73
+ if (idleTimer) clearTimeout(idleTimer);
74
+ idleTimer = undefined;
75
+ let renewed = false;
76
+ activeRequests++;
77
+ try {
78
+ if (req.method === "PUT") {
79
+ if (req.headers["content-type"] !== "application/json") { res.writeHead(415).end(); return; }
80
+ let body = "";
81
+ for await (const chunk of req) {
82
+ body += chunk;
83
+ if (Buffer.byteLength(body) > 16384) { res.writeHead(413).end(); return; }
84
+ }
85
+ const value: unknown = JSON.parse(body);
86
+ const saving = queue.then(() => update(value));
87
+ queue = saving.catch(() => {});
88
+ await saving;
89
+ } else if (req.method !== "GET") { res.writeHead(405).end(); return; }
90
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
91
+ res.end(JSON.stringify(snapshot()));
92
+ renewed = true;
93
+ } catch (error) {
94
+ res.writeHead(error instanceof TypeError || error instanceof SyntaxError ? 400 : 500);
95
+ res.end("无法保存设置,请检查配置文件权限后重试。");
96
+ } finally {
97
+ activeRequests--;
98
+ if (renewed) touch();
99
+ else armIdle();
100
+ }
101
+ });
102
+ server.requestTimeout = 10000;
103
+ server.headersTimeout = 10000;
104
+ await new Promise<void>((resolve, reject) => {
105
+ server.once("error", reject);
106
+ server.listen(0, "127.0.0.1", () => { server.off("error", reject); resolve(); });
107
+ });
108
+ const address = server.address();
109
+ if (!address || typeof address === "string") throw new Error("无法启动设置服务");
110
+ origin = `http://127.0.0.1:${address.port}`;
111
+ server.unref();
112
+ touch();
113
+ return {
114
+ url: `${origin}/#${token}`,
115
+ get closed() { return closed; },
116
+ touch,
117
+ close,
118
+ };
119
+ }
@@ -0,0 +1,180 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
4
+ <title>Pi Mini Mode 设置</title>
5
+ <style>
6
+ :root{color-scheme:light dark;--background:light-dark(#f4f3ef,#141614);--foreground:light-dark(#1f241f,#eceee8);--surface:light-dark(#fffcf7,#1d211d);--muted:light-dark(#667066,#a8b0a4);--border:light-dark(#e2ddd4,#3a4038);--accent:light-dark(#2f5a3e,#b7d4b0);--destructive:light-dark(#a52c26,#ffafa5);--ring:var(--accent);--text-sm:.875rem;--text-base:1rem;--text-lg:2.75rem;--radius:8px}
7
+ *{box-sizing:border-box}body{margin:0;background:var(--background);color:var(--foreground);font:var(--text-base)/1.5 ui-sans-serif,system-ui,sans-serif}main{max-width:1080px;margin:auto;padding:40px 24px 72px}header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap}h1{font:italic 400 var(--text-lg)/1.05 "Didot","Bodoni 72","Iowan Old Style","Songti SC","STSong",serif;letter-spacing:.04em;margin:0}h2{font-size:var(--text-sm);font-weight:600;margin:0 0 12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}.tagline{margin:8px 0 0;color:var(--muted);font-size:var(--text-sm)}nav{display:flex;gap:8px;align-items:center}.hint{margin:12px 0 0;color:var(--accent);font-weight:600}section{margin:28px 0}button{font:inherit;color:inherit;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:8px 12px;cursor:pointer}button:disabled{opacity:.4;cursor:default}:focus-visible{outline:2px solid var(--ring);outline-offset:3px}#preview{padding:16px 20px;background:var(--surface);border:1px dashed var(--accent);border-radius:var(--radius);font:var(--text-sm)/1.8 ui-monospace,monospace;display:flex;align-items:center;gap:12px;overflow-x:auto;min-height:72px;white-space:nowrap}#preview button{flex:none;font:inherit;padding:4px 2px;border-color:transparent;cursor:grab;white-space:nowrap}#preview button:hover{border-color:var(--border)}#preview button.over{border-left:2px solid var(--accent)}#preview #preview-context{flex:1;display:flex;align-items:center;gap:8px;min-width:180px}.progress{flex:1;overflow:hidden;text-align:left;color:var(--accent);min-width:0}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:4px 16px}label{display:flex;align-items:center;gap:10px;padding:10px 0;cursor:pointer}input{accent-color:var(--accent);width:18px;height:18px;flex-shrink:0}.dragging{opacity:.45}#status{min-height:24px;color:var(--accent)}#status.error{color:var(--destructive)}#retry{margin-left:12px}[hidden]{display:none!important}nav button[aria-pressed=true]{border-color:var(--accent);color:var(--accent)}.features{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:12px}.feature{display:flex;flex-direction:column;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 18px}.feature-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.feature-head h3{margin:0;font-size:var(--text-base);font-weight:600}.feature-body{margin:10px 0 0;color:var(--muted);font-size:var(--text-sm);line-height:1.65}.feature-points{margin:10px 0 0;padding-left:1.15em;font-size:var(--text-sm);line-height:1.7}.feature-points li{margin:2px 0}.feature-points li::marker{color:var(--accent)}.feature-hint{margin:auto 0 0;padding-top:12px;color:var(--muted);font:var(--text-sm)/1.6 ui-monospace,monospace;overflow-wrap:anywhere}.feature-hint::before{content:'› ';color:var(--accent)}.switch{display:flex;align-items:center;gap:8px;padding:0;font-size:var(--text-sm);color:var(--muted)}@media(max-width:450px){h1{font-size:2rem}main{padding:24px 16px}}
8
+ </style>
9
+ <main>
10
+ <header>
11
+ <div><h1 id="title"></h1><p class="tagline" id="tagline"></p></div>
12
+ <nav>
13
+ <button type="button" id="lang-zh" aria-pressed="false">中文</button>
14
+ <button type="button" id="lang-en" aria-pressed="false">EN</button>
15
+ <button type="button" id="reset" disabled></button>
16
+ </nav>
17
+ </header>
18
+ <p class="hint" id="dragHint"></p>
19
+ <div role="status" aria-live="polite"><span id="status"></span><button id="retry" hidden></button></div>
20
+ <section><h2 id="previewHeading"></h2><div id="preview" role="group" tabindex="0"></div></section>
21
+ <section><h2 id="featuresHeading"></h2><div class="features" id="features"></div></section>
22
+ <section><h2 id="fieldsHeading"></h2><div class="grid" id="fields"></div></section>
23
+ <section><h2 id="optionsHeading"></h2><div class="grid" id="options"></div></section>
24
+ </main>
25
+ <script>
26
+ const $=id=>document.getElementById(id),token=location.hash.slice(1);
27
+ history.replaceState(null,'',location.pathname);
28
+ const I18N={
29
+ title:{zh:'Pi Mini Mode',en:'Pi Mini Mode'},
30
+ documentTitle:{zh:'Pi Mini Mode 设置',en:'Pi Mini Mode Settings'},
31
+ tagline:{zh:'极简状态栏配置',en:'Minimal status bar setup'},
32
+ dragHint:{zh:'拖拽预览中的字段可调整顺序,松手自动保存',en:'Drag items in the preview to reorder · Auto-saves on drop'},
33
+ previewHeading:{zh:'效果预览',en:'Preview'},
34
+ featuresHeading:{zh:'功能说明',en:'Features'},
35
+ fieldsHeading:{zh:'状态栏字段',en:'Status Bar Items'},
36
+ optionsHeading:{zh:'状态栏样式',en:'Status bar style'},
37
+ on:{zh:'开启',en:'On'},off:{zh:'关闭',en:'Off'},
38
+ featureList:{
39
+ zh:[
40
+ {id:'status',title:'状态栏指标',body:'一行看清会话状态,随终端宽度自动取舍,不换行。',points:['模型与思考等级,会话与缓存 Token、缓存命中率、费用估算','上下文用量进度条与百分比','生成速度 tok/s,从第一个输出 token 起算,不含等待首字'],hint:'勾选需要的字段,拖拽预览中的条目即可排序。'},
41
+ {id:'minimal',setting:'pi-mini-mode-minimal-show',title:'极简输出',body:'把对话收成结论:思考、工具与技能汇成一棵按时间排序的可折叠过程树。',points:['长用户消息默认保留前四行,点击折叠控件展开全文','子代理行可展开活动记录与最终输出','Ctrl+O 展开或收起完整过程树,新问题默认收起','最终 Markdown 流畅呈现,失败与中断明确标记'],hint:'/pi-mini-mode-minimal on|off · /pi-mini-mode-prompts · /pi-mini-mode-history'},
42
+ {id:'input-enhancements',setting:'pi-mini-mode-input-enhancements',title:'输入增强',body:'让输入框和消息里的图片、技能与文件路径直接可用。',points:['光标移入图片路径即可预览,全屏编辑器也支持悬停','图片路径收纳为 [image1] 标签,提交时保留原图','空白后输入 / 就地搜索技能,并在光标处插入','点击图片标签或消息中的文件路径,用系统默认应用打开'],hint:'Ctrl+V 粘贴图片(Windows/WSL 使用 Alt+V)'},
43
+ {id:'themes',title:'明暗主题',body:'内置 cc-dark 与 cc-light 两套主题,Markdown、代码高亮、表格与 Mermaid 图表一并适配明暗。',points:['用户消息使用主题的用户背景色,与正文清晰区分','不支持、不完整或过宽的图表保留源文本'],hint:'/pi-mini-mode-setup 重新选择主题与全局全屏模式'}
44
+ ],
45
+ en:[
46
+ {id:'status',title:'Status bar metrics',body:'The whole session state on one line, trimmed to fit narrow terminals instead of wrapping.',points:['Model and thinking level, session and cache tokens, cache hit rate, cost estimate','Context usage bar with percentage','Speed in tok/s, measured from the first output token, excluding time to first token'],hint:'Enable the items you need, then drag entries in the preview to reorder.'},
47
+ {id:'minimal',setting:'pi-mini-mode-minimal-show',title:'Minimal transcript',body:'Turns the conversation into conclusions: thinking, tools and skills collapse into one chronological, foldable tree.',points:['Long user messages keep four lines; click the fold control to expand','Subagent rows expand to activity and final output','Ctrl+O expands or collapses the full process tree; new questions start collapsed','Final Markdown streams plainly; failures and interrupts are marked'],hint:'/pi-mini-mode-minimal on|off · /pi-mini-mode-prompts · /pi-mini-mode-history'},
48
+ {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:['Preview an image as soon as the cursor enters its path; hovering works in fullscreen','Image paths collapse to [image1] labels while keeping the original path on submit','Type / after a space to search skills and insert one at the cursor','Click image labels or file paths in messages to open them in the default app'],hint:'Ctrl+V pastes images (Windows/WSL: Alt+V)'},
49
+ {id:'themes',title:'Light and dark themes',body:'Built-in cc-dark and cc-light adapt Markdown, code highlighting, tables and Mermaid diagrams to the color scheme.',points:['User messages use the theme user background to stand apart from the body','Unsupported, incomplete or overly wide diagrams keep their source text'],hint:'/pi-mini-mode-setup to pick a theme and global fullscreen mode again'}
50
+ ]
51
+ },
52
+ reset:{zh:'恢复默认',en:'Reset defaults'},
53
+ retry:{zh:'重试',en:'Retry'},
54
+ confirmReset:{zh:'恢复默认排序与显示设置?',en:'Reset layout and visibility to defaults?'},
55
+ connecting:{zh:'正在同步…',en:'Connecting…'},
56
+ connected:{zh:'已同步',en:'In sync'},
57
+ unsaved:{zh:'未保存修改',en:'Unsaved changes'},
58
+ saving:{zh:'正在保存…',en:'Saving…'},
59
+ saved:{zh:'已保存',en:'Saved'},
60
+ saveFailed:{zh:'保存失败',en:'Failed to save'},
61
+ reconnect:{zh:'连接已断开,请从终端重新打开',en:'Disconnected. Please reopen from the terminal.'},
62
+ emptyPreview:{zh:'(未启用任何字段)',en:'(No items enabled)'},
63
+ fields:{
64
+ 'project-branch':{zh:'项目与分支',en:'Project & Branch'},
65
+ model:{zh:'模型名称',en:'Model'},
66
+ thinking:{zh:'思考等级',en:'Thinking Level'},
67
+ branch:{zh:'仅分支',en:'Branch Only'},
68
+ 'session-tokens':{zh:'会话 Token',en:'Session Tokens'},
69
+ 'cache-tokens':{zh:'缓存 Token',en:'Cache Tokens'},
70
+ ch:{zh:'缓存命中率',en:'Cache Hit Rate'},
71
+ cost:{zh:'累计费用',en:'Cost'},
72
+ mcp:{zh:'MCP 服务数',en:'MCP Count'},
73
+ context:{zh:'上下文进度条',en:'Context Bar'},
74
+ 'context-percent':{zh:'上下文百分比',en:'Context %'},
75
+ speed:{zh:'生成速度',en:'Speed'},
76
+ 'context-dots':{zh:'点阵进度条',en:'Dot-matrix bar'},
77
+ 'speed-unit':{zh:'速度附带单位',en:'Speed unit (tok/s)'},
78
+ minimal:{zh:'极简对话输出',en:'Minimal transcript'},
79
+ 'input-enhancements':{zh:'输入体验增强',en:'Input enhancements'}
80
+ }
81
+ };
82
+ const FIELD_KEY={minimal:'pi-mini-mode-minimal-show','input-enhancements':'pi-mini-mode-input-enhancements','context-dots':'pi-mini-mode-context-dots-show','speed-unit':'pi-mini-mode-speed-unit-show'};
83
+ let lang=localStorage.piMiniModeLang||(navigator.language.startsWith('zh')?'zh':'en');
84
+ let data,state,order,dragged,saving=false,dirty=false,timer;
85
+ const key=id=>'pi-mini-mode-'+id+'-show';
86
+ const t=(id,fallback='')=>(I18N[id]?.[lang]??fallback);
87
+ const fieldLabel=id=>I18N.fields[id]?.[lang]||id;
88
+ const examples={'project-branch':'pi-mini-mode(main)',model:'deepseek-v4-flash',thinking:'high',branch:'main','session-tokens':'Total 45K','cache-tokens':'Cached 25K',ch:'CH 40.0%',cost:'$0.012',mcp:'◇ MCP 3',context:'500/1.0M','context-percent':'1%',speed:'120 tok/s'};
89
+ function status(text,error=false){$('status').textContent=text;$('status').className=error?'error':''}
90
+ function applyLang(){
91
+ document.documentElement.lang=lang==='zh'?'zh-CN':'en';
92
+ document.title=t('documentTitle');
93
+ for(const id of ['title','tagline','dragHint','previewHeading','featuresHeading','fieldsHeading','optionsHeading']) $(id).textContent=t(id);
94
+ $('reset').textContent=t('reset');$('retry').textContent=t('retry');
95
+ $('lang-zh').setAttribute('aria-pressed',String(lang==='zh'));
96
+ $('lang-en').setAttribute('aria-pressed',String(lang==='en'));
97
+ $('preview').setAttribute('aria-label',t('dragHint'));
98
+ }
99
+ async function request(method,body){
100
+ const response=await fetch('/settings',{method,headers:{Authorization:'Bearer '+token,...(body?{'Content-Type':'application/json'}:{})},body:body?JSON.stringify(body):undefined});
101
+ if(!response.ok)throw Error(await response.text()||t('saveFailed'));
102
+ return response.json();
103
+ }
104
+ function preview(){
105
+ const panel=$('preview'),scroll=panel.scrollLeft;
106
+ panel.replaceChildren();
107
+ const visible=order.filter(id=>state[key(id)]);
108
+ const values={...examples,speed:state['pi-mini-mode-speed-unit-show']?'120 tok/s':'120'};
109
+ for(const id of visible){
110
+ const button=document.createElement('button');
111
+ button.id='preview-'+id;button.type='button';button.textContent=values[id];button.draggable=true;
112
+ if(id==='context'){const bar=document.createElement('span');bar.className='progress';bar.setAttribute('aria-hidden','true');bar.textContent=state['pi-mini-mode-context-dots-show']?'⣿'+'⣀'.repeat(300):'█'+'░'.repeat(300);button.append(bar)}
113
+ button.setAttribute('aria-label',fieldLabel(id)+' · '+t('dragHint'));
114
+ button.ondragstart=event=>{dragged=id;event.dataTransfer.setData('text/plain',id);event.dataTransfer.effectAllowed='move';button.classList.add('dragging')};
115
+ button.ondragend=()=>{dragged=undefined;button.classList.remove('dragging');document.querySelectorAll('.over').forEach(el=>el.classList.remove('over'))};
116
+ button.ondragover=event=>{if(dragged){event.preventDefault();button.classList.add('over')}};
117
+ button.ondragleave=()=>button.classList.remove('over');
118
+ button.ondrop=event=>{event.preventDefault();const source=dragged;dragged=undefined;if(source){move(order.indexOf(source),order.indexOf(id));$('preview-'+source)?.focus()}};
119
+ button.onkeydown=event=>{if(event.key!=='ArrowLeft'&&event.key!=='ArrowRight')return;event.preventDefault();const target=visible[visible.indexOf(id)+(event.key==='ArrowLeft'?-1:1)];if(target){move(order.indexOf(id),order.indexOf(target));$('preview-'+id)?.focus()}};
120
+ panel.append(button);
121
+ }
122
+ if(!visible.length)panel.textContent=t('emptyPreview');
123
+ panel.scrollLeft=scroll;
124
+ }
125
+ function change(){dirty=true;state.footerOrder=[...order];preview();status(t('unsaved'));clearTimeout(timer);timer=setTimeout(save,250)}
126
+ async function save(){
127
+ if(saving)return;saving=true;$('retry').hidden=true;
128
+ try{while(dirty){dirty=false;const body=structuredClone(state);status(t('saving'));await request('PUT',body)}status(t('saved'))}
129
+ catch(error){dirty=true;status(t('saveFailed')+':'+error.message,true);$('retry').hidden=false}
130
+ finally{saving=false}
131
+ }
132
+ function box(settingId,onToggle){
133
+ const input=document.createElement('input');
134
+ input.type='checkbox';input.checked=!!state[settingId];input.id=settingId;
135
+ input.onchange=()=>{state[settingId]=input.checked;onToggle?.(input.checked)};
136
+ return input;
137
+ }
138
+ function feature(item){
139
+ const card=document.createElement('article');card.className='feature';
140
+ const head=document.createElement('div');head.className='feature-head';
141
+ const title=document.createElement('h3');title.textContent=item.title;head.append(title);
142
+ if(item.setting){
143
+ const label=document.createElement('label');label.className='switch';label.htmlFor=item.setting;
144
+ const text=document.createElement('span');text.textContent=state[item.setting]?t('on'):t('off');
145
+ label.append(box(item.setting,checked=>{text.textContent=checked?t('on'):t('off');change()}),text);
146
+ head.append(label);
147
+ }
148
+ const body=document.createElement('p');body.className='feature-body';body.textContent=item.body;
149
+ const points=document.createElement('ul');points.className='feature-points';
150
+ points.append(...item.points.map(point=>{const li=document.createElement('li');li.textContent=point;return li}));
151
+ const hint=document.createElement('p');hint.className='feature-hint';hint.textContent=item.hint;
152
+ card.append(head,body,points,hint);
153
+ return card;
154
+ }
155
+ function checkbox(id,settingId){
156
+ const label=document.createElement('label'),input=box(settingId,()=>{
157
+ if(state[settingId]&&(id==='project-branch'||id==='branch')){const other=key(id==='branch'?'project-branch':'branch');state[other]=false;const peer=$(other);if(peer)peer.checked=false}
158
+ change();
159
+ });
160
+ label.append(input,document.createTextNode(fieldLabel(id)));
161
+ return label;
162
+ }
163
+ function move(from,to){if(from===to||from<0||to<0||to>=order.length)return;const [id]=order.splice(from,1);order.splice(to,0,id);preview();change()}
164
+ function render(){
165
+ applyLang();
166
+ $('fields').replaceChildren(...order.map(id=>checkbox(id,key(id))));
167
+ $('features').replaceChildren(...t('featureList').map(feature));
168
+ $('options').replaceChildren(...['context-dots','speed-unit'].map(id=>checkbox(id,FIELD_KEY[id])));
169
+ preview();
170
+ }
171
+ function setLang(next){lang=next;localStorage.piMiniModeLang=lang;render()}
172
+ $('lang-zh').onclick=()=>setLang('zh');
173
+ $('lang-en').onclick=()=>setLang('en');
174
+ $('retry').onclick=save;
175
+ $('reset').onclick=()=>{if(!confirm(t('confirmReset')))return;state={...data.defaults};order=[...data.order];render();change()};
176
+ window.addEventListener('beforeunload',event=>{if(dirty||saving){event.preventDefault();event.returnValue=''}});
177
+ applyLang();status(t('connecting'));
178
+ request('GET').then(value=>{data=value;state={...data.settings};order=[...(state.footerOrder||data.order)];render();$('reset').disabled=false;status(t('connected'))}).catch(()=>status(t('reconnect'),true));
179
+ </script>
180
+ </html>
@@ -60,7 +60,7 @@ export function attachStickyTool(tui: unknown, document: Component, view: Sticky
60
60
  }
61
61
  // At the original heading, use its document row rather than duplicating it.
62
62
  shown = transcript.scrollTop > target.y ? target : undefined;
63
- return shown ? [truncateToWidth(width < 5 ? "▾" : shown.line, width, "")] : [];
63
+ return shown ? [truncateToWidth(width < 5 ? "▼" : shown.line, width, "")] : [];
64
64
  },
65
65
  handleMouse(event) {
66
66
  if (!shown) return;
@@ -1,13 +1,13 @@
1
1
  import { Markdown, Text, truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui";
2
2
  import { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { diagramMarkdown, isMarkdownProse, minimalMarkdownTheme } from "./minimal-markdown.ts";
3
+ import { diagramMarkdown, isMarkdownProse, renderMinimalMarkdown } from "./minimal-markdown.ts";
4
4
  import { stripVTControlCharacters } from "node:util";
5
5
  import { attachStickyTool } from "./sticky-tool.ts";
6
6
 
7
7
  const record = (value: unknown): Record<string, unknown> | undefined => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
8
8
  const clean = (text: string) => stripVTControlCharacters(text).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
9
- const renderMarkdownBody = (body: string, width: number) => isMarkdownProse(body)
10
- ? new Markdown(body, 0, 0, minimalMarkdownTheme(getMarkdownTheme()), undefined, { transform: diagramMarkdown }).render(Math.max(1, width))
9
+ const renderMarkdownBody = (body: string, width: number, theme?: ExtensionContext["ui"]["theme"]) => isMarkdownProse(body)
10
+ ? renderMinimalMarkdown(body, Math.max(1, width), getMarkdownTheme(), theme?.getBgAnsi?.("userMessageBg") ?? "", undefined, diagramMarkdown)
11
11
  : new Text(body, 0, 0).render(Math.max(1, width));
12
12
  const isSupervisorReply = (message: unknown) => record(message)?.customType === "subagent_supervisor_reply";
13
13
 
@@ -146,19 +146,22 @@ export function supervisorNotice(message: unknown) {
146
146
  const header = content?.match(/^(?:Background task|Detached foreground task) (completed|failed|paused|stopped):\s+\*\*([^\*\n]+)\*\*/m);
147
147
  if (!content || !header) return;
148
148
  const status = header[1];
149
- const failed = status === "failed" || status === "stopped";
149
+ const failed = status === "failed" || status === "stopped"
150
+ || /^- key=\S+ run=[0-9a-f-]{36} status=failed\s*$/mi.test(content)
151
+ || /^Child runs:.*\(failed\)/mi.test(content);
150
152
  const attention = status === "paused";
151
153
  const workflowRunId = content.match(/^Workflow run:\s*([0-9a-f-]{36})\s*$/mi)?.[1]
152
154
  ?? content.match(/^Workflow receipt:\s*.*?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/mi)?.[1];
153
155
  const childRunIds = content.match(/^Child runs:\s*(.+)$/mi)?.[1]
154
156
  ?.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) ?? [];
155
- const runIds = [...new Set([workflowRunId, ...childRunIds].filter((id): id is string => !!id))];
156
- const runId = workflowRunId || childRunIds[0];
157
+ const directoryRunId = content.match(/^Retention-managed async directory:[ \t]*(?:\r?\n)?[^\r\n]*\/async-subagent-runs\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/?[ \t]*\r?$/mi)?.[1];
158
+ const runIds = [...new Set([workflowRunId, directoryRunId, ...childRunIds].filter((id): id is string => !!id))];
159
+ const runId = workflowRunId || directoryRunId || childRunIds[0];
157
160
  const metadata = /^(?:Workflow (?:receipt|run):|Child runs:|Session(?: file| share error)?:|Retention-managed|Reconciled detached|Parallel handoff:|Watchdog blockers:)/i;
158
161
  let preview = "";
159
162
  for (const line of content.split("\n").slice(1)) {
160
163
  const text = line.trim();
161
- if (!text || text.startsWith("Workflow receipt:")) continue;
164
+ if (!text || text === `${header[2]}:` || text.startsWith("Workflow receipt:")) continue;
162
165
  if (metadata.test(text)) break;
163
166
  preview = text;
164
167
  break;
@@ -171,7 +174,8 @@ export function supervisorNotice(message: unknown) {
171
174
  alert: failed || attention,
172
175
  state: failed ? "执行失败" : attention ? "需要关注" : "已完成",
173
176
  color: failed ? "error" as const : attention ? "warning" as const : "muted" as const,
174
- summary: clean(preview) || (failed ? "子任务失败" : attention ? "等待回复" : "子任务已完成"),
177
+ summary: failed && status === "completed" ? "工作流包含失败子任务"
178
+ : clean(preview) || (failed ? "子任务失败" : attention ? "等待回复" : "子任务已完成"),
175
179
  label: clean(header[2]),
176
180
  showLabel: true,
177
181
  body: content,
@@ -239,7 +243,7 @@ export function compactGoalCard(entry: unknown, theme: ExtensionContext["ui"]["t
239
243
  const hint = theme.fg(expanded ? "accent" : "muted", " · Ctrl+O");
240
244
  const summary = truncateToWidth(objective, Math.max(0, width - visibleWidth(title) - visibleWidth(hint) - 3), "…");
241
245
  const rows = [truncateToWidth(`${title} · ${theme.fg(expanded ? "accent" : "text", summary)}${hint}`, width, "")];
242
- if (expanded) rows.push(...renderMarkdownBody(objective, width));
246
+ if (expanded) rows.push(...renderMarkdownBody(objective, width, theme));
243
247
  return rows;
244
248
  }
245
249
 
@@ -277,7 +281,7 @@ export function compactSupervisorNotice(message: unknown, theme: ExtensionContex
277
281
  if (body && !bodies.includes(body)) bodies.push(body);
278
282
  }
279
283
  for (const body of bodies) {
280
- rows.push(...renderMarkdownBody(body, width));
284
+ rows.push(...renderMarkdownBody(body, width, theme));
281
285
  }
282
286
  }
283
287
  return rows;
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@each1024/pi-mini-mode",
3
- "version": "1.3.11",
3
+ "version": "1.3.13",
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": {
7
7
  "check": "tsc --noEmit -p tsconfig.json",
8
- "test": "node test/footer-tidy.mjs && node test/footer-status-self-check.mjs && node test/settings-interaction.mjs && node test/transcript-adapter.mjs && node test/prompt-folding.mjs && node test/tool-folding.mjs && node test/sticky-tool.mjs && node test/minimal-markdown.mjs && node test/agent-view.mjs && node test/publish-self-check.mjs && node test/compaction-transcript.mjs && node test/input-enhancements.mjs && node test/user-message-surface.mjs"
8
+ "test": "node test/settings-web.mjs && node test/footer-tidy.mjs && node test/footer-status-self-check.mjs && node test/settings-interaction.mjs && node test/transcript-adapter.mjs && node test/prompt-folding.mjs && node test/tool-folding.mjs && node test/sticky-tool.mjs && node test/minimal-markdown.mjs && node test/agent-view.mjs && node test/publish-self-check.mjs && node test/compaction-transcript.mjs && node test/input-enhancements.mjs && node test/user-message-surface.mjs"
9
9
  },
10
10
  "license": "MIT",
11
11
  "author": "eachann1024",
@@ -21,7 +21,7 @@
21
21
  "text": "#f5f5f5",
22
22
  "muted": "#a1a1aa",
23
23
  "dim": "#71717a",
24
- "selectedBg": "#252035",
24
+ "selectedBg": "#293a5d",
25
25
  "userMessageBg": "#1c273b",
26
26
  "toolPendingBg": "#1b1924",
27
27
  "toolSuccessBg": "#1e1e2e",