Something went wrong. Try again.
fork of prime agent with changes i want but are not upstreamable probqbly (and some fixes)
Something went wrong. Try again.
38 kB · 1377 lines
TypeScript
at main
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378import { eastAsianWidth } from "get-east-asian-width";
// Grapheme segmenter (shared instance)const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
/** * Get the shared grapheme segmenter instance. */export function getSegmenter(): Intl.Segmenter { return segmenter;}
/** * Check if a grapheme cluster (after segmentation) could possibly be an RGI emoji. * This is a fast heuristic to avoid the expensive rgiEmojiRegex test. * The tested Unicode blocks are deliberately broad to account for future * Unicode additions. */function couldBeEmoji(segment: string): boolean { const cp = segment.codePointAt(0)!; return ( (cp >= 0x1f000 && cp <= 0x1fbff) || // Emoji and Pictograph (cp >= 0x2300 && cp <= 0x23ff) || // Misc technical (cp >= 0x2600 && cp <= 0x27bf) || // Misc symbols, dingbats (cp >= 0x2b50 && cp <= 0x2b55) || // Specific stars/circles segment.includes("\uFE0F") || // Contains VS16 (emoji presentation selector) segment.length > 2 // Multi-codepoint sequences (ZWJ, skin tones, etc.) );}
// Regexes for character classification (same as string-width library)const nonPrintableAsciiRegex = /[^\x20-\x7e]/;const zeroWidthRegex = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/v;const leadingNonPrintingRegex = /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v;const rgiEmojiRegex = /^\p{RGI_Emoji}$/v;
// Cache for non-ASCII stringsconst WIDTH_CACHE_SIZE = 512;const widthCache = new Map<string, number>();
function isPrintableAscii(str: string): boolean { return !nonPrintableAsciiRegex.test(str);}
function truncateFragmentToWidth(text: string, maxWidth: number): { text: string; width: number } { if (maxWidth <= 0 || text.length === 0) { return { text: "", width: 0 }; }
if (isPrintableAscii(text)) { const clipped = text.slice(0, maxWidth); return { text: clipped, width: clipped.length }; }
const hasAnsi = text.includes("\x1b"); const hasTabs = text.includes("\t"); if (!hasAnsi && !hasTabs) { let result = ""; let width = 0; for (const { segment } of segmenter.segment(text)) { const w = graphemeWidth(segment); if (width + w > maxWidth) { break; } result += segment; width += w; } return { text: result, width }; }
let result = ""; let width = 0; let i = 0; let pendingAnsi = ""; const extractAnsi = createAnsiCodeExtractor(text);
while (i < text.length) { const ansi = extractAnsi(i); if (ansi) { pendingAnsi += ansi.code; i += ansi.length; continue; }
if (text[i] === "\t") { if (width + 3 > maxWidth) { break; } if (pendingAnsi) { result += pendingAnsi; pendingAnsi = ""; } result += "\t"; width += 3; i++; continue; }
let end = i; while (end < text.length && text[end] !== "\t") { const nextAnsi = extractAnsi(end); if (nextAnsi) { break; } end++; }
for (const { segment } of segmenter.segment(text.slice(i, end))) { const w = graphemeWidth(segment); if (width + w > maxWidth) { return { text: result, width }; } if (pendingAnsi) { result += pendingAnsi; pendingAnsi = ""; } result += segment; width += w; } i = end; }
return { text: result, width };}
function finalizeTruncatedResult( prefix: string, prefixWidth: number, ellipsis: string, ellipsisWidth: number, maxWidth: number, pad: boolean,): string { const reset = "\x1b[0m"; const visibleWidth = prefixWidth + ellipsisWidth; const prefixHasAnsi = prefix.includes("\x1b"); const ellipsisHasAnsi = ellipsis.includes("\x1b"); const beforeEllipsis = prefixHasAnsi ? reset : ""; const afterEllipsis = prefixHasAnsi || ellipsisHasAnsi ? reset : ""; const result = ellipsis.length > 0 ? `${prefix}${beforeEllipsis}${ellipsis}${afterEllipsis}` : `${prefix}${beforeEllipsis}`;
return pad ? result + " ".repeat(Math.max(0, maxWidth - visibleWidth)) : result;}
/** * Calculate the terminal width of a single grapheme cluster. * Based on code from the string-width library, but includes a possible-emoji * check to avoid running the RGI_Emoji regex unnecessarily. */function graphemeWidth(segment: string): number { // Zero-width clusters if (zeroWidthRegex.test(segment)) { return 0; }
// Emoji check with pre-filter if (couldBeEmoji(segment) && rgiEmojiRegex.test(segment)) { return 2; }
// Get base visible codepoint const base = segment.replace(leadingNonPrintingRegex, ""); const cp = base.codePointAt(0); if (cp === undefined) { return 0; }
// Regional indicator symbols (U+1F1E6..U+1F1FF) are often rendered as // full-width emoji in terminals, even when isolated during streaming. // Keep width conservative (2) to avoid terminal auto-wrap drift artifacts. if (cp >= 0x1f1e6 && cp <= 0x1f1ff) { return 2; }
let width = eastAsianWidth(cp);
// Trailing halfwidth/fullwidth forms and AM vowels that segment with a base. if (segment.length > 1) { for (const char of segment.slice(1)) { const c = char.codePointAt(0)!; if (c >= 0xff00 && c <= 0xffef) { width += eastAsianWidth(c); } else if (c === 0x0e33 || c === 0x0eb3) { width += 1; } } }
return width;}
/** * Calculate the visible width of a string in terminal columns. */export function visibleWidth(str: string): number { if (str.length === 0) { return 0; }
// Fast path: pure ASCII printable if (isPrintableAscii(str)) { return str.length; }
// Check cache const cached = widthCache.get(str); if (cached !== undefined) { return cached; }
// Normalize: tabs to 3 spaces, strip ANSI escape codes let clean = str; if (str.includes("\t")) { clean = clean.replace(/\t/g, " "); } if (clean.includes("\x1b")) { // Strip supported ANSI/OSC/APC escape sequences in one pass. // This covers CSI styling/cursor codes, OSC hyperlinks and prompt markers, // and APC sequences like CURSOR_MARKER. let stripped = ""; let i = 0; const extractAnsi = createAnsiCodeExtractor(clean); while (i < clean.length) { const ansi = extractAnsi(i); if (ansi) { i += ansi.length; continue; } stripped += clean[i]; i++; } clean = stripped; }
// Calculate width let width = 0; for (const { segment } of segmenter.segment(clean)) { width += graphemeWidth(segment); }
// Cache result if (widthCache.size >= WIDTH_CACHE_SIZE) { const firstKey = widthCache.keys().next().value; if (firstKey !== undefined) { widthCache.delete(firstKey); } } widthCache.set(str, width);
return width;}
/** Find the terminal-column span containing visible, non-whitespace content. */export function visibleContentSpan(line: string, maxWidth: number): { from: number; to: number } | null { const limit = Math.floor(maxWidth); if (line.length === 0 || !Number.isFinite(limit) || limit <= 0) { return null; }
let from = -1; let to = -1; let currentCol = 0; let i = 0; const extractAnsi = createAnsiCodeExtractor(line);
while (i < line.length && currentCol < limit) { const ansi = extractAnsi(i); if (ansi) { i += ansi.length; continue; }
if (line[i] === "\t") { currentCol += 3; i++; continue; }
let textEnd = i; while (textEnd < line.length && line[textEnd] !== "\t" && !extractAnsi(textEnd)) { textEnd++; }
for (const { segment } of segmenter.segment(line.slice(i, textEnd))) { const width = graphemeWidth(segment); const segmentStart = currentCol; const segmentEnd = currentCol + width; if (width > 0 && segment.trim().length > 0 && segmentStart < limit) { if (from === -1) from = segmentStart; to = Math.min(segmentEnd, limit); } currentCol = segmentEnd; if (currentCol >= limit) break; } i = textEnd; }
return from === -1 ? null : { from, to };}
/** * Normalize text for terminal output without changing logical editor content. * Some terminals render precomposed Thai/Lao AM vowels inconsistently during * differential repaint. Their compatibility decompositions have the same cell * width but avoid stale-cell artifacts in terminal renderers. */const THAI_LAO_AM_REGEX = /[\u0e33\u0eb3]/;const THAI_LAO_AM_GLOBAL_REGEX = /[\u0e33\u0eb3]/g;const TAB_REGEX = /\t/;const TAB_GLOBAL_REGEX = /\t/g;
export function normalizeTerminalOutput(str: string): string { const hasThaiLaoAm = THAI_LAO_AM_REGEX.test(str); const hasTab = TAB_REGEX.test(str); if (!hasThaiLaoAm && !hasTab) return str;
let normalized = str; if (hasThaiLaoAm) { normalized = normalized.replace(THAI_LAO_AM_GLOBAL_REGEX, (char) => char === "\u0e33" ? "\u0e4d\u0e32" : "\u0ecd\u0eb2", ); } if (hasTab) { normalized = normalized.replace(TAB_GLOBAL_REGEX, " "); } return normalized;}
interface AnsiCode { code: string; length: number;}
type ControlStringEnds = Map<number, number | null>;
interface AnsiScanState { controlStringEnds?: ControlStringEnds;}
function cacheControlStringEnds(str: string, from: number, ends: ControlStringEnds): void { let nextBel = -1; let nextSt = -1;
for (let i = str.length - 1; i >= from; i--) { if (str[i] === "\x07") { nextBel = i; } if (str[i] !== "\x1b") { continue; }
const next = str[i + 1]; if (next === "\\") { nextSt = i; } else if (next === "]" || next === "_") { if (nextBel !== -1 && (nextSt === -1 || nextBel < nextSt)) { ends.set(i, nextBel + 1); } else { ends.set(i, nextSt === -1 ? null : nextSt + 2); } } else if (next === "P" || next === "^" || next === "X") { ends.set(i, nextSt === -1 ? null : nextSt + 2); } }}
function extractControlStringEnd(str: string, pos: number, allowBel: boolean, state?: AnsiScanState): number | null { if (state?.controlStringEnds?.has(pos)) { const end = state.controlStringEnds.get(pos); return end ?? null; }
let j = pos + 2; while (j < str.length) { if (allowBel && str[j] === "\x07") { return j + 1; } if (str[j] === "\x1b" && str[j + 1] === "\\") { return j + 2; } j++; } if (state) { const ends: ControlStringEnds = new Map(); cacheControlStringEnds(str, pos, ends); state.controlStringEnds = ends; } return null;}
function extractAnsiEndAt(str: string, pos: number, state?: AnsiScanState): number | null { if (pos >= str.length || str[pos] !== "\x1b") return null;
const next = str[pos + 1];
// CSI: parameter bytes, then intermediate bytes, then one final byte. if (next === "[") { let j = pos + 2; let hasIntermediate = false; while (j < str.length) { const byte = str.charCodeAt(j); if (byte >= 0x30 && byte <= 0x3f && !hasIntermediate) { j++; continue; } if (byte >= 0x20 && byte <= 0x2f) { hasIntermediate = true; j++; continue; } if (byte >= 0x40 && byte <= 0x7e) { return j + 1; } return null; } return null; }
// OSC uses BEL or ST. APC also accepts BEL for existing private markers. if (next === "]" || next === "_") { return extractControlStringEnd(str, pos, true, state); }
// DCS, PM, and SOS are terminated by ST. if (next === "P" || next === "^" || next === "X") { return extractControlStringEnd(str, pos, false, state); }
return null;}
function extractAnsiCodeAt(str: string, pos: number, state?: AnsiScanState): AnsiCode | null { const end = extractAnsiEndAt(str, pos, state); return end === null ? null : { code: str.substring(pos, end), length: end - pos };}
/** Extract an ANSI escape sequence from a string at the given position. */export function extractAnsiCode(str: string, pos: number): AnsiCode | null { return extractAnsiCodeAt(str, pos);}
/** Create a scanner whose malformed-control-string cache is released after this string scan. */export function createAnsiCodeExtractor(str: string): (pos: number) => AnsiCode | null { const state: AnsiScanState = {}; return (pos) => extractAnsiCodeAt(str, pos, state);}
function createAnsiEndExtractor(str: string): (pos: number) => number | null { const state: AnsiScanState = {}; return (pos) => extractAnsiEndAt(str, pos, state);}
type Osc8Terminator = "\x07" | "\x1b\\";
interface ActiveHyperlink { params: string; url: string; terminator: Osc8Terminator;}
function parseOsc8Hyperlink(ansiCode: string): ActiveHyperlink | null | undefined { if (!ansiCode.startsWith("\x1b]8;")) { return undefined; }
const terminator: Osc8Terminator = ansiCode.endsWith("\x07") ? "\x07" : "\x1b\\"; const body = ansiCode.slice(4, terminator === "\x07" ? -1 : -2); const separatorIndex = body.indexOf(";"); if (separatorIndex === -1) { return undefined; }
const params = body.slice(0, separatorIndex); const url = body.slice(separatorIndex + 1); if (!url) { return null; } return { params, url, terminator };}
function formatOsc8Hyperlink(hyperlink: ActiveHyperlink): string { return `\x1b]8;${hyperlink.params};${hyperlink.url}${hyperlink.terminator}`;}
function formatOsc8Close(terminator: Osc8Terminator): string { return `\x1b]8;;${terminator}`;}
/** * Track active ANSI SGR codes to preserve styling across line breaks. */class AnsiCodeTracker { // Track individual attributes separately so we can reset them specifically private bold = false; private dim = false; private italic = false; private underline = false; private blink = false; private inverse = false; private hidden = false; private strikethrough = false; private fgColor: string | null = null; // Stores the full code like "31" or "38;5;240" private bgColor: string | null = null; // Stores the full code like "41" or "48;5;240" private activeHyperlink: ActiveHyperlink | null = null;
process(ansiCode: string): void { // OSC 8 hyperlink: \x1b]8;;<url>\x1b\\ (open) or \x1b]8;;\x1b\\ (close). // Preserve the original terminator because some terminals only make BEL-terminated // links clickable. OAuth login URLs use BEL, so reopening wrapped lines with ST // made only the first physical line clickable in those terminals. const hyperlink = parseOsc8Hyperlink(ansiCode); if (hyperlink !== undefined) { this.activeHyperlink = hyperlink; return; }
if (!ansiCode.endsWith("m")) { return; }
// Extract the parameters between \x1b[ and m const match = ansiCode.match(/\x1b\[([\d;]*)m/); if (!match) return;
const params = match[1]; if (params === "" || params === "0") { // Full reset this.reset(); return; }
// Parse parameters (can be semicolon-separated) const parts = params.split(";"); let i = 0; while (i < parts.length) { const code = Number.parseInt(parts[i], 10);
// Handle 256-color and RGB codes which consume multiple parameters if (code === 38 || code === 48) { // 38;5;N (256 color fg) or 38;2;R;G;B (RGB fg) // 48;5;N (256 color bg) or 48;2;R;G;B (RGB bg) if (parts[i + 1] === "5" && parts[i + 2] !== undefined) { // 256 color: 38;5;N or 48;5;N const colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]}`; if (code === 38) { this.fgColor = colorCode; } else { this.bgColor = colorCode; } i += 3; continue; } else if (parts[i + 1] === "2" && parts[i + 4] !== undefined) { // RGB color: 38;2;R;G;B or 48;2;R;G;B const colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]};${parts[i + 3]};${parts[i + 4]}`; if (code === 38) { this.fgColor = colorCode; } else { this.bgColor = colorCode; } i += 5; continue; } }
// Standard SGR codes switch (code) { case 0: this.reset(); break; case 1: this.bold = true; break; case 2: this.dim = true; break; case 3: this.italic = true; break; case 4: this.underline = true; break; case 5: this.blink = true; break; case 7: this.inverse = true; break; case 8: this.hidden = true; break; case 9: this.strikethrough = true; break; case 21: this.bold = false; break; // Some terminals case 22: this.bold = false; this.dim = false; break; case 23: this.italic = false; break; case 24: this.underline = false; break; case 25: this.blink = false; break; case 27: this.inverse = false; break; case 28: this.hidden = false; break; case 29: this.strikethrough = false; break; case 39: this.fgColor = null; break; // Default fg case 49: this.bgColor = null; break; // Default bg default: // Standard foreground colors 30-37, 90-97 if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) { this.fgColor = String(code); } // Standard background colors 40-47, 100-107 else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) { this.bgColor = String(code); } break; } i++; } }
private reset(): void { this.bold = false; this.dim = false; this.italic = false; this.underline = false; this.blink = false; this.inverse = false; this.hidden = false; this.strikethrough = false; this.fgColor = null; this.bgColor = null; // SGR reset does not affect OSC 8 hyperlink state }
/** Clear all state for reuse. */ clear(): void { this.reset(); this.activeHyperlink = null; }
getActiveCodes(): string { const codes: string[] = []; if (this.bold) codes.push("1"); if (this.dim) codes.push("2"); if (this.italic) codes.push("3"); if (this.underline) codes.push("4"); if (this.blink) codes.push("5"); if (this.inverse) codes.push("7"); if (this.hidden) codes.push("8"); if (this.strikethrough) codes.push("9"); if (this.fgColor) codes.push(this.fgColor); if (this.bgColor) codes.push(this.bgColor);
let result = codes.length > 0 ? `\x1b[${codes.join(";")}m` : ""; if (this.activeHyperlink) { result += formatOsc8Hyperlink(this.activeHyperlink); } return result; }
hasActiveCodes(): boolean { return ( this.bold || this.dim || this.italic || this.underline || this.blink || this.inverse || this.hidden || this.strikethrough || this.fgColor !== null || this.bgColor !== null || this.activeHyperlink !== null ); }
/** * Get reset codes for attributes that need to be turned off at line end. * Underline must be closed to prevent bleeding into padding. * Active OSC 8 hyperlinks must be closed and re-opened on the next line. * Returns empty string if no attributes need closing. */ getLineEndReset(): string { let result = ""; if (this.underline) { result += "\x1b[24m"; // Underline off only } if (this.activeHyperlink) { result += formatOsc8Close(this.activeHyperlink.terminator); // Re-opened at line start via getActiveCodes() } return result; }}
function updateTrackerFromText(text: string, tracker: AnsiCodeTracker): void { let i = 0; const extractAnsi = createAnsiCodeExtractor(text); while (i < text.length) { const ansiResult = extractAnsi(i); if (ansiResult) { tracker.process(ansiResult.code); i += ansiResult.length; } else { i++; } }}
/** * Split text into words while keeping ANSI codes attached. */function splitIntoTokensWithAnsi(text: string): string[] { const tokens: string[] = []; let current = ""; let pendingAnsi = ""; // ANSI codes waiting to be attached to next visible content let inWhitespace = false; let i = 0; const extractAnsi = createAnsiCodeExtractor(text);
while (i < text.length) { const ansiResult = extractAnsi(i); if (ansiResult) { // Hold ANSI codes separately - they'll be attached to the next visible char pendingAnsi += ansiResult.code; i += ansiResult.length; continue; }
const char = text[i]; const charIsSpace = char === " ";
if (charIsSpace !== inWhitespace && current) { // Switching between whitespace and non-whitespace, push current token tokens.push(current); current = ""; }
// Attach any pending ANSI codes to this visible character if (pendingAnsi) { current += pendingAnsi; pendingAnsi = ""; }
inWhitespace = charIsSpace; current += char; i++; }
// Handle any remaining pending ANSI codes (attach to last token) if (pendingAnsi) { current += pendingAnsi; }
if (current) { tokens.push(current); }
return tokens;}
/** * Wrap text with ANSI codes preserved. * * ONLY does word wrapping - NO padding, NO background colors. * Returns lines where each line is <= width visible chars. * Active ANSI codes are preserved across line breaks. * * @param text - Text to wrap (may contain ANSI codes and newlines) * @param width - Maximum visible width per line * @returns Array of wrapped lines (NOT padded to width) */export function wrapTextWithAnsi(text: string, width: number): string[] { if (!text) { return [""]; }
// Handle newlines by processing each line separately // Track ANSI state across lines so styles carry over after literal newlines const inputLines = text.split("\n"); const result: string[] = []; const tracker = new AnsiCodeTracker();
for (const inputLine of inputLines) { // Prepend active ANSI codes from previous lines (except for first line) const prefix = result.length > 0 ? tracker.getActiveCodes() : ""; result.push(...wrapSingleLine(prefix + inputLine, width)); // Update tracker with codes from this line for next iteration updateTrackerFromText(inputLine, tracker); }
return result.length > 0 ? result : [""];}
function wrapSingleLine(line: string, width: number): string[] { if (!line) { return [""]; }
const visibleLength = visibleWidth(line); if (visibleLength <= width) { return [line]; }
const wrapped: string[] = []; const tracker = new AnsiCodeTracker(); const tokens = splitIntoTokensWithAnsi(line);
let currentLine = ""; let currentVisibleLength = 0;
for (const token of tokens) { const tokenVisibleLength = visibleWidth(token); const isWhitespace = token.trim() === "";
// Token itself is too long - break it character by character if (tokenVisibleLength > width && !isWhitespace) { if (currentLine) { // Add specific reset for underline only (preserves background) const lineEndReset = tracker.getLineEndReset(); if (lineEndReset) { currentLine += lineEndReset; } wrapped.push(currentLine); currentLine = ""; currentVisibleLength = 0; }
// Break long token - breakLongWord handles its own resets const broken = breakLongWord(token, width, tracker); wrapped.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; currentVisibleLength = visibleWidth(currentLine); continue; }
// Check if adding this token would exceed width const totalNeeded = currentVisibleLength + tokenVisibleLength;
if (totalNeeded > width && currentVisibleLength > 0) { // Trim trailing whitespace, then add underline reset (not full reset, to preserve background) let lineToWrap = currentLine.trimEnd(); const lineEndReset = tracker.getLineEndReset(); if (lineEndReset) { lineToWrap += lineEndReset; } wrapped.push(lineToWrap); if (isWhitespace) { // Don't start new line with whitespace currentLine = tracker.getActiveCodes(); currentVisibleLength = 0; } else { currentLine = tracker.getActiveCodes() + token; currentVisibleLength = tokenVisibleLength; } } else { // Add to current line currentLine += token; currentVisibleLength += tokenVisibleLength; }
updateTrackerFromText(token, tracker); }
if (currentLine) { // No reset at end of final line - let caller handle it wrapped.push(currentLine); }
// Trailing whitespace can cause lines to exceed the requested width return wrapped.length > 0 ? wrapped.map((line) => line.trimEnd()) : [""];}
const PUNCTUATION_REGEX = /[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;// Fast path for the common CSI form. The shared scanner handles the wider CSI// grammar, control strings, malformed sequences, and ordinary two-byte escapes.const COMMON_CSI_REGEX = /\x1b\[[0-9;:?<=>]*[\x40-\x7e]/g;
/** Remove all escape sequences (CSI, OSC, DCS/APC, two-char) leaving plain text. */export function stripAnsi(str: string): string { if (!str.includes("\x1b")) return str;
const input = str.replace(COMMON_CSI_REGEX, ""); let escapeIndex = input.indexOf("\x1b"); if (escapeIndex === -1) return input;
const result: string[] = []; let plainStart = 0; const extractAnsiEnd = createAnsiEndExtractor(input); while (escapeIndex !== -1) { const ansiEnd = extractAnsiEnd(escapeIndex); if (ansiEnd !== null) { if (plainStart < escapeIndex) result.push(input.slice(plainStart, escapeIndex)); plainStart = ansiEnd; } else { const next = input.charCodeAt(escapeIndex + 1); if (escapeIndex + 1 < input.length && next !== 0x0a && next !== 0x0d && next !== 0x2028 && next !== 0x2029) { if (plainStart < escapeIndex) result.push(input.slice(plainStart, escapeIndex)); plainStart = escapeIndex + 2; } } escapeIndex = input.indexOf("\x1b", Math.max(escapeIndex + 1, plainStart)); } if (plainStart < input.length) result.push(input.slice(plainStart)); return result.join("");}
/** * Check if a character is whitespace. */export function isWhitespaceChar(char: string): boolean { return /\s/.test(char);}
/** * Check if a character is punctuation. */export function isPunctuationChar(char: string): boolean { return PUNCTUATION_REGEX.test(char);}
function breakLongWord(word: string, width: number, tracker: AnsiCodeTracker): string[] { const lines: string[] = []; let currentLine = tracker.getActiveCodes(); let currentWidth = 0;
// First, separate ANSI codes from visible content // We need to handle ANSI codes specially since they're not graphemes let i = 0; const segments: Array<{ type: "ansi" | "grapheme"; value: string }> = []; const extractAnsi = createAnsiCodeExtractor(word);
while (i < word.length) { const ansiResult = extractAnsi(i); if (ansiResult) { segments.push({ type: "ansi", value: ansiResult.code }); i += ansiResult.length; } else { // Find the next ANSI code or end of string let end = i; while (end < word.length) { const nextAnsi = extractAnsi(end); if (nextAnsi) break; end++; } // Segment this non-ANSI portion into graphemes const textPortion = word.slice(i, end); for (const seg of segmenter.segment(textPortion)) { segments.push({ type: "grapheme", value: seg.segment }); } i = end; } }
// Now process segments for (const seg of segments) { if (seg.type === "ansi") { currentLine += seg.value; tracker.process(seg.value); continue; }
const grapheme = seg.value; // Skip empty graphemes to avoid issues with string-width calculation if (!grapheme) continue;
const graphemeWidth = visibleWidth(grapheme);
if (currentWidth + graphemeWidth > width) { // Add specific reset for underline only (preserves background) const lineEndReset = tracker.getLineEndReset(); if (lineEndReset) { currentLine += lineEndReset; } lines.push(currentLine); currentLine = tracker.getActiveCodes(); currentWidth = 0; }
currentLine += grapheme; currentWidth += graphemeWidth; }
if (currentLine) { // No reset at end of final segment - caller handles continuation lines.push(currentLine); }
return lines.length > 0 ? lines : [""];}
/** * Apply background color to a line, padding to full width. * * @param line - Line of text (may contain ANSI codes) * @param width - Total width to pad to * @param bgFn - Background color function * @returns Line with background applied and padded to width */export function applyBackgroundToLine(line: string, width: number, bgFn: (text: string) => string): string { // Calculate padding needed const visibleLen = visibleWidth(line); const paddingNeeded = Math.max(0, width - visibleLen); const padding = " ".repeat(paddingNeeded);
// Apply background to content + padding const withPadding = line + padding; return bgFn(withPadding);}
/** * Truncate text to fit within a maximum visible width, adding ellipsis if needed. * Optionally pad with spaces to reach exactly maxWidth. * Properly handles ANSI escape codes (they don't count toward width). * * @param text - Text to truncate (may contain ANSI codes) * @param maxWidth - Maximum visible width * @param ellipsis - Ellipsis string to append when truncating (default: "...") * @param pad - If true, pad result with spaces to exactly maxWidth (default: false) * @returns Truncated text, optionally padded to exactly maxWidth */export function truncateToWidth( text: string, maxWidth: number, ellipsis: string = "...", pad: boolean = false,): string { if (maxWidth <= 0) { return ""; }
if (text.length === 0) { return pad ? " ".repeat(maxWidth) : ""; }
const ellipsisWidth = visibleWidth(ellipsis); if (ellipsisWidth >= maxWidth) { const textWidth = visibleWidth(text); if (textWidth <= maxWidth) { return pad ? text + " ".repeat(maxWidth - textWidth) : text; }
const clippedEllipsis = truncateFragmentToWidth(ellipsis, maxWidth); if (clippedEllipsis.width === 0) { return pad ? " ".repeat(maxWidth) : ""; } return finalizeTruncatedResult("", 0, clippedEllipsis.text, clippedEllipsis.width, maxWidth, pad); }
if (isPrintableAscii(text)) { if (text.length <= maxWidth) { return pad ? text + " ".repeat(maxWidth - text.length) : text; } const targetWidth = maxWidth - ellipsisWidth; return finalizeTruncatedResult(text.slice(0, targetWidth), targetWidth, ellipsis, ellipsisWidth, maxWidth, pad); }
const targetWidth = maxWidth - ellipsisWidth; let result = ""; let pendingAnsi = ""; let visibleSoFar = 0; let keptWidth = 0; let keepContiguousPrefix = true; let overflowed = false; let exhaustedInput = false; const hasAnsi = text.includes("\x1b"); const hasTabs = text.includes("\t");
if (!hasAnsi && !hasTabs) { for (const { segment } of segmenter.segment(text)) { const width = graphemeWidth(segment); if (keepContiguousPrefix && keptWidth + width <= targetWidth) { result += segment; keptWidth += width; } else { keepContiguousPrefix = false; } visibleSoFar += width; if (visibleSoFar > maxWidth) { overflowed = true; break; } } exhaustedInput = !overflowed; } else { let i = 0; const extractAnsi = createAnsiCodeExtractor(text); while (i < text.length) { const ansi = extractAnsi(i); if (ansi) { pendingAnsi += ansi.code; i += ansi.length; continue; }
if (text[i] === "\t") { if (keepContiguousPrefix && keptWidth + 3 <= targetWidth) { if (pendingAnsi) { result += pendingAnsi; pendingAnsi = ""; } result += "\t"; keptWidth += 3; } else { keepContiguousPrefix = false; pendingAnsi = ""; } visibleSoFar += 3; if (visibleSoFar > maxWidth) { overflowed = true; break; } i++; continue; }
let end = i; while (end < text.length && text[end] !== "\t") { const nextAnsi = extractAnsi(end); if (nextAnsi) { break; } end++; }
for (const { segment } of segmenter.segment(text.slice(i, end))) { const width = graphemeWidth(segment); if (keepContiguousPrefix && keptWidth + width <= targetWidth) { if (pendingAnsi) { result += pendingAnsi; pendingAnsi = ""; } result += segment; keptWidth += width; } else { keepContiguousPrefix = false; pendingAnsi = ""; }
visibleSoFar += width; if (visibleSoFar > maxWidth) { overflowed = true; break; } } if (overflowed) { break; } i = end; } exhaustedInput = i >= text.length; }
if (!overflowed && exhaustedInput) { return pad ? text + " ".repeat(Math.max(0, maxWidth - visibleSoFar)) : text; }
return finalizeTruncatedResult(result, keptWidth, ellipsis, ellipsisWidth, maxWidth, pad);}
/** * Extract a range of visible columns from a line. Handles ANSI codes and wide chars. * @param strict - If true, exclude wide chars at boundary that would extend past the range */export function sliceByColumn(line: string, startCol: number, length: number, strict = false): string { return sliceWithWidth(line, startCol, length, strict).text;}
/** Like sliceByColumn but also returns the actual visible width of the result. */export function sliceWithWidth( line: string, startCol: number, length: number, strict = false,): { text: string; width: number } { if (length <= 0) return { text: "", width: 0 }; const endCol = startCol + length; let result = "", resultWidth = 0, currentCol = 0, i = 0, pendingAnsi = ""; const extractAnsi = createAnsiCodeExtractor(line);
while (i < line.length) { const ansi = extractAnsi(i); if (ansi) { if (currentCol >= startCol && currentCol < endCol) result += ansi.code; else if (currentCol < startCol) pendingAnsi += ansi.code; i += ansi.length; continue; }
let textEnd = i; while (textEnd < line.length && !extractAnsi(textEnd)) textEnd++;
for (const { segment } of segmenter.segment(line.slice(i, textEnd))) { const w = graphemeWidth(segment); const inRange = currentCol >= startCol && currentCol < endCol; const fits = !strict || currentCol + w <= endCol; if (inRange && fits) { if (pendingAnsi) { result += pendingAnsi; pendingAnsi = ""; } result += segment; resultWidth += w; } currentCol += w; if (currentCol >= endCol) break; } i = textEnd; if (currentCol >= endCol) break; } return { text: result, width: resultWidth };}
/** * Return the OSC 8 hyperlink URL covering the given visible column, or null * when the column is not inside a hyperlink (or is past the end of the line). */export function hyperlinkAtColumn(line: string, column: number): string | null { if (column < 0) return null; const extractAnsi = createAnsiCodeExtractor(line); let currentCol = 0; let activeUrl: string | null = null; let i = 0; while (i < line.length) { const ansi = extractAnsi(i); if (ansi) { const hyperlink = parseOsc8Hyperlink(ansi.code); if (hyperlink !== undefined) activeUrl = hyperlink?.url ?? null; i += ansi.length; continue; } let textEnd = i; while (textEnd < line.length && !extractAnsi(textEnd)) textEnd++; for (const { segment } of segmenter.segment(line.slice(i, textEnd))) { const w = graphemeWidth(segment); if (column < currentCol + w) return activeUrl; currentCol += w; } i = textEnd; } return null;}
/** * Return an explicit OSC 8 URL or terminal-style bare HTTP(S) URL covering a * visible column. OSC 8 remains authoritative when its label resembles a URL. */export function urlAtColumn(line: string, column: number): string | null { const explicitUrl = hyperlinkAtColumn(line, column); if (explicitUrl || column < 0) return explicitUrl;
// Fullscreen normalizes tabs before painting, and strips ANSI without // changing visible columns. Mirror that representation for bare URL spans. const plainText = stripAnsi(line).replace(/\t/g, " "); const urlPattern = /https?:\/\/[^\s<>"'`]+/giu; for (const match of plainText.matchAll(urlPattern)) { let url = match[0].replace(/[.,;:!?]+$/u, ""); for (const [open, close] of [ ["(", ")"], ["[", "]"], ["{", "}"], ] as const) { while (url.endsWith(close) && url.split(close).length > url.split(open).length) { url = url.slice(0, -1); } } const start = visibleWidth(plainText.slice(0, match.index)); const end = start + visibleWidth(url); if (column >= start && column < end) return url; } return null;}
// Pooled tracker instance for extractSegments (avoids allocation per call)const pooledStyleTracker = new AnsiCodeTracker();
/** * Extract "before" and "after" segments from a line in a single pass. * Used for overlay compositing where we need content before and after the overlay region. * Preserves styling from before the overlay that should affect content after it. */export function extractSegments( line: string, beforeEnd: number, afterStart: number, afterLen: number, strictAfter = false,): { before: string; beforeWidth: number; after: string; afterWidth: number } { let before = "", beforeWidth = 0, after = "", afterWidth = 0; let currentCol = 0, i = 0; let pendingAnsiBefore = ""; let afterStarted = false; const afterEnd = afterStart + afterLen; const extractAnsi = createAnsiCodeExtractor(line);
// Track styling state so "after" inherits styling from before the overlay pooledStyleTracker.clear();
while (i < line.length) { const ansi = extractAnsi(i); if (ansi) { // Track all SGR codes to know styling state at afterStart pooledStyleTracker.process(ansi.code); // Include ANSI codes in their respective segments if (currentCol < beforeEnd) { pendingAnsiBefore += ansi.code; } else if (currentCol >= afterStart && currentCol < afterEnd && afterStarted) { // Only include after we've started "after" (styling already prepended) after += ansi.code; } i += ansi.length; continue; }
let textEnd = i; while (textEnd < line.length && !extractAnsi(textEnd)) textEnd++;
for (const { segment } of segmenter.segment(line.slice(i, textEnd))) { const w = graphemeWidth(segment);
if (currentCol < beforeEnd) { if (pendingAnsiBefore) { before += pendingAnsiBefore; pendingAnsiBefore = ""; } before += segment; beforeWidth += w; } else if (currentCol >= afterStart && currentCol < afterEnd) { const fits = !strictAfter || currentCol + w <= afterEnd; if (fits) { // On first "after" grapheme, prepend inherited styling from before overlay if (!afterStarted) { after += pooledStyleTracker.getActiveCodes(); afterStarted = true; } after += segment; afterWidth += w; } }
currentCol += w; // Early exit: done with "before" only, or done with both segments if (afterLen <= 0 ? currentCol >= beforeEnd : currentCol >= afterEnd) break; } i = textEnd; if (afterLen <= 0 ? currentCol >= beforeEnd : currentCol >= afterEnd) break; }
return { before, beforeWidth, after, afterWidth };}