@each1024/pi-mini-mode 1.3.1 → 1.3.3

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.
@@ -1,10 +1,111 @@
1
- import { Marked } from "@earendil-works/pi-tui";
1
+ import { Marked, type MarkdownTheme } from "@earendil-works/pi-tui";
2
2
  import { render } from "grok-mermaid";
3
3
 
4
4
  const parser = new Marked();
5
+
6
+ /** Theme emphasis remains visible when the terminal's CJK font lacks bold/italic faces. */
7
+ export function minimalMarkdownTheme(base: MarkdownTheme): MarkdownTheme {
8
+ // Inline prose arrives with its default foreground already applied. Remove
9
+ // those foreground codes before wrapping, otherwise they override emphasis.
10
+ const emphasis = (text: string) => base.heading(text.replace(/\x1b\[(?:38;(?:2;\d+;\d+;\d+|5;\d+)|3[0-9]|9[0-7])m/g, ""));
11
+ return {
12
+ ...base,
13
+ bold: text => emphasis(base.bold(text)),
14
+ italic: text => emphasis(base.italic(text)),
15
+ };
16
+ }
17
+
18
+ type MarkdownNode = {
19
+ type?: string;
20
+ raw?: string;
21
+ text?: string;
22
+ tokens?: MarkdownNode[];
23
+ items?: MarkdownNode[];
24
+ header?: MarkdownNode[] | boolean;
25
+ rows?: MarkdownNode[][];
26
+ };
27
+
28
+ /** Tolerate model-generated emphasis in prose, preserving code, escapes and URLs. */
29
+ export function normalizeProseMarkdown(source: string): string {
30
+ if (!/[*_~]/.test(source)) return source;
31
+ const repairInline = (raw: string, mask: string): string => {
32
+ // Mask parsed constructs so delimiters in code, links or existing emphasis
33
+ // cannot be mistaken for an opening/closing pair. Their contents can still
34
+ // sit between a pair of otherwise unparsed prose delimiters.
35
+ const pattern = /(?<![\\*_~])(\*\*|__|~~|\*|_)(?![*_~])([^\n]*?)\1(?![*_~])/g;
36
+ const edits: { start: number; end: number; text: string }[] = [];
37
+ for (const match of mask.matchAll(pattern)) {
38
+ const start = match.index!;
39
+ const marker = match[1];
40
+ if (marker.includes("_") && /[\p{L}\p{N}_]/u.test(raw[start - 1] ?? "")) continue;
41
+ const body = raw.slice(start + marker.length, start + match[0].length - marker.length);
42
+ if (marker.length === 1 && /^\s/.test(body)) continue; // e.g. prose multiplication: a * b * c
43
+ const trimmed = body.trim();
44
+ if (!trimmed || trimmed.endsWith("\\")) continue;
45
+ const punctuation = /[,。!?;:、]+$/.exec(trimmed)?.[0] ?? "";
46
+ const content = trimmed.slice(0, trimmed.length - punctuation.length);
47
+ if (!content) continue;
48
+ const delimiter = marker.replace(/_/g, "*");
49
+ edits.push({ start, end: start + match[0].length,
50
+ text: `${body.match(/^\s*/)?.[0] ?? ""}${delimiter}${content}${delimiter}${punctuation}${body.match(/\s*$/)?.[0] ?? ""}` });
51
+ }
52
+ for (const edit of edits.reverse()) raw = raw.slice(0, edit.start) + edit.text + raw.slice(edit.end);
53
+ return raw;
54
+ };
55
+ const rewrite = (node: MarkdownNode): string => {
56
+ const raw = node.raw ?? node.text ?? "";
57
+ const children = node.tokens ?? node.items ?? (Array.isArray(node.header) ? [...node.header, ...(node.rows ?? []).flat()] : undefined);
58
+ if (!children) return raw;
59
+ const inline = ["paragraph", "heading", "text", "strong", "em", "del", "link"].includes(node.type ?? "") || !node.type;
60
+ let cursor = 0;
61
+ let result = "";
62
+ let mask = "";
63
+ for (const child of children) {
64
+ const original = child.raw ?? child.text;
65
+ if (!original) continue;
66
+ const replacement = rewrite(child);
67
+ const start = raw.indexOf(original, cursor);
68
+ if (start < 0) {
69
+ // Blockquote/list prefixes interrupt multiline raw tokens. Map each
70
+ // line separately, retaining those prefixes and the original layout.
71
+ const before = original.split("\n");
72
+ const after = replacement.split("\n");
73
+ if (inline || before.length !== after.length) return raw;
74
+ for (let i = 0; i < before.length; i++) {
75
+ if (!before[i]) continue;
76
+ const position = raw.indexOf(before[i], cursor);
77
+ if (position < 0) return raw;
78
+ result += raw.slice(cursor, position) + after[i];
79
+ cursor = position + before[i].length;
80
+ }
81
+ continue;
82
+ }
83
+ result += raw.slice(cursor, start) + replacement;
84
+ mask += raw.slice(cursor, start).replace(/[^\n]/g, "\0")
85
+ + (child.type === "text" && !child.tokens ? replacement : replacement.replace(/[^\n]/g, "\0"));
86
+ cursor = start + original.length;
87
+ }
88
+ result += raw.slice(cursor);
89
+ mask += raw.slice(cursor).replace(/[^\n]/g, "\0");
90
+ return inline ? repairInline(result, mask) : result;
91
+ };
92
+ return parser.lexer(source).map(rewrite).join("");
93
+ }
94
+
95
+ /** Markdown is rendered only for semantic prose bodies; structured tool output stays literal. */
96
+ export function isMarkdownProse(source: string): boolean {
97
+ const text = source.trim();
98
+ if (!text || /^(?:\{[\s\S]*\}|\[[\s\S]*\])$/.test(text)) {
99
+ try { JSON.parse(text); return false; } catch { /* a Markdown list may start with [ */ }
100
+ }
101
+ if (/^(?:\s*```|\s*#{1,6}\s|\s*>\s|\s*(?:[-+*]\s+|\d+[.)]\s))/m.test(text)) return true;
102
+ return /(?:\*\*|__|~~|`[^`\n]+`|\[[^\]\n]+\]\([^\n)]+\))/.test(text)
103
+ && !/^(?:const|let|var|function|class|import|export|SELECT|INSERT|UPDATE|DELETE)\b/m.test(text);
104
+ }
105
+
5
106
  /** Keep incomplete, unsupported and over-wide diagrams readable as source. */
6
107
  export function diagramMarkdown(source: string, width: number): string {
7
- return parser.lexer(source).map((token) => {
108
+ return parser.lexer(normalizeProseMarkdown(source)).map((token) => {
8
109
  if (token.type !== "code" || token.lang?.trim().toLowerCase() !== "mermaid") return token.raw;
9
110
  const art = render(token.text);
10
111
  if (!art || art.width > width || art.warnings.length) return token.raw;
@@ -0,0 +1,100 @@
1
+ import { ScrollView, VStack, truncateToWidth, type Component } from "@earendil-works/pi-tui";
2
+ import { createRequire } from "node:module";
3
+ import type { getLayoutNode as GetLayoutNode } from "@earendil-works/pi-tui/dist/layout-node.js";
4
+
5
+ interface StickyToolView {
6
+ pinnedTool(): { id: string; y: number; line: string; autoScroll?: boolean } | undefined;
7
+ unpinTool(): void;
8
+ toggleTool(id: string): void;
9
+ }
10
+
11
+ /** ponytail: Pi 0.85 layoutRoot + optional internal layout-node export;
12
+ * replace discovery with a public primary-scroll/layout getter when available. */
13
+ export function attachStickyTool(tui: unknown, document: Component, view: StickyToolView, setMinHeight: (height: number) => void = () => {}): (() => void) | undefined {
14
+ const host = tui as { mode?: string; terminal?: { rows: number }; layoutRoot?: Component; setLayoutRoot?: (root: Component) => void; requestRender?: () => void };
15
+ if (host.mode !== "fullscreen" || !host.layoutRoot || !host.setLayoutRoot || !host.requestRender) return;
16
+ let getNode: typeof GetLayoutNode;
17
+ try { getNode = createRequire(import.meta.url)("@earendil-works/pi-tui/dist/layout-node.js").getLayoutNode; }
18
+ catch { return; }
19
+ if (typeof getNode !== "function") return;
20
+ const originalRoot = host.layoutRoot;
21
+ let scroll: ScrollView | undefined;
22
+ let primaries = 0;
23
+ const seen = new Set<Component>();
24
+ const inspect = (component: Component): boolean => {
25
+ if (seen.has(component)) return false;
26
+ seen.add(component);
27
+ const node = getNode(component);
28
+ if (!node) return true;
29
+ if (node.type === "scroll") {
30
+ if (node.state.primary) {
31
+ primaries++;
32
+ if (component instanceof ScrollView && node.component === document) scroll = component;
33
+ }
34
+ return true;
35
+ }
36
+ if (node.type !== "vstack" || !(component instanceof VStack)) return false;
37
+ return node.entries.every(entry => inspect(entry.component));
38
+ };
39
+ try { if (!inspect(originalRoot) || primaries !== 1 || !scroll) return; }
40
+ catch { return; }
41
+ const transcript = scroll;
42
+ let currentId: string | undefined;
43
+ let shown: { id: string; line: string } | undefined;
44
+ const heading: Component = {
45
+ invalidate() {},
46
+ render(width) {
47
+ // Measure the unchanged document before moving the existing ScrollView.
48
+ setMinHeight(0);
49
+ document.render(transcript.getContentWidth(width));
50
+ const target = view.pinnedTool();
51
+ if (!target) {
52
+ currentId = undefined;
53
+ shown = undefined;
54
+ return [];
55
+ }
56
+ if (target.id !== currentId) {
57
+ currentId = target.id;
58
+ // Suspend follow-end before layout grows, without moving the reading position.
59
+ transcript.scrollTo(transcript.scrollTop, { disableFollow: true });
60
+ }
61
+ // At the original heading, use its document row rather than duplicating it.
62
+ shown = transcript.scrollTop > target.y ? target : undefined;
63
+ return shown ? [truncateToWidth(width < 5 ? "▾" : shown.line, width, "")] : [];
64
+ },
65
+ handleMouse(event) {
66
+ if (!shown) return;
67
+ if (event.type === "wheel") {
68
+ transcript.scrollBy(event.wheelDelta ?? 0);
69
+ return { handled: true, render: true };
70
+ }
71
+ // Dedicated layout row: never dispatch its clicks into underlying links.
72
+ if (event.button === "left" && !event.shift && !event.ctrl && !event.alt) {
73
+ if (event.type === "press") return { handled: true };
74
+ if (event.type === "click") {
75
+ view.toggleTool(shown.id);
76
+ return { handled: true, render: true };
77
+ }
78
+ }
79
+ },
80
+ };
81
+ const section = new VStack([
82
+ { component: heading, basis: "auto", shrink: 0 },
83
+ { component: transcript, basis: 0, grow: 1, shrink: 1, minSize: 1 },
84
+ ]);
85
+ const replace = (component: Component): Component => {
86
+ if (component === transcript) return section;
87
+ const node = getNode(component);
88
+ if (node?.type !== "vstack") return component;
89
+ const entries = node.entries.map(entry => ({ ...entry, component: replace(entry.component) }));
90
+ return entries.some((entry, index) => entry.component !== node.entries[index].component)
91
+ ? new VStack(entries, { gap: node.gap, align: node.align }) : component;
92
+ };
93
+ const root = replace(originalRoot);
94
+ host.setLayoutRoot(root);
95
+ return () => {
96
+ view.unpinTool();
97
+ setMinHeight(0);
98
+ if (host.layoutRoot === root) host.setLayoutRoot!(originalRoot);
99
+ };
100
+ }
@@ -0,0 +1,57 @@
1
+ /** Strip noisy prefixes/suffixes from the terminal window title. */
2
+
3
+ import { basename } from "node:path";
4
+
5
+ type TitleCtx = {
6
+ cwd?: string;
7
+ getSessionName?: () => string | undefined;
8
+ ui: { setTitle(title: string): void };
9
+ };
10
+
11
+ type ExtensionAPILike = {
12
+ getSessionName?: () => string | undefined;
13
+ on(event: string, handler: (...args: any[]) => void): void;
14
+ };
15
+
16
+ function escapeRe(s: string): string {
17
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
18
+ }
19
+
20
+ function plainTitle(name: string | undefined, cwd: string | undefined): string {
21
+ let t = String(name || "").replace(/[\r\n\t]+/g, " ").trim();
22
+ t = t.replace(/^(π|pi)\s*[-–—:|]\s*/i, "");
23
+ const base = cwd ? basename(cwd.replace(/\/+$/, "")) : "";
24
+ if (base) t = t.replace(new RegExp(`\\s*[-–—]\\s*${escapeRe(base)}\\s*$`, "i"), "");
25
+ t = t.replace(/\s*[-–—]\s*(ravenclaw|goose-agent|goose-note|goose-monitor|loopdesk|diteng[\w-]*)\s*$/i, "");
26
+ return t.trim();
27
+ }
28
+
29
+ function apply(ctx: TitleCtx, name: string | undefined, pi: ExtensionAPILike): void {
30
+ const raw = name ?? ctx.getSessionName?.() ?? pi.getSessionName?.();
31
+ const title = plainTitle(raw, ctx.cwd);
32
+ if (title) ctx.ui.setTitle(title);
33
+ }
34
+
35
+ /** Attach title-plain behavior. */
36
+ export default function attachTitlePlain(pi: ExtensionAPILike): void {
37
+ let timer: ReturnType<typeof setInterval> | undefined;
38
+ let lastCtx: TitleCtx | undefined;
39
+
40
+ const start = (event: { name?: string } | undefined, ctx: TitleCtx) => {
41
+ lastCtx = ctx;
42
+ apply(ctx, event?.name ?? pi.getSessionName?.(), pi);
43
+ if (timer) clearInterval(timer);
44
+ timer = setInterval(() => {
45
+ if (lastCtx) apply(lastCtx, pi.getSessionName?.(), pi);
46
+ }, 400);
47
+ timer.unref?.();
48
+ };
49
+
50
+ pi.on("session_start", start);
51
+ pi.on("session_info_changed", start);
52
+ pi.on("session_shutdown", () => {
53
+ if (timer) clearInterval(timer);
54
+ timer = undefined;
55
+ lastCtx = undefined;
56
+ });
57
+ }