import { stripTerminalSequences, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; import { CustomStyleConfig, SPINNERS, normalizeExtensionName, resolveSeparator, resolveStyleKey, styleSeparator, } from "./presets"; import { resolveActivePreset, runtime } from "./config"; export type BadgeSeverity = "error" | "warning" | "accent" | "success"; export interface ThemeLike { fg: (color: "success" | "warning" | "error" | "accent" | "muted" | "dim" | "text", text: string) => string; inverse?: (text: string) => string; } export interface Badge { key: string; val: string; rendered: string; isHighPriority: boolean; width: number; compactRendered: string; compactWidth: number; severity: BadgeSeverity; isSpinning: boolean; } export const GENERIC_IDLE_WORDS = new Set([ "ready", "idle", "ok", "online", "active", "connected", "listening", ]); const ERROR_PATTERN = /❌|πŸ”΄|βœ—|β–²|\b(?:error|err|fail(?:ed|ure)?|offline|stopped|crashed|broken)\b/i; const WARNING_PATTERN = /⏸|🟑|⚠|\b(?:warn(?:ing)?|paused?|blocked|waiting|retry(?:ing)?)\b/i; const SPINNING_PATTERN = /\b(?:running|working|starting|waiting|building|compiling|syncing|loading|streaming|implementing|verifying)\b|\.\.\.$|…$/i; const LEADING_ICON_PATTERN = /^[βŒ–βŒ¬β‡„β—β—β—“β—‘β—’βœ“βœ”βœ—βŒβš πŸ”΄πŸŸ‘πŸŸ’βΈβ–ͺβ—†β–²β—‡βœ¦βœ§βœΆ]+\s*/u; const MAX_DETAIL_COLS = 34; export function isSpinningStatus(value: string | undefined): boolean { if (!value) return false; return SPINNING_PATTERN.test(value) || /^\[\d+\/\d+\]/.test(value.trim()); } export function classifyStatus( name: string, cleanVal: string ): { severity: BadgeSeverity; isHighPriority: boolean; isSpinning: boolean } { const isSpinning = isSpinningStatus(cleanVal); if (ERROR_PATTERN.test(cleanVal)) { return { severity: "error", isHighPriority: true, isSpinning }; } if (WARNING_PATTERN.test(cleanVal)) { return { severity: "warning", isHighPriority: true, isSpinning }; } if (isSpinning || /^\[\d+\/\d+\]/.test(cleanVal)) { return { severity: "success", isHighPriority: true, isSpinning }; } if (name === "plan") { return { severity: "accent", isHighPriority: false, isSpinning: false }; } return { severity: "success", isHighPriority: false, isSpinning: false }; } function escapeRegExp(str: string): string { return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } /** * Strips ANSI escapes, collapses whitespace, removes redundant extension-name echo prefixes * and duplicate leading ecosystem icons, while keeping actual text intact. */ function extractBadgeDetail(rawKey: string, name: string, strippedVal: string): string { let detail = strippedVal.replace(/[\r\n\t]+/g, " ").replace(/ +/g, " ").trim(); if (!detail) return ""; const singleBracketMatch = detail.match(/^\[([^\]]+)\]$/); if (singleBracketMatch) { detail = singleBracketMatch[1].trim(); } for (const prefixCandidate of new Set([rawKey.trim(), name])) { if (!prefixCandidate) continue; const prefixRe = new RegExp(`^${escapeRegExp(prefixCandidate)}(?::\\s*|\\s+)`, "i"); if (prefixRe.test(detail)) { detail = detail.replace(prefixRe, "").trim(); } } detail = detail.replace(LEADING_ICON_PATTERN, "").trim(); if (!detail) return ""; return truncateToWidth(detail, MAX_DETAIL_COLS, "…"); } function renderBadgePair( name: string, detail: string | undefined, severity: BadgeSeverity, glyph: string, preset: CustomStyleConfig, theme: ThemeLike | null | undefined ): { rendered: string; plain: string } { const sep = resolveSeparator(preset); const openBracket = preset.brackets?.[0] ?? ""; const closeBracket = preset.brackets?.[1] ?? ""; const prefix = preset.prefix ?? ""; const suffix = preset.suffix ?? ""; const hasFg = Boolean(theme && typeof theme.fg === "function"); const visualName = preset.padName === true ? truncateToWidth(name, 10).padEnd(10, " ") : name; const styledName = hasFg ? theme!.fg("muted", visualName) : visualName; const styledGlyph = hasFg ? theme!.fg(severity, glyph) : glyph; const styledSep = styleSeparator(sep, theme); if (preset.inverse) { const pillContent = ` ${glyph}${detail ? ` ${detail}` : ""} `; const plain = `${prefix}${visualName}${sep}${pillContent}${suffix}`; if (theme && typeof theme.inverse === "function") { const coloredPill = theme.inverse(hasFg ? theme.fg(severity, pillContent) : pillContent); return { plain, rendered: `${prefix}${styledName}${styledSep}${coloredPill}${suffix}`, }; } return { plain, rendered: `${prefix}${styledName}${styledSep}${pillContent}${suffix}`, }; } let plainBody = glyph; let renderedBody = styledGlyph; if (openBracket && closeBracket) { plainBody = `${openBracket}${glyph}${detail ? ` ${detail}` : ""}${closeBracket}`; const openStyled = hasFg ? theme!.fg("dim", openBracket) : openBracket; const closeStyled = hasFg ? theme!.fg("dim", closeBracket) : closeBracket; renderedBody = `${openStyled}${styledGlyph}${detail ? ` ${detail}` : ""}${closeStyled}`; } else if (detail) { plainBody = `${glyph} (${detail})`; renderedBody = `${styledGlyph}${hasFg ? theme!.fg("dim", ` (${detail})`) : ` (${detail})`}`; } return { plain: `${prefix}${visualName}${sep}${plainBody}${suffix}`, rendered: `${prefix}${styledName}${styledSep}${renderedBody}${suffix}`, }; } function pickGlyph( name: string, severity: BadgeSeverity, isSpinning: boolean, styleKey: string, preset: CustomStyleConfig ): string { if (isSpinning) { return SPINNERS[Math.floor(Date.now() / 300) % SPINNERS.length]; } const isEcosystem = name === "anchor" || name === "toolflow" || name === "lingual"; if (isEcosystem && styleKey !== "custom") { if (name === "anchor") return "βŒ–"; if (name === "toolflow") return "⌬"; return "⇄"; } const customGlyph = preset.glyphs?.[severity]; if (customGlyph) return customGlyph; if (severity === "warning") return "β—Œ"; if (severity === "error") return "β–²"; if (severity === "accent") return "β—†"; return "●"; } export function formatBadge( key: string, originalVal: string | undefined, theme: ThemeLike | null | undefined, style: string, customCfg?: CustomStyleConfig ): Badge | null { if (originalVal === undefined) return null; const stripped = stripTerminalSequences(originalVal); const bounded = stripped.length > 512 ? [...stripped].slice(0, 512).join("") : stripped; const cleanVal = bounded.replace(/[\r\n\t]+/g, " ").replace(/ +/g, " ").trim(); if (!cleanVal) return null; const name = normalizeExtensionName(key); const styleKey = resolveStyleKey(style); if (styleKey === "off") { const plain = cleanVal; return { key, val: originalVal, rendered: originalVal, isHighPriority: false, width: visibleWidth(plain), compactRendered: originalVal, compactWidth: visibleWidth(plain), severity: "success", isSpinning: false, }; } const { preset } = resolveActivePreset(styleKey, customCfg, runtime.custom); const { severity, isHighPriority, isSpinning } = classifyStatus(name, cleanVal); const glyph = pickGlyph(name, severity, isSpinning, styleKey, preset); const detail = extractBadgeDetail(key, name, cleanVal); const fullPair = renderBadgePair(name, detail || undefined, severity, glyph, preset, theme); const compactDetail = detail && !GENERIC_IDLE_WORDS.has(detail.toLowerCase()) ? detail : undefined; const compactPair = compactDetail === (detail || undefined) ? fullPair : renderBadgePair(name, compactDetail, severity, glyph, preset, theme); return { key, val: originalVal, rendered: fullPair.rendered, isHighPriority, width: visibleWidth(fullPair.plain), compactRendered: compactPair.rendered, compactWidth: visibleWidth(compactPair.plain), severity, isSpinning, }; } export function beautifyStatus( key: string, originalVal: string | undefined, theme: ThemeLike | null | undefined, style: string, customCfg?: CustomStyleConfig, options?: { compact?: boolean } ): string | undefined { if (originalVal === undefined) return undefined; if (resolveStyleKey(style) === "off") return originalVal; if (stripTerminalSequences(originalVal).trim() === "") return ""; const badge = formatBadge(key, originalVal, theme, style, customCfg); if (!badge) return ""; return options?.compact ? badge.compactRendered : badge.rendered; } const SEP = " "; const SEP_WIDTH = 2; function foldLabel(theme: ThemeLike | null | undefined, count: number, kind: "idle" | "more"): { text: string; width: number; } { const plain = `(+${count} ${kind})`; return { text: theme && typeof theme.fg === "function" ? theme.fg("dim", plain) : plain, width: visibleWidth(plain), }; } function packListWithLabel( items: Array<{ rendered: string; width: number }>, maxWidth: number, extraFolded: number, kind: "idle" | "more", theme: ThemeLike | null | undefined ): string { if (items.length === 0) { if (extraFolded <= 0) return ""; const label = foldLabel(theme, extraFolded, kind); return label.width <= maxWidth ? label.text : truncateToWidth(`(+${extraFolded} more)`, maxWidth, ""); } let usedWidth = 0; let shown = 0; for (let i = 0; i < items.length; i++) { const remaining = items.length - (i + 1) + extraFolded; const label = remaining > 0 ? foldLabel(theme, remaining, kind) : undefined; const candidateWidth = usedWidth + (i > 0 ? SEP_WIDTH : 0) + items[i].width + (label ? SEP_WIDTH + label.width : 0); if (candidateWidth <= maxWidth) { usedWidth += (i > 0 ? SEP_WIDTH : 0) + items[i].width; shown = i + 1; } else { break; } } if (shown === 0) { const total = items.length + extraFolded; const label = foldLabel(theme, total, kind); return label.width <= maxWidth ? label.text : truncateToWidth(`(+${total} more)`, maxWidth, ""); } const head = items .slice(0, shown) .map((x) => x.rendered) .join(SEP); const remaining = items.length - shown + extraFolded; if (remaining <= 0) return head; return `${head}${SEP}${foldLabel(theme, remaining, kind).text}`; } export function formatFoldedBadges( badges: Badge[], maxWidth: number, theme: ThemeLike | null | undefined ): string { if (!badges || badges.length === 0 || maxWidth <= 0) return ""; const fullWidth = badges.reduce((sum, b, idx) => sum + (idx > 0 ? SEP_WIDTH : 0) + b.width, 0); if (fullWidth <= maxWidth) { return badges.map((b) => b.rendered).join(SEP); } const allCompactWidth = badges.reduce( (sum, b, idx) => sum + (idx > 0 ? SEP_WIDTH : 0) + b.compactWidth, 0 ); if (allCompactWidth <= maxWidth) { return badges.map((b) => b.compactRendered).join(SEP); } const high = badges.filter((b) => b.isHighPriority); const low = badges.filter((b) => !b.isHighPriority); if (high.length === 0) { return packListWithLabel( low.map((b) => ({ rendered: b.compactRendered, width: b.compactWidth })), maxWidth, 0, "idle", theme ); } const highCompact = high.map((b) => ({ rendered: b.compactRendered, width: b.compactWidth })); const highWidth = highCompact.reduce((sum, x, idx) => sum + (idx > 0 ? SEP_WIDTH : 0) + x.width, 0); if (highWidth > maxWidth) { return packListWithLabel(highCompact, maxWidth, low.length, "more", theme); } // Greedily pack as many compact idle badges as fit after high-priority badges before folding. const keptLow: string[] = []; let runningWidth = highWidth; for (let i = 0; i < low.length; i++) { const remainingAfter = low.length - (i + 1); const tail = remainingAfter > 0 ? SEP_WIDTH + foldLabel(theme, remainingAfter, "idle").width : 0; const candidateWidth = runningWidth + SEP_WIDTH + low[i].compactWidth + tail; if (candidateWidth <= maxWidth) { runningWidth += SEP_WIDTH + low[i].compactWidth; keptLow.push(low[i].compactRendered); } else { break; } } const combinedHead = [...highCompact.map((x) => x.rendered), ...keptLow].join(SEP); const foldedLow = low.length - keptLow.length; if (foldedLow === 0) return combinedHead; const tail = foldLabel(theme, foldedLow, "idle"); if (runningWidth + SEP_WIDTH + tail.width <= maxWidth) { return `${combinedHead}${SEP}${tail.text}`; } return highCompact.map((x) => x.rendered).join(SEP); }